@pontlabsai/eventdispatch 0.0.0-stage → 0.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +115 -2
- package/dist/cs.d.ts +32 -0
- package/dist/cs.js +203 -0
- package/dist/cs.js.map +1 -0
- package/dist/dispatcher.d.ts +66 -0
- package/dist/dispatcher.js +170 -0
- package/dist/dispatcher.js.map +1 -0
- package/dist/event.d.ts +77 -0
- package/dist/event.js +138 -0
- package/dist/event.js.map +1 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.js +14 -0
- package/dist/index.js.map +1 -0
- package/dist/recording.d.ts +103 -0
- package/dist/recording.js +239 -0
- package/dist/recording.js.map +1 -0
- package/dist/semaphore.d.ts +45 -0
- package/dist/semaphore.js +125 -0
- package/dist/semaphore.js.map +1 -0
- package/dist/sim.d.ts +68 -0
- package/dist/sim.js +203 -0
- package/dist/sim.js.map +1 -0
- package/package.json +50 -4
- package/src/cs.ts +192 -0
- package/src/dispatcher.ts +203 -0
- package/src/event.ts +172 -0
- package/src/index.ts +19 -0
- package/src/recording.ts +282 -0
- package/src/semaphore.ts +128 -0
- package/src/sim.ts +217 -0
package/dist/sim.js
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
import { Dispatcher } from "./dispatcher.js";
|
|
2
|
+
import { Handoff } from "./event.js";
|
|
3
|
+
/** Completions fired between yields to the host's task queue, so a long run never freezes a page. */
|
|
4
|
+
const YIELD_EVERY = 256;
|
|
5
|
+
function isCS(it) {
|
|
6
|
+
return Array.isArray(it) && (it[0] === "CSWait" || it[0] === "CSRelease");
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* A sim dispatch (spec sim.md): a CS queue dispatch whose events quote
|
|
10
|
+
* durations. Its clock, `now`, starts at 0 and moves only when an
|
|
11
|
+
* event completes. One driver fires completions in order of completion
|
|
12
|
+
* time, ties in quote order, so a run is deterministic.
|
|
13
|
+
*
|
|
14
|
+
* An event's `dispatch` returns its quote synchronously (a number
|
|
15
|
+
* >= 0) and does nothing else; its `finish` is the completion step.
|
|
16
|
+
* CSWait and CSRelease stay outside the clock, in their own tasks.
|
|
17
|
+
*/
|
|
18
|
+
export class SimDispatcher extends Dispatcher {
|
|
19
|
+
/** The simulated clock. */
|
|
20
|
+
now = 0;
|
|
21
|
+
/** Whether an engine is attached (a stepWorld was given). */
|
|
22
|
+
engineAttached;
|
|
23
|
+
stepWorldFn;
|
|
24
|
+
heap = [];
|
|
25
|
+
scheduledMap = new Map();
|
|
26
|
+
seq = 0;
|
|
27
|
+
outstanding = new Set(); // accepted CSWaits not yet waiting
|
|
28
|
+
fired = 0;
|
|
29
|
+
constructor(name, options = {}) {
|
|
30
|
+
super(name, { ...options, cs: true });
|
|
31
|
+
this.stepWorldFn = options.stepWorld;
|
|
32
|
+
this.engineAttached = options.stepWorld !== undefined;
|
|
33
|
+
}
|
|
34
|
+
/** Completions scheduled and not yet fired or cancelled. */
|
|
35
|
+
get scheduledEvents() {
|
|
36
|
+
return this.scheduledMap.size;
|
|
37
|
+
}
|
|
38
|
+
/** Clock time until the next scheduled completion, or null. */
|
|
39
|
+
timeToNext() {
|
|
40
|
+
const at = this.nextAt();
|
|
41
|
+
return at === null ? null : at - this.now;
|
|
42
|
+
}
|
|
43
|
+
/** @internal The earliest live completion time, or null. */
|
|
44
|
+
nextAt() {
|
|
45
|
+
let best = null;
|
|
46
|
+
for (const s of this.scheduledMap.values())
|
|
47
|
+
if (best === null || s.completeAt < best)
|
|
48
|
+
best = s.completeAt;
|
|
49
|
+
return best;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Removes a scheduled completion: the event never finishes (spec
|
|
53
|
+
* sim.md#cancel). An id that is not scheduled does nothing. Returns
|
|
54
|
+
* whether it cancelled.
|
|
55
|
+
*/
|
|
56
|
+
cancel(eventId) {
|
|
57
|
+
const s = this.scheduledMap.get(eventId);
|
|
58
|
+
if (!s)
|
|
59
|
+
return false;
|
|
60
|
+
this.scheduledMap.delete(eventId);
|
|
61
|
+
this.cancelled(s);
|
|
62
|
+
return true;
|
|
63
|
+
}
|
|
64
|
+
/** Called when a scheduled event is cancelled. */
|
|
65
|
+
cancelled(_s) { }
|
|
66
|
+
// -- the driver ------------------------------------------------------
|
|
67
|
+
async run() {
|
|
68
|
+
while (this.running) {
|
|
69
|
+
if (this.queue.length === 0 && this.scheduledMap.size === 0) {
|
|
70
|
+
await this.idle();
|
|
71
|
+
continue;
|
|
72
|
+
}
|
|
73
|
+
const open = await this.drainCycle();
|
|
74
|
+
if (this.scheduledMap.size > 0)
|
|
75
|
+
await this.advanceOne();
|
|
76
|
+
else if (!open)
|
|
77
|
+
await Promise.race([this.cs.changed.wait(), this.idle()]); // a registration, enqueue or stop
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* One drain: the CS gate as a verdict (spec sim.md#cs). While an
|
|
82
|
+
* accepted CSWait is not yet waiting, the rest of the queue stays
|
|
83
|
+
* queued and the driver keeps firing completions.
|
|
84
|
+
*/
|
|
85
|
+
async drainCycle() {
|
|
86
|
+
await Handoff.at("gate");
|
|
87
|
+
const cs = this.cs;
|
|
88
|
+
const { expected, rest } = cs.dispatchWaits(this, this.queue);
|
|
89
|
+
this.queue = rest;
|
|
90
|
+
for (const id of expected)
|
|
91
|
+
this.outstanding.add(id);
|
|
92
|
+
for (const id of [...this.outstanding])
|
|
93
|
+
if (!cs.outstanding([id]))
|
|
94
|
+
this.outstanding.delete(id);
|
|
95
|
+
if (this.outstanding.size > 0)
|
|
96
|
+
return false;
|
|
97
|
+
const batch = this.queue;
|
|
98
|
+
this.queue = [];
|
|
99
|
+
// releases complete by condition, not duration: never quoted
|
|
100
|
+
for (const it of batch)
|
|
101
|
+
if (isCS(it))
|
|
102
|
+
super.dispatchItem(it);
|
|
103
|
+
for (const it of batch)
|
|
104
|
+
if (!isCS(it))
|
|
105
|
+
this.dispatchItem(it);
|
|
106
|
+
return true;
|
|
107
|
+
}
|
|
108
|
+
/** Quotes an item and schedules its completion; false (logged) if it fails. @internal */
|
|
109
|
+
dispatchItem(it) {
|
|
110
|
+
if (isCS(it))
|
|
111
|
+
return super.dispatchItem(it);
|
|
112
|
+
try {
|
|
113
|
+
const { event, env, args } = this.prepare(it);
|
|
114
|
+
const quote = event.dispatch(env, args);
|
|
115
|
+
if (typeof quote !== "number" || !Number.isFinite(quote) || quote < 0) {
|
|
116
|
+
const got = quote instanceof Promise ? "a promise" : String(quote);
|
|
117
|
+
throw new Error(`sim dispatch must return a duration >= 0 synchronously, got ${got}`);
|
|
118
|
+
}
|
|
119
|
+
const s = {
|
|
120
|
+
event, env, args, startedAt: this.now, duration: quote, completeAt: this.now + quote, seq: this.seq++,
|
|
121
|
+
};
|
|
122
|
+
this.scheduledMap.set(env.id, s);
|
|
123
|
+
this.push({ at: s.completeAt, seq: s.seq, id: env.id });
|
|
124
|
+
return true;
|
|
125
|
+
}
|
|
126
|
+
catch (e) {
|
|
127
|
+
this.logger("warn", `${this.name}: item failed: ${JSON.stringify(it)}`, e);
|
|
128
|
+
return false;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
/** Fires the soonest scheduled completion; returns its event id, or null. */
|
|
132
|
+
async advanceOne() {
|
|
133
|
+
for (;;) {
|
|
134
|
+
const top = this.pop();
|
|
135
|
+
if (!top)
|
|
136
|
+
return null;
|
|
137
|
+
const s = this.scheduledMap.get(top.id);
|
|
138
|
+
if (!s || s.seq !== top.seq)
|
|
139
|
+
continue; // cancelled
|
|
140
|
+
// taking it is one step: a cancel from now on is a no-op
|
|
141
|
+
this.scheduledMap.delete(top.id);
|
|
142
|
+
if (this.stepWorldFn)
|
|
143
|
+
await this.stepWorldFn(this.now, s.completeAt);
|
|
144
|
+
this.now = s.completeAt;
|
|
145
|
+
this.live++;
|
|
146
|
+
try {
|
|
147
|
+
await Handoff.at("finish");
|
|
148
|
+
await this.complete(s);
|
|
149
|
+
}
|
|
150
|
+
finally {
|
|
151
|
+
this.live--;
|
|
152
|
+
}
|
|
153
|
+
if (++this.fired % YIELD_EVERY === 0)
|
|
154
|
+
await new Promise((r) => setTimeout(r, 0));
|
|
155
|
+
return top.id;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
/** The completion step: finish. */
|
|
159
|
+
async complete(s) {
|
|
160
|
+
await this.guard("finish", s.env, () => s.event.finish(s.env, s.args));
|
|
161
|
+
}
|
|
162
|
+
// -- the heap ----------------------------------------------------------
|
|
163
|
+
less(a, b) {
|
|
164
|
+
return a.at < b.at || (a.at === b.at && a.seq < b.seq);
|
|
165
|
+
}
|
|
166
|
+
push(e) {
|
|
167
|
+
const h = this.heap;
|
|
168
|
+
h.push(e);
|
|
169
|
+
let i = h.length - 1;
|
|
170
|
+
while (i > 0) {
|
|
171
|
+
const p = (i - 1) >> 1;
|
|
172
|
+
if (!this.less(h[i], h[p]))
|
|
173
|
+
break;
|
|
174
|
+
[h[i], h[p]] = [h[p], h[i]];
|
|
175
|
+
i = p;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
pop() {
|
|
179
|
+
const h = this.heap;
|
|
180
|
+
if (h.length === 0)
|
|
181
|
+
return undefined;
|
|
182
|
+
const top = h[0];
|
|
183
|
+
const last = h.pop();
|
|
184
|
+
if (h.length > 0) {
|
|
185
|
+
h[0] = last;
|
|
186
|
+
let i = 0;
|
|
187
|
+
for (;;) {
|
|
188
|
+
const l = 2 * i + 1, r = l + 1;
|
|
189
|
+
let m = i;
|
|
190
|
+
if (l < h.length && this.less(h[l], h[m]))
|
|
191
|
+
m = l;
|
|
192
|
+
if (r < h.length && this.less(h[r], h[m]))
|
|
193
|
+
m = r;
|
|
194
|
+
if (m === i)
|
|
195
|
+
break;
|
|
196
|
+
[h[i], h[m]] = [h[m], h[i]];
|
|
197
|
+
i = m;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
return top;
|
|
201
|
+
}
|
|
202
|
+
}
|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,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;QACjB,MAAM,IAAI,GAAG,CAAC,CAAC,GAAG,EAAG,CAAC;QACtB,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACjB,CAAC,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC;YACZ,IAAI,CAAC,GAAG,CAAC,CAAC;YACV,SAAS,CAAC;gBACR,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;gBAC/B,IAAI,CAAC,GAAG,CAAC,CAAC;gBACV,IAAI,CAAC,GAAG,CAAC,CAAC,MAAM,IAAI,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;oBAAE,CAAC,GAAG,CAAC,CAAC;gBACjD,IAAI,CAAC,GAAG,CAAC,CAAC,MAAM,IAAI,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;oBAAE,CAAC,GAAG,CAAC,CAAC;gBACjD,IAAI,CAAC,KAAK,CAAC;oBAAE,MAAM;gBACnB,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;gBAC5B,CAAC,GAAG,CAAC,CAAC;YACR,CAAC;QACH,CAAC;QACD,OAAO,GAAG,CAAC;IACb,CAAC;CACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,52 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@pontlabsai/eventdispatch",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.3.2",
|
|
4
|
+
"description": "Events dispatched from a queue, each finish deciding what runs next. Clockless; runs in browsers, Node.js, Deno and Bun.",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/pontlabsai/typescript-eventdispatch.git"
|
|
9
|
+
},
|
|
10
|
+
"homepage": "https://github.com/pontlabsai/typescript-eventdispatch#readme",
|
|
11
|
+
"keywords": [
|
|
12
|
+
"event",
|
|
13
|
+
"dispatch",
|
|
14
|
+
"queue",
|
|
15
|
+
"semaphore",
|
|
16
|
+
"simulation"
|
|
17
|
+
],
|
|
18
|
+
"type": "module",
|
|
19
|
+
"sideEffects": false,
|
|
20
|
+
"exports": {
|
|
21
|
+
".": {
|
|
22
|
+
"types": "./dist/index.d.ts",
|
|
23
|
+
"default": "./dist/index.js"
|
|
24
|
+
}
|
|
25
|
+
},
|
|
26
|
+
"main": "./dist/index.js",
|
|
27
|
+
"types": "./dist/index.d.ts",
|
|
28
|
+
"files": [
|
|
29
|
+
"dist",
|
|
30
|
+
"src"
|
|
31
|
+
],
|
|
32
|
+
"engines": {
|
|
33
|
+
"node": ">=20"
|
|
34
|
+
},
|
|
35
|
+
"scripts": {
|
|
36
|
+
"build": "tsc -p tsconfig.json",
|
|
37
|
+
"check:types": "tsc -p tsconfig.test.json",
|
|
38
|
+
"check:web": "node test/check-web.mjs",
|
|
39
|
+
"test": "npm run build && npm run check:types && npm run check:web && node test/unit.mjs && node test/conformance.mjs",
|
|
40
|
+
"test:browser": "node test/browser.mjs",
|
|
41
|
+
"test:stress": "node test/conformance.mjs --stress 10",
|
|
42
|
+
"prepublishOnly": "npm test"
|
|
43
|
+
},
|
|
44
|
+
"devDependencies": {
|
|
45
|
+
"@types/node": "^22.10.0",
|
|
46
|
+
"playwright": "^1.65.1",
|
|
47
|
+
"typescript": "~5.7.2"
|
|
48
|
+
},
|
|
49
|
+
"publishConfig": {
|
|
50
|
+
"access": "public"
|
|
51
|
+
}
|
|
52
|
+
}
|
package/src/cs.ts
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
import type { Dispatcher } from "./dispatcher.js";
|
|
2
|
+
import { type Env, type Event, Handoff, type Item, Signal } from "./event.js";
|
|
3
|
+
import { CompositeSemaphore } from "./semaphore.js";
|
|
4
|
+
|
|
5
|
+
/** The status a cleared CS wait is released with; its CSWait enqueues nothing (spec cs.md#clear). */
|
|
6
|
+
export const CLEARED_STATUS = -1;
|
|
7
|
+
|
|
8
|
+
/** Normalizes a lefts string: split on ",", deduplicated, sorted (spec cs.md#lefts). */
|
|
9
|
+
export function parseLefts(s: string): { lefts: string[]; identifier: string } {
|
|
10
|
+
const lefts = [...new Set(s.split(","))].sort();
|
|
11
|
+
return { lefts, identifier: lefts.join(",") };
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** @internal A dispatcher's CS registry. */
|
|
15
|
+
export class CsState {
|
|
16
|
+
readonly registry = new Map<string, CompositeSemaphore>(); // left -> semaphore
|
|
17
|
+
readonly ids = new Set<string>(); // identifiers of live CSWaits
|
|
18
|
+
readonly pending = new Map<string, number>(); // dispatched CSWaits not yet waiting
|
|
19
|
+
readonly changed = new Signal(); // a CSWait registered
|
|
20
|
+
|
|
21
|
+
/** Counts one CSWait on identifier as waiting (or as never going to), and wakes the gate. */
|
|
22
|
+
registered(identifier: string): void {
|
|
23
|
+
const n = this.pending.get(identifier) ?? 0;
|
|
24
|
+
if (n <= 1) this.pending.delete(identifier);
|
|
25
|
+
else this.pending.set(identifier, n - 1);
|
|
26
|
+
this.changed.notify();
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Takes this batch's CSWaits out, rejects overlapping ones, and
|
|
31
|
+
* dispatches the rest (spec queue.md#cs-gate). Returns the accepted
|
|
32
|
+
* identifiers and the remaining items.
|
|
33
|
+
*/
|
|
34
|
+
dispatchWaits(d: Dispatcher, batch: Item[]): { expected: string[]; rest: Item[] } {
|
|
35
|
+
const accepted: [Item, string][] = [];
|
|
36
|
+
const rest: Item[] = [];
|
|
37
|
+
const claimed = new Set<string>(); // lefts of CSWaits accepted in this batch
|
|
38
|
+
const batchIds = new Set<string>(); // their identifiers
|
|
39
|
+
for (const it of batch) {
|
|
40
|
+
if (!Array.isArray(it) || it.length === 0 || it[0] !== "CSWait") {
|
|
41
|
+
rest.push(it);
|
|
42
|
+
continue;
|
|
43
|
+
}
|
|
44
|
+
const raw = it[1];
|
|
45
|
+
if (typeof raw !== "string") {
|
|
46
|
+
d.warn(`malformed CSWait ${JSON.stringify(it)}`);
|
|
47
|
+
continue;
|
|
48
|
+
}
|
|
49
|
+
const { lefts, identifier } = parseLefts(raw);
|
|
50
|
+
if (this.ids.has(identifier) || batchIds.has(identifier)) {
|
|
51
|
+
// exactly the same lefts: joins
|
|
52
|
+
} else if (lefts.some((l) => this.registry.has(l) || claimed.has(l))) {
|
|
53
|
+
d.warn(`CSWait ${identifier} overlaps a live CSWait, rejected`);
|
|
54
|
+
continue;
|
|
55
|
+
} else {
|
|
56
|
+
for (const l of lefts) claimed.add(l);
|
|
57
|
+
batchIds.add(identifier);
|
|
58
|
+
}
|
|
59
|
+
accepted.push([it, identifier]);
|
|
60
|
+
}
|
|
61
|
+
for (const [it, identifier] of accepted) {
|
|
62
|
+
this.pending.set(identifier, (this.pending.get(identifier) ?? 0) + 1);
|
|
63
|
+
if (!d.dispatchItem(it)) this.registered(identifier); // never started: never waits
|
|
64
|
+
}
|
|
65
|
+
return { expected: accepted.map(([, id]) => id), rest };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Whether any of these identifiers has a CSWait not yet waiting. */
|
|
69
|
+
outstanding(expected: Iterable<string>): boolean {
|
|
70
|
+
for (const id of expected) if ((this.pending.get(id) ?? 0) > 0) return true;
|
|
71
|
+
return false;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** The gate: dispatch the CSWaits, then wait until every accepted one is waiting. */
|
|
75
|
+
async gate(d: Dispatcher, batch: Item[]): Promise<Item[]> {
|
|
76
|
+
await Handoff.at("gate");
|
|
77
|
+
const { expected, rest } = this.dispatchWaits(d, batch);
|
|
78
|
+
await Handoff.at("gate.wait");
|
|
79
|
+
// judged by pending counts, never by registration, which cleanup empties
|
|
80
|
+
while (this.outstanding(expected)) await this.changed.wait();
|
|
81
|
+
await Handoff.at("gate.open");
|
|
82
|
+
return rest;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Releases waiting CSWaits with CLEARED_STATUS: all, or those on left key's semaphore. */
|
|
86
|
+
clear(key?: string): void {
|
|
87
|
+
const done = new Set<CompositeSemaphore>();
|
|
88
|
+
for (const [left, sem] of this.registry) {
|
|
89
|
+
if ((key !== undefined && left !== key) || done.has(sem)) continue;
|
|
90
|
+
done.add(sem);
|
|
91
|
+
sem.releaseAll(CLEARED_STATUS);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function csOf(env: Env): CsState {
|
|
97
|
+
const s = env.dispatcher.cs;
|
|
98
|
+
if (!s) throw new Error("dispatcher has no CS (cs: true)");
|
|
99
|
+
return s;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Holds a pending item until every one of its lefts has been released
|
|
104
|
+
* (spec cs.md#cswait). Item: `["CSWait", lefts, requester, <pending item...>]`.
|
|
105
|
+
*/
|
|
106
|
+
export class CSWait implements Event {
|
|
107
|
+
private state: CsState | null = null;
|
|
108
|
+
private lefts: string[] = [];
|
|
109
|
+
private identifier = "";
|
|
110
|
+
private sem: CompositeSemaphore | null = null;
|
|
111
|
+
private status: unknown = null;
|
|
112
|
+
private using = false;
|
|
113
|
+
private cleaned = false;
|
|
114
|
+
private signalled = false;
|
|
115
|
+
|
|
116
|
+
async dispatch(env: Env, args: unknown[]): Promise<void> {
|
|
117
|
+
const s = csOf(env);
|
|
118
|
+
this.state = s;
|
|
119
|
+
try {
|
|
120
|
+
if (args.length < 2) throw new Error("CSWait: want lefts, requester, pending item");
|
|
121
|
+
const raw = args[0];
|
|
122
|
+
if (typeof raw !== "string") throw new Error(`CSWait: lefts ${String(raw)} is not a string`);
|
|
123
|
+
const { lefts, identifier } = parseLefts(raw);
|
|
124
|
+
this.lefts = lefts;
|
|
125
|
+
this.identifier = identifier;
|
|
126
|
+
const requester = String(args[1]);
|
|
127
|
+
// join or create, in one step
|
|
128
|
+
let sem = s.ids.has(identifier) ? s.registry.get(lefts[0]) : undefined;
|
|
129
|
+
if (!sem) {
|
|
130
|
+
sem = new CompositeSemaphore(lefts);
|
|
131
|
+
s.ids.add(identifier);
|
|
132
|
+
for (const l of lefts) s.registry.set(l, sem);
|
|
133
|
+
}
|
|
134
|
+
sem.users++; // created or joined: hold a share until cleanup
|
|
135
|
+
this.using = true;
|
|
136
|
+
this.sem = sem;
|
|
137
|
+
try {
|
|
138
|
+
this.status = await sem.acquire(requester, () => this.signal());
|
|
139
|
+
} catch (e) {
|
|
140
|
+
await this.cleanup();
|
|
141
|
+
throw e;
|
|
142
|
+
}
|
|
143
|
+
} finally {
|
|
144
|
+
this.signal(); // however dispatch ends, the gate must not wait for it
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
private signal(): void {
|
|
149
|
+
if (this.signalled) return;
|
|
150
|
+
this.signalled = true;
|
|
151
|
+
this.state?.registered(this.identifier);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** Gives back this CSWait's share (once); the last user removes the registration. */
|
|
155
|
+
private async cleanup(): Promise<void> {
|
|
156
|
+
if (this.cleaned || !this.using) return;
|
|
157
|
+
this.cleaned = true;
|
|
158
|
+
await Handoff.at("cswait.cleanup");
|
|
159
|
+
const s = this.state;
|
|
160
|
+
const sem = this.sem;
|
|
161
|
+
if (!s || !sem) return;
|
|
162
|
+
sem.users--;
|
|
163
|
+
if (sem.users > 0) return; // a later CSWait still uses it
|
|
164
|
+
const owned = s.registry.get(this.lefts[0]) === sem;
|
|
165
|
+
for (const l of this.lefts) if (s.registry.get(l) === sem) s.registry.delete(l);
|
|
166
|
+
if (owned) s.ids.delete(this.identifier);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
async finish(env: Env, args: unknown[]): Promise<void> {
|
|
170
|
+
await this.cleanup();
|
|
171
|
+
if (this.status === CLEARED_STATUS) return;
|
|
172
|
+
env.enqueue(args.slice(2));
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** Releases lefts (spec cs.md#csrelease). Item: `["CSRelease", lefts, <unused>, status]`. */
|
|
177
|
+
export class CSRelease implements Event {
|
|
178
|
+
async dispatch(env: Env, args: unknown[]): Promise<void> {
|
|
179
|
+
const s = csOf(env);
|
|
180
|
+
if (args.length !== 3) throw new Error(`CSRelease: want 3 arguments, got ${args.length}`);
|
|
181
|
+
const raw = args[0];
|
|
182
|
+
if (typeof raw !== "string") throw new Error(`CSRelease: lefts ${String(raw)} is not a string`);
|
|
183
|
+
const status = args[2];
|
|
184
|
+
if (typeof status !== "number" || !Number.isInteger(status)) {
|
|
185
|
+
throw new Error(`CSRelease: status ${String(status)} is not an integer`);
|
|
186
|
+
}
|
|
187
|
+
await Handoff.at("semaphore.release");
|
|
188
|
+
for (const l of parseLefts(raw).lefts) s.registry.get(l)?.releaseNow(l, status);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
finish(): void {}
|
|
192
|
+
}
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
import { CSRelease, CSWait, CsState } from "./cs.js";
|
|
2
|
+
import type { CompositeSemaphore } from "./semaphore.js";
|
|
3
|
+
import {
|
|
4
|
+
Blackboard,
|
|
5
|
+
Deserializers,
|
|
6
|
+
Env,
|
|
7
|
+
Handoff,
|
|
8
|
+
type Deserializer,
|
|
9
|
+
type Event,
|
|
10
|
+
type Item,
|
|
11
|
+
type Logger,
|
|
12
|
+
Loggers,
|
|
13
|
+
Registry,
|
|
14
|
+
} from "./event.js";
|
|
15
|
+
|
|
16
|
+
/** Event ids are taken modulo this (spec queue.md#event-ids). */
|
|
17
|
+
export const MAX_EVENT_ID = 30000;
|
|
18
|
+
|
|
19
|
+
export interface DispatcherOptions {
|
|
20
|
+
blackboard?: Blackboard;
|
|
21
|
+
registry?: Registry;
|
|
22
|
+
/** Enable the composite semaphore: registers CSWait and CSRelease, and runs the CS gate. */
|
|
23
|
+
cs?: boolean;
|
|
24
|
+
logger?: Logger;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* A queue dispatch (spec queue.md): drains its queue and dispatches
|
|
29
|
+
* every item, each event in its own task. Everything runs on one
|
|
30
|
+
* thread; an event that awaits never blocks another, but one that
|
|
31
|
+
* computes without awaiting does, as any JavaScript would.
|
|
32
|
+
*/
|
|
33
|
+
export class Dispatcher {
|
|
34
|
+
readonly name: string;
|
|
35
|
+
readonly blackboard: Blackboard;
|
|
36
|
+
readonly registry: Registry;
|
|
37
|
+
/** The dispatch switch (spec core.md#dispatch-switch): while off, items are dropped. */
|
|
38
|
+
switch = true;
|
|
39
|
+
|
|
40
|
+
protected readonly logger: Logger;
|
|
41
|
+
protected queue: Item[] = [];
|
|
42
|
+
protected running = false;
|
|
43
|
+
protected live = 0;
|
|
44
|
+
protected nextId = 0;
|
|
45
|
+
private wakeup: (() => void) | null = null;
|
|
46
|
+
private loop: Promise<void> | null = null;
|
|
47
|
+
/** @internal */
|
|
48
|
+
readonly cs: CsState | null;
|
|
49
|
+
|
|
50
|
+
constructor(name: string, options: DispatcherOptions = {}) {
|
|
51
|
+
this.name = name;
|
|
52
|
+
this.blackboard = options.blackboard ?? new Blackboard();
|
|
53
|
+
this.registry = options.registry ?? new Registry();
|
|
54
|
+
this.logger = options.logger ?? Loggers.console;
|
|
55
|
+
this.cs = options.cs ? new CsState() : null;
|
|
56
|
+
if (this.cs) {
|
|
57
|
+
this.registry.register("CSWait", () => new CSWait(), Deserializers.anyArguments);
|
|
58
|
+
this.registry.register("CSRelease", () => new CSRelease(), Deserializers.anyArguments);
|
|
59
|
+
}
|
|
60
|
+
this.blackboard.set(`${name}_dispatch`, this);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Items queued and not yet taken by a drain. */
|
|
64
|
+
get queueLength(): number {
|
|
65
|
+
return this.queue.length;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Events dispatched whose finish has not returned. */
|
|
69
|
+
get liveEvents(): number {
|
|
70
|
+
return this.live;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
register(name: string, factory: () => Event, deserialize?: Deserializer): void {
|
|
74
|
+
this.registry.register(name, factory, deserialize);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Appends items to the queue in one batch, and wakes the dispatch. */
|
|
78
|
+
enqueue(...items: Item[]): void {
|
|
79
|
+
if (items.length === 0) return;
|
|
80
|
+
this.queue.push(...items);
|
|
81
|
+
this.wake();
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
enqueueAll(items: Item[]): void {
|
|
85
|
+
this.enqueue(...items);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Starts the drain loop (once). */
|
|
89
|
+
start(): void {
|
|
90
|
+
if (this.loop) return;
|
|
91
|
+
this.running = true;
|
|
92
|
+
this.loop = this.run().catch((e) => this.logger("error", `${this.name}: drain loop failed`, e));
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Stops after the current drain. Events already dispatched are not interrupted. */
|
|
96
|
+
stop(): void {
|
|
97
|
+
this.running = false;
|
|
98
|
+
this.wake();
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Resolves once the drain loop has ended. */
|
|
102
|
+
async join(): Promise<void> {
|
|
103
|
+
await this.loop;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
protected wake(): void {
|
|
107
|
+
const w = this.wakeup;
|
|
108
|
+
this.wakeup = null;
|
|
109
|
+
w?.();
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Resolves on the next enqueue or stop. */
|
|
113
|
+
protected idle(): Promise<void> {
|
|
114
|
+
return new Promise((r) => (this.wakeup = r));
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// -- the drain loop ------------------------------------------------
|
|
118
|
+
|
|
119
|
+
protected async run(): Promise<void> {
|
|
120
|
+
while (this.running) {
|
|
121
|
+
if (this.queue.length === 0) {
|
|
122
|
+
await this.idle();
|
|
123
|
+
continue;
|
|
124
|
+
}
|
|
125
|
+
const batch = this.queue;
|
|
126
|
+
this.queue = [];
|
|
127
|
+
const rest = this.cs ? await this.cs.gate(this, batch) : batch;
|
|
128
|
+
for (const it of rest) this.dispatchItem(it);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Looks up, deserializes, constructs and dispatches one item; false
|
|
134
|
+
* (logged) if it fails (spec queue.md#failed-items).
|
|
135
|
+
* @internal
|
|
136
|
+
*/
|
|
137
|
+
dispatchItem(it: Item): boolean {
|
|
138
|
+
try {
|
|
139
|
+
const { event, env, args } = this.prepare(it);
|
|
140
|
+
this.startEvent(event, env, args);
|
|
141
|
+
return true;
|
|
142
|
+
} catch (e) {
|
|
143
|
+
this.logger("warn", `${this.name}: item failed: ${JSON.stringify(it)}`, e);
|
|
144
|
+
return false;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** Deserializes and constructs an item's event, and reserves its id; throws if it fails. */
|
|
149
|
+
protected prepare(it: Item): { event: Event; env: Env; args: unknown[] } {
|
|
150
|
+
if (!Array.isArray(it) || it.length === 0) throw new Error("empty item");
|
|
151
|
+
const name = it[0];
|
|
152
|
+
if (typeof name !== "string") throw new Error(`item name ${String(name)} is not a string`);
|
|
153
|
+
const { event, args } = this.registry.create(name, it.slice(1));
|
|
154
|
+
const id = this.nextId;
|
|
155
|
+
this.nextId = (this.nextId + 1) % MAX_EVENT_ID;
|
|
156
|
+
if (!this.switch) throw new Error("dispatch switch is off");
|
|
157
|
+
return { event, env: new Env(id, name, this.blackboard, this), args };
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** Runs an event in its own task. */
|
|
161
|
+
protected startEvent(event: Event, env: Env, args: unknown[]): void {
|
|
162
|
+
this.live++;
|
|
163
|
+
void this.runEvent(event, env, args);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** Dispatch, then finish unless dispatch failed; the event is released either way. */
|
|
167
|
+
protected async runEvent(event: Event, env: Env, args: unknown[]): Promise<void> {
|
|
168
|
+
try {
|
|
169
|
+
await Handoff.at("dispatch"); // its own task: never inside the drain
|
|
170
|
+
const dispatched = await this.guard("dispatch", env, () => event.dispatch(env, args));
|
|
171
|
+
await Handoff.at("finish");
|
|
172
|
+
if (dispatched) await this.guard("finish", env, () => event.finish(env, args));
|
|
173
|
+
} finally {
|
|
174
|
+
this.live--;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** Runs `f`; logs and returns false if it throws or rejects. */
|
|
179
|
+
protected async guard(stage: string, env: Env, f: () => unknown): Promise<boolean> {
|
|
180
|
+
try {
|
|
181
|
+
await f();
|
|
182
|
+
return true;
|
|
183
|
+
} catch (e) {
|
|
184
|
+
this.logger("error", `${this.name}: ${env.name}@${env.id} ${stage} failed`, e);
|
|
185
|
+
return false;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** Releases waiting CSWaits without their pending items (spec cs.md#clear): all, or those on left `key`. */
|
|
190
|
+
clearCSWaits(key?: string): void {
|
|
191
|
+
this.cs?.clear(key);
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** The composite semaphore registered for `left`, if any. */
|
|
195
|
+
semaphore(left: string): CompositeSemaphore | undefined {
|
|
196
|
+
return this.cs?.registry.get(left);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** @internal */
|
|
200
|
+
warn(message: string): void {
|
|
201
|
+
this.logger("warn", `${this.name}: ${message}`);
|
|
202
|
+
}
|
|
203
|
+
}
|