@kylewillett/troupe 0.0.0-stage → 0.1.0

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.
Files changed (97) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/LICENSE +21 -0
  3. package/README.md +376 -2
  4. package/dist/actor.d.ts +13 -0
  5. package/dist/actor.js +14 -0
  6. package/dist/ask.d.ts +39 -0
  7. package/dist/ask.js +135 -0
  8. package/dist/backstage/encode.d.ts +36 -0
  9. package/dist/backstage/encode.js +183 -0
  10. package/dist/backstage/index.d.ts +4 -0
  11. package/dist/backstage/index.js +4 -0
  12. package/dist/backstage/requests.d.ts +8 -0
  13. package/dist/backstage/requests.js +137 -0
  14. package/dist/backstage/source.d.ts +10 -0
  15. package/dist/backstage/source.js +143 -0
  16. package/dist/backstage/types.d.ts +135 -0
  17. package/dist/backstage/types.js +3 -0
  18. package/dist/backstage-ui/assets/index-Bg0MCiqs.css +1 -0
  19. package/dist/backstage-ui/assets/index-CeefBsDh.js +9 -0
  20. package/dist/backstage-ui/index.html +13 -0
  21. package/dist/cell.d.ts +129 -0
  22. package/dist/cell.js +763 -0
  23. package/dist/checks.d.ts +9 -0
  24. package/dist/checks.js +25 -0
  25. package/dist/dispatcher.d.ts +36 -0
  26. package/dist/dispatcher.js +65 -0
  27. package/dist/errors.d.ts +37 -0
  28. package/dist/errors.js +41 -0
  29. package/dist/events.d.ts +37 -0
  30. package/dist/events.js +88 -0
  31. package/dist/index.d.ts +7 -0
  32. package/dist/index.js +7 -0
  33. package/dist/internal.d.ts +81 -0
  34. package/dist/internal.js +36 -0
  35. package/dist/logger.d.ts +31 -0
  36. package/dist/logger.js +56 -0
  37. package/dist/names.d.ts +20 -0
  38. package/dist/names.js +50 -0
  39. package/dist/node/backstage/index.d.ts +1 -0
  40. package/dist/node/backstage/index.js +2 -0
  41. package/dist/node/backstage/server.d.ts +60 -0
  42. package/dist/node/backstage/server.js +342 -0
  43. package/dist/node/sqlite/index.d.ts +1 -0
  44. package/dist/node/sqlite/index.js +2 -0
  45. package/dist/node/sqlite/schema.d.ts +2 -0
  46. package/dist/node/sqlite/schema.js +36 -0
  47. package/dist/node/sqlite/schema.sql +32 -0
  48. package/dist/node/sqlite/sqlite.d.ts +24 -0
  49. package/dist/node/sqlite/sqlite.js +183 -0
  50. package/dist/persistence/actor.d.ts +158 -0
  51. package/dist/persistence/actor.js +454 -0
  52. package/dist/persistence/backend.d.ts +32 -0
  53. package/dist/persistence/backend.js +96 -0
  54. package/dist/persistence/errors.d.ts +60 -0
  55. package/dist/persistence/errors.js +82 -0
  56. package/dist/persistence/index.d.ts +6 -0
  57. package/dist/persistence/index.js +5 -0
  58. package/dist/persistence/json.d.ts +7 -0
  59. package/dist/persistence/json.js +75 -0
  60. package/dist/persistence/memory.d.ts +18 -0
  61. package/dist/persistence/memory.js +143 -0
  62. package/dist/persistence/postgres/index.d.ts +1 -0
  63. package/dist/persistence/postgres/index.js +3 -0
  64. package/dist/persistence/postgres/postgres.d.ts +66 -0
  65. package/dist/persistence/postgres/postgres.js +236 -0
  66. package/dist/persistence/postgres/schema.d.ts +12 -0
  67. package/dist/persistence/postgres/schema.js +57 -0
  68. package/dist/persistence/postgres/schema.sql +35 -0
  69. package/dist/persistence/projection.d.ts +48 -0
  70. package/dist/persistence/projection.js +102 -0
  71. package/dist/persistence/standard-schema.d.ts +63 -0
  72. package/dist/persistence/standard-schema.js +7 -0
  73. package/dist/persistence/types.d.ts +73 -0
  74. package/dist/persistence/types.js +3 -0
  75. package/dist/queue.d.ts +11 -0
  76. package/dist/queue.js +31 -0
  77. package/dist/scheduler.d.ts +24 -0
  78. package/dist/scheduler.js +23 -0
  79. package/dist/supervision.d.ts +91 -0
  80. package/dist/supervision.js +120 -0
  81. package/dist/system.d.ts +28 -0
  82. package/dist/system.js +216 -0
  83. package/dist/testkit/index.d.ts +4 -0
  84. package/dist/testkit/index.js +4 -0
  85. package/dist/testkit/kit.d.ts +63 -0
  86. package/dist/testkit/kit.js +93 -0
  87. package/dist/testkit/manual-scheduler.d.ts +58 -0
  88. package/dist/testkit/manual-scheduler.js +187 -0
  89. package/dist/testkit/probe.d.ts +50 -0
  90. package/dist/testkit/probe.js +124 -0
  91. package/dist/testkit/random.d.ts +11 -0
  92. package/dist/testkit/random.js +23 -0
  93. package/dist/timers.d.ts +37 -0
  94. package/dist/timers.js +110 -0
  95. package/dist/types.d.ts +364 -0
  96. package/dist/types.js +1 -0
  97. package/package.json +110 -4
@@ -0,0 +1,454 @@
1
+ var _a;
2
+ import { checkInt, checkKeys, describe } from '../checks.js';
3
+ import { internalsOf, PERSISTENT, START, } from '../internal.js';
4
+ import { isValidName } from '../names.js';
5
+ import { EventValidationError, EventVersionError, JournalSequenceError } from './errors.js';
6
+ import { jsonProblem } from './json.js';
7
+ const OPTIONS = new Set([
8
+ 'id',
9
+ 'persistence',
10
+ 'initial',
11
+ 'onCommand',
12
+ 'onEvent',
13
+ 'onSignal',
14
+ 'tags',
15
+ 'events',
16
+ 'snapshots',
17
+ ]);
18
+ const SNAPSHOT_OPTIONS = new Set(['every', 'version']);
19
+ const EVENT_OPTIONS = new Set(['schema', 'version', 'upcasters']);
20
+ const MAX_ID_LENGTH = 255;
21
+ /** Events per read during recovery and `stateAt`. */
22
+ const PAGE_SIZE = 256;
23
+ /** The one implementation of `Effect`, so `onCommand` can't return something else by accident. */
24
+ class EffectImpl {
25
+ events;
26
+ steps;
27
+ constructor(events, steps) {
28
+ this.events = events;
29
+ this.steps = steps;
30
+ Object.freeze(this);
31
+ }
32
+ thenReply(to, message) {
33
+ checkRef(to, 'thenReply');
34
+ if (typeof message !== 'function') {
35
+ throw new TypeError(`thenReply: message must be a function, got ${describe(message)}`);
36
+ }
37
+ return this.#then((state) => {
38
+ to.tell(message(state));
39
+ });
40
+ }
41
+ thenRun(fn) {
42
+ if (typeof fn !== 'function') {
43
+ throw new TypeError(`thenRun: fn must be a function, got ${describe(fn)}`);
44
+ }
45
+ return this.#then((state) => {
46
+ fn(state);
47
+ });
48
+ }
49
+ thenStop() {
50
+ return this.#then((_state, ctx) => {
51
+ ctx.stop();
52
+ });
53
+ }
54
+ #then(step) {
55
+ return new _a(this.events, [...this.steps, step]);
56
+ }
57
+ }
58
+ _a = EffectImpl;
59
+ const NONE = new EffectImpl([], []);
60
+ /**
61
+ * Defines an event-sourced actor. Commands go to `onCommand`, which returns an effect. Its events
62
+ * are appended to the journal before they're applied with `onEvent`, and before any reply. On start
63
+ * and on every restart, the actor recovers its state by replaying its events, and commands wait in
64
+ * the mailbox until it's done (decision 0011).
65
+ *
66
+ * The result is an ordinary `ActorDef`: spawn, name and supervise it like any other actor. Every
67
+ * append says which sequence number it follows, so a second writer to the same `id` fails with
68
+ * `JournalConflictError` instead of corrupting the stream (decision 0013).
69
+ *
70
+ * @example
71
+ * const account = (id: string) =>
72
+ * persistentActor<AccountCmd, AccountEvent, Account>({
73
+ * id: `account-${id}`,
74
+ * persistence,
75
+ * initial: { balance: 0 },
76
+ * onCommand: (state, cmd, { persist, reply }) =>
77
+ * cmd.type === 'deposit'
78
+ * ? persist({ type: 'deposited', amount: cmd.amount }).thenReply(cmd.replyTo, (s) => s.balance)
79
+ * : reply(cmd.replyTo, state.balance),
80
+ * onEvent: (state, event) => ({ balance: state.balance + event.amount }),
81
+ * });
82
+ * @throws TypeError for a definition that can't be used, unknown fields included.
83
+ */
84
+ export function persistentActor(def) {
85
+ checkDef(def);
86
+ const { id } = def;
87
+ const journal = def.persistence.journal;
88
+ const snapshotting = snapshotPlan(def);
89
+ const { schema, version, upcasters } = eventPlan(def.events);
90
+ /** The schema's output for `event`. */
91
+ const check = async (using, event, seq) => {
92
+ const result = await using['~standard'].validate(event);
93
+ if (result.issues)
94
+ throw new EventValidationError(id, seq, result.issues);
95
+ return result.value;
96
+ };
97
+ /** A stored event raised to the current version, not yet checked. */
98
+ const upcast = (stored) => {
99
+ if (stored.version > version) {
100
+ throw new EventVersionError(id, stored.seq, stored.version, version);
101
+ }
102
+ let event = stored.event;
103
+ for (let v = stored.version; v < version; v++) {
104
+ const up = upcasters[v];
105
+ // Only a backend that broke its contract stores a version below 1.
106
+ if (up === undefined) {
107
+ throw new TypeError(`${id}: event ${String(stored.seq)} has version ${String(stored.version)}, ` +
108
+ 'which no upcaster covers');
109
+ }
110
+ event = up(event);
111
+ }
112
+ return event;
113
+ };
114
+ const persist = (...events) => events.length === 0 ? NONE : new EffectImpl(events, []);
115
+ const reply = (to, message) => {
116
+ checkRef(to, 'reply');
117
+ return new EffectImpl([], [
118
+ () => {
119
+ to.tell(message);
120
+ },
121
+ ]);
122
+ };
123
+ const none = () => NONE;
124
+ const contextFor = (ctx, lastSeq) => Object.freeze({ ...ctx, persistenceId: id, lastSeq, persist, reply, none });
125
+ const runSteps = (effect, state, ctx) => {
126
+ for (const step of effect.steps)
127
+ step(state, ctx);
128
+ };
129
+ /** Appends, then applies and runs the steps. The cell holds the mailbox until it settles. */
130
+ /** An event's tags, checked so a bad one fails the command instead of the append. */
131
+ const tagsFor = (event, i) => {
132
+ if (def.tags === undefined)
133
+ return [];
134
+ const tags = def.tags(event);
135
+ if (!Array.isArray(tags)) {
136
+ throw new TypeError(`${id}: tags() must return an array for event ${String(i)}`);
137
+ }
138
+ const seen = new Set();
139
+ for (const tag of tags) {
140
+ if (!isValidName(tag)) {
141
+ throw new TypeError(`${id}: tags() returned ${describe(tag)} for event ${String(i)}, but a tag must be 1 ` +
142
+ 'to 64 letters, digits, ".", "_", "~" or "-", starting with a letter or digit');
143
+ }
144
+ if (seen.has(tag)) {
145
+ throw new TypeError(`${id}: tags() repeats "${tag}" for event ${String(i)}`);
146
+ }
147
+ seen.add(tag);
148
+ }
149
+ return [...seen];
150
+ };
151
+ const persistThen = async (current, effect, ctx) => {
152
+ // If this rejects, the actor can't know what the journal holds, so it applies nothing. A
153
+ // restart recovers from the journal, which settles it (decision 0013).
154
+ // Checked before the append, so an event that fails its schema is never written. In order,
155
+ // one at a time, so an async schema's failures are deterministic. Without a schema nothing
156
+ // awaits, so the append starts in the same turn as the command.
157
+ let applied = effect.events;
158
+ if (schema !== undefined) {
159
+ const checked = [];
160
+ for (const event of effect.events)
161
+ checked.push(await check(schema, event, undefined));
162
+ applied = checked;
163
+ }
164
+ // Stored as persist got it (decision 0018), but tagged from the schema's output, so tags see
165
+ // the value onEvent folds. `applied` has one entry per event, in the same order.
166
+ const batch = effect.events.map((event, i) => ({
167
+ event,
168
+ version,
169
+ tags: tagsFor(applied[i], i),
170
+ }));
171
+ await journal.append(id, current.seq, batch);
172
+ let state = current.state;
173
+ // The schema's output, as recovery will see it, so a write and its replay fold the same value.
174
+ for (const event of applied)
175
+ state = def.onEvent(state, event);
176
+ const next = { seq: current.seq + batch.length, state };
177
+ internalsOf(ctx).publish({
178
+ type: 'persisted',
179
+ path: ctx.self.path,
180
+ persistenceId: id,
181
+ fromSeq: current.seq + 1,
182
+ toSeq: next.seq,
183
+ });
184
+ // After the append's await, so outside the cell's turn: the steps' tells name this actor as
185
+ // their sender only through the hook (decision 0020).
186
+ internalsOf(ctx).asSender(() => {
187
+ runSteps(effect, state, ctx);
188
+ });
189
+ if (snapshotting !== undefined && snapshotDue(current.seq, next.seq, snapshotting.every)) {
190
+ saveSnapshot(snapshotting, next, ctx);
191
+ }
192
+ return next;
193
+ };
194
+ /** Starts a save without waiting for it: the events are safe, so a snapshot is only a shortcut. */
195
+ const saveSnapshot = (plan, { seq, state }, ctx) => {
196
+ // Checked here rather than left to the backend, so a state that breaks decision 0001 is an
197
+ // error under the actor's path, not a failed save.
198
+ const problem = jsonProblem(state);
199
+ if (problem !== undefined) {
200
+ ctx.log.error(`${id}: state is not a JSON value, so no snapshot was saved: ${problem}`, {
201
+ persistenceId: id,
202
+ seq,
203
+ });
204
+ return;
205
+ }
206
+ const saving = plan.store.save(id, { seq, version: plan.version, state }).then(() => { }, (error) => {
207
+ ctx.log.warn(`${id}: saving the snapshot at ${String(seq)} failed`, {
208
+ persistenceId: id,
209
+ seq,
210
+ error,
211
+ });
212
+ });
213
+ internalsOf(ctx).track(saving);
214
+ };
215
+ /** The state to replay from: the latest usable snapshot, or `start` when there isn't one. */
216
+ const startFrom = async (start, ctx) => {
217
+ if (snapshotting === undefined)
218
+ return start;
219
+ let snapshot;
220
+ try {
221
+ snapshot = await snapshotting.store.load(id);
222
+ }
223
+ catch (error) {
224
+ ctx.log.warn(`${id}: loading the snapshot failed, so recovery replays every event`, {
225
+ persistenceId: id,
226
+ error,
227
+ });
228
+ return start;
229
+ }
230
+ if (snapshot === undefined)
231
+ return start;
232
+ if (snapshot.version !== snapshotting.version) {
233
+ ctx.log.info(`${id}: ignoring the snapshot at ${String(snapshot.seq)}, which has version ` +
234
+ `${String(snapshot.version)}, not ${String(snapshotting.version)}`, { persistenceId: id, seq: snapshot.seq });
235
+ return start;
236
+ }
237
+ // The version matches, so the stored state has this definition's shape.
238
+ return { seq: snapshot.seq, state: snapshot.state };
239
+ };
240
+ /**
241
+ * Folds the journal's events after `start.seq`, up to `until` or the end, whichever comes first:
242
+ * upcast, checked and applied, as recovery and `stateAt` both need.
243
+ */
244
+ const fold = async (start, until) => {
245
+ let { seq, state } = start;
246
+ for (;;) {
247
+ const want = Math.min(PAGE_SIZE, until - seq);
248
+ if (want <= 0)
249
+ break;
250
+ const page = await journal.read(id, seq + 1, want);
251
+ for (const stored of page) {
252
+ if (stored.seq !== seq + 1)
253
+ throw new JournalSequenceError(id, seq + 1, stored.seq);
254
+ const event = upcast(stored);
255
+ // Without a schema, the definition's types are the only claim about the event's shape.
256
+ state = def.onEvent(state, schema === undefined ? event : await check(schema, event, stored.seq));
257
+ seq = stored.seq;
258
+ }
259
+ if (page.length < want)
260
+ break;
261
+ }
262
+ return { seq, state };
263
+ };
264
+ const recover = async (initial, ctx) => {
265
+ const start = await startFrom(initial, ctx);
266
+ const { seq, state } = await fold(start, Infinity);
267
+ internalsOf(ctx).publish({
268
+ type: 'recovered',
269
+ path: ctx.self.path,
270
+ persistenceId: id,
271
+ snapshotSeq: start.seq,
272
+ lastSeq: seq,
273
+ });
274
+ // A throw here is a failure in the start, like one in recovery: this is where the actor
275
+ // restarts its timers, and carrying on without them would hide the bug.
276
+ // After recovery's awaits, so outside the cell's turn, like the effect steps.
277
+ internalsOf(ctx).asSender(() => {
278
+ def.onSignal?.(state, { type: 'recoveryCompleted', seq }, contextFor(ctx, seq));
279
+ });
280
+ return { seq, state };
281
+ };
282
+ /** For inspectors: the state after event `seq`, from the journal alone, with no snapshot. */
283
+ const stateAt = async (seq) => {
284
+ if (!Number.isSafeInteger(seq) || seq < 0) {
285
+ throw new TypeError(`${id}: stateAt needs a non-negative integer, got ${describe(seq)}`);
286
+ }
287
+ const reached = await fold({ seq: 0, state: def.initial }, seq);
288
+ if (reached.seq < seq) {
289
+ throw new RangeError(`${id}: the journal ends at event ${String(reached.seq)}, before ${String(seq)}`);
290
+ }
291
+ return reached.state;
292
+ };
293
+ const hook = Object.freeze({
294
+ persistenceId: id,
295
+ persistence: def.persistence,
296
+ stateAt,
297
+ });
298
+ const result = {
299
+ initial: { seq: 0, state: def.initial },
300
+ receive(current, command, ctx) {
301
+ const effect = def.onCommand(current.state, command, contextFor(ctx, current.seq));
302
+ if (!(effect instanceof EffectImpl)) {
303
+ throw new TypeError(`${id}: onCommand must return an effect from ctx.persist, ctx.reply or ctx.none, ` +
304
+ `got ${describe(effect)}`);
305
+ }
306
+ const made = effect;
307
+ if (made.events.length === 0) {
308
+ // Nothing to wait for, so the mailbox stays open.
309
+ runSteps(made, current.state, ctx);
310
+ return current;
311
+ }
312
+ made.events.forEach((event, i) => {
313
+ // Checked here, so the failure lands in the command that made the event (decision 0014).
314
+ const problem = jsonProblem(event);
315
+ if (problem !== undefined) {
316
+ throw new TypeError(`${id}: event ${String(i)} is not a JSON value: ${problem}`);
317
+ }
318
+ });
319
+ return persistThen(current, made, ctx);
320
+ },
321
+ [START]: recover,
322
+ };
323
+ // Not enumerable, so spreading a definition doesn't carry it to a def that isn't this one.
324
+ Object.defineProperty(result, PERSISTENT, { value: hook });
325
+ if (def.onSignal !== undefined) {
326
+ result.onSignal = (current, signal, ctx) => {
327
+ def.onSignal?.(current.state, signal, contextFor(ctx, current.seq));
328
+ return current;
329
+ };
330
+ }
331
+ return result;
332
+ }
333
+ function checkDef(def) {
334
+ checkKeys(def, OPTIONS, 'persistentActor');
335
+ const d = def;
336
+ const { id, persistence } = d;
337
+ if (typeof id !== 'string' || id === '' || id.length > MAX_ID_LENGTH) {
338
+ throw new TypeError(`persistentActor: id must be a string of 1 to ${String(MAX_ID_LENGTH)} characters, ` +
339
+ `got ${typeof id === 'string' ? `one of ${String(id.length)}` : describe(id)}`);
340
+ }
341
+ if (!isPersistence(persistence)) {
342
+ throw new TypeError('persistentActor: persistence must have a journal with append and read');
343
+ }
344
+ if (!('initial' in d))
345
+ throw new TypeError('persistentActor: the definition has no initial');
346
+ for (const key of ['onCommand', 'onEvent']) {
347
+ if (typeof d[key] !== 'function') {
348
+ throw new TypeError(`persistentActor: ${key} must be a function, got ${describe(d[key])}`);
349
+ }
350
+ }
351
+ for (const key of ['onSignal', 'tags']) {
352
+ if (d[key] !== undefined && typeof d[key] !== 'function') {
353
+ throw new TypeError(`persistentActor: ${key} must be a function when it is set`);
354
+ }
355
+ }
356
+ if (d.events !== undefined)
357
+ checkEvents(d.events);
358
+ if (d.snapshots !== undefined)
359
+ checkSnapshots(d.snapshots, persistence);
360
+ }
361
+ function checkEvents(events) {
362
+ checkKeys(events, EVENT_OPTIONS, 'persistentActor: events');
363
+ const { schema, version = 1, upcasters } = events;
364
+ if (schema !== undefined && !isStandardSchema(schema)) {
365
+ throw new TypeError('persistentActor: events.schema must be a Standard Schema, with ~standard.validate');
366
+ }
367
+ checkInt(version, 'persistentActor: events.version');
368
+ const current = version;
369
+ if (upcasters === undefined) {
370
+ if (current > 1) {
371
+ throw new TypeError(`persistentActor: events.version is ${String(current)}, so events.upcasters must ` +
372
+ `cover versions 1 to ${String(current - 1)}`);
373
+ }
374
+ return;
375
+ }
376
+ if (typeof upcasters !== 'object' || upcasters === null || Array.isArray(upcasters)) {
377
+ throw new TypeError('persistentActor: events.upcasters must be an object');
378
+ }
379
+ const ups = upcasters;
380
+ // A key outside 1 to version - 1 usually means the version wasn't bumped with the upcaster.
381
+ for (const key of Object.keys(ups)) {
382
+ const from = Number(key);
383
+ if (!Number.isSafeInteger(from) || String(from) !== key || from < 1 || from >= current) {
384
+ throw new TypeError(`persistentActor: events.upcasters has a key "${key}", but upcasters run from each ` +
385
+ `version below events.version (${String(current)}), starting at 1`);
386
+ }
387
+ }
388
+ for (let from = 1; from < current; from++) {
389
+ if (typeof ups[String(from)] !== 'function') {
390
+ throw new TypeError(`persistentActor: events.upcasters has no function for version ${String(from)}, so ` +
391
+ `events stored at it can't reach version ${String(current)}`);
392
+ }
393
+ }
394
+ }
395
+ function isStandardSchema(value) {
396
+ if ((typeof value !== 'object' && typeof value !== 'function') || value === null)
397
+ return false;
398
+ const props = value['~standard'];
399
+ return (typeof props === 'object' &&
400
+ props !== null &&
401
+ typeof props.validate === 'function');
402
+ }
403
+ /** The checked event options, with their defaults. */
404
+ function eventPlan(events) {
405
+ return {
406
+ schema: events?.schema,
407
+ version: events?.version ?? 1,
408
+ upcasters: events?.upcasters ?? {},
409
+ };
410
+ }
411
+ function checkSnapshots(snapshots, persistence) {
412
+ checkKeys(snapshots, SNAPSHOT_OPTIONS, 'persistentActor: snapshots');
413
+ const { every, version } = snapshots;
414
+ checkInt(every, 'persistentActor: snapshots.every');
415
+ if (version !== undefined)
416
+ checkInt(version, 'persistentActor: snapshots.version');
417
+ if (!isSnapshotStore(persistence.snapshots)) {
418
+ throw new TypeError('persistentActor: snapshots needs persistence.snapshots, with save and load');
419
+ }
420
+ }
421
+ /** The checked snapshot options, with their defaults, or undefined when there are none. */
422
+ function snapshotPlan(def) {
423
+ const { snapshots } = def;
424
+ const store = def.persistence.snapshots;
425
+ if (snapshots === undefined || store === undefined)
426
+ return undefined;
427
+ return { store, every: snapshots.every, version: snapshots.version ?? 1 };
428
+ }
429
+ /** Whether a persist from `fromSeq` to `toSeq` crossed a multiple of `every`. */
430
+ function snapshotDue(fromSeq, toSeq, every) {
431
+ return Math.floor(fromSeq / every) < Math.floor(toSeq / every);
432
+ }
433
+ function isSnapshotStore(value) {
434
+ if (typeof value !== 'object' || value === null)
435
+ return false;
436
+ const s = value;
437
+ return typeof s.save === 'function' && typeof s.load === 'function';
438
+ }
439
+ function isPersistence(value) {
440
+ if (typeof value !== 'object' || value === null)
441
+ return false;
442
+ const journal = value.journal;
443
+ if (typeof journal !== 'object' || journal === null)
444
+ return false;
445
+ const j = journal;
446
+ return typeof j.append === 'function' && typeof j.read === 'function';
447
+ }
448
+ function checkRef(to, what) {
449
+ if (typeof to !== 'object' ||
450
+ to === null ||
451
+ typeof to.tell !== 'function') {
452
+ throw new TypeError(`${what}: to must be an actor ref`);
453
+ }
454
+ }
@@ -0,0 +1,32 @@
1
+ /** An event checked and ready to store, with the event itself as JSON text. */
2
+ export interface SerializedEvent {
3
+ readonly version: number;
4
+ readonly tags: readonly string[];
5
+ readonly json: string;
6
+ }
7
+ /** A snapshot checked and ready to store, with its state as JSON text. */
8
+ export interface SerializedSnapshot {
9
+ readonly seq: number;
10
+ readonly version: number;
11
+ readonly json: string;
12
+ }
13
+ /**
14
+ * Checks a backend's `clock` option, and returns a reader that rejects anything but integer ms.
15
+ * `where` names the backend in error messages.
16
+ */
17
+ export declare function wallClock(clock: unknown, where: string): () => number;
18
+ /**
19
+ * Throws unless `value` is a non-empty string that every backend can store as it is: a persistence
20
+ * id, tag or projection name.
21
+ */
22
+ export declare function checkId(value: unknown, what: string): void;
23
+ /** Checks `append`'s arguments and serializes the batch, before anything touches the stream. */
24
+ export declare function checkAppend(persistenceId: unknown, expectedSeq: unknown, events: unknown): SerializedEvent[];
25
+ /** Checks `read`'s arguments. */
26
+ export declare function checkRead(persistenceId: unknown, fromSeq: unknown, limit: unknown): void;
27
+ /** Checks `readByTag`'s arguments. */
28
+ export declare function checkReadByTag(tag: unknown, afterOffset: unknown, limit: unknown): void;
29
+ /** Checks an offset store `save`'s arguments. */
30
+ export declare function checkOffsetSave(name: unknown, offset: unknown): void;
31
+ /** Checks a snapshot store `save`'s arguments and serializes the state. */
32
+ export declare function serializeSnapshot(persistenceId: unknown, value: unknown): SerializedSnapshot;
@@ -0,0 +1,96 @@
1
+ // Shared by every backend, never exported from an entry point: the argument checks and the clock
2
+ // wrapper, so the in-memory, SQLite and Postgres backends reject exactly the same calls.
3
+ import { checkInt, describe } from '../checks.js';
4
+ import { jsonProblem } from './json.js';
5
+ /**
6
+ * Checks a backend's `clock` option, and returns a reader that rejects anything but integer ms.
7
+ * `where` names the backend in error messages.
8
+ */
9
+ export function wallClock(clock, where) {
10
+ if (typeof clock !== 'function') {
11
+ throw new TypeError(`${where}: clock must be a function, got ${describe(clock)}`);
12
+ }
13
+ const read = clock;
14
+ return () => {
15
+ const time = read();
16
+ checkInt(time, `${where}: clock()`, { min: 0 });
17
+ return time;
18
+ };
19
+ }
20
+ // U+0000, or a surrogate with no partner. Postgres text can't hold the first, and neither
21
+ // database's UTF-8 can hold the second, so an id with either would be stored as something else.
22
+ // The `u` flag makes a valid pair one code point, which \p{Cs} doesn't match.
23
+ // eslint-disable-next-line no-control-regex -- U+0000 is the point.
24
+ const UNSTORABLE = /[\u0000\p{Cs}]/u;
25
+ /**
26
+ * Throws unless `value` is a non-empty string that every backend can store as it is: a persistence
27
+ * id, tag or projection name.
28
+ */
29
+ export function checkId(value, what) {
30
+ if (typeof value !== 'string' || value === '') {
31
+ throw new TypeError(`${what} must be a non-empty string, got ${describe(value)}`);
32
+ }
33
+ if (UNSTORABLE.test(value)) {
34
+ throw new TypeError(`${what} must not contain U+0000 or a lone surrogate`);
35
+ }
36
+ }
37
+ /** Checks `append`'s arguments and serializes the batch, before anything touches the stream. */
38
+ export function checkAppend(persistenceId, expectedSeq, events) {
39
+ checkId(persistenceId, 'append: persistenceId');
40
+ checkInt(expectedSeq, 'append: expectedSeq', { min: 0 });
41
+ if (!Array.isArray(events))
42
+ throw new TypeError('append: events must be an array');
43
+ return events.map((event, i) => serializeEvent(event, i));
44
+ }
45
+ /** Checks `read`'s arguments. */
46
+ export function checkRead(persistenceId, fromSeq, limit) {
47
+ checkId(persistenceId, 'read: persistenceId');
48
+ checkInt(fromSeq, 'read: fromSeq');
49
+ checkInt(limit, 'read: limit');
50
+ }
51
+ /** Checks `readByTag`'s arguments. */
52
+ export function checkReadByTag(tag, afterOffset, limit) {
53
+ checkId(tag, 'readByTag: tag');
54
+ checkInt(afterOffset, 'readByTag: afterOffset', { min: 0 });
55
+ checkInt(limit, 'readByTag: limit');
56
+ }
57
+ /** Checks an offset store `save`'s arguments. */
58
+ export function checkOffsetSave(name, offset) {
59
+ checkId(name, 'offsets.save: name');
60
+ checkInt(offset, 'offsets.save: offset', { min: 0 });
61
+ }
62
+ function serializeEvent(value, index) {
63
+ const where = `append: events[${String(index)}]`;
64
+ if (typeof value !== 'object' || value === null) {
65
+ throw new TypeError(`${where} must be an object`);
66
+ }
67
+ const { event, version, tags } = value;
68
+ checkInt(version, `${where}.version`);
69
+ if (!Array.isArray(tags))
70
+ throw new TypeError(`${where}.tags must be an array`);
71
+ const seen = new Set();
72
+ for (const tag of tags) {
73
+ checkId(tag, `${where}.tags[]`);
74
+ if (seen.has(tag))
75
+ throw new TypeError(`${where}.tags repeats "${tag}"`);
76
+ seen.add(tag);
77
+ }
78
+ const problem = jsonProblem(event);
79
+ if (problem !== undefined)
80
+ throw new TypeError(`${where}.event is not JSON: ${problem}`);
81
+ return { version: version, tags: [...seen], json: JSON.stringify(event) };
82
+ }
83
+ /** Checks a snapshot store `save`'s arguments and serializes the state. */
84
+ export function serializeSnapshot(persistenceId, value) {
85
+ checkId(persistenceId, 'snapshots.save: persistenceId');
86
+ if (typeof value !== 'object' || value === null) {
87
+ throw new TypeError('snapshots.save: snapshot must be an object');
88
+ }
89
+ const { seq, version, state } = value;
90
+ checkInt(seq, 'snapshots.save: seq');
91
+ checkInt(version, 'snapshots.save: version');
92
+ const problem = jsonProblem(state);
93
+ if (problem !== undefined)
94
+ throw new TypeError(`snapshots.save: state is not JSON: ${problem}`);
95
+ return { seq: seq, version: version, json: JSON.stringify(state) };
96
+ }
@@ -0,0 +1,60 @@
1
+ import type { StandardSchemaV1 } from './standard-schema.js';
2
+ /**
3
+ * The reason `Journal.append` rejects when the stream's last sequence number isn't the expected
4
+ * one: another writer got there first (decision 0013). Nothing was written. Backends throw it.
5
+ */
6
+ export declare class JournalConflictError extends Error {
7
+ /** Always `"JournalConflictError"`, so the error can be recognized without `instanceof`. */
8
+ readonly name = "JournalConflictError";
9
+ /** The stream the append was for. */
10
+ readonly persistenceId: string;
11
+ /** The sequence number the append expected to follow. */
12
+ readonly expectedSeq: number;
13
+ /** Creates the error for an append to `persistenceId` at `expectedSeq`. */
14
+ constructor(persistenceId: string, expectedSeq: number);
15
+ }
16
+ /** The reason recovery fails when a backend returns an event out of sequence. */
17
+ export declare class JournalSequenceError extends Error {
18
+ /** Always `"JournalSequenceError"`, so the error can be recognized without `instanceof`. */
19
+ readonly name = "JournalSequenceError";
20
+ /** The stream being read. */
21
+ readonly persistenceId: string;
22
+ /** The sequence number that should have come next. */
23
+ readonly expected: number;
24
+ /** The sequence number that came instead. */
25
+ readonly got: number;
26
+ /** Creates the error for a read of `persistenceId` that got `got` where `expected` was due. */
27
+ constructor(persistenceId: string, expected: number, got: number);
28
+ }
29
+ /**
30
+ * The reason a command or a recovery fails when an event doesn't pass its schema. On write it's
31
+ * thrown before the append, so nothing was written. On recovery it names the stored event.
32
+ */
33
+ export declare class EventValidationError extends Error {
34
+ /** Always `"EventValidationError"`, so the error can be recognized without `instanceof`. */
35
+ readonly name = "EventValidationError";
36
+ /** The stream the event belongs to. */
37
+ readonly persistenceId: string;
38
+ /** The stored event's sequence number, on recovery. Undefined on write. */
39
+ readonly seq: number | undefined;
40
+ /** What the schema found wrong, as it reported it. */
41
+ readonly issues: readonly StandardSchemaV1.Issue[];
42
+ /** Creates the error for an event of `persistenceId`, at `seq` when it was read. */
43
+ constructor(persistenceId: string, seq: number | undefined, issues: readonly StandardSchemaV1.Issue[]);
44
+ }
45
+ /**
46
+ * The reason recovery fails when a stored event's version is newer than the actor's. It usually
47
+ * means an older deployment is reading events a newer one wrote.
48
+ */
49
+ export declare class EventVersionError extends Error {
50
+ /** Always `"EventVersionError"`, so the error can be recognized without `instanceof`. */
51
+ readonly name = "EventVersionError";
52
+ /** The stream being read. */
53
+ readonly persistenceId: string;
54
+ /** The stored event's sequence number. */
55
+ readonly seq: number;
56
+ /** The stored event's version. */
57
+ readonly version: number;
58
+ /** Creates the error for event `seq` of `persistenceId`, stored at `version`. */
59
+ constructor(persistenceId: string, seq: number, version: number, current: number);
60
+ }