@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/src/sim.ts ADDED
@@ -0,0 +1,217 @@
1
+ import { type DispatcherOptions, Dispatcher } from "./dispatcher.js";
2
+ import { type Env, type Event, Handoff, type Item } from "./event.js";
3
+
4
+ /** A scheduled completion. */
5
+ export interface Scheduled {
6
+ readonly event: Event;
7
+ readonly env: Env;
8
+ readonly args: unknown[];
9
+ readonly startedAt: number;
10
+ readonly duration: number;
11
+ readonly completeAt: number;
12
+ /** @internal */ readonly seq: number;
13
+ }
14
+
15
+ export interface SimDispatcherOptions extends Omit<DispatcherOptions, "cs"> {
16
+ /**
17
+ * Steps an engine's world from one clock time to the next, before
18
+ * each completion fires (spec sim.md#world-stepping). Passing it is
19
+ * what makes an engine attached.
20
+ */
21
+ stepWorld?: (from: number, to: number) => void | Promise<void>;
22
+ }
23
+
24
+ /** Completions fired between yields to the host's task queue, so a long run never freezes a page. */
25
+ const YIELD_EVERY = 256;
26
+
27
+ function isCS(it: Item): boolean {
28
+ return Array.isArray(it) && (it[0] === "CSWait" || it[0] === "CSRelease");
29
+ }
30
+
31
+ /**
32
+ * A sim dispatch (spec sim.md): a CS queue dispatch whose events quote
33
+ * durations. Its clock, `now`, starts at 0 and moves only when an
34
+ * event completes. One driver fires completions in order of completion
35
+ * time, ties in quote order, so a run is deterministic.
36
+ *
37
+ * An event's `dispatch` returns its quote synchronously (a number
38
+ * >= 0) and does nothing else; its `finish` is the completion step.
39
+ * CSWait and CSRelease stay outside the clock, in their own tasks.
40
+ */
41
+ export class SimDispatcher extends Dispatcher {
42
+ /** The simulated clock. */
43
+ now = 0;
44
+ /** Whether an engine is attached (a stepWorld was given). */
45
+ readonly engineAttached: boolean;
46
+
47
+ private readonly stepWorldFn: SimDispatcherOptions["stepWorld"];
48
+ private readonly heap: { at: number; seq: number; id: number }[] = [];
49
+ private readonly scheduledMap = new Map<number, Scheduled>();
50
+ private seq = 0;
51
+ private readonly outstanding = new Set<string>(); // accepted CSWaits not yet waiting
52
+ private fired = 0;
53
+
54
+ constructor(name: string, options: SimDispatcherOptions = {}) {
55
+ super(name, { ...options, cs: true });
56
+ this.stepWorldFn = options.stepWorld;
57
+ this.engineAttached = options.stepWorld !== undefined;
58
+ }
59
+
60
+ /** Completions scheduled and not yet fired or cancelled. */
61
+ get scheduledEvents(): number {
62
+ return this.scheduledMap.size;
63
+ }
64
+
65
+ /** Clock time until the next scheduled completion, or null. */
66
+ timeToNext(): number | null {
67
+ const at = this.nextAt();
68
+ return at === null ? null : at - this.now;
69
+ }
70
+
71
+ /** @internal The earliest live completion time, or null. */
72
+ nextAt(): number | null {
73
+ let best: number | null = null;
74
+ for (const s of this.scheduledMap.values()) if (best === null || s.completeAt < best) best = s.completeAt;
75
+ return best;
76
+ }
77
+
78
+ /**
79
+ * Removes a scheduled completion: the event never finishes (spec
80
+ * sim.md#cancel). An id that is not scheduled does nothing. Returns
81
+ * whether it cancelled.
82
+ */
83
+ cancel(eventId: number): boolean {
84
+ const s = this.scheduledMap.get(eventId);
85
+ if (!s) return false;
86
+ this.scheduledMap.delete(eventId);
87
+ this.cancelled(s);
88
+ return true;
89
+ }
90
+
91
+ /** Called when a scheduled event is cancelled. */
92
+ protected cancelled(_s: Scheduled): void {}
93
+
94
+ // -- the driver ------------------------------------------------------
95
+
96
+ protected override async run(): Promise<void> {
97
+ while (this.running) {
98
+ if (this.queue.length === 0 && this.scheduledMap.size === 0) {
99
+ await this.idle();
100
+ continue;
101
+ }
102
+ const open = await this.drainCycle();
103
+ if (this.scheduledMap.size > 0) await this.advanceOne();
104
+ else if (!open) await Promise.race([this.cs!.changed.wait(), this.idle()]); // a registration, enqueue or stop
105
+ }
106
+ }
107
+
108
+ /**
109
+ * One drain: the CS gate as a verdict (spec sim.md#cs). While an
110
+ * accepted CSWait is not yet waiting, the rest of the queue stays
111
+ * queued and the driver keeps firing completions.
112
+ */
113
+ private async drainCycle(): Promise<boolean> {
114
+ await Handoff.at("gate");
115
+ const cs = this.cs!;
116
+ const { expected, rest } = cs.dispatchWaits(this, this.queue);
117
+ this.queue = rest;
118
+ for (const id of expected) this.outstanding.add(id);
119
+ for (const id of [...this.outstanding]) if (!cs.outstanding([id])) this.outstanding.delete(id);
120
+ if (this.outstanding.size > 0) return false;
121
+ const batch = this.queue;
122
+ this.queue = [];
123
+ // releases complete by condition, not duration: never quoted
124
+ for (const it of batch) if (isCS(it)) super.dispatchItem(it);
125
+ for (const it of batch) if (!isCS(it)) this.dispatchItem(it);
126
+ return true;
127
+ }
128
+
129
+ /** Quotes an item and schedules its completion; false (logged) if it fails. @internal */
130
+ override dispatchItem(it: Item): boolean {
131
+ if (isCS(it)) return super.dispatchItem(it);
132
+ try {
133
+ const { event, env, args } = this.prepare(it);
134
+ const quote = event.dispatch(env, args);
135
+ if (typeof quote !== "number" || !Number.isFinite(quote) || quote < 0) {
136
+ const got = quote instanceof Promise ? "a promise" : String(quote);
137
+ throw new Error(`sim dispatch must return a duration >= 0 synchronously, got ${got}`);
138
+ }
139
+ const s: Scheduled = {
140
+ event, env, args, startedAt: this.now, duration: quote, completeAt: this.now + quote, seq: this.seq++,
141
+ };
142
+ this.scheduledMap.set(env.id, s);
143
+ this.push({ at: s.completeAt, seq: s.seq, id: env.id });
144
+ return true;
145
+ } catch (e) {
146
+ this.logger("warn", `${this.name}: item failed: ${JSON.stringify(it)}`, e);
147
+ return false;
148
+ }
149
+ }
150
+
151
+ /** Fires the soonest scheduled completion; returns its event id, or null. */
152
+ private async advanceOne(): Promise<number | null> {
153
+ for (;;) {
154
+ const top = this.pop();
155
+ if (!top) return null;
156
+ const s = this.scheduledMap.get(top.id);
157
+ if (!s || s.seq !== top.seq) continue; // cancelled
158
+ // taking it is one step: a cancel from now on is a no-op
159
+ this.scheduledMap.delete(top.id);
160
+ if (this.stepWorldFn) await this.stepWorldFn(this.now, s.completeAt);
161
+ this.now = s.completeAt;
162
+ this.live++;
163
+ try {
164
+ await Handoff.at("finish");
165
+ await this.complete(s);
166
+ } finally {
167
+ this.live--;
168
+ }
169
+ if (++this.fired % YIELD_EVERY === 0) await new Promise((r) => setTimeout(r, 0));
170
+ return top.id;
171
+ }
172
+ }
173
+
174
+ /** The completion step: finish. */
175
+ protected async complete(s: Scheduled): Promise<void> {
176
+ await this.guard("finish", s.env, () => s.event.finish(s.env, s.args));
177
+ }
178
+
179
+ // -- the heap ----------------------------------------------------------
180
+
181
+ private less(a: { at: number; seq: number }, b: { at: number; seq: number }): boolean {
182
+ return a.at < b.at || (a.at === b.at && a.seq < b.seq);
183
+ }
184
+
185
+ private push(e: { at: number; seq: number; id: number }): void {
186
+ const h = this.heap;
187
+ h.push(e);
188
+ let i = h.length - 1;
189
+ while (i > 0) {
190
+ const p = (i - 1) >> 1;
191
+ if (!this.less(h[i], h[p])) break;
192
+ [h[i], h[p]] = [h[p], h[i]];
193
+ i = p;
194
+ }
195
+ }
196
+
197
+ private pop(): { at: number; seq: number; id: number } | undefined {
198
+ const h = this.heap;
199
+ if (h.length === 0) return undefined;
200
+ const top = h[0];
201
+ const last = h.pop()!;
202
+ if (h.length > 0) {
203
+ h[0] = last;
204
+ let i = 0;
205
+ for (;;) {
206
+ const l = 2 * i + 1, r = l + 1;
207
+ let m = i;
208
+ if (l < h.length && this.less(h[l], h[m])) m = l;
209
+ if (r < h.length && this.less(h[r], h[m])) m = r;
210
+ if (m === i) break;
211
+ [h[i], h[m]] = [h[m], h[i]];
212
+ i = m;
213
+ }
214
+ }
215
+ return top;
216
+ }
217
+ }