@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,183 @@
1
+ import { DatabaseSync } from 'node:sqlite';
2
+ import { checkKeys } from '../../checks.js';
3
+ import { checkAppend, checkId, checkOffsetSave, checkRead, checkReadByTag, serializeSnapshot, wallClock, } from '../../persistence/backend.js';
4
+ import { JournalConflictError } from '../../persistence/errors.js';
5
+ import { SQLITE_SCHEMA } from './schema.js';
6
+ const OPTIONS = new Set(['path', 'clock']);
7
+ // How long an append waits for another connection's write lock before it fails. node:sqlite is
8
+ // synchronous, so the wait blocks this thread.
9
+ const BUSY_TIMEOUT_MS = 5_000;
10
+ // SQLITE_CONSTRAINT_UNIQUE, the extended result code node:sqlite reports as `errcode`.
11
+ const UNIQUE_VIOLATION = 2067;
12
+ const EVENT_COLUMNS = 'e.persistence_id, e.seq, e.global_offset, e.timestamp, e.version, e.tags, e.event';
13
+ /**
14
+ * A backend on SQLite, through Node's built-in `node:sqlite`, so it adds no dependency. Node only.
15
+ *
16
+ * File databases use WAL mode. An append runs in a `BEGIN IMMEDIATE` transaction, which takes the
17
+ * database's write lock before it checks the stream's last sequence number, so two connections,
18
+ * in one process or several, can't both win. The loser rejects with `JournalConflictError`.
19
+ *
20
+ * `node:sqlite` is synchronous: each call does its work before it returns its promise, and an
21
+ * append waits up to 5 s, blocking the thread, for another connection's write lock. On Node 22,
22
+ * the first load prints an experimental warning. Node 24 and later don't.
23
+ *
24
+ * @param opts.path A database file, created if it's missing, or `":memory:"`.
25
+ * @param opts.clock The wall clock for timestamps, in integer ms. Defaults to `Date.now`.
26
+ */
27
+ export function sqlitePersistence(opts) {
28
+ checkKeys(opts, OPTIONS, 'sqlitePersistence');
29
+ // The default wall clock for timestamps, which never order anything (decision 0015).
30
+ // eslint-disable-next-line no-restricted-properties
31
+ const { path, clock = Date.now } = opts;
32
+ checkId(path, 'sqlitePersistence: path');
33
+ const now = wallClock(clock, 'sqlitePersistence');
34
+ const db = new DatabaseSync(path);
35
+ try {
36
+ db.exec(`PRAGMA busy_timeout = ${String(BUSY_TIMEOUT_MS)}`);
37
+ // A no-op for ":memory:", which has no file to log to.
38
+ db.exec('PRAGMA journal_mode = WAL');
39
+ db.exec(SQLITE_SCHEMA);
40
+ }
41
+ catch (error) {
42
+ db.close();
43
+ throw error;
44
+ }
45
+ let open = true;
46
+ /**
47
+ * Runs synchronous `work` and settles a promise with its result, so a throw, from a check or
48
+ * from SQLite, becomes a rejection, as the store interfaces promise. After `close()`, it rejects
49
+ * with one message on every Node version, rather than whatever node:sqlite says.
50
+ */
51
+ function attempt(work) {
52
+ return new Promise((resolve) => {
53
+ if (!open)
54
+ throw new Error('sqlitePersistence: the database is closed');
55
+ resolve(work());
56
+ });
57
+ }
58
+ const lastSeq = db.prepare('SELECT COALESCE(MAX(seq), 0) AS seq FROM troupe_events WHERE persistence_id = ?');
59
+ const insertEvent = db.prepare('INSERT INTO troupe_events (persistence_id, seq, version, timestamp, event, tags) ' +
60
+ 'VALUES (?, ?, ?, ?, ?, ?) RETURNING global_offset');
61
+ const insertTag = db.prepare('INSERT INTO troupe_event_tags (tag, global_offset) VALUES (?, ?)');
62
+ const readStream = db.prepare(`SELECT ${EVENT_COLUMNS} FROM troupe_events e ` +
63
+ 'WHERE e.persistence_id = ? AND e.seq >= ? ORDER BY e.seq LIMIT ?');
64
+ const readTag = db.prepare(`SELECT ${EVENT_COLUMNS} FROM troupe_event_tags t ` +
65
+ 'JOIN troupe_events e ON e.global_offset = t.global_offset ' +
66
+ 'WHERE t.tag = ? AND t.global_offset > ? ORDER BY t.global_offset LIMIT ?');
67
+ // Saves don't hold the mailbox, so an older one can land after a newer one: keep the higher seq.
68
+ const saveSnapshot = db.prepare('INSERT INTO troupe_snapshots (persistence_id, seq, version, timestamp, state) ' +
69
+ 'VALUES (?, ?, ?, ?, ?) ON CONFLICT (persistence_id) DO UPDATE SET ' +
70
+ 'seq = excluded.seq, version = excluded.version, timestamp = excluded.timestamp, ' +
71
+ 'state = excluded.state WHERE excluded.seq >= troupe_snapshots.seq');
72
+ const loadSnapshot = db.prepare('SELECT seq, version, timestamp, state FROM troupe_snapshots WHERE persistence_id = ?');
73
+ const loadOffset = db.prepare('SELECT global_offset FROM troupe_offsets WHERE name = ?');
74
+ const saveOffset = db.prepare('INSERT INTO troupe_offsets (name, global_offset) VALUES (?, ?) ' +
75
+ 'ON CONFLICT (name) DO UPDATE SET global_offset = excluded.global_offset');
76
+ /** Runs `work` in a transaction that holds the write lock from its start. */
77
+ function writeTransaction(work) {
78
+ db.exec('BEGIN IMMEDIATE');
79
+ try {
80
+ work();
81
+ db.exec('COMMIT');
82
+ }
83
+ catch (error) {
84
+ db.exec('ROLLBACK');
85
+ throw error;
86
+ }
87
+ }
88
+ const journal = {
89
+ append: (persistenceId, expectedSeq, events) => attempt(() => {
90
+ // Check and serialize the whole batch before the transaction, so it's all or none.
91
+ const batch = checkAppend(persistenceId, expectedSeq, events);
92
+ try {
93
+ writeTransaction(() => {
94
+ // The check runs under the write lock, so no other writer can append between it and
95
+ // the inserts. This also rejects an expectedSeq ahead of the stream.
96
+ const { seq } = lastSeq.get(persistenceId);
97
+ if (seq !== expectedSeq)
98
+ throw new JournalConflictError(persistenceId, expectedSeq);
99
+ if (batch.length === 0)
100
+ return;
101
+ const timestamp = now();
102
+ batch.forEach(({ version, tags, json }, i) => {
103
+ const { global_offset } = insertEvent.get(persistenceId, expectedSeq + i + 1, version, timestamp, json, JSON.stringify(tags));
104
+ for (const tag of tags)
105
+ insertTag.run(tag, global_offset);
106
+ });
107
+ });
108
+ }
109
+ catch (error) {
110
+ // The lock check settles every race, so this is a backstop: the unique key on
111
+ // (persistence_id, seq) still says the stream already has that event.
112
+ if (isUniqueViolation(error))
113
+ throw new JournalConflictError(persistenceId, expectedSeq);
114
+ throw error;
115
+ }
116
+ }),
117
+ read: (persistenceId, fromSeq, limit) => attempt(() => {
118
+ checkRead(persistenceId, fromSeq, limit);
119
+ return readStream.all(persistenceId, fromSeq, limit).map(toStored);
120
+ }),
121
+ readByTag: (tag, afterOffset, limit) => attempt(() => {
122
+ checkReadByTag(tag, afterOffset, limit);
123
+ return readTag.all(tag, afterOffset, limit).map(toStored);
124
+ }),
125
+ };
126
+ const snapshots = {
127
+ save: (persistenceId, snapshot) => attempt(() => {
128
+ const { seq, version, json } = serializeSnapshot(persistenceId, snapshot);
129
+ saveSnapshot.run(persistenceId, seq, version, now(), json);
130
+ }),
131
+ load: (persistenceId) => attempt(() => {
132
+ checkId(persistenceId, 'snapshots.load: persistenceId');
133
+ const row = loadSnapshot.get(persistenceId);
134
+ if (row === undefined)
135
+ return undefined;
136
+ const loaded = {
137
+ seq: row.seq,
138
+ version: row.version,
139
+ state: JSON.parse(row.state),
140
+ timestamp: row.timestamp,
141
+ };
142
+ return loaded;
143
+ }),
144
+ };
145
+ const offsets = {
146
+ load: (name) => attempt(() => {
147
+ checkId(name, 'offsets.load: name');
148
+ const row = loadOffset.get(name);
149
+ return row?.global_offset ?? 0;
150
+ }),
151
+ save: (name, offset) => attempt(() => {
152
+ checkOffsetSave(name, offset);
153
+ saveOffset.run(name, offset);
154
+ }),
155
+ };
156
+ return {
157
+ journal,
158
+ snapshots,
159
+ offsets,
160
+ close() {
161
+ if (!open)
162
+ return;
163
+ open = false;
164
+ db.close();
165
+ },
166
+ };
167
+ }
168
+ function isUniqueViolation(error) {
169
+ return (typeof error === 'object' &&
170
+ error !== null &&
171
+ error.errcode === UNIQUE_VIOLATION);
172
+ }
173
+ function toStored(row) {
174
+ return {
175
+ persistenceId: row.persistence_id,
176
+ seq: row.seq,
177
+ offset: row.global_offset,
178
+ timestamp: row.timestamp,
179
+ version: row.version,
180
+ tags: JSON.parse(row.tags),
181
+ event: JSON.parse(row.event),
182
+ };
183
+ }
@@ -0,0 +1,158 @@
1
+ import type { ActorContext, ActorDef, ActorRef, Signal } from '../types.js';
2
+ import type { StandardSchemaV1 } from './standard-schema.js';
3
+ import type { Persistence } from './types.js';
4
+ /** A lifecycle signal for a persistent actor: the actor signals, plus the end of recovery. */
5
+ export type PersistentSignal = Signal
6
+ /**
7
+ * Recovery has finished at sequence number `seq`, and commands are about to run. The place to
8
+ * start the timers the state implies, since timers don't survive a restart.
9
+ */
10
+ | {
11
+ readonly type: 'recoveryCompleted';
12
+ readonly seq: number;
13
+ };
14
+ /** What a persistent actor's cell holds: plain data, so milestone 3's inspector can show it. */
15
+ export interface PersistentState<S> {
16
+ /** The sequence number of the last event applied, 0 before any. */
17
+ readonly seq: number;
18
+ /** The state the events have folded to. */
19
+ readonly state: S;
20
+ }
21
+ /**
22
+ * An immutable value describing what a command does: the events to persist, then the steps to run
23
+ * once they're applied. Make one with `ctx.persist`, `ctx.reply` or `ctx.none`. Each method returns
24
+ * a new effect.
25
+ */
26
+ export interface Effect<E, S> {
27
+ /** The events this effect persists, in order. Empty when it persists nothing. */
28
+ readonly events: readonly E[];
29
+ /**
30
+ * After the events are applied, tells `to` the message built from the new state.
31
+ * @throws TypeError unless `to` is a ref and `message` a function.
32
+ */
33
+ thenReply<R>(to: ActorRef<R>, message: (state: S) => NoInfer<R>): Effect<E, S>;
34
+ /**
35
+ * After the events are applied, runs `fn` with the new state. For side effects only.
36
+ * @throws TypeError unless `fn` is a function.
37
+ */
38
+ thenRun(fn: (state: S) => void): Effect<E, S>;
39
+ /**
40
+ * Stops the actor once the events are written. Like `ctx.stop()`, it takes effect after the
41
+ * current command, so steps chained after it still run.
42
+ */
43
+ thenStop(): Effect<E, S>;
44
+ }
45
+ /**
46
+ * What a persistent actor can see and do while it runs: its `ActorContext`, plus its place in the
47
+ * journal and the builders for effects. The builders are arrow properties, so they destructure
48
+ * safely.
49
+ */
50
+ export interface PersistentContext<C, E, S> extends ActorContext<C> {
51
+ /** The event stream's id in the journal. */
52
+ readonly persistenceId: string;
53
+ /** The sequence number of the last event applied, 0 before any. */
54
+ readonly lastSeq: number;
55
+ /** Persists these events, in order, then applies them. With no events, it's `none()`. */
56
+ readonly persist: (...events: E[]) => Effect<E, S>;
57
+ /**
58
+ * Persists nothing, and tells `to` the message at once.
59
+ * @throws TypeError unless `to` is a ref.
60
+ */
61
+ readonly reply: <R>(to: ActorRef<R>, message: NoInfer<R>) => Effect<E, S>;
62
+ /** Persists nothing. */
63
+ readonly none: () => Effect<E, S>;
64
+ }
65
+ /**
66
+ * Runtime checks and versions for a persistent actor's events (decision 0018). Every event is
67
+ * stored as `persist` got it, with `version`. The schema checks it before the append, and again on
68
+ * recovery after the upcasters, and `onEvent` gets the schema's output both times.
69
+ */
70
+ export interface EventOptions<E> {
71
+ /**
72
+ * Checks events on write, before the append, and on recovery, after upcasting. Any Standard
73
+ * Schema library works, sync or async. A failure is `EventValidationError`, with the issues.
74
+ */
75
+ schema?: StandardSchemaV1<unknown, E>;
76
+ /** The current event version, a positive integer, stored with every new event. Default 1. */
77
+ version?: number;
78
+ /**
79
+ * One function per old version, keyed by the version it upgrades from: `upcasters[n]` turns a
80
+ * version-n event into a version-(n + 1) one. They must cover every version from 1 to
81
+ * `version - 1`, and nothing else. A stored event runs through each of them from its own
82
+ * version up, then through the schema.
83
+ */
84
+ upcasters?: Readonly<Record<number, (event: unknown) => unknown>>;
85
+ }
86
+ /** A persistent actor: a command handler, an event handler and an initial state. */
87
+ export interface PersistentActorDef<C, E, S> {
88
+ /** The event stream's id in the journal: a non-empty string of at most 255 characters. */
89
+ id: string;
90
+ /** Where events are kept. */
91
+ persistence: Persistence;
92
+ /** The state before any event. */
93
+ initial: S;
94
+ /**
95
+ * Decides what a command does. Synchronous, and returns an effect from `ctx`: it can't change the
96
+ * state, only persist events that `onEvent` applies (decision 0012).
97
+ */
98
+ onCommand(state: S, command: C, ctx: PersistentContext<C, E, S>): Effect<E, S>;
99
+ /**
100
+ * Applies one event. Pure: it runs again for every event on every recovery, so it must not throw
101
+ * for any event it has accepted before.
102
+ */
103
+ onEvent(state: S, event: E): S;
104
+ /** Lifecycle signals, for side effects only. Optional. */
105
+ onSignal?(state: S, signal: PersistentSignal, ctx: PersistentContext<C, E, S>): void;
106
+ /**
107
+ * The tags to store with an event, for projections to follow it by. Optional. It gets the
108
+ * schema's output, as `onEvent` does. Each tag matches the actor name pattern: 1 to 64 letters,
109
+ * digits, ".", "_", "~" or "-", starting with a letter or digit, and an event's tags don't
110
+ * repeat. A tag that breaks these rules fails the command with a `TypeError`, and nothing is
111
+ * written.
112
+ */
113
+ tags?(event: E): readonly string[];
114
+ /** Runtime checks and versions for events. Optional. */
115
+ events?: EventOptions<E>;
116
+ /**
117
+ * Snapshotting, so recovery doesn't replay the whole stream. Optional, and needs
118
+ * `persistence.snapshots`. A snapshot is only a shortcut: events are never deleted after one, and
119
+ * recovery replays every event when it can't use it.
120
+ */
121
+ snapshots?: {
122
+ /**
123
+ * Saves a snapshot after any persist that takes `lastSeq` across a multiple of `every`, at the
124
+ * new `lastSeq`. A positive integer.
125
+ */
126
+ every: number;
127
+ /**
128
+ * The state's schema version, a positive integer. Default 1. Recovery ignores a snapshot with
129
+ * another version, so bump it whenever the state's shape changes.
130
+ */
131
+ version?: number;
132
+ };
133
+ }
134
+ /**
135
+ * Defines an event-sourced actor. Commands go to `onCommand`, which returns an effect. Its events
136
+ * are appended to the journal before they're applied with `onEvent`, and before any reply. On start
137
+ * and on every restart, the actor recovers its state by replaying its events, and commands wait in
138
+ * the mailbox until it's done (decision 0011).
139
+ *
140
+ * The result is an ordinary `ActorDef`: spawn, name and supervise it like any other actor. Every
141
+ * append says which sequence number it follows, so a second writer to the same `id` fails with
142
+ * `JournalConflictError` instead of corrupting the stream (decision 0013).
143
+ *
144
+ * @example
145
+ * const account = (id: string) =>
146
+ * persistentActor<AccountCmd, AccountEvent, Account>({
147
+ * id: `account-${id}`,
148
+ * persistence,
149
+ * initial: { balance: 0 },
150
+ * onCommand: (state, cmd, { persist, reply }) =>
151
+ * cmd.type === 'deposit'
152
+ * ? persist({ type: 'deposited', amount: cmd.amount }).thenReply(cmd.replyTo, (s) => s.balance)
153
+ * : reply(cmd.replyTo, state.balance),
154
+ * onEvent: (state, event) => ({ balance: state.balance + event.amount }),
155
+ * });
156
+ * @throws TypeError for a definition that can't be used, unknown fields included.
157
+ */
158
+ export declare function persistentActor<C, E, S>(def: PersistentActorDef<C, E, S>): ActorDef<C, PersistentState<S>>;