@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/event.ts ADDED
@@ -0,0 +1,172 @@
1
+ /**
2
+ * Core types: items, events, the registry, the blackboard, logging and
3
+ * the hand-off hook. Web-standard JavaScript only: no Node, Deno or Bun
4
+ * APIs, so the library runs in browsers and every server runtime.
5
+ */
6
+
7
+ import type { Dispatcher } from "./dispatcher.js";
8
+
9
+ /** The spec version this library implements (major.minor). */
10
+ export const SPEC_VERSION = "0.3";
11
+
12
+ /** A queue item: `[name, arg1, ...]`, as decoded from JSON. */
13
+ export type Item = unknown[];
14
+
15
+ /** Builds an item. */
16
+ export function item(name: string, ...args: unknown[]): Item {
17
+ return [name, ...args];
18
+ }
19
+
20
+ /** What an event sees: its id, its registry name, the blackboard and its dispatcher. */
21
+ export class Env {
22
+ /** @internal */
23
+ constructor(
24
+ readonly id: number,
25
+ readonly name: string,
26
+ readonly blackboard: Blackboard,
27
+ readonly dispatcher: Dispatcher,
28
+ ) {}
29
+
30
+ /** Appends items to the dispatcher's queue in one batch. */
31
+ enqueue(...items: Item[]): void {
32
+ this.dispatcher.enqueue(...items);
33
+ }
34
+ }
35
+
36
+ /**
37
+ * An event (spec core.md#lifecycle). `dispatch` does the work in its
38
+ * own task; `finish` runs when it returns, and is the only place that
39
+ * decides what is dispatched next.
40
+ *
41
+ * An error thrown (or a rejected promise) in `dispatch` releases the
42
+ * event without `finish`; one in `finish` is logged and the dispatcher
43
+ * carries on.
44
+ */
45
+ export interface Event {
46
+ dispatch(env: Env, args: unknown[]): unknown;
47
+ finish(env: Env, args: unknown[]): void | Promise<void>;
48
+ }
49
+
50
+ /** Turns an item's arguments into dispatch arguments, or throws to reject the item. */
51
+ export type Deserializer = (args: unknown[]) => unknown[];
52
+
53
+ export const Deserializers = {
54
+ /** The default (spec queue.md#deserialize): arguments unchanged; rejects an item with none. */
55
+ default: ((args) => {
56
+ if (args.length === 0) throw new Error("item has no arguments");
57
+ return args;
58
+ }) as Deserializer,
59
+ /** Accepts any arguments, including none (recording events use this). */
60
+ anyArguments: ((args) => args) as Deserializer,
61
+ };
62
+
63
+ /** Maps names to event factories. */
64
+ export class Registry {
65
+ private readonly map = new Map<string, { factory: () => Event; deserialize: Deserializer }>();
66
+
67
+ register(name: string, factory: () => Event, deserialize: Deserializer = Deserializers.default): void {
68
+ this.map.set(name, { factory, deserialize });
69
+ }
70
+
71
+ has(name: string): boolean {
72
+ return this.map.has(name);
73
+ }
74
+
75
+ /** @internal Deserializes (rejecting before constructing), then constructs. */
76
+ create(name: string, args: unknown[]): { event: Event; args: unknown[] } {
77
+ const reg = this.map.get(name);
78
+ if (!reg) throw new Error(`no event registered as "${name}"`);
79
+ const dispatchArgs = reg.deserialize(args);
80
+ return { event: reg.factory(), args: dispatchArgs };
81
+ }
82
+ }
83
+
84
+ /** The key/value store shared by events and dispatchers (spec core.md#blackboard). */
85
+ export class Blackboard {
86
+ private readonly map = new Map<string, unknown>();
87
+
88
+ get<T = unknown>(key: string): T | undefined {
89
+ return this.map.get(key) as T | undefined;
90
+ }
91
+
92
+ set(key: string, value: unknown): void {
93
+ this.map.set(key, value);
94
+ }
95
+
96
+ has(key: string): boolean {
97
+ return this.map.has(key);
98
+ }
99
+
100
+ delete(key: string): boolean {
101
+ return this.map.delete(key);
102
+ }
103
+
104
+ /** Replaces a value with `f(old)`, and returns it. */
105
+ update<T>(key: string, f: (old: T | undefined) => T): T {
106
+ const v = f(this.map.get(key) as T | undefined);
107
+ this.map.set(key, v);
108
+ return v;
109
+ }
110
+ }
111
+
112
+ export type Level = "debug" | "warn" | "error";
113
+
114
+ /** Where a dispatcher reports failures. */
115
+ export type Logger = (level: Level, message: string, error?: unknown) => void;
116
+
117
+ export const Loggers = {
118
+ /** Warnings and errors to the console. */
119
+ console: ((level, message, error) => {
120
+ if (level === "debug") return;
121
+ const text = `eventdispatch ${level}: ${message}` + (error === undefined ? "" : `: ${String(error)}`);
122
+ if (level === "error") console.error(text);
123
+ else console.warn(text);
124
+ }) as Logger,
125
+ /** Logs nothing. */
126
+ discard: (() => {}) as Logger,
127
+ };
128
+
129
+ /**
130
+ * The seam stress tests use: `hook` is awaited wherever work moves
131
+ * between tasks (spec conformance/README.md#stress-mode). Random delays
132
+ * there must never change an outcome. Null in production.
133
+ */
134
+ export const Handoff = {
135
+ hook: null as null | ((site: string) => void | Promise<void>),
136
+ /** @internal */
137
+ async at(site: string): Promise<void> {
138
+ const h = Handoff.hook;
139
+ if (h) await h(site);
140
+ },
141
+ };
142
+
143
+ /** @internal A promise with its resolver. */
144
+ export class Deferred<T> {
145
+ readonly promise: Promise<T>;
146
+ resolve!: (v: T) => void;
147
+ settled = false;
148
+ value: T | undefined;
149
+ constructor() {
150
+ this.promise = new Promise<T>((r) => {
151
+ this.resolve = (v: T) => {
152
+ if (this.settled) return;
153
+ this.settled = true;
154
+ this.value = v;
155
+ r(v);
156
+ };
157
+ });
158
+ }
159
+ }
160
+
161
+ /** @internal Wakes whoever is waiting; a wait made after a notify waits for the next one. */
162
+ export class Signal {
163
+ private d = new Deferred<void>();
164
+ wait(): Promise<void> {
165
+ return this.d.promise;
166
+ }
167
+ notify(): void {
168
+ const d = this.d;
169
+ this.d = new Deferred<void>();
170
+ d.resolve();
171
+ }
172
+ }
package/src/index.ts ADDED
@@ -0,0 +1,19 @@
1
+ /**
2
+ * eventdispatch: work runs as Events, each constructed from a
3
+ * serialized queue item, dispatched in its own task, and finished —
4
+ * and only an event's finish decides what is dispatched next.
5
+ *
6
+ * eventdispatch spec v0.3: base, sim, recording.
7
+ */
8
+ export {
9
+ Blackboard, Deserializers, Env, Handoff, item, Loggers, Registry, SPEC_VERSION,
10
+ type Deserializer, type Event, type Item, type Level, type Logger,
11
+ } from "./event.js";
12
+ export { Dispatcher, MAX_EVENT_ID, type DispatcherOptions } from "./dispatcher.js";
13
+ export { CompositeSemaphore, RightWaitingError, ROLLOVER } from "./semaphore.js";
14
+ export { CLEARED_STATUS, CSRelease, CSWait, parseLefts } from "./cs.js";
15
+ export { SimDispatcher, type Scheduled, type SimDispatcherOptions } from "./sim.js";
16
+ export {
17
+ PREEMPTED, RECORDINGS_KEY, RecordingEvent, RecordingLog, SimRecordingDispatcher, WallRecordingDispatcher,
18
+ type Record,
19
+ } from "./recording.js";
@@ -0,0 +1,282 @@
1
+ import { type DispatcherOptions, Dispatcher } from "./dispatcher.js";
2
+ import { Deferred, Deserializers, type Env, type Event, Handoff } from "./event.js";
3
+ import { type Scheduled, SimDispatcher, type SimDispatcherOptions } from "./sim.js";
4
+
5
+ /** The blackboard key of the recordings field (spec recording.md#blackboard-keys). */
6
+ export const RECORDINGS_KEY = "recordings";
7
+ /** The outcome of a preempted event's record. */
8
+ export const PREEMPTED = "PREEMPTED";
9
+
10
+ /** A record (spec schemas/record.schema.json). */
11
+ export interface Record {
12
+ event_id: number;
13
+ event: string;
14
+ args: unknown[];
15
+ started_at: number;
16
+ t: number;
17
+ wake: boolean;
18
+ outcome: unknown;
19
+ duration?: number;
20
+ actual_duration?: number;
21
+ elapsed?: number;
22
+ progress?: number;
23
+ notes?: { [key: string]: unknown };
24
+ partial_outcome?: unknown;
25
+ }
26
+
27
+ /**
28
+ * The recordings field: a buffer with exactly one consumer (spec
29
+ * recording.md#the-recordings-field).
30
+ */
31
+ export class RecordingLog {
32
+ private records: Record[] = [];
33
+ private arrived = new Deferred<void>();
34
+
35
+ /** @internal */
36
+ append(r: Record): void {
37
+ this.records.push(r);
38
+ const a = this.arrived;
39
+ this.arrived = new Deferred<void>();
40
+ a.resolve();
41
+ }
42
+
43
+ /** Resolves once at least one record is buffered, with everything buffered, in order; removes them. */
44
+ async take(): Promise<Record[]> {
45
+ while (this.records.length === 0) await this.arrived.promise;
46
+ const out = this.records;
47
+ this.records = [];
48
+ return out;
49
+ }
50
+
51
+ /** Records buffered now (not yet taken). */
52
+ get pending(): number {
53
+ return this.records.length;
54
+ }
55
+
56
+ /** A copy of everything buffered; does not consume. For tests and diagnostics. */
57
+ snapshot(): Record[] {
58
+ return [...this.records];
59
+ }
60
+ }
61
+
62
+ /**
63
+ * An event that opts in to recording (spec recording.md#recording-protocol).
64
+ * Subclasses implement `runOutcome`, and `dispatch` (the quote) to run
65
+ * on the sim clock; never `finish`. Register them with
66
+ * `RecordingEvent.deserialize`, which accepts zero arguments.
67
+ */
68
+ export abstract class RecordingEvent implements Event {
69
+ /** The recording deserialize: any arguments, including none. */
70
+ static readonly deserialize = Deserializers.anyArguments;
71
+
72
+ /** Whether this record requests the consumer's attention; the event's own decision. */
73
+ wake = true;
74
+ /** Set by runOutcome when the outcome took less than the quote. */
75
+ actualDuration: number | undefined = undefined;
76
+
77
+ private readonly preempt = new AbortController();
78
+
79
+ /** Scheduling only: keep the arguments, return a quote. Required on the sim clock; ignored on the wall clock. */
80
+ dispatch(_env: Env, _args: unknown[]): number | undefined {
81
+ return undefined;
82
+ }
83
+
84
+ /** The work: produce and apply the outcome, and return it. */
85
+ abstract runOutcome(env: Env, args: unknown[]): unknown;
86
+
87
+ /** Called when the event is preempted; may set wake and return notes. Must not change world state. */
88
+ onPreempt(_env: Env): { [key: string]: unknown } | undefined | void {
89
+ return undefined;
90
+ }
91
+
92
+ /** On a dispatch that does not record: runs the outcome, records nothing. */
93
+ async finish(env: Env, args: unknown[]): Promise<void> {
94
+ await this.runOutcome(env, args);
95
+ }
96
+
97
+ // -- wall-clock cooperation ----------------------------------------
98
+
99
+ /** Aborted once the dispatch asks this event to stop. */
100
+ get preemptSignal(): AbortSignal {
101
+ return this.preempt.signal;
102
+ }
103
+
104
+ preemptRequested(): boolean {
105
+ return this.preempt.signal.aborted;
106
+ }
107
+
108
+ /** Resolves once a preempt is requested. */
109
+ waitPreempt(): Promise<void> {
110
+ const s = this.preempt.signal;
111
+ if (s.aborted) return Promise.resolve();
112
+ return new Promise((r) => s.addEventListener("abort", () => r(), { once: true }));
113
+ }
114
+
115
+ /** @internal */
116
+ requestPreempt(): void {
117
+ this.preempt.abort();
118
+ }
119
+ }
120
+
121
+ /** Builds a record. */
122
+ function record(
123
+ env: Env, ev: RecordingEvent, args: unknown[], startedAt: number, t: number,
124
+ outcome: unknown, fields: Partial<Record>,
125
+ ): Record {
126
+ const r: Record = {
127
+ event_id: env.id, event: env.name, args: [...args], started_at: startedAt, t, wake: Boolean(ev.wake), outcome,
128
+ };
129
+ if (ev.actualDuration !== undefined) r.actual_duration = ev.actualDuration;
130
+ return Object.assign(r, fields);
131
+ }
132
+
133
+ /** on_preempt's notes, then the elapsed (and progress) fields. */
134
+ function preemptFields(env: Env, ev: RecordingEvent, elapsed: number, duration?: number): Partial<Record> {
135
+ const f: Partial<Record> = {};
136
+ const notes = ev.onPreempt(env);
137
+ if (notes && typeof notes === "object" && Object.keys(notes).length > 0) f.notes = notes;
138
+ f.elapsed = elapsed;
139
+ if (duration !== undefined && duration > 0) f.progress = elapsed / duration;
140
+ return f;
141
+ }
142
+
143
+ function registerLog(d: Dispatcher): RecordingLog {
144
+ let log = d.blackboard.get<RecordingLog>(RECORDINGS_KEY);
145
+ if (!(log instanceof RecordingLog)) {
146
+ log = new RecordingLog();
147
+ d.blackboard.set(RECORDINGS_KEY, log);
148
+ }
149
+ return log;
150
+ }
151
+
152
+ /**
153
+ * Recording on the sim clock (spec recording.md). A recording event's
154
+ * runOutcome runs at completion time; its record carries the quote.
155
+ */
156
+ export class SimRecordingDispatcher extends SimDispatcher {
157
+ readonly recordings: RecordingLog;
158
+
159
+ constructor(name: string, options: SimDispatcherOptions = {}) {
160
+ super(name, options);
161
+ this.recordings = registerLog(this);
162
+ }
163
+
164
+ protected override async complete(s: Scheduled): Promise<void> {
165
+ const ev = s.event;
166
+ if (!(ev instanceof RecordingEvent)) return super.complete(s);
167
+ let outcome: unknown;
168
+ try {
169
+ outcome = await ev.runOutcome(s.env, s.args);
170
+ } catch (e) {
171
+ this.logger("error", `${this.name}: ${s.env.name}@${s.env.id} run_outcome failed`, e);
172
+ return; // no record; the event is released
173
+ }
174
+ this.recordings.append(record(s.env, ev, s.args, s.startedAt, this.now, outcome, { duration: s.duration }));
175
+ this.settle(s, ev);
176
+ }
177
+
178
+ /** Settles the clock back to started_at + actual_duration (spec recording.md#settling). */
179
+ private settle(s: Scheduled, ev: RecordingEvent): void {
180
+ if (ev.actualDuration === undefined) return;
181
+ const settled = s.startedAt + ev.actualDuration;
182
+ if (settled >= this.now) return; // at or beyond the quote: recorded, never settled
183
+ if (this.engineAttached) {
184
+ this.logger("error", `${this.name}: cannot settle the clock for ${s.env.name}@${s.env.id} back from `
185
+ + `${this.now} to ${settled}: an engine is attached, and has already stepped to the quote`,
186
+ new Error("settle with an engine attached"));
187
+ return;
188
+ }
189
+ const next = this.nextAt();
190
+ if (next !== null && next < settled) return;
191
+ this.now = settled;
192
+ }
193
+
194
+ /** A cancelled recording event's PREEMPTED record is written now. */
195
+ protected override cancelled(s: Scheduled): void {
196
+ const ev = s.event;
197
+ if (!(ev instanceof RecordingEvent)) return;
198
+ const elapsed = this.now - s.startedAt;
199
+ this.recordings.append(record(s.env, ev, s.args, s.startedAt, this.now, PREEMPTED,
200
+ { duration: s.duration, ...preemptFields(s.env, ev, elapsed, s.duration) }));
201
+ }
202
+ }
203
+
204
+ /** A monotonic clock in seconds (web standard `performance.now`). */
205
+ function monotonicSeconds(): number {
206
+ return performance.now() / 1000;
207
+ }
208
+
209
+ /**
210
+ * Recording on the wall clock (spec recording.md#wall-clock): a CS
211
+ * queue dispatch whose `now` is monotonic seconds. A recording event's
212
+ * dispatch runs inline (its quote is ignored), then runOutcome runs in
213
+ * its own task; the record is written when it returns.
214
+ */
215
+ export class WallRecordingDispatcher extends Dispatcher {
216
+ readonly recordings: RecordingLog;
217
+ private readonly active = new Map<number, { ev: RecordingEvent; cancelled: boolean }>();
218
+
219
+ constructor(name: string, options: Omit<DispatcherOptions, "cs"> = {}) {
220
+ super(name, { ...options, cs: true });
221
+ this.recordings = registerLog(this);
222
+ }
223
+
224
+ get now(): number {
225
+ return monotonicSeconds();
226
+ }
227
+
228
+ /**
229
+ * Asks a running recording event to stop; its PREEMPTED record is
230
+ * written when it returns. Returns whether it asked.
231
+ */
232
+ cancel(eventId: number): boolean {
233
+ const r = this.active.get(eventId);
234
+ if (!r) return false;
235
+ r.cancelled = true;
236
+ r.ev.requestPreempt();
237
+ return true;
238
+ }
239
+
240
+ /** Recording events running now. */
241
+ get runningRecordings(): number[] {
242
+ return [...this.active.keys()];
243
+ }
244
+
245
+ protected override startEvent(event: Event, env: Env, args: unknown[]): void {
246
+ if (!(event instanceof RecordingEvent)) return super.startEvent(event, env, args);
247
+ event.dispatch(env, args); // inline: keeps the arguments; the quote is ignored
248
+ const startedAt = this.now;
249
+ const entry = { ev: event, cancelled: false };
250
+ this.active.set(env.id, entry);
251
+ this.live++;
252
+ void this.runRecording(event, env, args, startedAt, entry);
253
+ }
254
+
255
+ private async runRecording(
256
+ ev: RecordingEvent, env: Env, args: unknown[], startedAt: number, entry: { cancelled: boolean },
257
+ ): Promise<void> {
258
+ try {
259
+ await Handoff.at("dispatch");
260
+ let outcome: unknown;
261
+ let failed = false;
262
+ try {
263
+ outcome = await ev.runOutcome(env, args);
264
+ } catch (e) {
265
+ failed = true;
266
+ this.logger("error", `${this.name}: ${env.name}@${env.id} run_outcome failed`, e);
267
+ }
268
+ await Handoff.at("finish");
269
+ this.active.delete(env.id);
270
+ if (failed) return;
271
+ const t = this.now;
272
+ if (entry.cancelled) {
273
+ this.recordings.append(record(env, ev, args, startedAt, t, PREEMPTED,
274
+ { ...preemptFields(env, ev, t - startedAt), partial_outcome: outcome }));
275
+ } else {
276
+ this.recordings.append(record(env, ev, args, startedAt, t, outcome, {}));
277
+ }
278
+ } finally {
279
+ this.live--;
280
+ }
281
+ }
282
+ }
@@ -0,0 +1,128 @@
1
+ import { Deferred, Handoff } from "./event.js";
2
+
3
+ /** The round counter wraps here (spec cs.md#rounds). */
4
+ export const ROLLOVER = 100;
5
+
6
+ /** Thrown by acquire when the right is already waiting. */
7
+ export class RightWaitingError extends Error {
8
+ constructor(id: string) {
9
+ super(`right is already waiting: ${id}`);
10
+ this.name = "RightWaitingError";
11
+ }
12
+ }
13
+
14
+ /**
15
+ * Releases every waiting right once each of its lefts has been
16
+ * released in the current round (spec cs.md#composite-semaphore).
17
+ *
18
+ * The cut point: a right that acquires before a round completes is
19
+ * released by it; one that acquires after waits for the next round.
20
+ * Released rights are forgotten, so an identifier may acquire again.
21
+ */
22
+ export class CompositeSemaphore {
23
+ private readonly counters = new Map<string, number>();
24
+ private tick = 1;
25
+ private keyCount: number;
26
+ private inRound = false;
27
+ private roundDone = new Deferred<void>();
28
+ private rights = new Map<string, Deferred<unknown>>();
29
+ /** @internal CSWaits using this semaphore. */
30
+ users = 0;
31
+
32
+ constructor(lefts: Iterable<string>) {
33
+ for (const l of lefts) this.counters.set(l, 0);
34
+ this.keyCount = this.counters.size;
35
+ }
36
+
37
+ /** Advances k's counter to this round; false if already released this round. */
38
+ private tickLeft(k: string): boolean {
39
+ const v = this.counters.get(k)!;
40
+ if (this.tick > v) {
41
+ this.counters.set(k, v + 1);
42
+ return true;
43
+ }
44
+ if (this.tick < v) {
45
+ this.counters.set(k, 0); // the round counter wrapped
46
+ return true;
47
+ }
48
+ return false;
49
+ }
50
+
51
+ /**
52
+ * Releases left k for the current round. If that completes the
53
+ * round, every waiting right is released with status (1 if none)
54
+ * and a new round begins. A key that is not a left does nothing.
55
+ */
56
+ async release(k: string, status: unknown = null): Promise<void> {
57
+ await Handoff.at("semaphore.release");
58
+ this.releaseNow(k, status);
59
+ }
60
+
61
+ /** @internal release without the hand-off. */
62
+ releaseNow(k: string, status: unknown): void {
63
+ if (!this.counters.has(k) || !this.tickLeft(k)) return;
64
+ this.inRound = true;
65
+ if (this.keyCount > 0) this.keyCount--;
66
+ if (this.keyCount > 0) return;
67
+ // take exactly the rights waiting now, in O(1)
68
+ const taken = this.rights;
69
+ this.rights = new Map();
70
+ this.tick = (this.tick + 1) % ROLLOVER;
71
+ this.keyCount = this.counters.size;
72
+ this.inRound = false;
73
+ const finished = this.roundDone;
74
+ this.roundDone = new Deferred<void>();
75
+ const st = status ?? 1;
76
+ for (const r of taken.values()) r.resolve(st);
77
+ finished.resolve();
78
+ }
79
+
80
+ /**
81
+ * Registers the right id and waits until a round releases it,
82
+ * returning the round's status. onRegistered, if given, runs once
83
+ * the right is waiting: a round that completes after it releases
84
+ * this right.
85
+ */
86
+ async acquire(id: string, onRegistered?: () => void | Promise<void>): Promise<unknown> {
87
+ await Handoff.at("semaphore.acquire");
88
+ if (this.rights.has(id)) throw new RightWaitingError(id);
89
+ const right = new Deferred<unknown>();
90
+ this.rights.set(id, right);
91
+ await onRegistered?.();
92
+ return right.promise;
93
+ }
94
+
95
+ /** Whether the right id is waiting. */
96
+ waiting(id: string): boolean {
97
+ return this.rights.has(id);
98
+ }
99
+
100
+ /** @internal Releases every waiting right with status, without a round (clearing CS waits). */
101
+ releaseAll(status: unknown): void {
102
+ const taken = this.rights;
103
+ this.rights = new Map();
104
+ for (const r of taken.values()) r.resolve(status);
105
+ }
106
+
107
+ /** Adds a left; if a round is in progress, waits for it to end. */
108
+ addLeft(k: string): Promise<void> {
109
+ return this.betweenRounds(() => {
110
+ if (!this.counters.has(k)) {
111
+ this.counters.set(k, (((this.tick - 1) % ROLLOVER) + ROLLOVER) % ROLLOVER);
112
+ this.keyCount++;
113
+ }
114
+ });
115
+ }
116
+
117
+ /** Removes a left (a key that is not a left does nothing); waits for a round in progress. */
118
+ clearLeft(k: string): Promise<void> {
119
+ return this.betweenRounds(() => {
120
+ if (this.counters.delete(k)) this.keyCount--;
121
+ });
122
+ }
123
+
124
+ private async betweenRounds(change: () => void): Promise<void> {
125
+ while (this.inRound) await this.roundDone.promise;
126
+ change();
127
+ }
128
+ }