forked from serverless-dns/serverless-dns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
system.js
272 lines (235 loc) · 6.69 KB
/
system.js
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
/*
* Copyright (c) 2021 RethinkDNS and its authors.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
import * as util from "./commons/util.js";
// Evaluate if EventTarget APIs can replace this hand-rolled impl
// developers.cloudflare.com/workers/platform/changelog#2021-09-24
/** @typedef {any[]?} parcel */
/** @typedef {function(parcel)} listenfn */
// once emitted, they stick; firing off new listeners forever, just the once.
const stickyEvents = new Set([
// when process bring-up is done
"prepare",
// when env setup is done
"ready",
// when svc setup is done
"steady",
// when all systems are a-go
"go",
]);
/** @type {Map<string, parcel>} */
const stickyParcels = new Map();
const events = new Set([
// when server should cease
"stop",
]);
/** @type {Set<string>} */
const ephemeralEvents = new Set();
/** @type {Map<string, Set<listenfn>>} */
const listeners = new Map();
/** @type {Map<string, Set<listenfn>>} */
const waitGroup = new Map();
(() => {
for (const e of events) {
listeners.set(e, new Set());
waitGroup.set(e, new Set());
}
for (const se of stickyEvents) {
listeners.set(se, new Set());
waitGroup.set(se, new Set());
}
})();
/**
* Fires event.
* @param {string} event
* @param {parcel} parcel
* @returns {int}
*/
export function pub(event, parcel = null) {
if (util.emptyString(event)) return;
const hadEphemeralEvent = ephemeralEvents.delete(event);
const tot = awaiters(event, parcel, hadEphemeralEvent);
return tot + callbacks(event, parcel, hadEphemeralEvent);
}
/**
* Invokes cb when event is fired.
* @param {string} event
* @param {listenfn} cb
* @param {int} timeout
* @returns {boolean}
*/
export function sub(event, cb, timeout = 0) {
if (util.emptyString(event)) return;
if (typeof cb !== "function") return;
const eventCallbacks = listeners.get(event);
if (!eventCallbacks) {
// event is sticky, fire off the listener at once
if (stickyEvents.has(event)) {
const parcel = stickyParcels.get(event); // may be null
microtaskBox(cb, parcel);
return true;
}
// event doesn't exist so make it ephemeral
ephemeralEvents.add(event);
listeners.set(event, new Set());
waitGroup.set(event, new Set());
return false;
}
const tid = timeout > 0 ? util.timeout(timeout, cb) : -2;
const fulfiller =
tid > 0
? (parcel) => {
clearTimeout(tid);
cb(parcel);
}
: cb;
eventCallbacks.add(fulfiller);
return true;
}
/**
* Waits till event fires or timesout.
* @param {string} event
* @param {int} timeout
* @returns {Promise<parcel>}
*/
export function when(event, timeout = 0) {
if (util.emptyString(event)) {
return Promise.reject(new Error("empty event"));
}
const wg = waitGroup.get(event);
if (!wg) {
// if stick event, fulfill promise right away
if (stickyEvents.has(event)) {
const parcel = stickyParcels.get(event); // may be null
return Promise.resolve(parcel);
}
// no such event so make it ephemeral
ephemeralEvents.add(event);
listeners.set(event, new Set());
waitGroup.set(event, new Set());
return Promise.reject(new Error(event + " missing event"));
}
return new Promise((accept, reject) => {
const tid =
timeout > 0
? util.timeout(timeout, () => {
reject(new Error(event + " event elapsed " + timeout));
})
: -2;
/** @type {listenfn} */
const fulfiller = (parcel) => {
if (tid >= 0) clearTimeout(tid);
accept(parcel);
};
wg.add(fulfiller);
});
}
/**
* @param {string} event
* @param {parcel} parcel
* @param {boolean} ephemeralEvent
* @returns {int}
*/
function awaiters(event, parcel = null, ephemeralEvent = false) {
if (util.emptyString(event)) return 0;
const wg = waitGroup.get(event);
if (!wg) return 0;
// listeners valid just the once for stickyEvents & ephemeralEvents
if (stickyEvents.has(event)) {
waitGroup.delete(event);
stickyParcels.set(event, parcel);
} else if (ephemeralEvent) {
// log.d("sys: wg ephemeralEvent", event, parcel);
waitGroup.delete(event);
}
if (wg.size === 0) return 0;
safeBox(wg, parcel);
return wg.size;
}
/**
* @param {string} event
* @param {parcel} parcel
* @param {boolean} ephemeralEvent
* @returns {int}
*/
function callbacks(event, parcel = null, ephemeralEvent = false) {
if (util.emptyString(event)) return 0;
const cbs = listeners.get(event);
if (!cbs) return 0;
// listeners valid just the once for stickyEvents & ephemeralEvents
if (stickyEvents.has(event)) {
listeners.delete(event);
stickyParcels.set(event, parcel);
} else if (ephemeralEvent) {
// log.d("sys: cb ephemeralEvent", event, parcel);
listeners.delete(event);
}
if (cbs.size === 0) return 0;
// callbacks are queued async and don't block the caller. On Workers,
// where IOs or timers require event-context aka network-context,
// which is only available when fns are invoked in response to an
// incoming request (through the fetch event handler), such callbacks
// may not even fire. Instead use: awaiters and not callbacks.
microtaskBox(cbs, parcel);
return cbs.size;
}
/**
* Queues fn in a macro-task queue of the event-loop
* exec order: github.com/nodejs/node/issues/22257
* @param {listenfn} fn
*/
export function taskBox(fn) {
// TODO: could be replaced with scheduler.wait
// developers.cloudflare.com/workers/platform/changelog#2021-12-10
util.timeout(/* with 0ms delay*/ 0, () => safeBox(fn));
}
// ref: MDN: Web/API/HTML_DOM_API/Microtask_guide/In_depth
// queue-task polyfill: stackoverflow.com/a/61605098
const taskboxPromise = { p: Promise.resolve() };
/**
* Queues fns in a micro-task queue
* @param {listenfn[]} fns
* @param {parcel} arg
*/
function microtaskBox(fns, arg) {
let enqueue = null;
if (typeof queueMicrotask === "function") {
enqueue = queueMicrotask;
} else {
enqueue = taskboxPromise.p.then.bind(taskboxPromise.p);
}
enqueue(() => safeBox(fns, arg));
}
/**
* stackoverflow.com/questions/38508420
* @param {listenfn[]|listenfn?} fns
* @param {parcel} arg
* @returns {any[]}
*/
function safeBox(fns, arg) {
// TODO: safeBox for async fns with r.push(await f())?
if (typeof fns === "function") {
fns = [fns];
}
const r = [];
if (!util.isIterable(fns)) {
return r;
}
for (const f of fns) {
if (typeof f !== "function") {
r.push(null);
continue;
}
try {
r.push(f(arg));
} catch (ignore) {
// log.e("sys: safeBox err", ignore);
r.push(null);
}
}
return r;
}