|
1
|
import { EventEmitter } from "events" |
|
2
|
|
|
3
|
type EventBus = { |
|
4
|
eventEmitter_: EventEmitter |
|
5
|
} |
|
6
|
|
|
7
|
type WaitSubscribersExecutionOptions = { |
|
8
|
/** Timeout in milliseconds for waiting for the event. Defaults to 15000ms. */ |
|
9
|
timeout?: number |
|
10
|
/** Number of times the event should be triggered before resolving. Defaults to 1. */ |
|
11
|
triggerCount?: number |
|
12
|
} |
|
13
|
|
|
14
|
// Map to hold pending promises for each event. |
|
15
|
const waits = new Map<string | symbol, Promise<any>>() |
|
16
|
|
|
17
|
/** |
|
18
|
* Creates a promise that rejects after a specified timeout. |
|
19
|
* @param timeout - The timeout in milliseconds. |
|
20
|
* @param eventName - The name of the event being waited on. |
|
21
|
* @returns A tuple containing the timeout promise and a function to clear the timeout. |
|
22
|
*/ |
|
23
|
const createTimeoutPromise = ( |
|
24
|
timeout: number, |
|
25
|
eventName: string | symbol |
|
26
|
): [Promise<never>, () => void] => { |
|
27
|
let timeoutId: NodeJS.Timeout | null = null |
|
28
|
const promise = new Promise<never>((_, reject) => { |
|
29
|
timeoutId = setTimeout(() => { |
|
30
|
reject( |
|
31
|
new Error( |
|
32
|
`Timeout of ${timeout}ms exceeded while waiting for event "${String( |
|
33
|
eventName |
|
34
|
)}"` |
|
35
|
) |
|
36
|
) |
|
37
|
}, timeout) |
|
38
|
timeoutId.unref() |
|
39
|
}) |
|
40
|
return [promise, () => timeoutId && clearTimeout(timeoutId)] |
|
41
|
} |
|
42
|
|
|
43
|
// Core logic to wait for subscribers. |
|
44
|
const doWaitSubscribersExecution = ( |
|
45
|
eventName: string | symbol, |
|
46
|
eventBus: EventBus, |
|
47
|
{ timeout = 15000, triggerCount = 1 }: WaitSubscribersExecutionOptions = {} |
|
48
|
): Promise<any> => { |
|
49
|
const eventEmitter = eventBus.eventEmitter_ |
|
50
|
const subscriberPromises: Promise<any>[] = [] |
|
51
|
const [timeoutPromise, clearTimeout] = createTimeoutPromise( |
|
52
|
timeout, |
|
53
|
eventName |
|
54
|
) |
|
55
|
|
|
56
|
let currentCount = 0 |
|
57
|
|
|
58
|
if (!eventEmitter.listeners(eventName).length) { |
|
59
|
let ok: (value?: any) => void |
|
60
|
const promise = new Promise((resolve) => { |
|
61
|
ok = resolve |
|
62
|
}) |
|
63
|
subscriberPromises.push(promise) |
|
64
|
|
|
65
|
let res: any[] = [] |
|
66
|
const newListener = async (...args: any[]) => { |
|
67
|
currentCount++ |
|
68
|
res.push(args) |
|
69
|
|
|
70
|
if (currentCount >= triggerCount) { |
|
71
|
eventEmitter.removeListener(eventName, newListener) |
|
72
|
if (triggerCount === 1) { |
|
73
|
ok(...args) |
|
74
|
} else { |
|
75
|
ok(res) |
|
76
|
} |
|
77
|
} |
|
78
|
} |
|
79
|
|
|
80
|
Object.defineProperty(newListener, "__isSubscribersExecutionWrapper", { |
|
81
|
value: true, |
|
82
|
configurable: true, |
|
83
|
enumerable: false, |
|
84
|
}) |
|
85
|
|
|
86
|
eventEmitter.on(eventName, newListener) |
|
87
|
} else { |
|
88
|
eventEmitter.listeners(eventName).forEach((listener: any) => { |
|
89
|
if (listener.__isSubscribersExecutionWrapper) { |
|
90
|
return |
|
91
|
} |
|
92
|
|
|
93
|
eventEmitter.removeListener(eventName, listener) |
|
94
|
|
|
95
|
let ok: (value?: any) => void, nok: (reason?: any) => void |
|
96
|
const promise = new Promise((resolve, reject) => { |
|
97
|
ok = resolve |
|
98
|
nok = reject |
|
99
|
}) |
|
100
|
subscriberPromises.push(promise) |
|
101
|
let res: any[] = [] |
|
102
|
let cleanupDone = false |
|
103
|
|
|
104
|
const newListener = async (...args2: any[]) => { |
|
105
|
try { |
|
106
|
const listenerRes = listener.apply(eventBus, args2) |
|
107
|
if (typeof listenerRes?.then === "function") { |
|
108
|
await listenerRes.then((res_) => { |
|
109
|
res.push(res_) |
|
110
|
currentCount++ |
|
111
|
}) |
|
112
|
} else { |
|
113
|
res.push(listenerRes) |
|
114
|
currentCount++ |
|
115
|
} |
|
116
|
|
|
117
|
if (currentCount >= triggerCount) { |
|
118
|
const res_ = triggerCount === 1 ? res[0] : res |
|
119
|
ok(res_) |
|
120
|
} |
|
121
|
} catch (error) { |
|
122
|
nok(error) |
|
123
|
} |
|
124
|
|
|
125
|
if (currentCount >= triggerCount && !cleanupDone) { |
|
126
|
// As soon as the subscriber is executed the required number of times, we restore the original listener |
|
127
|
cleanupDone = true |
|
128
|
eventEmitter.removeListener(eventName, newListener) |
|
129
|
|
|
130
|
// Unwrap to find the true original listener |
|
131
|
let listenerToAdd = listener |
|
132
|
while (listenerToAdd?.originalListener) { |
|
133
|
listenerToAdd = listenerToAdd.originalListener |
|
134
|
} |
|
135
|
|
|
136
|
if (listenerToAdd) { |
|
137
|
eventEmitter.on(eventName, listenerToAdd) |
|
138
|
} |
|
139
|
} |
|
140
|
} |
|
141
|
|
|
142
|
Object.defineProperty(newListener, "__isSubscribersExecutionWrapper", { |
|
143
|
value: true, |
|
144
|
configurable: true, |
|
145
|
enumerable: false, |
|
146
|
}) |
|
147
|
Object.defineProperty(newListener, "originalListener", { |
|
148
|
value: listener, |
|
149
|
configurable: true, |
|
150
|
enumerable: false, |
|
151
|
}) |
|
152
|
eventEmitter.on(eventName, newListener) |
|
153
|
}) |
|
154
|
} |
|
155
|
|
|
156
|
const subscribersPromise = Promise.all(subscriberPromises).finally(() => { |
|
157
|
// Clear the timeout since events have been fired and handled |
|
158
|
clearTimeout() |
|
159
|
}) |
|
160
|
|
|
161
|
// Race between the subscribers and the timeout |
|
162
|
return Promise.race([subscribersPromise, timeoutPromise]) |
|
163
|
} |
|
164
|
|
|
165
|
/** |
|
166
|
* Allows you to wait for all subscribers to execute for a given event. |
|
167
|
* It ensures that concurrent waits for the same event are queued and executed sequentially. |
|
168
|
* |
|
169
|
* @param eventName - The name of the event to wait for. |
|
170
|
* @param eventBus - The event bus instance. |
|
171
|
* @param options - Options including timeout and triggerCount. |
|
172
|
*/ |
|
173
|
export const waitSubscribersExecution = ( |
|
174
|
eventName: string | symbol, |
|
175
|
eventBus: any, |
|
176
|
options?: WaitSubscribersExecutionOptions |
|
177
|
): Promise<any> => { |
|
178
|
const chain = waits.get(eventName) |
|
179
|
|
|
180
|
if (!chain) { |
|
181
|
const newPromise = doWaitSubscribersExecution( |
|
182
|
eventName, |
|
183
|
eventBus, |
|
184
|
options |
|
185
|
).finally(() => { |
|
186
|
// Once this chain is done, remove it from the map |
|
187
|
// if it's still the same promise. This prevents race conditions |
|
188
|
// where a new wait is queued before this one is removed. |
|
189
|
if (waits.get(eventName) === newPromise) { |
|
190
|
waits.delete(eventName) |
|
191
|
} |
|
192
|
}) |
|
193
|
waits.set(eventName, newPromise) |
|
194
|
return newPromise |
|
195
|
} |
|
196
|
|
|
197
|
const runner = () => { |
|
198
|
return doWaitSubscribersExecution(eventName, eventBus, options) |
|
199
|
} |
|
200
|
|
|
201
|
const newPromise = chain.then(runner, runner).finally(() => { |
|
202
|
// Once this chain is done, remove it from the map |
|
203
|
// if it's still the same promise. This prevents race conditions |
|
204
|
// where a new wait is queued before this one is removed. |
|
205
|
if (waits.get(eventName) === newPromise) { |
|
206
|
waits.delete(eventName) |
|
207
|
} |
|
208
|
}) |
|
209
|
|
|
210
|
waits.set(eventName, newPromise) |
|
211
|
|
|
212
|
return newPromise |
|
213
|
} |