forked from ipfs/ipfs-desktop
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontext.js
More file actions
172 lines (157 loc) · 6.24 KB
/
context.js
File metadata and controls
172 lines (157 loc) · 6.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
const pDefer = require('p-defer')
const logger = require('./common/logger')
/**
* @typedef { 'tray' | 'tray.update-menu' | 'countlyDeviceId' | 'manualCheckForUpdates' | 'startIpfs' | 'stopIpfs' | 'restartIpfs' | 'getIpfsd' | 'launchWebUI' | 'webui' | 'splashScreen' | 'i18n.initDone' } ContextProperties
*/
/**
* Context helps the app do many different things without explicitly depending on each other. Instead, each module
* can set a property on the context and other modules can get that property from the context when they need it.
*
* Benefits:
* Avoid passing the same object to many different modules.
* Avoid circular dependencies and makes it easier to test modules in isolation.
* Speed up startup time by only loading what we need when we need it.
*
*
* | Context property exists? | Is the backing promise fulfilled? | Method called | Is a deferred promise created? | Returned Value |
* |--------------------------|-----------------------------------|---------------|--------------------------------|----------------------------------------------------------------------------------------------------------|
* | No | N/A | GetProp | Yes | A newly created deferred promise(unfulfilled) |
* | No | N/A | SetProp | Yes | void |
* | Yes | No | GetProp | No | The found deferred promise (unfulfilled) |
* | Yes | No | SetProp | No | void |
* | Yes | Yes | GetProp | No | The found deferred promise (fulfilled) |
* | Yes | Yes | SetProp | No | We throw an error here. Any getProps called for the property prior to this would have a hanging promise. |
*
* @extends {Record<string, unknown>}
* @property {Function} launchWebUI
*/
class Context {
constructor () {
/**
* Stores prop->value mappings.
*
* @type {Map<string|symbol, unknown>}
*/
this._properties = new Map()
/**
* Stores prop->Promise mappings.
*
* @type {Map<string|symbol, pDefer.DeferredPromise<unknown>>}
*/
this._promiseMap = new Map()
}
/**
* Set the value of a property to a value.
* This method supports overwriting values.
*
* @template T
* @param {ContextProperties} propertyName
* @param {T} value
*
* @returns {void}
*/
setProp (propertyName, value) {
if (this._properties.has(propertyName)) {
logger.error('[ctx] Property already exists')
throw new Error(`[ctx] Property ${String(propertyName)} already exists`)
}
logger.info(`[ctx] setting ${String(propertyName)}`)
try {
this._properties.set(propertyName, value)
this._resolvePropToValue(propertyName, value)
} catch (e) {
logger.error(String(e))
}
}
/**
* Get the value of a property wrapped in a promise.
*
* @template T
* @param {ContextProperties} propertyName
* @returns {Promise<T>}
*/
async getProp (propertyName) {
logger.info(`[ctx] getting ${String(propertyName)}`)
const value = this._properties.get(propertyName)
if (value != null) {
logger.info(`[ctx] Found existing property ${String(propertyName)}`)
this._resolvePropToValue(propertyName, value)
// @ts-ignore
return value
} else {
logger.info(`[ctx] Could not find property ${String(propertyName)}`)
}
// no value exists, create deferred promise and return the promise
return this._createDeferredForProp(propertyName).promise
}
/**
* A simple helper to improve DX and UX when calling functions.
*
* This function allows you to request a function from AppContext without blocking until you actually need to call it.
*
* @param {ContextProperties} propertyName
* @returns {(...args: unknown[]) => Promise<unknown>}
*/
getFn (propertyName) {
const originalFnPromise = this.getProp(propertyName)
return async (...args) => {
const originalFn = await originalFnPromise
try {
return await originalFn(...args)
} catch (err) {
logger.error(`[ctx] Error calling ${String(propertyName)}`)
logger.error(String(err))
throw err
}
}
}
/**
* Gets existing promise and resolves it with the given value.
*
* @private
* @template T
* @param {ContextProperties} propertyName
* @param {T} value
* @returns {void}
*/
_resolvePropToValue (propertyName, value) {
let deferred = this._promiseMap.get(propertyName)
if (deferred == null) {
logger.info(`[ctx] No promise found for ${String(propertyName)}`)
deferred = this._createDeferredForProp(propertyName)
}
logger.info(`[ctx] Resolving promise for ${String(propertyName)}`)
deferred.resolve(value)
}
/**
* Returns the existing promise for a property if it exists.
* If not, one is created and set in the `_promiseMap`, then returned
*
* @private
* @template T
* @param {ContextProperties} propertyName
* @returns {pDefer.DeferredPromise<T>}
*/
_createDeferredForProp (propertyName) {
let deferred = this._promiseMap.get(propertyName)
if (deferred == null) {
deferred = pDefer()
this._promiseMap.set(propertyName, deferred)
}
// @ts-expect-error - Need to fix generics
return deferred
}
}
/**
* @type {Context}
*/
let appContext
/**
*
* @returns {Context}
*/
function getAppContext () {
appContext = appContext ?? new Context()
return appContext
}
module.exports = getAppContext