-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy patheventEmitter.ts
More file actions
335 lines (282 loc) · 10.6 KB
/
Copy patheventEmitter.ts
File metadata and controls
335 lines (282 loc) · 10.6 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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
import { v4 as uuidv4 } from 'uuid'
import { ErrorRef, IEventEmitterRegistryController, Statuses } from '../../interfaces/eventEmitter'
import {
debugLog as moduleDebugLog,
debugLoggerRegistry,
DebugLogOptions
} from '../../libs/debugLogger/debugLogger'
import wait from '../../utils/wait'
const LIMIT_ON_THE_NUMBER_OF_ERRORS = 100
// Can be overwritten by controllers to narrow the flow tags for better console filtering and type safety.
export default class EventEmitter<DebugFlow extends string = string> {
id: string
#registry: IEventEmitterRegistryController | null = null
#callbacksWithId: {
id: string | null
cb: (forceEmit?: boolean) => void
}[] = []
#callbacks: ((forceEmit?: boolean) => void)[] = []
#errorCallbacksWithId: {
id: string | null
cb: (error: ErrorRef) => void
}[] = []
#errorCallbacks: ((error: ErrorRef) => void)[] = []
#errors: ErrorRef[] = []
statuses: Statuses<string> = {}
/**
*
* @param registry - EventEmitterRegistryController instance to be used by this controller. Controllers
* added to the registry will have their updates and errors propagated to the front-end.
* @param registerImmediately - Most of the time we want to register the controller in the registry
* immediately upon construction. However, there are some dynamic controllers (like SignAccountOpController)
* that should be registered only after a condition is met (e.g. when the request is open)
*/
constructor(registry?: IEventEmitterRegistryController, registerImmediately: boolean = true) {
this.id = uuidv4()
// Register the controller on construction
debugLoggerRegistry.registerNamespace(this.name)
if (registry) {
this.#registry = registry
if (registerImmediately) {
this.registerInRegistry()
}
}
}
get name(): string {
return this.constructor.name
}
get onUpdateIds() {
return this.#callbacksWithId.map((item) => item.id)
}
get onErrorIds() {
return this.#errorCallbacksWithId.map((item) => item.id)
}
// called emittedErrors and not just errors because some of the other controllers
// that extend this one have errors defined already
get emittedErrors() {
return this.#errors
}
/**
* Emits an update immediately, bypassing both background batching
* (where updates on the same tick are debounced and batched for performance)
* and React batching (where rapid state updates are merged).
*
* This ensures the state change is applied instantly at the React application level.
* It is especially useful when multiple status flags change in quick succession.
*
* For example, if a flow updates a status from INITIAL -> LOADING -> SUCCESS -> INITIAL,
* normal batching may skip intermediate states and only emit the first and last ones.
*/
async forceEmitUpdate() {
// Bypassing background batching on the same tick
await wait(1)
// Passing `true` to the cb will bypass React batching
for (const i of this.#callbacksWithId) i.cb(true)
for (const cb of this.#callbacks) cb(true)
}
protected emitUpdate() {
for (const i of this.#callbacksWithId) i.cb()
for (const cb of this.#callbacks) cb()
}
/**
* Propagates updates from a child controller to its parent in a parent -> child setup,
* ensuring child state updates reach the application without being lost due to batching.
*
* Used when a parent controller (e.g. swapAndBridgeController) subscribes to child updates:
*
* this.#signAccountOpController.onUpdate((forceEmit) => {
* this.propagateUpdate(forceEmit)
* })
*
* Child controllers may update their status very quickly
* (e.g. INITIAL -> LOADING -> SUCCESS -> INITIAL).
* If the parent propagates these updates via `forceEmitUpdate()`,
* the update is scheduled in a new tick and intermediate states may be lost.
*
* `propagateUpdate` forwards the update in the same tick while preserving the
* `forceEmit` behavior, ensuring all states are correctly propagated.
*
* Notes:
* - If `forceEmit` is falsy, this behaves the same as calling `emitUpdate()`.
* For consistency and clarity, parent -> child setups should always use
* `propagateUpdate()` instead of mixing `emitUpdate()` and `propagateUpdate()`.
*
* - For all direct controller updates (i.e. when there is no child controller involved
* and the controller updates its own state), use `emitUpdate()` or `forceEmitUpdate()`.
*/
protected propagateUpdate(forceEmit?: boolean) {
for (const i of this.#callbacksWithId) i.cb(forceEmit)
for (const cb of this.#callbacks) cb(forceEmit)
}
/** True when this controller's debug logging is toggled on. */
get isDebugLogEnabled(): boolean {
return debugLoggerRegistry.isEnabled(this.name)
}
/** Per-controller gated debug log. No-op unless this controller's namespace is
* toggled on via DebugController. */
protected debugLog(
message: string,
payload?: unknown | (() => unknown),
options?: DebugLogOptions & { flow?: DebugFlow }
): void {
moduleDebugLog(this.name, message, payload, options)
}
protected emitError(error: ErrorRef) {
this.#errors.push(error)
this.#trimErrorsIfNeeded()
console.log(
`[Еmitted error in controller ${this.constructor.name}] ${error.message}`,
this.#errors
)
for (const i of this.#errorCallbacksWithId) i.cb(error)
for (const cb of this.#errorCallbacks) cb(error)
}
protected async withStatus(
callName: string,
fn: Function,
allowConcurrentActions = false,
// Silence this error in prod to avoid displaying wired error messages.
// The only benefit of displaying it is for devs to see when an action is dispatched twice.
// TODO: If this happens on PROD, ideally we should get an error report somehow somewhere.
errorLevel: ErrorRef['level'] = process.env.APP_ENV === 'production' &&
process.env.IS_TESTING !== 'true'
? 'silent'
: 'minor'
) {
const someStatusIsLoading = Object.values(this.statuses).some((status) => status !== 'INITIAL')
if (!this.statuses[callName]) {
console.error(`${callName} is not defined in "statuses".`)
}
// By default, concurrent actions are disallowed to maintain consistency, particularly within sub-controllers where
// simultaneous actions can lead to unintended side effects. The 'allowConcurrentActions' flag is provided to enable
// concurrent execution at the main controller level. This is useful when multiple actions need to modify the state
// of different sub-controllers simultaneously.
if (
(someStatusIsLoading && !allowConcurrentActions) ||
!['INITIAL', 'SUCCESS'].includes(this.statuses[callName] as any)
) {
this.emitError({
level: errorLevel,
message: `Please wait for the completion of the previous action before initiating another one, ${callName}`,
error: new Error(
'Another function is already being handled by withStatus refrain from invoking a second function.'
)
})
return
}
if (this.statuses[callName] === 'SUCCESS') {
await wait(2) // to let the INITIAL status be fired from the prev session
}
this.statuses[callName] = 'LOADING'
await this.forceEmitUpdate()
try {
await fn()
this.statuses[callName] = 'SUCCESS'
await this.forceEmitUpdate()
} catch (error: any) {
this.statuses[callName] = 'ERROR'
if ('message' in error && 'level' in error && 'error' in error) {
this.emitError(error)
// Sometimes we don't want to show an error message to the user. For example, if the user cancels a request
// we don't want to go through the SUCCESS state, but we also don't want to show an error message.
} else if (error?.message) {
this.emitError({
message: error?.message || 'An unexpected error occurred',
level: 'major',
error
})
}
await this.forceEmitUpdate()
}
this.statuses[callName] = 'INITIAL'
await this.forceEmitUpdate()
}
// Prevents memory leaks and storing huge amount of errors
#trimErrorsIfNeeded() {
if (this.#errors.length > LIMIT_ON_THE_NUMBER_OF_ERRORS) {
const excessErrors = this.#errors.length - LIMIT_ON_THE_NUMBER_OF_ERRORS
this.#errors = this.#errors.slice(excessErrors)
}
}
// returns an unsub function
onUpdate(cb: (forceUpdate?: boolean) => void, id?: string): () => void {
if (id) {
this.#callbacksWithId.push({ id, cb })
} else {
this.#callbacks.push(cb)
}
return () => {
if (id) {
this.#callbacksWithId = this.#callbacksWithId.filter(
(callbackItem) => callbackItem.id !== id
)
} else {
this.#callbacks.splice(this.#callbacks.indexOf(cb), 1)
}
}
}
// returns an unsub function for error events
onError(cb: (error: ErrorRef) => void, id?: string): () => void {
if (id) {
this.#errorCallbacksWithId.push({ id, cb })
} else {
this.#errorCallbacks.push(cb)
}
return () => {
if (id) {
this.#errorCallbacksWithId = this.#errorCallbacksWithId.filter(
(callbackItem) => callbackItem.id !== id
)
} else {
this.#errorCallbacks.splice(this.#errorCallbacks.indexOf(cb), 1)
}
}
}
/**
* Destroys the controller, unregistering it from the EventEmitterRegistry and
* clearing all callbacks and errors.
*/
destroy() {
this.unregisterFromRegistry()
this.#callbacks = []
this.#callbacksWithId = []
this.#errorCallbacks = []
this.#errorCallbacksWithId = []
this.#errors = []
}
/**
* Registers the controller into the EventEmitterRegistry (if set)
* to propagate its updates and errors to the front-end.
*/
registerInRegistry() {
if (!this.#registry) {
this.emitError({
level: 'silent',
message: `EventEmitter: Trying to register a controller while the registry is not set. Controller: ${this.name}`,
error: new Error(
'EventEmitter: Trying to register a controller while the registry is not set.'
)
})
return
}
this.#registry.set(this.id, this)
}
/**
* Unregisters the controller from the EventEmitterRegistry (if set).
* Used when controllers are destroyed or by dynamic controllers.
*/
unregisterFromRegistry() {
if (!this.#registry) return
this.#registry?.delete(this.id)
}
isInRegistry(): boolean {
return !!this.#registry?.has(this.id)
}
toJSON() {
return {
...this,
name: this.name,
emittedErrors: this.emittedErrors // includes the getter in the stringified instance
}
}
}