@kylewillett/troupe 0.1.1 → 0.3.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 (106) hide show
  1. package/CHANGELOG.md +26 -1
  2. package/README.md +134 -4
  3. package/dist/ask.d.ts +5 -1
  4. package/dist/ask.js +16 -0
  5. package/dist/backstage/index.d.ts +2 -1
  6. package/dist/backstage/index.js +1 -0
  7. package/dist/backstage/source.d.ts +1 -1
  8. package/dist/backstage/source.js +65 -2
  9. package/dist/backstage/types.d.ts +65 -4
  10. package/dist/backstage/types.js +2 -1
  11. package/dist/backstage-ui/assets/index-CG896RLZ.css +1 -0
  12. package/dist/backstage-ui/assets/index-DF_Xnc1u.js +9 -0
  13. package/dist/backstage-ui/index.html +2 -2
  14. package/dist/cell.d.ts +19 -16
  15. package/dist/cell.js +46 -20
  16. package/dist/checks.d.ts +10 -0
  17. package/dist/checks.js +34 -2
  18. package/dist/cluster/index.d.ts +6 -0
  19. package/dist/cluster/index.js +4 -0
  20. package/dist/cluster/leases.d.ts +37 -0
  21. package/dist/cluster/leases.js +132 -0
  22. package/dist/cluster/membership.d.ts +100 -0
  23. package/dist/cluster/membership.js +559 -0
  24. package/dist/cluster/memory.d.ts +31 -0
  25. package/dist/cluster/memory.js +187 -0
  26. package/dist/cluster/placement.d.ts +10 -0
  27. package/dist/cluster/placement.js +30 -0
  28. package/dist/cluster/postgres/index.d.ts +1 -0
  29. package/dist/cluster/postgres/index.js +3 -0
  30. package/dist/cluster/postgres/schema.d.ts +7 -0
  31. package/dist/cluster/postgres/schema.js +33 -0
  32. package/dist/cluster/postgres/schema.sql +18 -0
  33. package/dist/cluster/postgres/store.d.ts +28 -0
  34. package/dist/cluster/postgres/store.js +124 -0
  35. package/dist/cluster/region.d.ts +103 -0
  36. package/dist/cluster/region.js +843 -0
  37. package/dist/cluster/remoting.d.ts +79 -0
  38. package/dist/cluster/remoting.js +755 -0
  39. package/dist/cluster/shard-memory.d.ts +14 -0
  40. package/dist/cluster/shard-memory.js +92 -0
  41. package/dist/cluster/shard-store.d.ts +62 -0
  42. package/dist/cluster/shard-store.js +36 -0
  43. package/dist/cluster/shard.d.ts +54 -0
  44. package/dist/cluster/shard.js +278 -0
  45. package/dist/cluster/sharding.d.ts +116 -0
  46. package/dist/cluster/sharding.js +286 -0
  47. package/dist/cluster/table.d.ts +29 -0
  48. package/dist/cluster/table.js +74 -0
  49. package/dist/cluster/timed-store.d.ts +4 -0
  50. package/dist/cluster/timed-store.js +19 -0
  51. package/dist/cluster/transport.d.ts +29 -0
  52. package/dist/cluster/transport.js +4 -0
  53. package/dist/cluster/wire.d.ts +90 -0
  54. package/dist/cluster/wire.js +177 -0
  55. package/dist/hash.d.ts +7 -0
  56. package/dist/hash.js +25 -0
  57. package/dist/index.d.ts +1 -0
  58. package/dist/index.js +1 -0
  59. package/dist/internal.d.ts +139 -2
  60. package/dist/internal.js +12 -1
  61. package/dist/json.d.ts +44 -0
  62. package/dist/json.js +143 -0
  63. package/dist/node/cluster/frames.d.ts +31 -0
  64. package/dist/node/cluster/frames.js +73 -0
  65. package/dist/node/cluster/index.d.ts +1 -0
  66. package/dist/node/cluster/index.js +3 -0
  67. package/dist/node/cluster/tcp.d.ts +101 -0
  68. package/dist/node/cluster/tcp.js +416 -0
  69. package/dist/persistence/actor.d.ts +9 -0
  70. package/dist/persistence/actor.js +21 -10
  71. package/dist/persistence/backend.d.ts +1 -10
  72. package/dist/persistence/backend.js +4 -34
  73. package/dist/persistence/errors.d.ts +19 -0
  74. package/dist/persistence/errors.js +22 -0
  75. package/dist/persistence/index.d.ts +1 -1
  76. package/dist/persistence/index.js +1 -1
  77. package/dist/persistence/postgres/index.d.ts +2 -1
  78. package/dist/persistence/postgres/index.js +1 -1
  79. package/dist/persistence/postgres/pool.d.ts +44 -0
  80. package/dist/persistence/postgres/pool.js +65 -0
  81. package/dist/persistence/postgres/postgres.d.ts +1 -33
  82. package/dist/persistence/postgres/postgres.js +4 -63
  83. package/dist/persistence/projection.d.ts +6 -0
  84. package/dist/persistence/projection.js +21 -5
  85. package/dist/rehearsal/clock.d.ts +54 -0
  86. package/dist/rehearsal/clock.js +203 -0
  87. package/dist/rehearsal/database.d.ts +116 -0
  88. package/dist/rehearsal/database.js +349 -0
  89. package/dist/rehearsal/loop.d.ts +57 -0
  90. package/dist/rehearsal/loop.js +153 -0
  91. package/dist/rehearsal/network.d.ts +120 -0
  92. package/dist/rehearsal/network.js +524 -0
  93. package/dist/rehearsal/ranges.d.ts +8 -0
  94. package/dist/rehearsal/ranges.js +27 -0
  95. package/dist/rehearsal/yield.d.ts +9 -0
  96. package/dist/rehearsal/yield.js +24 -0
  97. package/dist/system.d.ts +13 -1
  98. package/dist/system.js +204 -25
  99. package/dist/timeout.d.ts +8 -0
  100. package/dist/timeout.js +26 -0
  101. package/dist/types.d.ts +86 -3
  102. package/package.json +21 -2
  103. package/dist/backstage-ui/assets/index-Bg0MCiqs.css +0 -1
  104. package/dist/backstage-ui/assets/index-CeefBsDh.js +0 -9
  105. package/dist/persistence/json.d.ts +0 -7
  106. package/dist/persistence/json.js +0 -75
@@ -2,8 +2,9 @@ var _a;
2
2
  import { checkInt, checkKeys, describe } from '../checks.js';
3
3
  import { internalsOf, PERSISTENT, START, } from '../internal.js';
4
4
  import { isValidName } from '../names.js';
5
- import { EventValidationError, EventVersionError, JournalSequenceError } from './errors.js';
6
- import { jsonProblem } from './json.js';
5
+ import { EventValidationError, EventVersionError, JournalSequenceError, PersistenceTimeoutError, } from './errors.js';
6
+ import { jsonProblem } from '../json.js';
7
+ import { withTimeout } from '../timeout.js';
7
8
  const OPTIONS = new Set([
8
9
  'id',
9
10
  'persistence',
@@ -14,12 +15,14 @@ const OPTIONS = new Set([
14
15
  'tags',
15
16
  'events',
16
17
  'snapshots',
18
+ 'timeoutMs',
17
19
  ]);
18
20
  const SNAPSHOT_OPTIONS = new Set(['every', 'version']);
19
21
  const EVENT_OPTIONS = new Set(['schema', 'version', 'upcasters']);
20
22
  const MAX_ID_LENGTH = 255;
21
23
  /** Events per read during recovery and `stateAt`. */
22
24
  const PAGE_SIZE = 256;
25
+ const DEFAULT_TIMEOUT_MS = 10_000;
23
26
  /** The one implementation of `Effect`, so `onCommand` can't return something else by accident. */
24
27
  class EffectImpl {
25
28
  events;
@@ -87,6 +90,9 @@ export function persistentActor(def) {
87
90
  const journal = def.persistence.journal;
88
91
  const snapshotting = snapshotPlan(def);
89
92
  const { schema, version, upcasters } = eventPlan(def.events);
93
+ const timeoutMs = def.timeoutMs ?? DEFAULT_TIMEOUT_MS;
94
+ /** `call`, timed on the actor's scheduler (decision 0036). */
95
+ const timed = (ctx, operation, call) => withTimeout(call, timeoutMs, internalsOf(ctx).setTimer, () => new PersistenceTimeoutError(id, operation, timeoutMs));
90
96
  /** The schema's output for `event`. */
91
97
  const check = async (using, event, seq) => {
92
98
  const result = await using['~standard'].validate(event);
@@ -126,7 +132,6 @@ export function persistentActor(def) {
126
132
  for (const step of effect.steps)
127
133
  step(state, ctx);
128
134
  };
129
- /** Appends, then applies and runs the steps. The cell holds the mailbox until it settles. */
130
135
  /** An event's tags, checked so a bad one fails the command instead of the append. */
131
136
  const tagsFor = (event, i) => {
132
137
  if (def.tags === undefined)
@@ -148,6 +153,7 @@ export function persistentActor(def) {
148
153
  }
149
154
  return [...seen];
150
155
  };
156
+ /** Appends, then applies and runs the steps. The cell holds the mailbox until it settles. */
151
157
  const persistThen = async (current, effect, ctx) => {
152
158
  // If this rejects, the actor can't know what the journal holds, so it applies nothing. A
153
159
  // restart recovers from the journal, which settles it (decision 0013).
@@ -168,7 +174,8 @@ export function persistentActor(def) {
168
174
  version,
169
175
  tags: tagsFor(applied[i], i),
170
176
  }));
171
- await journal.append(id, current.seq, batch);
177
+ // A timeout rejects here too: the outcome is unknown, so nothing is applied and no step runs.
178
+ await timed(ctx, 'append', journal.append(id, current.seq, batch));
172
179
  let state = current.state;
173
180
  // The schema's output, as recovery will see it, so a write and its replay fold the same value.
174
181
  for (const event of applied)
@@ -203,7 +210,7 @@ export function persistentActor(def) {
203
210
  });
204
211
  return;
205
212
  }
206
- const saving = plan.store.save(id, { seq, version: plan.version, state }).then(() => { }, (error) => {
213
+ const saving = timed(ctx, 'saveSnapshot', plan.store.save(id, { seq, version: plan.version, state })).then(() => { }, (error) => {
207
214
  ctx.log.warn(`${id}: saving the snapshot at ${String(seq)} failed`, {
208
215
  persistenceId: id,
209
216
  seq,
@@ -218,7 +225,7 @@ export function persistentActor(def) {
218
225
  return start;
219
226
  let snapshot;
220
227
  try {
221
- snapshot = await snapshotting.store.load(id);
228
+ snapshot = await timed(ctx, 'loadSnapshot', snapshotting.store.load(id));
222
229
  }
223
230
  catch (error) {
224
231
  ctx.log.warn(`${id}: loading the snapshot failed, so recovery replays every event`, {
@@ -237,17 +244,18 @@ export function persistentActor(def) {
237
244
  // The version matches, so the stored state has this definition's shape.
238
245
  return { seq: snapshot.seq, state: snapshot.state };
239
246
  };
247
+ const untimedRead = (fromSeq, limit) => journal.read(id, fromSeq, limit);
240
248
  /**
241
249
  * Folds the journal's events after `start.seq`, up to `until` or the end, whichever comes first:
242
250
  * upcast, checked and applied, as recovery and `stateAt` both need.
243
251
  */
244
- const fold = async (start, until) => {
252
+ const fold = async (start, until, read) => {
245
253
  let { seq, state } = start;
246
254
  for (;;) {
247
255
  const want = Math.min(PAGE_SIZE, until - seq);
248
256
  if (want <= 0)
249
257
  break;
250
- const page = await journal.read(id, seq + 1, want);
258
+ const page = await read(seq + 1, want);
251
259
  for (const stored of page) {
252
260
  if (stored.seq !== seq + 1)
253
261
  throw new JournalSequenceError(id, seq + 1, stored.seq);
@@ -263,7 +271,7 @@ export function persistentActor(def) {
263
271
  };
264
272
  const recover = async (initial, ctx) => {
265
273
  const start = await startFrom(initial, ctx);
266
- const { seq, state } = await fold(start, Infinity);
274
+ const { seq, state } = await fold(start, Infinity, (fromSeq, limit) => timed(ctx, 'read', journal.read(id, fromSeq, limit)));
267
275
  internalsOf(ctx).publish({
268
276
  type: 'recovered',
269
277
  path: ctx.self.path,
@@ -284,7 +292,8 @@ export function persistentActor(def) {
284
292
  if (!Number.isSafeInteger(seq) || seq < 0) {
285
293
  throw new TypeError(`${id}: stateAt needs a non-negative integer, got ${describe(seq)}`);
286
294
  }
287
- const reached = await fold({ seq: 0, state: def.initial }, seq);
295
+ // An inspector's call, with no actor and so no scheduler of its own to time it on.
296
+ const reached = await fold({ seq: 0, state: def.initial }, seq, untimedRead);
288
297
  if (reached.seq < seq) {
289
298
  throw new RangeError(`${id}: the journal ends at event ${String(reached.seq)}, before ${String(seq)}`);
290
299
  }
@@ -357,6 +366,8 @@ function checkDef(def) {
357
366
  checkEvents(d.events);
358
367
  if (d.snapshots !== undefined)
359
368
  checkSnapshots(d.snapshots, persistence);
369
+ if (d.timeoutMs !== undefined)
370
+ checkInt(d.timeoutMs, 'persistentActor: timeoutMs');
360
371
  }
361
372
  function checkEvents(events) {
362
373
  checkKeys(events, EVENT_OPTIONS, 'persistentActor: events');
@@ -1,3 +1,4 @@
1
+ export { checkId, wallClock } from '../checks.js';
1
2
  /** An event checked and ready to store, with the event itself as JSON text. */
2
3
  export interface SerializedEvent {
3
4
  readonly version: number;
@@ -10,16 +11,6 @@ export interface SerializedSnapshot {
10
11
  readonly version: number;
11
12
  readonly json: string;
12
13
  }
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
14
  /** Checks `append`'s arguments and serializes the batch, before anything touches the stream. */
24
15
  export declare function checkAppend(persistenceId: unknown, expectedSeq: unknown, events: unknown): SerializedEvent[];
25
16
  /** Checks `read`'s arguments. */
@@ -1,39 +1,9 @@
1
1
  // Shared by every backend, never exported from an entry point: the argument checks and the clock
2
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
- }
3
+ import { checkId, checkInt } from '../checks.js';
4
+ import { jsonProblem } from '../json.js';
5
+ // The clock and id checks live with the core's, since the cluster's stores use them too.
6
+ export { checkId, wallClock } from '../checks.js';
37
7
  /** Checks `append`'s arguments and serializes the batch, before anything touches the stream. */
38
8
  export function checkAppend(persistenceId, expectedSeq, events) {
39
9
  checkId(persistenceId, 'append: persistenceId');
@@ -58,3 +58,22 @@ export declare class EventVersionError extends Error {
58
58
  /** Creates the error for event `seq` of `persistenceId`, stored at `version`. */
59
59
  constructor(persistenceId: string, seq: number, version: number, current: number);
60
60
  }
61
+ /** The store call a {@link PersistenceTimeoutError} gave up on. */
62
+ export type PersistenceOperation = 'append' | 'read' | 'loadSnapshot' | 'saveSnapshot' | 'readByTag' | 'loadOffset' | 'saveOffset';
63
+ /**
64
+ * The reason a persistent actor or a projection fails when a journal, snapshot or offset call
65
+ * hasn't answered within its `timeoutMs` (decision 0036). Its outcome is unknown: an append that
66
+ * timed out may still have been written. A restart recovers from the journal, which settles it.
67
+ */
68
+ export declare class PersistenceTimeoutError extends Error {
69
+ /** Always `"PersistenceTimeoutError"`, so the error can be recognized without `instanceof`. */
70
+ readonly name = "PersistenceTimeoutError";
71
+ /** The persistent actor's persistence id, or the projection's name. */
72
+ readonly id: string;
73
+ /** The call that didn't answer. */
74
+ readonly operation: PersistenceOperation;
75
+ /** How long it waited, in ms. */
76
+ readonly timeoutMs: number;
77
+ /** Creates the error for `operation` by `id`, which waited `timeoutMs`. */
78
+ constructor(id: string, operation: PersistenceOperation, timeoutMs: number);
79
+ }
@@ -80,3 +80,25 @@ export class EventVersionError extends Error {
80
80
  this.version = version;
81
81
  }
82
82
  }
83
+ /**
84
+ * The reason a persistent actor or a projection fails when a journal, snapshot or offset call
85
+ * hasn't answered within its `timeoutMs` (decision 0036). Its outcome is unknown: an append that
86
+ * timed out may still have been written. A restart recovers from the journal, which settles it.
87
+ */
88
+ export class PersistenceTimeoutError extends Error {
89
+ /** Always `"PersistenceTimeoutError"`, so the error can be recognized without `instanceof`. */
90
+ name = 'PersistenceTimeoutError';
91
+ /** The persistent actor's persistence id, or the projection's name. */
92
+ id;
93
+ /** The call that didn't answer. */
94
+ operation;
95
+ /** How long it waited, in ms. */
96
+ timeoutMs;
97
+ /** Creates the error for `operation` by `id`, which waited `timeoutMs`. */
98
+ constructor(id, operation, timeoutMs) {
99
+ super(`${operation} for "${id}" did not answer within ${String(timeoutMs)} ms`);
100
+ this.id = id;
101
+ this.operation = operation;
102
+ this.timeoutMs = timeoutMs;
103
+ }
104
+ }
@@ -1,5 +1,5 @@
1
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';
2
+ export { EventValidationError, EventVersionError, JournalConflictError, JournalSequenceError, PersistenceTimeoutError, type PersistenceOperation, } from './errors.js';
3
3
  export { inMemoryPersistence, type InMemoryPersistence } from './memory.js';
4
4
  export { projection, type ProjectionOptions, type ProjectionState } from './projection.js';
5
5
  export type { StandardSchemaV1 } from './standard-schema.js';
@@ -1,5 +1,5 @@
1
1
  // The /persistence entry point: runs on any JavaScript runtime. Export only from here.
2
2
  export { persistentActor, } from './actor.js';
3
- export { EventValidationError, EventVersionError, JournalConflictError, JournalSequenceError, } from './errors.js';
3
+ export { EventValidationError, EventVersionError, JournalConflictError, JournalSequenceError, PersistenceTimeoutError, } from './errors.js';
4
4
  export { inMemoryPersistence } from './memory.js';
5
5
  export { projection } from './projection.js';
@@ -1 +1,2 @@
1
- export { postgresPersistence, type PgPool, type PgPoolClient, type PgQueryable, type PostgresPersistence, } from './postgres.js';
1
+ export { postgresPersistence, type PostgresPersistence } from './postgres.js';
2
+ export type { PgPool, PgPoolClient, PgQueryable } from './pool.js';
@@ -1,3 +1,3 @@
1
1
  // The /persistence/postgres entry point: any runtime with a pg-compatible pool. It never imports
2
2
  // pg. Export only from here.
3
- export { postgresPersistence, } from './postgres.js';
3
+ export { postgresPersistence } from './postgres.js';
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Something that runs a parameterized query, as `pg`'s pool and clients do. Only `rows` is read.
3
+ */
4
+ export interface PgQueryable {
5
+ /** Runs `text` with `$1`, `$2`, ... bound to `values`. */
6
+ query(text: string, values?: unknown[]): Promise<{
7
+ readonly rows: readonly unknown[];
8
+ }>;
9
+ }
10
+ /** One connection checked out of a {@link PgPool}, as `pg`'s `PoolClient` is. */
11
+ export interface PgPoolClient extends PgQueryable {
12
+ /** Returns the connection to the pool, or with `true` or an error, discards it. */
13
+ release(destroy?: boolean | Error): void;
14
+ }
15
+ /**
16
+ * A pool of Postgres connections, typed by shape so this entry point never imports `pg`
17
+ * (decision 0017). A `pg` `Pool` fits, and so does any pool with the same two methods.
18
+ */
19
+ export interface PgPool extends PgQueryable {
20
+ /** Checks out one connection, for a transaction. */
21
+ connect(): Promise<PgPoolClient>;
22
+ }
23
+ export declare const LOCK_CLASS = 1414681936;
24
+ /** Takes the advisory lock `($1, $2)` until the transaction ends. */
25
+ export declare const LOCK = "SELECT pg_advisory_xact_lock($1, $2)";
26
+ /** Throws unless `pool` has the two methods a {@link PgPool} needs. */
27
+ export declare function checkPool(pool: unknown, where: string): asserts pool is PgPool;
28
+ /**
29
+ * Runs `work` in a read-committed transaction on one connection. Read committed, whatever the
30
+ * database's default, so each statement sees what committed before it, including while this
31
+ * one waited for a lock. A connection whose rollback fails is discarded, not reused.
32
+ */
33
+ export declare function transaction<T>(pool: PgPool, work: (client: PgPoolClient) => Promise<T>): Promise<T>;
34
+ /**
35
+ * A 32-bit FNV-1a hash of `text`, as a signed integer for Postgres's `int4`. Computed here, not by
36
+ * Postgres's undocumented `hashtext`, so every process agrees on it, whatever the server version.
37
+ * A collision only makes two journals share a lock.
38
+ */
39
+ export declare function schemaHash(text: string): number;
40
+ /**
41
+ * A `bigint` column as a JavaScript number. `pg` returns them as strings by default, and other
42
+ * pools may parse them as numbers or bigints. The journal only stores safe integers.
43
+ */
44
+ export declare function toInt(value: unknown): number;
@@ -0,0 +1,65 @@
1
+ // What both Postgres backends share, never exported from an entry point: the pool's shape, the
2
+ // transaction runner, the advisory lock's keys and the integer reader. The journal
3
+ // (/persistence/postgres) and the shard store (/cluster/postgres) run on the same pool (0017).
4
+ import { describe } from '../../checks.js';
5
+ import { fnv1a } from '../../hash.js';
6
+ // The first key of the schema's advisory lock: "TRUP". The second is the schema's hash, so each
7
+ // schema in a database has its own lock. Journal appends take it (decision 0016), and so does
8
+ // every setup(), so two backends setting up one schema at once don't race to create it.
9
+ export const LOCK_CLASS = 0x54525550;
10
+ /** Takes the advisory lock `($1, $2)` until the transaction ends. */
11
+ export const LOCK = 'SELECT pg_advisory_xact_lock($1, $2)';
12
+ /** Throws unless `pool` has the two methods a {@link PgPool} needs. */
13
+ export function checkPool(pool, where) {
14
+ const ok = typeof pool === 'object' &&
15
+ pool !== null &&
16
+ typeof pool.query === 'function' &&
17
+ typeof pool.connect === 'function';
18
+ if (!ok) {
19
+ throw new TypeError(`${where}: pool must have query() and connect(), like pg.Pool`);
20
+ }
21
+ }
22
+ /**
23
+ * Runs `work` in a read-committed transaction on one connection. Read committed, whatever the
24
+ * database's default, so each statement sees what committed before it, including while this
25
+ * one waited for a lock. A connection whose rollback fails is discarded, not reused.
26
+ */
27
+ export async function transaction(pool, work) {
28
+ const client = await pool.connect();
29
+ let result;
30
+ try {
31
+ await client.query('BEGIN ISOLATION LEVEL READ COMMITTED');
32
+ result = await work(client);
33
+ await client.query('COMMIT');
34
+ }
35
+ catch (error) {
36
+ const rolledBack = await client.query('ROLLBACK').then(() => true, () => false);
37
+ client.release(!rolledBack);
38
+ throw error;
39
+ }
40
+ client.release();
41
+ return result;
42
+ }
43
+ /**
44
+ * A 32-bit FNV-1a hash of `text`, as a signed integer for Postgres's `int4`. Computed here, not by
45
+ * Postgres's undocumented `hashtext`, so every process agrees on it, whatever the server version.
46
+ * A collision only makes two journals share a lock.
47
+ */
48
+ export function schemaHash(text) {
49
+ return fnv1a(text) | 0;
50
+ }
51
+ /**
52
+ * A `bigint` column as a JavaScript number. `pg` returns them as strings by default, and other
53
+ * pools may parse them as numbers or bigints. The journal only stores safe integers.
54
+ */
55
+ export function toInt(value) {
56
+ const n = typeof value === 'string' || typeof value === 'bigint'
57
+ ? Number(value)
58
+ : typeof value === 'number'
59
+ ? value
60
+ : NaN;
61
+ if (!Number.isSafeInteger(n)) {
62
+ throw new TypeError(`Postgres: expected an integer from the database, got ${describe(value)}`);
63
+ }
64
+ return n;
65
+ }
@@ -1,26 +1,5 @@
1
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
- }
2
+ import { type PgPool } from './pool.js';
24
3
  /** The Postgres backend's stores, which share the caller's pool. */
25
4
  export interface PostgresPersistence extends Required<Persistence> {
26
5
  /**
@@ -53,14 +32,3 @@ export declare function postgresPersistence(opts: {
53
32
  schema?: string;
54
33
  clock?: () => number;
55
34
  }): 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;
@@ -1,11 +1,9 @@
1
1
  import { checkKeys, describe } from '../../checks.js';
2
2
  import { checkAppend, checkId, checkOffsetSave, checkRead, checkReadByTag, serializeSnapshot, wallClock, } from '../backend.js';
3
3
  import { JournalConflictError } from '../errors.js';
4
+ import { checkPool, LOCK, LOCK_CLASS, schemaHash, toInt, transaction, } from './pool.js';
4
5
  import { DEFAULT_SCHEMA, isSchemaName, postgresSchemaStatements } from './schema.js';
5
6
  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
7
  // Postgres's SQLSTATE for a unique violation.
10
8
  const UNIQUE_VIOLATION = '23505';
11
9
  /**
@@ -31,7 +29,7 @@ export function postgresPersistence(opts) {
31
29
  // The default wall clock for timestamps, which never order anything (decision 0015).
32
30
  // eslint-disable-next-line no-restricted-properties
33
31
  const { pool, schema = DEFAULT_SCHEMA, clock = Date.now } = opts;
34
- checkPool(pool);
32
+ checkPool(pool, 'postgresPersistence');
35
33
  if (!isSchemaName(schema)) {
36
34
  throw new TypeError('postgresPersistence: schema must be lower-case letters, digits and _, starting with a ' +
37
35
  `letter or _, at most 63, got ${describe(schema)}`);
@@ -41,7 +39,6 @@ export function postgresPersistence(opts) {
41
39
  const lockKey = schemaHash(schema);
42
40
  const COLUMNS = 'e.persistence_id, e.seq, e.global_offset, e.timestamp, e.version, ' +
43
41
  'e.tags::text AS tags, e.event::text AS event';
44
- const LOCK = 'SELECT pg_advisory_xact_lock($1, $2)';
45
42
  const LAST_SEQ = `SELECT COALESCE(MAX(seq), 0) AS seq FROM ${s}.events WHERE persistence_id = $1`;
46
43
  // One statement for the whole batch, so the lock is held for as few round trips as possible.
47
44
  // ORDER BY n draws the batch's offsets in its order.
@@ -69,25 +66,6 @@ export function postgresPersistence(opts) {
69
66
  const LOAD_OFFSET = `SELECT global_offset FROM ${s}.offsets WHERE name = $1`;
70
67
  const SAVE_OFFSET = `INSERT INTO ${s}.offsets (name, global_offset) VALUES ($1, $2)
71
68
  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
69
  /** Runs one query on the pool, and returns its rows. */
92
70
  async function rows(text, values) {
93
71
  const result = await pool.query(text, values);
@@ -99,7 +77,7 @@ export function postgresPersistence(opts) {
99
77
  const batch = checkAppend(persistenceId, expectedSeq, events);
100
78
  const timestamp = batch.length === 0 ? 0 : now();
101
79
  try {
102
- await transaction(async (client) => {
80
+ await transaction(pool, async (client) => {
103
81
  await client.query(LOCK, [LOCK_CLASS, lockKey]);
104
82
  // The check runs under the lock, so no other writer can append between it and the
105
83
  // insert. This also rejects an expectedSeq ahead of the stream.
@@ -173,7 +151,7 @@ export function postgresPersistence(opts) {
173
151
  async setup() {
174
152
  // Under the journal's lock, so two processes starting at once don't race to create the
175
153
  // same table, which IF NOT EXISTS alone doesn't prevent.
176
- await transaction(async (client) => {
154
+ await transaction(pool, async (client) => {
177
155
  await client.query(LOCK, [LOCK_CLASS, lockKey]);
178
156
  for (const statement of postgresSchemaStatements(schema))
179
157
  await client.query(statement);
@@ -181,43 +159,6 @@ export function postgresPersistence(opts) {
181
159
  },
182
160
  };
183
161
  }
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
162
  function isUniqueViolation(error) {
222
163
  return (typeof error === 'object' &&
223
164
  error !== null &&
@@ -22,6 +22,12 @@ export interface ProjectionOptions {
22
22
  pollMs?: number;
23
23
  /** The most events per read. A positive integer. Default 100. */
24
24
  batchSize?: number;
25
+ /**
26
+ * How long each read and each offset load or save may take, in ms: a positive integer. Default
27
+ * 10,000. One that takes longer fails the projection with `PersistenceTimeoutError`, and its
28
+ * supervision decides when it tries again (decision 0036).
29
+ */
30
+ timeoutMs?: number;
25
31
  }
26
32
  /** What a projection's cell holds: the offset of the last event it handled, 0 before any. */
27
33
  export interface ProjectionState {
@@ -1,10 +1,21 @@
1
1
  import { checkInt, checkKeys, describe } from '../checks.js';
2
2
  import { internalsOf, START } from '../internal.js';
3
3
  import { isValidName } from '../names.js';
4
- const OPTIONS = new Set(['name', 'persistence', 'tag', 'handle', 'pollMs', 'batchSize']);
4
+ import { withTimeout } from '../timeout.js';
5
+ import { PersistenceTimeoutError } from './errors.js';
6
+ const OPTIONS = new Set([
7
+ 'name',
8
+ 'persistence',
9
+ 'tag',
10
+ 'handle',
11
+ 'pollMs',
12
+ 'batchSize',
13
+ 'timeoutMs',
14
+ ]);
5
15
  const MAX_NAME_LENGTH = 255;
6
16
  const DEFAULT_POLL_MS = 1_000;
7
17
  const DEFAULT_BATCH_SIZE = 100;
18
+ const DEFAULT_TIMEOUT_MS = 10_000;
8
19
  const POLL_TIMER = 'poll';
9
20
  /** The projection's only message. Private, so nothing outside can tell it anything. */
10
21
  const POLL = Object.freeze({ type: 'poll' });
@@ -33,10 +44,13 @@ export function projection(opts) {
33
44
  const offsets = opts.persistence.offsets;
34
45
  const pollMs = opts.pollMs ?? DEFAULT_POLL_MS;
35
46
  const batchSize = opts.batchSize ?? DEFAULT_BATCH_SIZE;
47
+ const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
48
+ /** `call`, timed on the projection's scheduler (decision 0036). */
49
+ const timed = (ctx, operation, call) => withTimeout(call, timeoutMs, internalsOf(ctx).setTimer, () => new PersistenceTimeoutError(name, operation, timeoutMs));
36
50
  const def = {
37
51
  initial: { offset: 0 },
38
52
  async receive(current, _poll, ctx) {
39
- const batch = await journal.readByTag(tag, current.offset, batchSize);
53
+ const batch = await timed(ctx, 'readByTag', journal.readByTag(tag, current.offset, batchSize));
40
54
  // After the read's await, so outside the cell's turn: what handle tells names the projection
41
55
  // as its sender only through the hook (decision 0020). Called on opts, so a handle that uses
42
56
  // `this` sees the object it was defined on.
@@ -46,7 +60,7 @@ export function projection(opts) {
46
60
  const last = batch.at(-1);
47
61
  let next = current;
48
62
  if (last !== undefined) {
49
- await offsets.save(name, last.offset);
63
+ await timed(ctx, 'saveOffset', offsets.save(name, last.offset));
50
64
  next = { offset: last.offset };
51
65
  }
52
66
  // Exactly one poll is ever pending, in the mailbox or on the timer. A failure above consumes
@@ -58,7 +72,7 @@ export function projection(opts) {
58
72
  return next;
59
73
  },
60
74
  async [START](_state, ctx) {
61
- const offset = await offsets.load(name);
75
+ const offset = await timed(ctx, 'loadOffset', offsets.load(name));
62
76
  ctx.self.tell(POLL);
63
77
  return { offset };
64
78
  },
@@ -68,7 +82,7 @@ export function projection(opts) {
68
82
  }
69
83
  function checkOptions(opts) {
70
84
  checkKeys(opts, OPTIONS, 'projection');
71
- const { name, persistence, tag, handle, pollMs, batchSize } = opts;
85
+ const { name, persistence, tag, handle, pollMs, batchSize, timeoutMs } = opts;
72
86
  if (typeof name !== 'string' || name === '' || name.length > MAX_NAME_LENGTH) {
73
87
  throw new TypeError(`projection: name must be a string of 1 to ${String(MAX_NAME_LENGTH)} characters, ` +
74
88
  `got ${typeof name === 'string' ? `one of ${String(name.length)}` : describe(name)}`);
@@ -87,6 +101,8 @@ function checkOptions(opts) {
87
101
  checkInt(pollMs, 'projection: pollMs');
88
102
  if (batchSize !== undefined)
89
103
  checkInt(batchSize, 'projection: batchSize');
104
+ if (timeoutMs !== undefined)
105
+ checkInt(timeoutMs, 'projection: timeoutMs');
90
106
  }
91
107
  function hasStores(value) {
92
108
  if (typeof value !== 'object' || value === null)