@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,57 @@
1
+ // The Postgres backend's tables, in a schema the caller names. The build writes the default
2
+ // schema's SQL to dist/persistence/postgres/schema.sql, for people who manage migrations
3
+ // themselves. Every statement is safe to run again.
4
+ /** The schema the Postgres backend uses when none is given. */
5
+ export const DEFAULT_SCHEMA = 'troupe';
6
+ // Lower case only, so quoting the name never changes what it means, and short enough for
7
+ // Postgres's 63-byte identifier limit.
8
+ const SCHEMA_PATTERN = /^[a-z_][a-z0-9_]{0,62}$/;
9
+ /** Whether `name` can be a schema name: lower-case letters, digits and `_`, at most 63. */
10
+ export function isSchemaName(name) {
11
+ return typeof name === 'string' && SCHEMA_PATTERN.test(name);
12
+ }
13
+ /**
14
+ * The statements that create the backend's schema and tables, if they're missing. Separate
15
+ * statements rather than one string, because a pool that only speaks the extended query protocol
16
+ * runs one statement per query.
17
+ */
18
+ export function postgresSchemaStatements(schema) {
19
+ const s = `"${schema}"`;
20
+ return [
21
+ `CREATE SCHEMA IF NOT EXISTS ${s}`,
22
+ `CREATE TABLE IF NOT EXISTS ${s}.events (
23
+ -- An identity never hands out a value twice, so offsets only increase. Appends take the
24
+ -- journal's advisory lock before they draw one, so offsets also commit in order (decision 0016).
25
+ global_offset BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
26
+ persistence_id TEXT NOT NULL,
27
+ seq BIGINT NOT NULL,
28
+ version BIGINT NOT NULL,
29
+ timestamp BIGINT NOT NULL,
30
+ -- json, not jsonb: it keeps the text as written, so it accepts every JSON value the other
31
+ -- backends do. jsonb rejects \\u0000 and lone surrogates. Tags are an array in the order given.
32
+ event JSON NOT NULL,
33
+ tags JSON NOT NULL,
34
+ UNIQUE (persistence_id, seq)
35
+ )`,
36
+ `CREATE TABLE IF NOT EXISTS ${s}.event_tags (
37
+ tag TEXT NOT NULL,
38
+ global_offset BIGINT NOT NULL,
39
+ PRIMARY KEY (tag, global_offset)
40
+ )`,
41
+ `CREATE TABLE IF NOT EXISTS ${s}.snapshots (
42
+ persistence_id TEXT PRIMARY KEY,
43
+ seq BIGINT NOT NULL,
44
+ version BIGINT NOT NULL,
45
+ timestamp BIGINT NOT NULL,
46
+ state JSON NOT NULL
47
+ )`,
48
+ `CREATE TABLE IF NOT EXISTS ${s}.offsets (
49
+ name TEXT PRIMARY KEY,
50
+ global_offset BIGINT NOT NULL
51
+ )`,
52
+ ];
53
+ }
54
+ /** The SQL that creates the backend's schema and tables, as one script. */
55
+ export function postgresSchemaSql(schema = DEFAULT_SCHEMA) {
56
+ return `${postgresSchemaStatements(schema).join(';\n\n')};\n`;
57
+ }
@@ -0,0 +1,35 @@
1
+ CREATE SCHEMA IF NOT EXISTS "troupe";
2
+
3
+ CREATE TABLE IF NOT EXISTS "troupe".events (
4
+ -- An identity never hands out a value twice, so offsets only increase. Appends take the
5
+ -- journal's advisory lock before they draw one, so offsets also commit in order (decision 0016).
6
+ global_offset BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
7
+ persistence_id TEXT NOT NULL,
8
+ seq BIGINT NOT NULL,
9
+ version BIGINT NOT NULL,
10
+ timestamp BIGINT NOT NULL,
11
+ -- json, not jsonb: it keeps the text as written, so it accepts every JSON value the other
12
+ -- backends do. jsonb rejects \u0000 and lone surrogates. Tags are an array in the order given.
13
+ event JSON NOT NULL,
14
+ tags JSON NOT NULL,
15
+ UNIQUE (persistence_id, seq)
16
+ );
17
+
18
+ CREATE TABLE IF NOT EXISTS "troupe".event_tags (
19
+ tag TEXT NOT NULL,
20
+ global_offset BIGINT NOT NULL,
21
+ PRIMARY KEY (tag, global_offset)
22
+ );
23
+
24
+ CREATE TABLE IF NOT EXISTS "troupe".snapshots (
25
+ persistence_id TEXT PRIMARY KEY,
26
+ seq BIGINT NOT NULL,
27
+ version BIGINT NOT NULL,
28
+ timestamp BIGINT NOT NULL,
29
+ state JSON NOT NULL
30
+ );
31
+
32
+ CREATE TABLE IF NOT EXISTS "troupe".offsets (
33
+ name TEXT PRIMARY KEY,
34
+ global_offset BIGINT NOT NULL
35
+ );
@@ -0,0 +1,48 @@
1
+ import type { ActorDef } from '../types.js';
2
+ import type { Persistence, StoredEvent } from './types.js';
3
+ /** Options for a projection: what it follows, where it keeps its place, and what it does. */
4
+ export interface ProjectionOptions {
5
+ /**
6
+ * The projection's key in the offset store: a non-empty string of at most 255 characters. A new
7
+ * projection with the same name starts where the last one stopped.
8
+ */
9
+ name: string;
10
+ /** Where events and offsets are kept. Needs `journal` and `offsets`. */
11
+ persistence: Persistence;
12
+ /** The tag to follow. It matches the actor name pattern, as `tags()` results do. */
13
+ tag: string;
14
+ /**
15
+ * Handles one event, and may return a promise, which is awaited before the next event. At least
16
+ * once: after a failure, the batch runs again from its start, so an event can repeat. It gets
17
+ * the stored event as written, not upcast or checked, since a tag can span entity types. In
18
+ * message events, what it tells before any `await` of its own has the projection as its sender.
19
+ */
20
+ handle(event: StoredEvent): void | Promise<void>;
21
+ /** How long to wait after a batch that wasn't full, in ms. A positive integer. Default 1,000. */
22
+ pollMs?: number;
23
+ /** The most events per read. A positive integer. Default 100. */
24
+ batchSize?: number;
25
+ }
26
+ /** What a projection's cell holds: the offset of the last event it handled, 0 before any. */
27
+ export interface ProjectionState {
28
+ /** The offset of the last event handled and saved. */
29
+ readonly offset: number;
30
+ }
31
+ /**
32
+ * Follows a tag through the journal and hands each event to `handle`, in offset order. It's an
33
+ * actor: spawn and supervise it like any other. On start and on every restart, it loads its stored
34
+ * offset. Then it reads a batch after that offset, handles the events one at a time, and saves the
35
+ * offset of the last one. A full batch reads again at once, and a short one waits `pollMs`.
36
+ *
37
+ * A failure in `handle`, or in loading or saving the offset, goes to supervision. A restart reloads
38
+ * the stored offset, so the failed batch runs again: delivery is at least once.
39
+ *
40
+ * @example
41
+ * system.spawn(
42
+ * projection({ name: 'balances', persistence, tag: 'account', handle: (e) => totals.add(e) }),
43
+ * 'balances',
44
+ * { supervision: supervise.restartWithBackoff({ minMs: 200, maxMs: 5_000 }) },
45
+ * );
46
+ * @throws TypeError for options that can't be used, unknown fields included.
47
+ */
48
+ export declare function projection(opts: ProjectionOptions): ActorDef<never, ProjectionState>;
@@ -0,0 +1,102 @@
1
+ import { checkInt, checkKeys, describe } from '../checks.js';
2
+ import { internalsOf, START } from '../internal.js';
3
+ import { isValidName } from '../names.js';
4
+ const OPTIONS = new Set(['name', 'persistence', 'tag', 'handle', 'pollMs', 'batchSize']);
5
+ const MAX_NAME_LENGTH = 255;
6
+ const DEFAULT_POLL_MS = 1_000;
7
+ const DEFAULT_BATCH_SIZE = 100;
8
+ const POLL_TIMER = 'poll';
9
+ /** The projection's only message. Private, so nothing outside can tell it anything. */
10
+ const POLL = Object.freeze({ type: 'poll' });
11
+ /**
12
+ * Follows a tag through the journal and hands each event to `handle`, in offset order. It's an
13
+ * actor: spawn and supervise it like any other. On start and on every restart, it loads its stored
14
+ * offset. Then it reads a batch after that offset, handles the events one at a time, and saves the
15
+ * offset of the last one. A full batch reads again at once, and a short one waits `pollMs`.
16
+ *
17
+ * A failure in `handle`, or in loading or saving the offset, goes to supervision. A restart reloads
18
+ * the stored offset, so the failed batch runs again: delivery is at least once.
19
+ *
20
+ * @example
21
+ * system.spawn(
22
+ * projection({ name: 'balances', persistence, tag: 'account', handle: (e) => totals.add(e) }),
23
+ * 'balances',
24
+ * { supervision: supervise.restartWithBackoff({ minMs: 200, maxMs: 5_000 }) },
25
+ * );
26
+ * @throws TypeError for options that can't be used, unknown fields included.
27
+ */
28
+ export function projection(opts) {
29
+ checkOptions(opts);
30
+ const { name, tag } = opts;
31
+ // Checked above, so both stores are there.
32
+ const journal = opts.persistence.journal;
33
+ const offsets = opts.persistence.offsets;
34
+ const pollMs = opts.pollMs ?? DEFAULT_POLL_MS;
35
+ const batchSize = opts.batchSize ?? DEFAULT_BATCH_SIZE;
36
+ const def = {
37
+ initial: { offset: 0 },
38
+ async receive(current, _poll, ctx) {
39
+ const batch = await journal.readByTag(tag, current.offset, batchSize);
40
+ // After the read's await, so outside the cell's turn: what handle tells names the projection
41
+ // as its sender only through the hook (decision 0020). Called on opts, so a handle that uses
42
+ // `this` sees the object it was defined on.
43
+ const internals = internalsOf(ctx);
44
+ for (const event of batch)
45
+ await internals.asSender(() => opts.handle(event));
46
+ const last = batch.at(-1);
47
+ let next = current;
48
+ if (last !== undefined) {
49
+ await offsets.save(name, last.offset);
50
+ next = { offset: last.offset };
51
+ }
52
+ // Exactly one poll is ever pending, in the mailbox or on the timer. A failure above consumes
53
+ // it, and the restart's start sends the next one, so the loop never doubles up.
54
+ if (batch.length === batchSize)
55
+ ctx.self.tell(POLL);
56
+ else
57
+ ctx.timers.startSingle(POLL_TIMER, POLL, pollMs);
58
+ return next;
59
+ },
60
+ async [START](_state, ctx) {
61
+ const offset = await offsets.load(name);
62
+ ctx.self.tell(POLL);
63
+ return { offset };
64
+ },
65
+ };
66
+ // Poll is private, so the public type takes no messages. The cell only ever passes POLL.
67
+ return def;
68
+ }
69
+ function checkOptions(opts) {
70
+ checkKeys(opts, OPTIONS, 'projection');
71
+ const { name, persistence, tag, handle, pollMs, batchSize } = opts;
72
+ if (typeof name !== 'string' || name === '' || name.length > MAX_NAME_LENGTH) {
73
+ throw new TypeError(`projection: name must be a string of 1 to ${String(MAX_NAME_LENGTH)} characters, ` +
74
+ `got ${typeof name === 'string' ? `one of ${String(name.length)}` : describe(name)}`);
75
+ }
76
+ if (!isValidName(tag)) {
77
+ throw new TypeError(`projection: tag must be 1 to 64 letters, digits, ".", "_", "~" or "-", starting with a ` +
78
+ `letter or digit, got ${describe(tag)}`);
79
+ }
80
+ if (!hasStores(persistence)) {
81
+ throw new TypeError('projection: persistence must have a journal with readByTag, and offsets with load and save');
82
+ }
83
+ if (typeof handle !== 'function') {
84
+ throw new TypeError(`projection: handle must be a function, got ${describe(handle)}`);
85
+ }
86
+ if (pollMs !== undefined)
87
+ checkInt(pollMs, 'projection: pollMs');
88
+ if (batchSize !== undefined)
89
+ checkInt(batchSize, 'projection: batchSize');
90
+ }
91
+ function hasStores(value) {
92
+ if (typeof value !== 'object' || value === null)
93
+ return false;
94
+ const { journal, offsets } = value;
95
+ return hasMethods(journal, ['readByTag']) && hasMethods(offsets, ['load', 'save']);
96
+ }
97
+ function hasMethods(value, names) {
98
+ if (typeof value !== 'object' || value === null)
99
+ return false;
100
+ const v = value;
101
+ return names.every((n) => typeof v[n] === 'function');
102
+ }
@@ -0,0 +1,63 @@
1
+ /**
2
+ * The Standard Schema interface, which Zod, Valibot, ArkType and other libraries implement. A
3
+ * persistent actor's `events.schema` takes any value of this shape.
4
+ */
5
+ export interface StandardSchemaV1<Input = unknown, Output = Input> {
6
+ /** The Standard Schema properties. */
7
+ readonly '~standard': StandardSchemaV1.Props<Input, Output>;
8
+ }
9
+ export declare namespace StandardSchemaV1 {
10
+ /** The Standard Schema properties interface. */
11
+ interface Props<Input = unknown, Output = Input> {
12
+ /** The version number of the standard. */
13
+ readonly version: 1;
14
+ /** The vendor name of the schema library. */
15
+ readonly vendor: string;
16
+ /** Validates unknown input values. */
17
+ readonly validate: (value: unknown, options?: Options) => Result<Output> | Promise<Result<Output>>;
18
+ /** Inferred types associated with the schema. */
19
+ readonly types?: Types<Input, Output> | undefined;
20
+ }
21
+ /** The result interface of the validate function. */
22
+ type Result<Output> = SuccessResult<Output> | FailureResult;
23
+ /** The result interface if validation succeeds. */
24
+ interface SuccessResult<Output> {
25
+ /** The typed output value. */
26
+ readonly value: Output;
27
+ /** A falsy value for `issues` indicates success. */
28
+ readonly issues?: undefined;
29
+ }
30
+ /** The options for the validate function. */
31
+ interface Options {
32
+ /** Explicit support for additional vendor-specific parameters, if needed. */
33
+ readonly libraryOptions?: Record<string, unknown> | undefined;
34
+ }
35
+ /** The result interface if validation fails. */
36
+ interface FailureResult {
37
+ /** The issues of failed validation. */
38
+ readonly issues: readonly Issue[];
39
+ }
40
+ /** The issue interface of the failure output. */
41
+ interface Issue {
42
+ /** The error message of the issue. */
43
+ readonly message: string;
44
+ /** The path of the issue, if any. */
45
+ readonly path?: readonly (PropertyKey | PathSegment)[] | undefined;
46
+ }
47
+ /** The path segment interface of the issue. */
48
+ interface PathSegment {
49
+ /** The key representing a path segment. */
50
+ readonly key: PropertyKey;
51
+ }
52
+ /** The Standard types interface. */
53
+ interface Types<Input = unknown, Output = Input> {
54
+ /** The input type of the schema. */
55
+ readonly input: Input;
56
+ /** The output type of the schema. */
57
+ readonly output: Output;
58
+ }
59
+ /** Infers the input type of a Standard Schema. */
60
+ type InferInput<Schema extends StandardSchemaV1> = NonNullable<Schema['~standard']['types']>['input'];
61
+ /** Infers the output type of a Standard Schema. */
62
+ type InferOutput<Schema extends StandardSchemaV1> = NonNullable<Schema['~standard']['types']>['output'];
63
+ }
@@ -0,0 +1,7 @@
1
+ // The Standard Schema interface, copied from @standard-schema/spec 1.1.0 as its authors intend, so
2
+ // any conforming library works without a dependency (decision 0018). Only StandardSchemaV1 is
3
+ // copied: the Typed base is folded into it, and the JSON Schema interface is left out.
4
+ //
5
+ // Copyright (c) 2024 Colin McDonnell, Fabian Hiller and Gilles Neuville. MIT licensed:
6
+ // https://github.com/standard-schema/standard-schema/blob/main/LICENSE
7
+ export {};
@@ -0,0 +1,73 @@
1
+ /** An event to append: a JSON value, with its version and tags (decision 0014). */
2
+ export interface NewEvent {
3
+ /** The event itself. Must be a JSON value. */
4
+ readonly event: unknown;
5
+ /** The event's schema version, a positive integer. */
6
+ readonly version: number;
7
+ /** The tags projections follow the event by. No duplicates. */
8
+ readonly tags: readonly string[];
9
+ }
10
+ /** An event as the journal stores it. */
11
+ export interface StoredEvent extends NewEvent {
12
+ /** The event stream it belongs to. */
13
+ readonly persistenceId: string;
14
+ /** Its place in the stream: 1, 2, 3, ... with no gaps. */
15
+ readonly seq: number;
16
+ /**
17
+ * Its place in the whole journal. Offsets increase but may skip numbers. Once a reader has seen
18
+ * offset n, no event with a lower offset can appear later.
19
+ */
20
+ readonly offset: number;
21
+ /** Wall-clock ms from the backend's clock, when it was appended. For people, never for ordering. */
22
+ readonly timestamp: number;
23
+ }
24
+ /** Where events are kept: one stream per persistence id, each guarded by a sequence check. */
25
+ export interface Journal {
26
+ /**
27
+ * Appends events after `expectedSeq`, all or none. Rejects with `JournalConflictError` when the
28
+ * stream's last sequence number isn't `expectedSeq`, and writes nothing. `expectedSeq: 0`
29
+ * creates the stream.
30
+ */
31
+ append(persistenceId: string, expectedSeq: number, events: readonly NewEvent[]): Promise<void>;
32
+ /** The stream's events from `fromSeq` on, in order, at most `limit`. */
33
+ read(persistenceId: string, fromSeq: number, limit: number): Promise<readonly StoredEvent[]>;
34
+ /** Events with `tag`, after `afterOffset`, in offset order, at most `limit`. */
35
+ readByTag(tag: string, afterOffset: number, limit: number): Promise<readonly StoredEvent[]>;
36
+ }
37
+ /** A snapshot to save. The backend stamps its timestamp from its own clock (decision 0015). */
38
+ export interface NewSnapshot {
39
+ /** The sequence number of the last event the state includes. */
40
+ readonly seq: number;
41
+ /** The snapshot's schema version, a positive integer. */
42
+ readonly version: number;
43
+ /** The actor's state. Must be a JSON value. */
44
+ readonly state: unknown;
45
+ }
46
+ /** A snapshot as the store keeps it. */
47
+ export interface Snapshot extends NewSnapshot {
48
+ /** Wall-clock ms from the backend's clock, when it was saved. */
49
+ readonly timestamp: number;
50
+ }
51
+ /** Keeps the latest snapshot of each persistence id. */
52
+ export interface SnapshotStore {
53
+ /** Saves a snapshot. Ignored if the stored one has a higher `seq`. */
54
+ save(persistenceId: string, snapshot: NewSnapshot): Promise<void>;
55
+ /** The latest snapshot, if there is one. */
56
+ load(persistenceId: string): Promise<Snapshot | undefined>;
57
+ }
58
+ /** Keeps how far each projection has read. */
59
+ export interface OffsetStore {
60
+ /** The stored offset for a projection, 0 if none. */
61
+ load(name: string): Promise<number>;
62
+ /** Stores a projection's offset, replacing the one before. */
63
+ save(name: string, offset: number): Promise<void>;
64
+ }
65
+ /** One backend's stores. */
66
+ export interface Persistence {
67
+ /** Where events are kept. */
68
+ readonly journal: Journal;
69
+ /** Where snapshots are kept. Needed for snapshotting. */
70
+ readonly snapshots?: SnapshotStore;
71
+ /** Where projection offsets are kept. Needed for projections. */
72
+ readonly offsets?: OffsetStore;
73
+ }
@@ -0,0 +1,3 @@
1
+ // The storage interfaces every persistence backend implements. They're promise-based and know
2
+ // nothing about Node, so any runtime, and milestone 5's simulated journal, can implement them.
3
+ export {};
@@ -0,0 +1,11 @@
1
+ /**
2
+ * A FIFO queue with O(1) push and shift. `Array.prototype.shift` is O(n), which adds up for
3
+ * mailboxes that hold thousands of messages.
4
+ */
5
+ export declare class Queue<T> {
6
+ #private;
7
+ get size(): number;
8
+ push(item: T): void;
9
+ /** Removes and returns the oldest item, or `undefined` if the queue is empty. */
10
+ shift(): T | undefined;
11
+ }
package/dist/queue.js ADDED
@@ -0,0 +1,31 @@
1
+ /**
2
+ * A FIFO queue with O(1) push and shift. `Array.prototype.shift` is O(n), which adds up for
3
+ * mailboxes that hold thousands of messages.
4
+ */
5
+ export class Queue {
6
+ #items = [];
7
+ #head = 0;
8
+ get size() {
9
+ return this.#items.length - this.#head;
10
+ }
11
+ push(item) {
12
+ this.#items.push(item);
13
+ }
14
+ /** Removes and returns the oldest item, or `undefined` if the queue is empty. */
15
+ shift() {
16
+ if (this.#head === this.#items.length)
17
+ return undefined;
18
+ const item = this.#items[this.#head];
19
+ this.#head++;
20
+ if (this.#head === this.#items.length) {
21
+ this.#items = [];
22
+ this.#head = 0;
23
+ }
24
+ else if (this.#head > 1024 && this.#head * 2 > this.#items.length) {
25
+ // Reclaim the consumed prefix once it dominates the array.
26
+ this.#items = this.#items.slice(this.#head);
27
+ this.#head = 0;
28
+ }
29
+ return item;
30
+ }
31
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * The only way the core reads time or schedules work (decision 0003). Pass one to
3
+ * `createActorSystem` to control time, as the testkit's `ManualScheduler` does.
4
+ */
5
+ export interface Scheduler {
6
+ /** The current time in milliseconds. Only differences between readings matter. */
7
+ now(): number;
8
+ /** Runs `task` soon, after the current task finishes. Tasks run in the order they were queued. */
9
+ runSoon(task: () => void): void;
10
+ /**
11
+ * Runs `task` once, after at least `delayMs` milliseconds.
12
+ * @returns A function that cancels the timer. Calling it again, or after the timer ran, does
13
+ * nothing.
14
+ */
15
+ setTimer(task: () => void, delayMs: number): () => void;
16
+ }
17
+ /**
18
+ * A scheduler on the host's real clock and event loop: `performance.now()`, which is monotonic,
19
+ * rounded down to whole milliseconds, `queueMicrotask`, and `setTimeout`. It works on any
20
+ * JavaScript runtime (decision 0004).
21
+ *
22
+ * Its timers aren't `unref()`'d, which is Node-only, so pending timers keep a Node process alive.
23
+ */
24
+ export declare function realScheduler(): Scheduler;
@@ -0,0 +1,23 @@
1
+ /**
2
+ * A scheduler on the host's real clock and event loop: `performance.now()`, which is monotonic,
3
+ * rounded down to whole milliseconds, `queueMicrotask`, and `setTimeout`. It works on any
4
+ * JavaScript runtime (decision 0004).
5
+ *
6
+ * Its timers aren't `unref()`'d, which is Node-only, so pending timers keep a Node process alive.
7
+ */
8
+ export function realScheduler() {
9
+ return {
10
+ // Whole milliseconds, as on virtual time, so an event's `at` and a `processed` event's
11
+ // `durationMs` are integers whichever clock runs. Rounding down keeps it monotonic.
12
+ now: () => Math.floor(performance.now()),
13
+ runSoon: (task) => {
14
+ queueMicrotask(task);
15
+ },
16
+ setTimer: (task, delayMs) => {
17
+ const handle = setTimeout(task, delayMs);
18
+ return () => {
19
+ clearTimeout(handle);
20
+ };
21
+ },
22
+ };
23
+ }
@@ -0,0 +1,91 @@
1
+ /**
2
+ * What happens to an actor when it fails. The parent picks it when it spawns the child
3
+ * (decision 0006). Build one with {@link supervise}.
4
+ */
5
+ export type SupervisorStrategy = {
6
+ readonly type: 'stop';
7
+ } | {
8
+ readonly type: 'resume';
9
+ } | {
10
+ readonly type: 'restart';
11
+ readonly maxRestarts: number;
12
+ readonly withinMs: number;
13
+ } | {
14
+ readonly type: 'backoff';
15
+ readonly minMs: number;
16
+ readonly maxMs: number;
17
+ readonly randomFactor: number;
18
+ readonly resetAfterMs: number;
19
+ };
20
+ /** Builds supervisor strategies. Each one checks its options and throws `TypeError` for bad ones. */
21
+ export declare const supervise: Readonly<{
22
+ /** Stop the actor, with `failure` set on `terminated` and on the `stopped` event. The default. */
23
+ stop(): SupervisorStrategy;
24
+ /** Keep the actor's state, drop the message that failed, and carry on with the next one. */
25
+ resume(): SupervisorStrategy;
26
+ /**
27
+ * Run `preRestart`, stop the children, and run `initial` again. The mailbox, the ref and the
28
+ * actor's watchers carry over.
29
+ * @param opts.maxRestarts The most restarts within `withinMs`. One more failure stops the
30
+ * actor. Default `Infinity`.
31
+ * @param opts.withinMs The rolling window that `maxRestarts` counts over, in ms. Default
32
+ * `Infinity`.
33
+ */
34
+ restart(opts?: {
35
+ maxRestarts?: number;
36
+ withinMs?: number;
37
+ }): SupervisorStrategy;
38
+ /**
39
+ * Restart, as {@link supervise.restart} does, but wait first. Restart number `n`, counting from
40
+ * 0, waits `min(maxMs, minMs * 2^n) * (1 + random() * randomFactor)` ms, rounded. `n` goes back
41
+ * to 0 once the actor has run for `resetAfterMs` without failing.
42
+ * @param opts.randomFactor Jitter, so actors that failed together don't restart together.
43
+ * Default 0.2.
44
+ * @param opts.resetAfterMs Default `maxMs`.
45
+ */
46
+ restartWithBackoff(opts: {
47
+ minMs: number;
48
+ maxMs: number;
49
+ randomFactor?: number;
50
+ resetAfterMs?: number;
51
+ }): SupervisorStrategy;
52
+ }>;
53
+ /** Checks a strategy, including one built by hand rather than by {@link supervise}. */
54
+ export declare function checkStrategy(value: unknown, where: string): asserts value is SupervisorStrategy;
55
+ /** What an actor's failures so far mean for the next one. Owned by its cell. */
56
+ export interface RestartHistory {
57
+ /** Failure times inside the window, for `restart` with a finite `withinMs`. */
58
+ readonly times: readonly number[];
59
+ /** Failures counted, for `restart` with an infinite window. */
60
+ readonly count: number;
61
+ /** Backoff restarts since the last reset: `n` in the formula. */
62
+ readonly backoffs: number;
63
+ }
64
+ /** A history with no failures in it. */
65
+ export declare const NO_FAILURES: RestartHistory;
66
+ /** What supervision does about one failure. */
67
+ export type Decision = {
68
+ readonly directive: 'stop' | 'resume';
69
+ } | {
70
+ readonly directive: 'restart';
71
+ readonly attempt: number;
72
+ readonly delayMs: number;
73
+ };
74
+ /** The facts about one failure that a strategy decides on. */
75
+ export interface FailureFacts {
76
+ readonly now: number;
77
+ /** When the current incarnation ran `initial`. */
78
+ readonly startedAt: number;
79
+ /** True if `initial` failed, so there's no state to resume with. */
80
+ readonly inInitial: boolean;
81
+ readonly random: () => number;
82
+ }
83
+ /**
84
+ * Decides what to do about a failure, and returns the history to keep for the next one. Pure,
85
+ * apart from drawing from `random`, and only for backoff. Limits and resets are worked out from
86
+ * failure times when a failure happens, so no timer is needed to track them.
87
+ */
88
+ export declare function decide(strategy: SupervisorStrategy, history: RestartHistory, facts: FailureFacts): {
89
+ decision: Decision;
90
+ history: RestartHistory;
91
+ };