@kylewillett/troupe 0.2.0 → 0.3.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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,22 @@
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.1 (2026-11-24)
6
+
7
+ For Steadfast: a piped promise that the actor's own timer ends no longer holds up the testkit's `advance`. Released from 0.3.0, so Rehearsal still isn't exported.
8
+
9
+ - `ctx.pipeToSelf(promise, map, { signal })`: when `signal` aborts, the pipe delivers `{ ok: false, error: signal.reason }` at once and ignores whatever the promise does later. A pipe with a signal isn't busy work, so the testkit's `settle` and `advance` let time pass while it's pending, and Rehearsal's run loop doesn't count it as a stall. Abort it from one of the actor's timers or its `postStop`. `settle` still gives it one event-loop turn, so a promise that has already settled arrives first. `PipeOptions` and `PipeSignal`, a structural type every runtime's `AbortSignal` fits, are exported from the main entry. `pipeToSelf` without options is unchanged ([0038](https://github.com/Fours/troupe/blob/main/docs/decisions/0038-a-pipe-with-a-signal-ends-on-the-scheduler.md)).
10
+
11
+ ## 0.3.0 (2026-11-24)
12
+
13
+ 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**.
14
+
15
+ - **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)).
16
+ - `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)).
17
+ - `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)).
18
+ - `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)).
19
+ - `@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)).
20
+
5
21
  ## 0.2.0 (2026-11-24)
6
22
 
7
23
  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
@@ -163,6 +163,7 @@ const session = actor<SessionMsg, { lastLoaded?: string }>({
163
163
 
164
164
  - **Timers** are keyed. `startSingle` and `startPeriodic` replace any timer with the same key, and `cancel(key)` stops one. Once a timer is cancelled or replaced, its message is never received, even if it's already in the mailbox. Every timer is cancelled when the actor stops or restarts.
165
165
  - **`ctx.pipeToSelf(promise, map)`** waits for a promise without blocking the mailbox. When the promise settles, the actor gets `map(result)` as a message, where `result` is `{ ok: true, value }` or `{ ok: false, error }`. The mapper runs inside the actor, so a throw there goes to supervision.
166
+ - **`ctx.pipeToSelf(promise, map, { signal })`** also ends the pipe when `signal` aborts: the actor gets `map({ ok: false, error: signal.reason })` at once, and whatever the promise does afterwards is ignored. Use it for work that one of the actor's own timers, or its `postStop`, cancels, such as a call with a timeout. A promise that ignores its signal then can't hold the actor up ([0038](docs/decisions/0038-a-pipe-with-a-signal-ends-on-the-scheduler.md)).
166
167
 
167
168
  ## The testkit
168
169
 
@@ -184,7 +185,7 @@ await kit.advance(60_000); // fires every timer due in the next minute, in order
184
185
  await kit.shutdown();
185
186
  ```
186
187
 
187
- - **`kit.settle()`** runs everything that can happen without time passing: queued messages, due timers, and async `receive` work. It throws `SettleTimeoutError` if an actor stays busy, for example awaiting a promise that never settles.
188
+ - **`kit.settle()`** runs everything that can happen without time passing: queued messages, due timers, and async `receive` work. It throws `SettleTimeoutError` if an actor stays busy, for example awaiting a promise that never settles. A pipe with a signal isn't waited for, since the signal ends it, so `advance` can let time pass until the actor's timer aborts it. It gets one event-loop turn, so a promise that has already settled still arrives.
188
189
  - **`kit.advance(ms)`** moves virtual time forward. It fires timers in order, and settles at each due time.
189
190
  - **Probes** are refs that record what they're sent. Their assertions are synchronous: `expectMessage(value | predicate)`, `expectNoMessage()`, `messages()`, and `watch(ref)` then `expectTerminated(ref)`. Settle or advance first, then assert.
190
191
  - **`kit.events`** and **`kit.logs`** record everything the system published and logged.
@@ -236,7 +237,7 @@ const alice = system.spawn(account('alice'), 'alice');
236
237
  await alice.ask<Receipt>((replyTo) => ({ type: 'deposit', amount: 10, replyTo })); // balance 10
237
238
  ```
238
239
 
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.
240
+ `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
241
 
241
242
  ### Effects
242
243
 
@@ -328,6 +329,10 @@ An entity's events must form one stream. If two actors with the same `id` both w
328
329
 
329
330
  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
331
 
332
+ ### Timeouts
333
+
334
+ 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.
335
+
331
336
  ## Clusters
332
337
 
333
338
  `@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 +412,7 @@ await alice.ask<Receipt>((replyTo) => ({ type: 'deposit', amount: 10, replyTo })
407
412
 
408
413
  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
414
 
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`.
415
+ 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
416
 
412
417
  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
418
 
package/dist/cell.d.ts CHANGED
@@ -52,9 +52,15 @@ 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;
59
+ /**
60
+ * Called with +1 when a cell pipes a promise with a signal, and -1 when the pipe ends. These
61
+ * aren't busy work: the testkit's `settle` only gives them one event-loop turn (decision 0038).
62
+ */
63
+ trackBounded(delta: 1 | -1): void;
58
64
  /** Makes a ref with the system's `ask`. */
59
65
  makeRef<M>(path: string, tell: (msg: M) => void): ActorRef<M>;
60
66
  /**
package/dist/cell.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { checkKeys } from './checks.js';
1
2
  import { ActorStoppedError, NotAChildError } from './errors.js';
2
3
  import { INTERNALS, persistentHookOf, START, } from './internal.js';
3
4
  import { safeLogger } from './logger.js';
@@ -112,13 +113,14 @@ export class Cell {
112
113
  host.events.publish(body);
113
114
  },
114
115
  track: (promise) => {
115
- host.trackBusy(1);
116
+ host.trackBusy(this.path, 1);
116
117
  const done = () => {
117
- host.trackBusy(-1);
118
+ host.trackBusy(this.path, -1);
118
119
  };
119
120
  Promise.resolve(promise).then(done, done);
120
121
  },
121
122
  asSender: (fn) => this.#asSender(fn),
123
+ setTimer: (task, delayMs) => host.setTimer(task, delayMs),
122
124
  };
123
125
  this.ref = host.makeRef(path, (msg) => {
124
126
  this.#enqueue(msg);
@@ -256,11 +258,11 @@ export class Cell {
256
258
  child: (childName) => this.childCells.get(childName)?.ref,
257
259
  children: () => [...this.childCells.values()].map((c) => c.ref),
258
260
  timers: timersFor(this.#timers, () => current() && this.#phase === 'running'),
259
- pipeToSelf: (promise, map) => {
261
+ pipeToSelf: (promise, map, opts) => {
260
262
  if (typeof map !== 'function') {
261
263
  throw new TypeError('pipeToSelf: map must be a function');
262
264
  }
263
- this.#pipe(promise, map);
265
+ this.#pipe(promise, map, pipeSignal(opts));
264
266
  },
265
267
  };
266
268
  // Not enumerable, so spreading or logging a ctx doesn't show it.
@@ -340,22 +342,26 @@ export class Cell {
340
342
  * An ask's result is queued the moment the ask settles, with no promise hop, so piping an ask
341
343
  * runs entirely on the scheduler and isn't busy work for `settle` (decision 0010).
342
344
  */
343
- #pipe(promise, map) {
345
+ #pipe(promise, map, signal) {
344
346
  const host = this.#host;
345
347
  // The envelope only ever passes this result to this mapper, so widening T is safe.
346
348
  const widened = map;
347
349
  const enqueue = (result) => {
348
350
  this.#enqueue(new PipeEnvelope(result, widened));
349
351
  };
352
+ if (signal !== undefined) {
353
+ this.#pipeBounded(promise, enqueue, signal);
354
+ return;
355
+ }
350
356
  if (host.onAskSettled(promise, enqueue)) {
351
357
  // The result arrives through the listener. Handle the rejection here too, or a timed-out
352
358
  // ask would be an unhandled rejection.
353
359
  Promise.resolve(promise).then(undefined, () => { });
354
360
  return;
355
361
  }
356
- host.trackBusy(1);
362
+ host.trackBusy(this.path, 1);
357
363
  const deliver = (result) => {
358
- host.trackBusy(-1);
364
+ host.trackBusy(this.path, -1);
359
365
  enqueue(result);
360
366
  };
361
367
  Promise.resolve(promise).then((value) => {
@@ -364,6 +370,42 @@ export class Cell {
364
370
  deliver({ ok: false, error });
365
371
  });
366
372
  }
373
+ /**
374
+ * A pipe that its signal ends, whichever comes first, so the actor's own timer or stop bounds
375
+ * it. It isn't busy work for `settle` (decision 0038).
376
+ */
377
+ #pipeBounded(promise, enqueue, signal) {
378
+ const host = this.#host;
379
+ // Whatever comes second is dropped, and a rejection after the abort is handled here.
380
+ const settled = Promise.resolve(promise);
381
+ settled.then(undefined, () => { });
382
+ if (signal.aborted) {
383
+ enqueue({ ok: false, error: signal.reason });
384
+ return;
385
+ }
386
+ host.trackBounded(1);
387
+ let done = false;
388
+ const finish = (result) => {
389
+ if (done)
390
+ return;
391
+ done = true;
392
+ signal.removeEventListener('abort', onAbort);
393
+ host.trackBounded(-1);
394
+ enqueue(result);
395
+ };
396
+ // Abort listeners run synchronously in abort(), so the rejection is queued before it returns.
397
+ const onAbort = () => {
398
+ finish({ ok: false, error: signal.reason });
399
+ };
400
+ signal.addEventListener('abort', onAbort);
401
+ if (host.onAskSettled(promise, finish))
402
+ return;
403
+ settled.then((value) => {
404
+ finish({ ok: true, value });
405
+ }, (error) => {
406
+ finish({ ok: false, error });
407
+ });
408
+ }
367
409
  #stopping() {
368
410
  return this.#phase === 'stopping' || this.#phase === 'terminated';
369
411
  }
@@ -562,17 +604,17 @@ export class Cell {
562
604
  */
563
605
  #awaitBusy(promise, ok, failed) {
564
606
  this.#busy = true;
565
- this.#host.trackBusy(1);
607
+ this.#host.trackBusy(this.path, 1);
566
608
  Promise.resolve(promise).then((value) => {
567
609
  this.#busy = false;
568
- this.#host.trackBusy(-1);
610
+ this.#host.trackBusy(this.path, -1);
569
611
  this.#asSender(() => {
570
612
  ok(value);
571
613
  });
572
614
  this.#scheduleIfReady();
573
615
  }, (error) => {
574
616
  this.#busy = false;
575
- this.#host.trackBusy(-1);
617
+ this.#host.trackBusy(this.path, -1);
576
618
  this.#asSender(() => {
577
619
  failed(error);
578
620
  });
@@ -786,3 +828,22 @@ function isThenable(value) {
786
828
  value !== null &&
787
829
  typeof value.then === 'function');
788
830
  }
831
+ const PIPE_OPTIONS = new Set(['signal']);
832
+ /** Checks `pipeToSelf`'s options where they're passed in, and returns the signal, if any. */
833
+ function pipeSignal(opts) {
834
+ if (opts === undefined)
835
+ return undefined;
836
+ checkKeys(opts, PIPE_OPTIONS, 'pipeToSelf');
837
+ const { signal } = opts;
838
+ if (signal === undefined)
839
+ return undefined;
840
+ const candidate = signal;
841
+ if (typeof candidate !== 'object' ||
842
+ candidate === null ||
843
+ typeof candidate.aborted !== 'boolean' ||
844
+ typeof candidate.addEventListener !== 'function' ||
845
+ typeof candidate.removeEventListener !== 'function') {
846
+ throw new TypeError('pipeToSelf: signal must be an AbortSignal');
847
+ }
848
+ return signal;
849
+ }
@@ -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,7 +1,8 @@
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';
6
7
  export { createActorSystem } from './system.js';
7
- export type { ActorContext, ActorDef, ActorRef, ActorSystem, ActorSystemOptions, AnyRef, AskOptions, EventStream, Result, Signal, SpawnOptions, SystemEvent, Timers, } from './types.js';
8
+ export type { ActorContext, ActorDef, ActorRef, ActorSystem, ActorSystemOptions, AnyRef, AskOptions, EventStream, PipeOptions, PipeSignal, Result, Signal, SpawnOptions, SystemEvent, Timers, } from './types.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 {