@kylewillett/troupe 0.2.0 → 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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,16 @@
2
2
 
3
3
  This project follows [Semantic Versioning](https://semver.org/). Under 0.x, a minor version can break the API. 1.0 comes after milestone 5 ([0032](https://github.com/Fours/troupe/blob/main/docs/decisions/0032-1-0-comes-after-rehearsal.md)). Each design choice behind these entries has a record in [docs/decisions](https://github.com/Fours/troupe/tree/main/docs/decisions).
4
4
 
5
+ ## 0.3.0 (2026-11-24)
6
+
7
+ Part of milestone 5, Rehearsal, released early for Steadfast: timeouts on every store call, and the JSON check as public API. Rehearsal itself isn't exported yet, and goes out with 1.0.0. The timeouts can break code, and are marked **Breaking**.
8
+
9
+ - **Breaking:** journal, snapshot, offset and shard store calls that never answer now time out, after 10 s for persistence and `renewMs` for the shard store, instead of waiting forever. Code that relied on a call waiting forever, such as a backend that answers only after minutes, needs a longer `timeoutMs` ([0036](https://github.com/Fours/troupe/blob/main/docs/decisions/0036-timeouts-are-unknown-outcomes-settled-by-recovery.md)).
10
+ - `persistentActor` and `projection` take `timeoutMs`, a positive integer, default 10,000. A journal call or a recovery read that takes longer fails the actor with `PersistenceTimeoutError`, for its supervision to handle, and a persistent actor sends no reply for a write that timed out. The write may still have been made, and the restart recovers from the journal to find out. A snapshot load that times out is skipped, and recovery replays every event. A snapshot save that times out is logged ([0036](https://github.com/Fours/troupe/blob/main/docs/decisions/0036-timeouts-are-unknown-outcomes-settled-by-recovery.md)).
11
+ - `PersistenceTimeoutError` in `@kylewillett/troupe/persistence`, with `id`, the persistence id or projection name, `operation`, a `PersistenceOperation`, and `timeoutMs` ([0036](https://github.com/Fours/troupe/blob/main/docs/decisions/0036-timeouts-are-unknown-outcomes-settled-by-recovery.md)).
12
+ - `joinCluster`'s `leases` takes `storeTimeoutMs`, a positive integer, default `renewMs`: how long each shard store call may take before the node gives up on it. A renewal that times out counts as failed, and the holder still gives its shards up at its deadline. A handoff waits for the entity's own timeout, never for a journal that doesn't answer ([0036](https://github.com/Fours/troupe/blob/main/docs/decisions/0036-timeouts-are-unknown-outcomes-settled-by-recovery.md)).
13
+ - `@kylewillett/troupe` exports `JsonValue`, `isJsonValue(value)` and `jsonProblem(value)`: the check events, snapshot states and messages to entities must pass, for code that wants to check a value before it's written. `jsonProblem` names where a value stops being JSON, as a path such as `$.items[2] is a hole`, or returns `undefined` ([0037](https://github.com/Fours/troupe/blob/main/docs/decisions/0037-the-json-check-is-public.md)).
14
+
5
15
  ## 0.2.0 (2026-11-24)
6
16
 
7
17
  Milestone 4: multi-node. Three new entry points, `/cluster`, `/cluster/postgres` and `/cluster/tcp`, for cluster sharding across Node processes with at most one live instance of each entity. Still no runtime dependencies, and `/cluster` and `/cluster/postgres` run on any runtime. The core changes that can break code are marked **Breaking**: the `deadLetter` reasons, the new `SystemEvent` types, and Backstage's protocol version.
package/README.md CHANGED
@@ -236,7 +236,7 @@ const alice = system.spawn(account('alice'), 'alice');
236
236
  await alice.ask<Receipt>((replyTo) => ({ type: 'deposit', amount: 10, replyTo })); // balance 10
237
237
  ```
238
238
 
239
- `persistentActor` returns an ordinary actor definition: spawn, name, watch and supervise it like any other. `id` names its event stream in the journal. Events and states must be JSON values, and are checked before they're written.
239
+ `persistentActor` returns an ordinary actor definition: spawn, name, watch and supervise it like any other. `id` names its event stream in the journal. Events and states must be JSON values, and are checked before they're written. To check a value yourself first, `jsonProblem(value)` from `@kylewillett/troupe` names where it stops being JSON, such as `$.items[2] is a hole`, and `isJsonValue(value)` says whether it is one.
240
240
 
241
241
  ### Effects
242
242
 
@@ -328,6 +328,10 @@ An entity's events must form one stream. If two actors with the same `id` both w
328
328
 
329
329
  That's where supervision comes in. A restart replays the journal, so the loser catches up on the winner's events and carries on after them. Use **`restartWithBackoff`** for persistent actors. A conflict, or a database that's down, won't clear up in the next microtask, and every restart reads the whole stream again. Backoff spaces out those reads, with jitter so a fleet of entities doesn't retry in step, instead of hammering a journal that's already in trouble.
330
330
 
331
+ ### Timeouts
332
+
333
+ Every journal, snapshot and offset call a persistent actor or a projection makes gives up after **`timeoutMs`**, 10,000 by default, on the actor's scheduler, so a database that stops answering can't hold an entity's mailbox for good. An append or a read that takes longer fails the actor with **`PersistenceTimeoutError`**, which says the call (`operation`), the actor's `id` and the `timeoutMs`, and supervision takes it from there. No reply goes out for a write that timed out: it may still have been written, so the outcome is unknown, and the restart recovers from the journal to find out ([0036](docs/decisions/0036-timeouts-are-unknown-outcomes-settled-by-recovery.md)). A snapshot load that times out is skipped, and recovery replays every event. A save that times out is logged.
334
+
331
335
  ## Clusters
332
336
 
333
337
  `@kylewillett/troupe/cluster` spreads entities, such as accounts or shows, across several Node processes. You address an entity by its type and ID from any node, and `tell` or `ask` it as if it were local. Its ref works wherever the entity lives, and keeps working when it moves. If a node dies, its entities start again on the others, recovered from the journal.
@@ -407,7 +411,7 @@ await alice.ask<Receipt>((replyTo) => ({ type: 'deposit', amount: 10, replyTo })
407
411
 
408
412
  With the default leases (`ttlMs` 10,000, renewed every 3,000, given up 2,000 early), a node killed with `kill -9` has its entities back on the others once its leases expire. Over 60 kills of three nodes on TCP and Postgres, 20 on each of Node 22, 24 and 26, an entity on the killed node answered from another node after 10.4 to 11.0 s at the median, and 11.7 s at worst ([0031](docs/decisions/0031-failover-waits-for-the-lease-not-for-downing.md)). A graceful leave is much quicker: the handoff takes milliseconds, and no ask is lost.
409
413
 
410
- Shorter leases fail over faster, at a price: a node that stalls, in a long GC pause or a slow Postgres, for longer than `ttlMs` minus `marginMs` loses every lease it holds. Pass `leases: { ttlMs, renewMs, marginMs }` to `joinCluster`, the same on every node, and keep `unreachableAfterMs` shorter than `ttlMs` minus `renewMs`.
414
+ Shorter leases fail over faster, at a price: a node that stalls, in a long GC pause or a slow Postgres, for longer than `ttlMs` minus `marginMs` loses every lease it holds. Pass `leases: { ttlMs, renewMs, marginMs }` to `joinCluster`, the same on every node, and keep `unreachableAfterMs` shorter than `ttlMs` minus `renewMs`. Every shard store call gives up after `leases.storeTimeoutMs`, `renewMs` by default. A renewal that times out counts as failed, and the holder still gives its shards up at its own deadline, whether the store answers or not.
411
415
 
412
416
  Backstage works on a cluster node too. It adds a Cluster panel, with the members as this node sees them and a grid of who holds each shard, and shows the sharding tree above `/user`.
413
417
 
package/dist/cell.d.ts CHANGED
@@ -52,9 +52,10 @@ export interface CellHost {
52
52
  setTimer(task: () => void, delayMs: number): () => void;
53
53
  /**
54
54
  * Called with +1 when a cell starts waiting on a promise, from an async handler or
55
- * `pipeToSelf`, and -1 when it settles. The testkit's `settle` waits for the count to reach 0.
55
+ * `pipeToSelf`, and -1 when it settles, with the cell's path. The testkit's `settle` waits for
56
+ * the count to reach 0, and Rehearsal's run loop names the actors that stay busy.
56
57
  */
57
- trackBusy(delta: 1 | -1): void;
58
+ trackBusy(path: string, delta: 1 | -1): void;
58
59
  /** Makes a ref with the system's `ask`. */
59
60
  makeRef<M>(path: string, tell: (msg: M) => void): ActorRef<M>;
60
61
  /**
package/dist/cell.js CHANGED
@@ -112,13 +112,14 @@ export class Cell {
112
112
  host.events.publish(body);
113
113
  },
114
114
  track: (promise) => {
115
- host.trackBusy(1);
115
+ host.trackBusy(this.path, 1);
116
116
  const done = () => {
117
- host.trackBusy(-1);
117
+ host.trackBusy(this.path, -1);
118
118
  };
119
119
  Promise.resolve(promise).then(done, done);
120
120
  },
121
121
  asSender: (fn) => this.#asSender(fn),
122
+ setTimer: (task, delayMs) => host.setTimer(task, delayMs),
122
123
  };
123
124
  this.ref = host.makeRef(path, (msg) => {
124
125
  this.#enqueue(msg);
@@ -353,9 +354,9 @@ export class Cell {
353
354
  Promise.resolve(promise).then(undefined, () => { });
354
355
  return;
355
356
  }
356
- host.trackBusy(1);
357
+ host.trackBusy(this.path, 1);
357
358
  const deliver = (result) => {
358
- host.trackBusy(-1);
359
+ host.trackBusy(this.path, -1);
359
360
  enqueue(result);
360
361
  };
361
362
  Promise.resolve(promise).then((value) => {
@@ -562,17 +563,17 @@ export class Cell {
562
563
  */
563
564
  #awaitBusy(promise, ok, failed) {
564
565
  this.#busy = true;
565
- this.#host.trackBusy(1);
566
+ this.#host.trackBusy(this.path, 1);
566
567
  Promise.resolve(promise).then((value) => {
567
568
  this.#busy = false;
568
- this.#host.trackBusy(-1);
569
+ this.#host.trackBusy(this.path, -1);
569
570
  this.#asSender(() => {
570
571
  ok(value);
571
572
  });
572
573
  this.#scheduleIfReady();
573
574
  }, (error) => {
574
575
  this.#busy = false;
575
- this.#host.trackBusy(-1);
576
+ this.#host.trackBusy(this.path, -1);
576
577
  this.#asSender(() => {
577
578
  failed(error);
578
579
  });
@@ -78,6 +78,13 @@ export interface LeaseOptions {
78
78
  renewMs?: number;
79
79
  /** How long before the store's expiry this node gives a lease up. Default 2,000. */
80
80
  marginMs?: number;
81
+ /**
82
+ * How long each shard store call may take before this node gives up on it: an acquire, a
83
+ * renewal, a release, or a read of holders or remembered entities. Default `renewMs`. A
84
+ * renewal that times out counts as failed, and an acquire may still have been granted, so the
85
+ * next acquire finds the lease this node's own (decision 0036).
86
+ */
87
+ storeTimeoutMs?: number;
81
88
  }
82
89
  /** What sharding needs from its node. */
83
90
  export interface ShardingEnv {
@@ -9,6 +9,7 @@ import { ActorNameError } from '../errors.js';
9
9
  import { isValidName } from '../names.js';
10
10
  import { checkStrategy, supervise } from '../supervision.js';
11
11
  import { leaseKeeper } from './leases.js';
12
+ import { timedStore } from './timed-store.js';
12
13
  import { Internal, regionDef } from './region.js';
13
14
  import { utf8Bytes } from './remoting.js';
14
15
  import { entityPath } from './shard.js';
@@ -26,7 +27,7 @@ const OPTIONS = new Set([
26
27
  'rebalanceMs',
27
28
  'maxHandoffs',
28
29
  ]);
29
- const LEASE_OPTIONS = new Set(['ttlMs', 'renewMs', 'marginMs']);
30
+ const LEASE_OPTIONS = new Set(['ttlMs', 'renewMs', 'marginMs', 'storeTimeoutMs']);
30
31
  const MAX_SHARDS = 65_536;
31
32
  const MEMBER_EVENTS = new Set([
32
33
  'memberUp',
@@ -37,18 +38,21 @@ const MEMBER_EVENTS = new Set([
37
38
  ]);
38
39
  /** Checks `joinCluster`'s `leases` option, and fills in the defaults. */
39
40
  export function checkLeases(leases) {
40
- if (leases === undefined)
41
- return { ttlMs: 10_000, renewMs: 3_000, marginMs: 2_000 };
41
+ if (leases === undefined) {
42
+ return { ttlMs: 10_000, renewMs: 3_000, marginMs: 2_000, storeTimeoutMs: 3_000 };
43
+ }
42
44
  checkKeys(leases, LEASE_OPTIONS, 'joinCluster: leases');
43
45
  const { ttlMs = 10_000, renewMs = 3_000, marginMs = 2_000 } = leases;
46
+ const { storeTimeoutMs = renewMs } = leases;
44
47
  checkInt(ttlMs, 'joinCluster: leases.ttlMs');
45
48
  checkInt(renewMs, 'joinCluster: leases.renewMs');
46
49
  checkInt(marginMs, 'joinCluster: leases.marginMs', { min: 0 });
50
+ checkInt(storeTimeoutMs, 'joinCluster: leases.storeTimeoutMs');
47
51
  if (renewMs >= ttlMs - marginMs) {
48
52
  throw new TypeError(`joinCluster: leases.renewMs must be less than ttlMs - marginMs, so a renewal lands ` +
49
53
  `before the deadline, got ${String(renewMs)} with ttlMs ${String(ttlMs)} and marginMs ${String(marginMs)}`);
50
54
  }
51
- return { ttlMs, renewMs, marginMs };
55
+ return { ttlMs, renewMs, marginMs, storeTimeoutMs };
52
56
  }
53
57
  /** Whether `value` has a shard store's shape. */
54
58
  export function isShardStore(value) {
@@ -94,12 +98,17 @@ export function startSharding(env) {
94
98
  unsubscribe();
95
99
  keeper?.close();
96
100
  });
101
+ const { storeTimeoutMs, ...timing } = env.leases;
102
+ // One wrapper for every caller: the keeper, the regions and their shards.
103
+ const store = env.store === undefined
104
+ ? undefined
105
+ : timedStore(env.store, storeTimeoutMs, (task, ms) => hooks.scheduler.setTimer(task, ms));
97
106
  const keeperFor = (store) => {
98
107
  keeper ??= leaseKeeper({
99
108
  store,
100
109
  holder,
101
110
  scheduler: hooks.scheduler,
102
- ...env.leases,
111
+ ...timing,
103
112
  onLost: (lease, token) => {
104
113
  const slash = lease.indexOf('/');
105
114
  const registered = types.get(lease.slice(0, slash));
@@ -149,7 +158,6 @@ export function startSharding(env) {
149
158
  init(opts) {
150
159
  const checked = checkInit(opts);
151
160
  const { type, shardCount } = checked;
152
- const store = env.store;
153
161
  if (store === undefined) {
154
162
  throw new TypeError('sharding.init: the cluster has no shard store: pass joinCluster a `shards` option');
155
163
  }
@@ -0,0 +1,4 @@
1
+ import { type SetTimer } from '../timeout.js';
2
+ import type { ShardStore } from './shard-store.js';
3
+ /** `store`, with every call failing if it hasn't answered within `ms`. */
4
+ export declare function timedStore(store: ShardStore, ms: number, setTimer: SetTimer): ShardStore;
@@ -0,0 +1,19 @@
1
+ // Every shard store call the cluster makes, timed on the node's scheduler (decision 0036). Each
2
+ // caller already treats a failed call as one to retry or log, so a timeout reuses that path. A
3
+ // renewal that times out counts as failed, and the holder's deadline still drops the lease
4
+ // (decision 0029). An acquire that times out may have been granted: the holder's next acquire
5
+ // finds the lease its own and keeps it. Never exported.
6
+ import { withTimeout } from '../timeout.js';
7
+ /** `store`, with every call failing if it hasn't answered within `ms`. */
8
+ export function timedStore(store, ms, setTimer) {
9
+ const timed = (call, promise) => withTimeout(promise, ms, setTimer, () => new Error(`shard store: ${call} did not answer within ${String(ms)} ms`));
10
+ return {
11
+ acquire: (lease, holder, ttlMs) => timed('acquire', store.acquire(lease, holder, ttlMs)),
12
+ renewAll: (holder, ttlMs) => timed('renewAll', store.renewAll(holder, ttlMs)),
13
+ release: (lease, holder, token) => timed('release', store.release(lease, holder, token)),
14
+ holders: (prefix) => timed('holders', store.holders(prefix)),
15
+ remember: (shard, id) => timed('remember', store.remember(shard, id)),
16
+ forget: (shard, id) => timed('forget', store.forget(shard, id)),
17
+ remembered: (shard) => timed('remembered', store.remembered(shard)),
18
+ };
19
+ }
package/dist/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  export { actor } from './actor.js';
2
2
  export { ActorNameError, ActorStoppedError, ActorSystemTerminatedError, AskTimeoutError, NotAChildError, } from './errors.js';
3
+ export { isJsonValue, jsonProblem, type JsonValue } from './json.js';
3
4
  export { consoleLogger, silentLogger, type Logger, type LogLevel } from './logger.js';
4
5
  export { realScheduler, type Scheduler } from './scheduler.js';
5
6
  export { supervise, type SupervisorStrategy } from './supervision.js';
package/dist/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  // Public API. Export only from here and from testkit/index.ts.
2
2
  export { actor } from './actor.js';
3
3
  export { ActorNameError, ActorStoppedError, ActorSystemTerminatedError, AskTimeoutError, NotAChildError, } from './errors.js';
4
+ export { isJsonValue, jsonProblem } from './json.js';
4
5
  export { consoleLogger, silentLogger } from './logger.js';
5
6
  export { realScheduler } from './scheduler.js';
6
7
  export { supervise } from './supervision.js';
@@ -31,6 +31,11 @@ export interface CellInternals {
31
31
  * `await` on the actor's behalf: a persistent actor's effect steps (decision 0020).
32
32
  */
33
33
  asSender<T>(fn: () => T): T;
34
+ /**
35
+ * The system scheduler's `setTimer`, for a timeout an actor awaits inside `receive`, where its
36
+ * keyed timers can't help: their messages wait in the mailbox it holds (decision 0036).
37
+ */
38
+ readonly setTimer: (task: () => void, delayMs: number) => () => void;
34
39
  }
35
40
  /** The internals of a `ctx` the system made. */
36
41
  export declare function internalsOf(ctx: object): CellInternals;
@@ -130,6 +130,15 @@ export interface PersistentActorDef<C, E, S> {
130
130
  */
131
131
  version?: number;
132
132
  };
133
+ /**
134
+ * How long each journal and snapshot call may take, in ms: a positive integer. Default 10,000.
135
+ * An append or a recovery read that takes longer fails the actor with
136
+ * `PersistenceTimeoutError`, for its supervision to handle, and no reply is sent. The append
137
+ * may still have been written, so a restart recovers from the journal to find out (decision
138
+ * 0036). A snapshot load that takes longer is skipped, and recovery replays every event. A
139
+ * snapshot save that takes longer is logged.
140
+ */
141
+ timeoutMs?: number;
133
142
  }
134
143
  /**
135
144
  * Defines an event-sourced actor. Commands go to `onCommand`, which returns an effect. Its events
@@ -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';
5
+ import { EventValidationError, EventVersionError, JournalSequenceError, PersistenceTimeoutError, } from './errors.js';
6
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');
@@ -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';
@@ -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)
@@ -0,0 +1,54 @@
1
+ import type { Transport } from '../cluster/transport.js';
2
+ import type { Scheduler } from '../scheduler.js';
3
+ import type { ManualScheduler } from '../testkit/manual-scheduler.js';
4
+ /** Options for a {@link NodeClock}. */
5
+ export interface NodeClockOptions {
6
+ /**
7
+ * How far the clock's rate is from simulation time's, in parts per million: at 200, it reads
8
+ * 1,000,200 ms while a million pass. An integer from -100,000 to 100,000. Default 0.
9
+ */
10
+ driftPpm?: number;
11
+ /** What its `now()` reads when it's made, in ms. Default the simulation's time then. */
12
+ startAt?: number;
13
+ }
14
+ /**
15
+ * One node's scheduler in a simulation: a view onto the simulation's {@link ManualScheduler} at its
16
+ * own rate. Its `now()` is whole milliseconds and never goes backwards, and its timers fire when
17
+ * its own clock reaches them.
18
+ *
19
+ * {@link NodeClock.pause} stops the node's process, as a long GC or a suspended VM does: none of its
20
+ * tasks or timers run, though its clock keeps going. {@link NodeClock.resume} then runs everything
21
+ * that fell due meanwhile, in the order it fell due, before anything new.
22
+ */
23
+ export declare class NodeClock implements Scheduler {
24
+ #private;
25
+ /**
26
+ * Makes a clock for one node on `sim`.
27
+ * @throws TypeError for options that can't be used.
28
+ */
29
+ constructor(sim: ManualScheduler, opts?: NodeClockOptions);
30
+ /** The node's own time, in whole ms. */
31
+ now(): number;
32
+ /** Whether the node is paused. */
33
+ get paused(): boolean;
34
+ /** Queues `task` on the simulation, to run as this node's. */
35
+ runSoon(task: () => void): void;
36
+ /**
37
+ * Runs `task` once this node's clock has moved `delayMs` on: at the first whole millisecond of
38
+ * simulation time when `now()` reads at least that. A negative or `NaN` delay counts as 0.
39
+ */
40
+ setTimer(task: () => void, delayMs: number): () => void;
41
+ /** Stops the node's process. Its clock keeps going. Pausing a paused node does nothing. */
42
+ pause(): void;
43
+ /**
44
+ * Lets the node run again: what fell due while it was paused runs on the simulation's next turn,
45
+ * in order, before anything that falls due later. Resuming a running node does nothing.
46
+ */
47
+ resume(): void;
48
+ }
49
+ /**
50
+ * Wraps `transport` so that everything it hands its node, from new connections and frames to
51
+ * closes and refusals, arrives through the node's `clock`. While the node is paused, its frames
52
+ * wait at its sockets and it can't answer anyone, and when it resumes they arrive in order.
53
+ */
54
+ export declare function throughClock(transport: Transport, clock: Scheduler): Transport;