@kylewillett/troupe 0.0.0-stage → 0.1.1

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 +40 -0
  2. package/LICENSE +21 -0
  3. package/README.md +380 -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 +112 -4
@@ -0,0 +1,82 @@
1
+ /**
2
+ * The reason `Journal.append` rejects when the stream's last sequence number isn't the expected
3
+ * one: another writer got there first (decision 0013). Nothing was written. Backends throw it.
4
+ */
5
+ export class JournalConflictError extends Error {
6
+ /** Always `"JournalConflictError"`, so the error can be recognized without `instanceof`. */
7
+ name = 'JournalConflictError';
8
+ /** The stream the append was for. */
9
+ persistenceId;
10
+ /** The sequence number the append expected to follow. */
11
+ expectedSeq;
12
+ /** Creates the error for an append to `persistenceId` at `expectedSeq`. */
13
+ constructor(persistenceId, expectedSeq) {
14
+ super(`append to "${persistenceId}" expected sequence number ${String(expectedSeq)}, ` +
15
+ 'but another writer appended first');
16
+ this.persistenceId = persistenceId;
17
+ this.expectedSeq = expectedSeq;
18
+ }
19
+ }
20
+ /** The reason recovery fails when a backend returns an event out of sequence. */
21
+ export class JournalSequenceError extends Error {
22
+ /** Always `"JournalSequenceError"`, so the error can be recognized without `instanceof`. */
23
+ name = 'JournalSequenceError';
24
+ /** The stream being read. */
25
+ persistenceId;
26
+ /** The sequence number that should have come next. */
27
+ expected;
28
+ /** The sequence number that came instead. */
29
+ got;
30
+ /** Creates the error for a read of `persistenceId` that got `got` where `expected` was due. */
31
+ constructor(persistenceId, expected, got) {
32
+ super(`read of "${persistenceId}" expected sequence number ${String(expected)}, got ${String(got)}`);
33
+ this.persistenceId = persistenceId;
34
+ this.expected = expected;
35
+ this.got = got;
36
+ }
37
+ }
38
+ /**
39
+ * The reason a command or a recovery fails when an event doesn't pass its schema. On write it's
40
+ * thrown before the append, so nothing was written. On recovery it names the stored event.
41
+ */
42
+ export class EventValidationError extends Error {
43
+ /** Always `"EventValidationError"`, so the error can be recognized without `instanceof`. */
44
+ name = 'EventValidationError';
45
+ /** The stream the event belongs to. */
46
+ persistenceId;
47
+ /** The stored event's sequence number, on recovery. Undefined on write. */
48
+ seq;
49
+ /** What the schema found wrong, as it reported it. */
50
+ issues;
51
+ /** Creates the error for an event of `persistenceId`, at `seq` when it was read. */
52
+ constructor(persistenceId, seq, issues) {
53
+ const where = seq === undefined ? 'a new event' : `event ${String(seq)}`;
54
+ const first = issues[0]?.message ?? 'no issues reported';
55
+ super(`${where} of "${persistenceId}" failed its schema: ${first}`);
56
+ this.persistenceId = persistenceId;
57
+ this.seq = seq;
58
+ this.issues = issues;
59
+ }
60
+ }
61
+ /**
62
+ * The reason recovery fails when a stored event's version is newer than the actor's. It usually
63
+ * means an older deployment is reading events a newer one wrote.
64
+ */
65
+ export class EventVersionError extends Error {
66
+ /** Always `"EventVersionError"`, so the error can be recognized without `instanceof`. */
67
+ name = 'EventVersionError';
68
+ /** The stream being read. */
69
+ persistenceId;
70
+ /** The stored event's sequence number. */
71
+ seq;
72
+ /** The stored event's version. */
73
+ version;
74
+ /** Creates the error for event `seq` of `persistenceId`, stored at `version`. */
75
+ constructor(persistenceId, seq, version, current) {
76
+ super(`event ${String(seq)} of "${persistenceId}" has version ${String(version)}, ` +
77
+ `newer than this actor's ${String(current)}`);
78
+ this.persistenceId = persistenceId;
79
+ this.seq = seq;
80
+ this.version = version;
81
+ }
82
+ }
@@ -0,0 +1,6 @@
1
+ export { persistentActor, type Effect, type EventOptions, type PersistentActorDef, type PersistentContext, type PersistentSignal, type PersistentState, } from './actor.js';
2
+ export { EventValidationError, EventVersionError, JournalConflictError, JournalSequenceError, } from './errors.js';
3
+ export { inMemoryPersistence, type InMemoryPersistence } from './memory.js';
4
+ export { projection, type ProjectionOptions, type ProjectionState } from './projection.js';
5
+ export type { StandardSchemaV1 } from './standard-schema.js';
6
+ export type { Journal, NewEvent, NewSnapshot, OffsetStore, Persistence, Snapshot, SnapshotStore, StoredEvent, } from './types.js';
@@ -0,0 +1,5 @@
1
+ // The /persistence entry point: runs on any JavaScript runtime. Export only from here.
2
+ export { persistentActor, } from './actor.js';
3
+ export { EventValidationError, EventVersionError, JournalConflictError, JournalSequenceError, } from './errors.js';
4
+ export { inMemoryPersistence } from './memory.js';
5
+ export { projection } from './projection.js';
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Where `value` stops being a JSON value, as a path such as `$.items[2]` with the reason, or
3
+ * `undefined` if it is one.
4
+ */
5
+ export declare function jsonProblem(value: unknown): string | undefined;
6
+ /** Whether `value` is a JSON value: what `JSON.parse` could have produced. */
7
+ export declare function isJsonValue(value: unknown): boolean;
@@ -0,0 +1,75 @@
1
+ // Events and snapshot states are JSON values (decision 0014): what every backend can store and give
2
+ // back deep-equal. These checks run before anything is written, so a value that JSON would quietly
3
+ // change, such as `undefined` or a `Date`, fails where it's produced instead of on recovery.
4
+ /**
5
+ * Where `value` stops being a JSON value, as a path such as `$.items[2]` with the reason, or
6
+ * `undefined` if it is one.
7
+ */
8
+ export function jsonProblem(value) {
9
+ return problemAt(value, '$', new Set());
10
+ }
11
+ /** Whether `value` is a JSON value: what `JSON.parse` could have produced. */
12
+ export function isJsonValue(value) {
13
+ return jsonProblem(value) === undefined;
14
+ }
15
+ function problemAt(value, path, ancestors) {
16
+ switch (typeof value) {
17
+ case 'string':
18
+ case 'boolean':
19
+ return undefined;
20
+ case 'number':
21
+ // -0 passes, as JSON.parse('-0') gives it, though it comes back as 0.
22
+ return Number.isFinite(value) ? undefined : `${path} is ${String(value)}`;
23
+ case 'object':
24
+ if (value === null)
25
+ return undefined;
26
+ return objectProblem(value, path, ancestors);
27
+ case 'undefined':
28
+ return `${path} is undefined`;
29
+ default:
30
+ return `${path} is a ${typeof value}`;
31
+ }
32
+ }
33
+ function objectProblem(value, path, ancestors) {
34
+ if (ancestors.has(value))
35
+ return `${path} is a cycle`;
36
+ if (Object.getOwnPropertySymbols(value).length > 0)
37
+ return `${path} has symbol keys`;
38
+ ancestors.add(value);
39
+ try {
40
+ if (Array.isArray(value))
41
+ return arrayProblem(value, path, ancestors);
42
+ const proto = Object.getPrototypeOf(value);
43
+ if (proto !== Object.prototype && proto !== null) {
44
+ return `${path} is not a plain object (${constructorName(value)})`;
45
+ }
46
+ for (const [key, item] of Object.entries(value)) {
47
+ const problem = problemAt(item, `${path}${keyPath(key)}`, ancestors);
48
+ if (problem !== undefined)
49
+ return problem;
50
+ }
51
+ return undefined;
52
+ }
53
+ finally {
54
+ ancestors.delete(value);
55
+ }
56
+ }
57
+ function arrayProblem(value, path, ancestors) {
58
+ for (let i = 0; i < value.length; i++) {
59
+ // A hole would come back as null.
60
+ if (!(i in value))
61
+ return `${path}[${String(i)}] is a hole`;
62
+ const problem = problemAt(value[i], `${path}[${String(i)}]`, ancestors);
63
+ if (problem !== undefined)
64
+ return problem;
65
+ }
66
+ return undefined;
67
+ }
68
+ function constructorName(value) {
69
+ const ctor = value.constructor;
70
+ return typeof ctor === 'function' && ctor.name !== '' ? ctor.name : 'an anonymous class';
71
+ }
72
+ const IDENTIFIER = /^[A-Za-z_$][\w$]*$/;
73
+ function keyPath(key) {
74
+ return IDENTIFIER.test(key) ? `.${key}` : `[${JSON.stringify(key)}]`;
75
+ }
@@ -0,0 +1,18 @@
1
+ import type { Persistence, StoredEvent } from './types.js';
2
+ /** The in-memory backend's stores, plus a view of every event for tests and the inspector. */
3
+ export interface InMemoryPersistence extends Required<Persistence> {
4
+ /** Every stored event, in offset order, or only `persistenceId`'s when it's given. */
5
+ events(persistenceId?: string): readonly StoredEvent[];
6
+ }
7
+ /**
8
+ * A backend that keeps everything in memory, for tests, demos and the browser. It works on any
9
+ * JavaScript runtime. Every call resolves on a microtask, and nothing waits on time.
10
+ *
11
+ * Events and snapshot states round-trip through JSON, as on the SQL backends, so a test on this
12
+ * backend sees what Postgres would give back.
13
+ *
14
+ * @param opts.clock The wall clock for timestamps, in integer ms. Defaults to `Date.now`.
15
+ */
16
+ export declare function inMemoryPersistence(opts?: {
17
+ clock?: () => number;
18
+ }): InMemoryPersistence;
@@ -0,0 +1,143 @@
1
+ import { checkKeys } from '../checks.js';
2
+ import { checkAppend, checkId, checkOffsetSave, checkRead, checkReadByTag, serializeSnapshot, wallClock, } from './backend.js';
3
+ import { JournalConflictError } from './errors.js';
4
+ const OPTIONS = new Set(['clock']);
5
+ /**
6
+ * A backend that keeps everything in memory, for tests, demos and the browser. It works on any
7
+ * JavaScript runtime. Every call resolves on a microtask, and nothing waits on time.
8
+ *
9
+ * Events and snapshot states round-trip through JSON, as on the SQL backends, so a test on this
10
+ * backend sees what Postgres would give back.
11
+ *
12
+ * @param opts.clock The wall clock for timestamps, in integer ms. Defaults to `Date.now`.
13
+ */
14
+ export function inMemoryPersistence(opts = {}) {
15
+ checkKeys(opts, OPTIONS, 'inMemoryPersistence');
16
+ // The default wall clock for timestamps, which never order anything (decision 0015).
17
+ // eslint-disable-next-line no-restricted-properties
18
+ const { clock = Date.now } = opts;
19
+ const now = wallClock(clock, 'inMemoryPersistence');
20
+ const all = [];
21
+ const streams = new Map();
22
+ const byTag = new Map();
23
+ const snapshots = new Map();
24
+ const offsets = new Map();
25
+ let lastOffset = 0;
26
+ const journal = {
27
+ async append(persistenceId, expectedSeq, events) {
28
+ // Check and serialize the whole batch before touching the stream, so it's all or none.
29
+ const batch = checkAppend(persistenceId, expectedSeq, events);
30
+ await Promise.resolve();
31
+ const stream = streams.get(persistenceId) ?? [];
32
+ if (stream.length !== expectedSeq) {
33
+ throw new JournalConflictError(persistenceId, expectedSeq);
34
+ }
35
+ if (batch.length === 0)
36
+ return;
37
+ const timestamp = now();
38
+ for (const { version, tags, json } of batch) {
39
+ const row = {
40
+ persistenceId,
41
+ seq: stream.length + 1,
42
+ offset: ++lastOffset,
43
+ timestamp,
44
+ version,
45
+ tags,
46
+ json,
47
+ };
48
+ stream.push(row);
49
+ all.push(row);
50
+ for (const tag of tags) {
51
+ const rows = byTag.get(tag);
52
+ if (rows === undefined)
53
+ byTag.set(tag, [row]);
54
+ else
55
+ rows.push(row);
56
+ }
57
+ }
58
+ streams.set(persistenceId, stream);
59
+ },
60
+ async read(persistenceId, fromSeq, limit) {
61
+ checkRead(persistenceId, fromSeq, limit);
62
+ await Promise.resolve();
63
+ const stream = streams.get(persistenceId) ?? [];
64
+ return stream.slice(fromSeq - 1, fromSeq - 1 + limit).map(toStored);
65
+ },
66
+ async readByTag(tag, afterOffset, limit) {
67
+ checkReadByTag(tag, afterOffset, limit);
68
+ await Promise.resolve();
69
+ const rows = byTag.get(tag) ?? [];
70
+ const start = firstAfter(rows, afterOffset);
71
+ return rows.slice(start, start + limit).map(toStored);
72
+ },
73
+ };
74
+ const snapshotStore = {
75
+ async save(persistenceId, snapshot) {
76
+ const { seq, version, json } = serializeSnapshot(persistenceId, snapshot);
77
+ await Promise.resolve();
78
+ const stored = snapshots.get(persistenceId);
79
+ // Saves don't hold the mailbox, so an older one can land after a newer one.
80
+ if (stored !== undefined && stored.seq > seq)
81
+ return;
82
+ snapshots.set(persistenceId, { seq, version, timestamp: now(), json });
83
+ },
84
+ async load(persistenceId) {
85
+ checkId(persistenceId, 'snapshots.load: persistenceId');
86
+ await Promise.resolve();
87
+ const stored = snapshots.get(persistenceId);
88
+ if (stored === undefined)
89
+ return undefined;
90
+ const snapshot = {
91
+ seq: stored.seq,
92
+ version: stored.version,
93
+ state: JSON.parse(stored.json),
94
+ timestamp: stored.timestamp,
95
+ };
96
+ return snapshot;
97
+ },
98
+ };
99
+ const offsetStore = {
100
+ async load(name) {
101
+ checkId(name, 'offsets.load: name');
102
+ await Promise.resolve();
103
+ return offsets.get(name) ?? 0;
104
+ },
105
+ async save(name, offset) {
106
+ checkOffsetSave(name, offset);
107
+ await Promise.resolve();
108
+ offsets.set(name, offset);
109
+ },
110
+ };
111
+ return {
112
+ journal,
113
+ snapshots: snapshotStore,
114
+ offsets: offsetStore,
115
+ events: (persistenceId) => (persistenceId === undefined ? all : (streams.get(persistenceId) ?? [])).map(toStored),
116
+ };
117
+ }
118
+ /** A fresh copy each time, so nothing a reader holds can change what's stored. */
119
+ function toStored(row) {
120
+ return {
121
+ persistenceId: row.persistenceId,
122
+ seq: row.seq,
123
+ offset: row.offset,
124
+ timestamp: row.timestamp,
125
+ version: row.version,
126
+ tags: [...row.tags],
127
+ event: JSON.parse(row.json),
128
+ };
129
+ }
130
+ /** The index of the first row with an offset above `offset`. Rows are in offset order. */
131
+ function firstAfter(rows, offset) {
132
+ let lo = 0;
133
+ let hi = rows.length;
134
+ while (lo < hi) {
135
+ const mid = (lo + hi) >>> 1;
136
+ // mid is within [lo, hi), so the row exists.
137
+ if (rows[mid].offset <= offset)
138
+ lo = mid + 1;
139
+ else
140
+ hi = mid;
141
+ }
142
+ return lo;
143
+ }
@@ -0,0 +1 @@
1
+ export { postgresPersistence, type PgPool, type PgPoolClient, type PgQueryable, type PostgresPersistence, } from './postgres.js';
@@ -0,0 +1,3 @@
1
+ // The /persistence/postgres entry point: any runtime with a pg-compatible pool. It never imports
2
+ // pg. Export only from here.
3
+ export { postgresPersistence, } from './postgres.js';
@@ -0,0 +1,66 @@
1
+ import type { Persistence } from '../types.js';
2
+ /**
3
+ * Something that runs a parameterized query, as `pg`'s pool and clients do. Only `rows` is read.
4
+ */
5
+ export interface PgQueryable {
6
+ /** Runs `text` with `$1`, `$2`, ... bound to `values`. */
7
+ query(text: string, values?: unknown[]): Promise<{
8
+ readonly rows: readonly unknown[];
9
+ }>;
10
+ }
11
+ /** One connection checked out of a {@link PgPool}, as `pg`'s `PoolClient` is. */
12
+ export interface PgPoolClient extends PgQueryable {
13
+ /** Returns the connection to the pool, or with `true` or an error, discards it. */
14
+ release(destroy?: boolean | Error): void;
15
+ }
16
+ /**
17
+ * A pool of Postgres connections, typed by shape so this entry point never imports `pg`
18
+ * (decision 0017). A `pg` `Pool` fits, and so does any pool with the same two methods.
19
+ */
20
+ export interface PgPool extends PgQueryable {
21
+ /** Checks out one connection, for a transaction. */
22
+ connect(): Promise<PgPoolClient>;
23
+ }
24
+ /** The Postgres backend's stores, which share the caller's pool. */
25
+ export interface PostgresPersistence extends Required<Persistence> {
26
+ /**
27
+ * Creates the schema and tables if they're missing. Safe to run on every start, and from
28
+ * several processes at once. Skip it if you manage migrations yourself: the SQL ships as
29
+ * `dist/persistence/postgres/schema.sql`.
30
+ */
31
+ setup(): Promise<void>;
32
+ }
33
+ /**
34
+ * A backend on Postgres, through the caller's own `pg`-compatible pool, so it adds no dependency
35
+ * and runs wherever the pool does. Tables live in `schema`, so two journals can share a database.
36
+ * Call `setup()` once to create them, or create them yourself.
37
+ *
38
+ * An append runs in a transaction that takes a journal-wide advisory lock, then checks the
39
+ * stream's last sequence number. Two writers, in one process or several, can't both win, and the
40
+ * loser rejects with `JournalConflictError`. The lock also makes offsets commit in order, so a
41
+ * projection never misses an event (decision 0016). It serializes every append in the journal.
42
+ *
43
+ * Events and states are stored as `json`, so they come back deep-equal to what went in, and
44
+ * reads parse the text themselves, so the pool's type parsers don't matter.
45
+ *
46
+ * @param opts.pool The pool to run on. The backend never ends it.
47
+ * @param opts.schema The schema for the tables: lower-case letters, digits and `_`. Default
48
+ * `troupe`.
49
+ * @param opts.clock The wall clock for timestamps, in integer ms. Defaults to `Date.now`.
50
+ */
51
+ export declare function postgresPersistence(opts: {
52
+ pool: PgPool;
53
+ schema?: string;
54
+ clock?: () => number;
55
+ }): PostgresPersistence;
56
+ /**
57
+ * A 32-bit FNV-1a hash of `text`, as a signed integer for Postgres's `int4`. Computed here, not by
58
+ * Postgres's undocumented `hashtext`, so every process agrees on it, whatever the server version.
59
+ * A collision only makes two journals share a lock.
60
+ */
61
+ export declare function schemaHash(text: string): number;
62
+ /**
63
+ * A `bigint` column as a JavaScript number. `pg` returns them as strings by default, and other
64
+ * pools may parse them as numbers or bigints. The journal only stores safe integers.
65
+ */
66
+ export declare function toInt(value: unknown): number;
@@ -0,0 +1,236 @@
1
+ import { checkKeys, describe } from '../../checks.js';
2
+ import { checkAppend, checkId, checkOffsetSave, checkRead, checkReadByTag, serializeSnapshot, wallClock, } from '../backend.js';
3
+ import { JournalConflictError } from '../errors.js';
4
+ import { DEFAULT_SCHEMA, isSchemaName, postgresSchemaStatements } from './schema.js';
5
+ const OPTIONS = new Set(['pool', 'schema', 'clock']);
6
+ // The first key of the journal's advisory lock: "TRUP". The second is the schema's hash, so each
7
+ // journal in a database has its own lock.
8
+ const LOCK_CLASS = 0x54525550;
9
+ // Postgres's SQLSTATE for a unique violation.
10
+ const UNIQUE_VIOLATION = '23505';
11
+ /**
12
+ * A backend on Postgres, through the caller's own `pg`-compatible pool, so it adds no dependency
13
+ * and runs wherever the pool does. Tables live in `schema`, so two journals can share a database.
14
+ * Call `setup()` once to create them, or create them yourself.
15
+ *
16
+ * An append runs in a transaction that takes a journal-wide advisory lock, then checks the
17
+ * stream's last sequence number. Two writers, in one process or several, can't both win, and the
18
+ * loser rejects with `JournalConflictError`. The lock also makes offsets commit in order, so a
19
+ * projection never misses an event (decision 0016). It serializes every append in the journal.
20
+ *
21
+ * Events and states are stored as `json`, so they come back deep-equal to what went in, and
22
+ * reads parse the text themselves, so the pool's type parsers don't matter.
23
+ *
24
+ * @param opts.pool The pool to run on. The backend never ends it.
25
+ * @param opts.schema The schema for the tables: lower-case letters, digits and `_`. Default
26
+ * `troupe`.
27
+ * @param opts.clock The wall clock for timestamps, in integer ms. Defaults to `Date.now`.
28
+ */
29
+ export function postgresPersistence(opts) {
30
+ checkKeys(opts, OPTIONS, 'postgresPersistence');
31
+ // The default wall clock for timestamps, which never order anything (decision 0015).
32
+ // eslint-disable-next-line no-restricted-properties
33
+ const { pool, schema = DEFAULT_SCHEMA, clock = Date.now } = opts;
34
+ checkPool(pool);
35
+ if (!isSchemaName(schema)) {
36
+ throw new TypeError('postgresPersistence: schema must be lower-case letters, digits and _, starting with a ' +
37
+ `letter or _, at most 63, got ${describe(schema)}`);
38
+ }
39
+ const now = wallClock(clock, 'postgresPersistence');
40
+ const s = `"${schema}"`;
41
+ const lockKey = schemaHash(schema);
42
+ const COLUMNS = 'e.persistence_id, e.seq, e.global_offset, e.timestamp, e.version, ' +
43
+ 'e.tags::text AS tags, e.event::text AS event';
44
+ const LOCK = 'SELECT pg_advisory_xact_lock($1, $2)';
45
+ const LAST_SEQ = `SELECT COALESCE(MAX(seq), 0) AS seq FROM ${s}.events WHERE persistence_id = $1`;
46
+ // One statement for the whole batch, so the lock is held for as few round trips as possible.
47
+ // ORDER BY n draws the batch's offsets in its order.
48
+ const INSERT = `WITH inserted AS (
49
+ INSERT INTO ${s}.events (persistence_id, seq, version, timestamp, event, tags)
50
+ SELECT $1, $2::bigint + b.n, b.version, $3, b.event::json, b.tags::json
51
+ FROM unnest($4::bigint[], $5::text[], $6::text[]) WITH ORDINALITY AS b(version, event, tags, n)
52
+ ORDER BY b.n
53
+ RETURNING global_offset, tags
54
+ )
55
+ INSERT INTO ${s}.event_tags (tag, global_offset)
56
+ SELECT json_array_elements_text(tags), global_offset FROM inserted`;
57
+ const READ = `SELECT ${COLUMNS} FROM ${s}.events e
58
+ WHERE e.persistence_id = $1 AND e.seq >= $2 ORDER BY e.seq LIMIT $3`;
59
+ const READ_TAG = `SELECT ${COLUMNS} FROM ${s}.event_tags t
60
+ JOIN ${s}.events e ON e.global_offset = t.global_offset
61
+ WHERE t.tag = $1 AND t.global_offset > $2 ORDER BY t.global_offset LIMIT $3`;
62
+ // Saves don't hold the mailbox, so an older one can land after a newer one: keep the higher seq.
63
+ const SAVE_SNAPSHOT = `INSERT INTO ${s}.snapshots (persistence_id, seq, version, timestamp, state)
64
+ VALUES ($1, $2, $3, $4, $5::json) ON CONFLICT (persistence_id) DO UPDATE SET
65
+ seq = excluded.seq, version = excluded.version, timestamp = excluded.timestamp,
66
+ state = excluded.state WHERE excluded.seq >= ${s}.snapshots.seq`;
67
+ const LOAD_SNAPSHOT = `SELECT seq, version, timestamp, state::text AS state
68
+ FROM ${s}.snapshots WHERE persistence_id = $1`;
69
+ const LOAD_OFFSET = `SELECT global_offset FROM ${s}.offsets WHERE name = $1`;
70
+ const SAVE_OFFSET = `INSERT INTO ${s}.offsets (name, global_offset) VALUES ($1, $2)
71
+ ON CONFLICT (name) DO UPDATE SET global_offset = excluded.global_offset`;
72
+ /**
73
+ * Runs `work` in a read-committed transaction on one connection. Read committed, whatever the
74
+ * database's default, so each statement sees what committed before it, including while this
75
+ * one waited for the lock. A connection whose rollback fails is discarded, not reused.
76
+ */
77
+ async function transaction(work) {
78
+ const client = await pool.connect();
79
+ try {
80
+ await client.query('BEGIN ISOLATION LEVEL READ COMMITTED');
81
+ await work(client);
82
+ await client.query('COMMIT');
83
+ }
84
+ catch (error) {
85
+ const rolledBack = await client.query('ROLLBACK').then(() => true, () => false);
86
+ client.release(!rolledBack);
87
+ throw error;
88
+ }
89
+ client.release();
90
+ }
91
+ /** Runs one query on the pool, and returns its rows. */
92
+ async function rows(text, values) {
93
+ const result = await pool.query(text, values);
94
+ return result.rows;
95
+ }
96
+ const journal = {
97
+ async append(persistenceId, expectedSeq, events) {
98
+ // Check and serialize the whole batch before the transaction, so it's all or none.
99
+ const batch = checkAppend(persistenceId, expectedSeq, events);
100
+ const timestamp = batch.length === 0 ? 0 : now();
101
+ try {
102
+ await transaction(async (client) => {
103
+ await client.query(LOCK, [LOCK_CLASS, lockKey]);
104
+ // The check runs under the lock, so no other writer can append between it and the
105
+ // insert. This also rejects an expectedSeq ahead of the stream.
106
+ const [last] = (await client.query(LAST_SEQ, [persistenceId])).rows;
107
+ if (toInt(last?.seq) !== expectedSeq) {
108
+ throw new JournalConflictError(persistenceId, expectedSeq);
109
+ }
110
+ if (batch.length === 0)
111
+ return;
112
+ await client.query(INSERT, [
113
+ persistenceId,
114
+ expectedSeq,
115
+ timestamp,
116
+ batch.map((e) => e.version),
117
+ batch.map((e) => e.json),
118
+ batch.map((e) => JSON.stringify(e.tags)),
119
+ ]);
120
+ });
121
+ }
122
+ catch (error) {
123
+ // The lock settles every race, so this is a backstop: the unique key on
124
+ // (persistence_id, seq) still says the stream already has that event.
125
+ if (isUniqueViolation(error))
126
+ throw new JournalConflictError(persistenceId, expectedSeq);
127
+ throw error;
128
+ }
129
+ },
130
+ async read(persistenceId, fromSeq, limit) {
131
+ checkRead(persistenceId, fromSeq, limit);
132
+ return (await rows(READ, [persistenceId, fromSeq, limit])).map(toStored);
133
+ },
134
+ async readByTag(tag, afterOffset, limit) {
135
+ checkReadByTag(tag, afterOffset, limit);
136
+ return (await rows(READ_TAG, [tag, afterOffset, limit])).map(toStored);
137
+ },
138
+ };
139
+ const snapshots = {
140
+ async save(persistenceId, snapshot) {
141
+ const { seq, version, json } = serializeSnapshot(persistenceId, snapshot);
142
+ await pool.query(SAVE_SNAPSHOT, [persistenceId, seq, version, now(), json]);
143
+ },
144
+ async load(persistenceId) {
145
+ checkId(persistenceId, 'snapshots.load: persistenceId');
146
+ const [row] = await rows(LOAD_SNAPSHOT, [persistenceId]);
147
+ if (row === undefined)
148
+ return undefined;
149
+ const loaded = {
150
+ seq: toInt(row.seq),
151
+ version: toInt(row.version),
152
+ state: JSON.parse(row.state),
153
+ timestamp: toInt(row.timestamp),
154
+ };
155
+ return loaded;
156
+ },
157
+ };
158
+ const offsets = {
159
+ async load(name) {
160
+ checkId(name, 'offsets.load: name');
161
+ const [row] = await rows(LOAD_OFFSET, [name]);
162
+ return row === undefined ? 0 : toInt(row.global_offset);
163
+ },
164
+ async save(name, offset) {
165
+ checkOffsetSave(name, offset);
166
+ await pool.query(SAVE_OFFSET, [name, offset]);
167
+ },
168
+ };
169
+ return {
170
+ journal,
171
+ snapshots,
172
+ offsets,
173
+ async setup() {
174
+ // Under the journal's lock, so two processes starting at once don't race to create the
175
+ // same table, which IF NOT EXISTS alone doesn't prevent.
176
+ await transaction(async (client) => {
177
+ await client.query(LOCK, [LOCK_CLASS, lockKey]);
178
+ for (const statement of postgresSchemaStatements(schema))
179
+ await client.query(statement);
180
+ });
181
+ },
182
+ };
183
+ }
184
+ function checkPool(pool) {
185
+ const ok = typeof pool === 'object' &&
186
+ pool !== null &&
187
+ typeof pool.query === 'function' &&
188
+ typeof pool.connect === 'function';
189
+ if (!ok) {
190
+ throw new TypeError('postgresPersistence: pool must have query() and connect(), like pg.Pool');
191
+ }
192
+ }
193
+ /**
194
+ * A 32-bit FNV-1a hash of `text`, as a signed integer for Postgres's `int4`. Computed here, not by
195
+ * Postgres's undocumented `hashtext`, so every process agrees on it, whatever the server version.
196
+ * A collision only makes two journals share a lock.
197
+ */
198
+ export function schemaHash(text) {
199
+ let hash = 0x811c9dc5;
200
+ for (let i = 0; i < text.length; i++) {
201
+ hash ^= text.charCodeAt(i);
202
+ hash = Math.imul(hash, 0x01000193);
203
+ }
204
+ return hash | 0;
205
+ }
206
+ /**
207
+ * A `bigint` column as a JavaScript number. `pg` returns them as strings by default, and other
208
+ * pools may parse them as numbers or bigints. The journal only stores safe integers.
209
+ */
210
+ export function toInt(value) {
211
+ const n = typeof value === 'string' || typeof value === 'bigint'
212
+ ? Number(value)
213
+ : typeof value === 'number'
214
+ ? value
215
+ : NaN;
216
+ if (!Number.isSafeInteger(n)) {
217
+ throw new TypeError(`postgresPersistence: expected an integer from the database, got ${describe(value)}`);
218
+ }
219
+ return n;
220
+ }
221
+ function isUniqueViolation(error) {
222
+ return (typeof error === 'object' &&
223
+ error !== null &&
224
+ error.code === UNIQUE_VIOLATION);
225
+ }
226
+ function toStored(row) {
227
+ return {
228
+ persistenceId: row.persistence_id,
229
+ seq: toInt(row.seq),
230
+ offset: toInt(row.global_offset),
231
+ timestamp: toInt(row.timestamp),
232
+ version: toInt(row.version),
233
+ tags: JSON.parse(row.tags),
234
+ event: JSON.parse(row.event),
235
+ };
236
+ }
@@ -0,0 +1,12 @@
1
+ /** The schema the Postgres backend uses when none is given. */
2
+ export declare const DEFAULT_SCHEMA = "troupe";
3
+ /** Whether `name` can be a schema name: lower-case letters, digits and `_`, at most 63. */
4
+ export declare function isSchemaName(name: unknown): name is string;
5
+ /**
6
+ * The statements that create the backend's schema and tables, if they're missing. Separate
7
+ * statements rather than one string, because a pool that only speaks the extended query protocol
8
+ * runs one statement per query.
9
+ */
10
+ export declare function postgresSchemaStatements(schema: string): string[];
11
+ /** The SQL that creates the backend's schema and tables, as one script. */
12
+ export declare function postgresSchemaSql(schema?: string): string;