@kylewillett/troupe 0.3.0 → 0.3.2

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,18 @@
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.2 (2026-11-24)
6
+
7
+ For Steadfast: a failure can raise its backoff restart delay, for a 429's `retry-after`. Released from 0.3.1, so Rehearsal still isn't exported.
8
+
9
+ - `supervise.restartWithBackoff` takes `minDelayFor: (failure) => number | undefined`. It's called with each failure as it was thrown, and returns the fewest ms the restart must wait, such as a server's `retry-after`, or `undefined`. The restart waits `max(backoff, minimum)`, with jitter on top, so never sooner than the minimum. The minimum isn't capped by `maxMs`, and doesn't count as extra backoff steps. A `minDelayFor` that throws, or returns anything but a non-negative integer or `undefined`, is logged at `error` and the ordinary backoff applies. Without it, backoff is unchanged ([0041](https://github.com/Fours/troupe/blob/main/docs/decisions/0041-a-failure-can-raise-its-backoff-delay.md)).
10
+
11
+ ## 0.3.1 (2026-11-24)
12
+
13
+ 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.
14
+
15
+ - `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)).
16
+
5
17
  ## 0.3.0 (2026-11-24)
6
18
 
7
19
  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**.
package/README.md CHANGED
@@ -125,7 +125,20 @@ ctx.spawn(show, 'hamlet', {
125
125
  | `supervise.stop()` (the default) | The actor stops, and watchers get `terminated` with the `failure`. |
126
126
  | `supervise.resume()` | The actor keeps its state, drops the message that failed, and carries on. |
127
127
  | `supervise.restart({ maxRestarts, withinMs })` | It runs `preRestart`, stops its children and timers, and runs `initial` again. The mailbox and the ref carry over. Too many failures within the window stop it instead. |
128
- | `supervise.restartWithBackoff({ minMs, maxMs, randomFactor, resetAfterMs })` | A restart that first waits `minMs`, doubling each time up to `maxMs`, with random jitter. Messages queue up while it waits. |
128
+ | `supervise.restartWithBackoff({ minMs, maxMs, randomFactor, resetAfterMs, minDelayFor })` | A restart that first waits `minMs`, doubling each time up to `maxMs`, with random jitter. Messages queue up while it waits. |
129
+
130
+ When a failure says how long to wait, such as a 429 with a `retry-after`, give the backoff a **`minDelayFor`**. It's called with each failure, as it was thrown, and returns the fewest ms to wait, or `undefined`. The restart waits for that or for the backoff, whichever is longer, with jitter on top. A minimum isn't capped by `maxMs`, since the server knows better, and doesn't count as extra backoff steps ([0041](docs/decisions/0041-a-failure-can-raise-its-backoff-delay.md)):
131
+
132
+ ```ts
133
+ supervise.restartWithBackoff({
134
+ minMs: 1_000,
135
+ maxMs: 60_000,
136
+ minDelayFor: (failure) =>
137
+ failure instanceof Error && failure.cause instanceof ModelError
138
+ ? failure.cause.retryAfterMs // a 5 s retry-after waits 5 to 6 s, not 1 s
139
+ : undefined,
140
+ });
141
+ ```
129
142
 
130
143
  A restart is a new incarnation: its state starts from `initial`, and whatever the old one held is gone, unless it's a [persistent actor](#persistent-actors), which recovers its state from its journal. Every failure publishes a `failed` event and logs at `error`.
131
144
 
@@ -163,6 +176,7 @@ const session = actor<SessionMsg, { lastLoaded?: string }>({
163
176
 
164
177
  - **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
178
  - **`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.
179
+ - **`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
180
 
167
181
  ## The testkit
168
182
 
@@ -184,7 +198,7 @@ await kit.advance(60_000); // fires every timer due in the next minute, in order
184
198
  await kit.shutdown();
185
199
  ```
186
200
 
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.
201
+ - **`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
202
  - **`kit.advance(ms)`** moves virtual time forward. It fires timers in order, and settles at each due time.
189
203
  - **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
204
  - **`kit.events`** and **`kit.logs`** record everything the system published and logged.
package/dist/cell.d.ts CHANGED
@@ -56,6 +56,11 @@ export interface CellHost {
56
56
  * the count to reach 0, and Rehearsal's run loop names the actors that stay busy.
57
57
  */
58
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;
59
64
  /** Makes a ref with the system's `ask`. */
60
65
  makeRef<M>(path: string, tell: (msg: M) => void): ActorRef<M>;
61
66
  /**
package/dist/cell.js CHANGED
@@ -1,9 +1,10 @@
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';
4
5
  import { Names } from './names.js';
5
6
  import { Queue } from './queue.js';
6
- import { decide, NO_FAILURES, } from './supervision.js';
7
+ import { decide, minimumDelay, NO_FAILURES, } from './supervision.js';
7
8
  import { TimerEnvelope, TimerTable, timersFor } from './timers.js';
8
9
  /** A settled `pipeToSelf` promise in the mailbox. Its mapper runs when it's dequeued. */
9
10
  class PipeEnvelope {
@@ -257,11 +258,11 @@ export class Cell {
257
258
  child: (childName) => this.childCells.get(childName)?.ref,
258
259
  children: () => [...this.childCells.values()].map((c) => c.ref),
259
260
  timers: timersFor(this.#timers, () => current() && this.#phase === 'running'),
260
- pipeToSelf: (promise, map) => {
261
+ pipeToSelf: (promise, map, opts) => {
261
262
  if (typeof map !== 'function') {
262
263
  throw new TypeError('pipeToSelf: map must be a function');
263
264
  }
264
- this.#pipe(promise, map);
265
+ this.#pipe(promise, map, pipeSignal(opts));
265
266
  },
266
267
  };
267
268
  // Not enumerable, so spreading or logging a ctx doesn't show it.
@@ -341,13 +342,17 @@ export class Cell {
341
342
  * An ask's result is queued the moment the ask settles, with no promise hop, so piping an ask
342
343
  * runs entirely on the scheduler and isn't busy work for `settle` (decision 0010).
343
344
  */
344
- #pipe(promise, map) {
345
+ #pipe(promise, map, signal) {
345
346
  const host = this.#host;
346
347
  // The envelope only ever passes this result to this mapper, so widening T is safe.
347
348
  const widened = map;
348
349
  const enqueue = (result) => {
349
350
  this.#enqueue(new PipeEnvelope(result, widened));
350
351
  };
352
+ if (signal !== undefined) {
353
+ this.#pipeBounded(promise, enqueue, signal);
354
+ return;
355
+ }
351
356
  if (host.onAskSettled(promise, enqueue)) {
352
357
  // The result arrives through the listener. Handle the rejection here too, or a timed-out
353
358
  // ask would be an unhandled rejection.
@@ -365,6 +370,42 @@ export class Cell {
365
370
  deliver({ ok: false, error });
366
371
  });
367
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
+ }
368
409
  #stopping() {
369
410
  return this.#phase === 'stopping' || this.#phase === 'terminated';
370
411
  }
@@ -582,11 +623,17 @@ export class Cell {
582
623
  }
583
624
  /** Hands a failure to the strategy, then publishes and logs what it decided. */
584
625
  #fail(error, context, inInitial = false) {
626
+ const minimum = minimumDelay(this.#strategy, error);
627
+ if (minimum.problem !== undefined) {
628
+ const thrown = 'error' in minimum ? { thrown: minimum.error } : {};
629
+ this.#log.error(minimum.problem, { ...context, error, ...thrown });
630
+ }
585
631
  const { decision, history } = decide(this.#strategy, this.#history, {
586
632
  now: this.#host.now(),
587
633
  startedAt: this.#startedAt,
588
634
  inInitial,
589
635
  random: () => this.#host.random(),
636
+ minDelayMs: minimum.ms,
590
637
  });
591
638
  this.#history = history;
592
639
  const { directive } = decision;
@@ -787,3 +834,22 @@ function isThenable(value) {
787
834
  value !== null &&
788
835
  typeof value.then === 'function');
789
836
  }
837
+ const PIPE_OPTIONS = new Set(['signal']);
838
+ /** Checks `pipeToSelf`'s options where they're passed in, and returns the signal, if any. */
839
+ function pipeSignal(opts) {
840
+ if (opts === undefined)
841
+ return undefined;
842
+ checkKeys(opts, PIPE_OPTIONS, 'pipeToSelf');
843
+ const { signal } = opts;
844
+ if (signal === undefined)
845
+ return undefined;
846
+ const candidate = signal;
847
+ if (typeof candidate !== 'object' ||
848
+ candidate === null ||
849
+ typeof candidate.aborted !== 'boolean' ||
850
+ typeof candidate.addEventListener !== 'function' ||
851
+ typeof candidate.removeEventListener !== 'function') {
852
+ throw new TypeError('pipeToSelf: signal must be an AbortSignal');
853
+ }
854
+ return signal;
855
+ }
package/dist/index.d.ts CHANGED
@@ -5,4 +5,4 @@ export { consoleLogger, silentLogger, type Logger, type LogLevel } from './logge
5
5
  export { realScheduler, type Scheduler } from './scheduler.js';
6
6
  export { supervise, type SupervisorStrategy } from './supervision.js';
7
7
  export { createActorSystem } from './system.js';
8
- 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';
@@ -16,6 +16,11 @@ export type SupervisorStrategy = {
16
16
  readonly maxMs: number;
17
17
  readonly randomFactor: number;
18
18
  readonly resetAfterMs: number;
19
+ /**
20
+ * The fewest ms a restart must wait for a failure, or `undefined` for no minimum. See
21
+ * {@link supervise.restartWithBackoff}. Absent when no failure raises the delay.
22
+ */
23
+ readonly minDelayFor?: (failure: unknown) => number | undefined;
19
24
  };
20
25
  /** Builds supervisor strategies. Each one checks its options and throws `TypeError` for bad ones. */
21
26
  export declare const supervise: Readonly<{
@@ -37,17 +42,25 @@ export declare const supervise: Readonly<{
37
42
  }): SupervisorStrategy;
38
43
  /**
39
44
  * Restart, as {@link supervise.restart} does, but wait first. Restart number `n`, counting from
40
- * 0, waits `min(maxMs, minMs * 2^n) * (1 + random() * randomFactor)` ms, rounded. `n` goes back
41
- * to 0 once the actor has run for `resetAfterMs` without failing.
45
+ * 0, waits `max(min(maxMs, minMs * 2^n), minimum) * (1 + random() * randomFactor)` ms, rounded,
46
+ * where `minimum` is what `minDelayFor` returned for the failure, or 0. `n` goes back to 0 once
47
+ * the actor has run for `resetAfterMs` without failing.
42
48
  * @param opts.randomFactor Jitter, so actors that failed together don't restart together.
43
49
  * Default 0.2.
44
50
  * @param opts.resetAfterMs Default `maxMs`.
51
+ * @param opts.minDelayFor Called with each failure, the thrown value as it is. It returns the
52
+ * fewest ms the restart must wait, such as a server's `retry-after`, or `undefined` for no
53
+ * minimum. A minimum isn't capped by `maxMs`, and doesn't count as extra backoff steps: the next
54
+ * failure's step is `n + 1` as usual. Jitter still applies on top, so the restart never comes
55
+ * sooner than the minimum. A return that isn't a non-negative integer or `undefined`, or a
56
+ * throw, is logged at `error` and the ordinary backoff applies (decision 0041).
45
57
  */
46
58
  restartWithBackoff(opts: {
47
59
  minMs: number;
48
60
  maxMs: number;
49
61
  randomFactor?: number;
50
62
  resetAfterMs?: number;
63
+ minDelayFor?: (failure: unknown) => number | undefined;
51
64
  }): SupervisorStrategy;
52
65
  }>;
53
66
  /** Checks a strategy, including one built by hand rather than by {@link supervise}. */
@@ -79,7 +92,24 @@ export interface FailureFacts {
79
92
  /** True if `initial` failed, so there's no state to resume with. */
80
93
  readonly inInitial: boolean;
81
94
  readonly random: () => number;
95
+ /** The fewest ms a backoff restart must wait for this failure, from {@link minimumDelay}. */
96
+ readonly minDelayMs: number;
82
97
  }
98
+ /** What a strategy's `minDelayFor` said about a failure: a minimum, or a problem to log. */
99
+ export type MinimumDelay = {
100
+ readonly ms: number;
101
+ readonly problem?: undefined;
102
+ } | {
103
+ readonly ms: 0;
104
+ readonly problem: string;
105
+ readonly error?: unknown;
106
+ };
107
+ /**
108
+ * Asks a backoff strategy's `minDelayFor` about a failure. It runs the user's code, so it's kept
109
+ * out of {@link decide}, and it never throws: a throw or a bad return comes back as a problem for
110
+ * the cell to log, with no minimum, so a broken reader can't break supervision.
111
+ */
112
+ export declare function minimumDelay(strategy: SupervisorStrategy, failure: unknown): MinimumDelay;
83
113
  /**
84
114
  * Decides what to do about a failure, and returns the history to keep for the next one. Pure,
85
115
  * apart from drawing from `random`, and only for backoff. Limits and resets are worked out from
@@ -1,6 +1,6 @@
1
1
  import { checkInt, checkKeys, describe } from './checks.js';
2
2
  const RESTART_OPTIONS = new Set(['maxRestarts', 'withinMs']);
3
- const BACKOFF_OPTIONS = new Set(['minMs', 'maxMs', 'randomFactor', 'resetAfterMs']);
3
+ const BACKOFF_OPTIONS = new Set(['minMs', 'maxMs', 'randomFactor', 'resetAfterMs', 'minDelayFor']);
4
4
  /** Builds supervisor strategies. Each one checks its options and throws `TypeError` for bad ones. */
5
5
  export const supervise = Object.freeze({
6
6
  /** Stop the actor, with `failure` set on `terminated` and on the `stopped` event. The default. */
@@ -26,16 +26,31 @@ export const supervise = Object.freeze({
26
26
  },
27
27
  /**
28
28
  * Restart, as {@link supervise.restart} does, but wait first. Restart number `n`, counting from
29
- * 0, waits `min(maxMs, minMs * 2^n) * (1 + random() * randomFactor)` ms, rounded. `n` goes back
30
- * to 0 once the actor has run for `resetAfterMs` without failing.
29
+ * 0, waits `max(min(maxMs, minMs * 2^n), minimum) * (1 + random() * randomFactor)` ms, rounded,
30
+ * where `minimum` is what `minDelayFor` returned for the failure, or 0. `n` goes back to 0 once
31
+ * the actor has run for `resetAfterMs` without failing.
31
32
  * @param opts.randomFactor Jitter, so actors that failed together don't restart together.
32
33
  * Default 0.2.
33
34
  * @param opts.resetAfterMs Default `maxMs`.
35
+ * @param opts.minDelayFor Called with each failure, the thrown value as it is. It returns the
36
+ * fewest ms the restart must wait, such as a server's `retry-after`, or `undefined` for no
37
+ * minimum. A minimum isn't capped by `maxMs`, and doesn't count as extra backoff steps: the next
38
+ * failure's step is `n + 1` as usual. Jitter still applies on top, so the restart never comes
39
+ * sooner than the minimum. A return that isn't a non-negative integer or `undefined`, or a
40
+ * throw, is logged at `error` and the ordinary backoff applies (decision 0041).
34
41
  */
35
42
  restartWithBackoff(opts) {
36
43
  checkKeys(opts, BACKOFF_OPTIONS, 'supervise.restartWithBackoff');
37
- const { minMs, maxMs, randomFactor = 0.2, resetAfterMs = maxMs } = opts;
38
- return checked({ type: 'backoff', minMs, maxMs, randomFactor, resetAfterMs }, 'supervise.restartWithBackoff');
44
+ const { minMs, maxMs, randomFactor = 0.2, resetAfterMs = maxMs, minDelayFor } = opts;
45
+ return checked({
46
+ type: 'backoff',
47
+ minMs,
48
+ maxMs,
49
+ randomFactor,
50
+ resetAfterMs,
51
+ // Left out when absent, so a strategy without it is the same value it always was.
52
+ ...(minDelayFor === undefined ? {} : { minDelayFor }),
53
+ }, 'supervise.restartWithBackoff');
39
54
  },
40
55
  });
41
56
  function checked(strategy, where) {
@@ -70,6 +85,9 @@ export function checkStrategy(value, where) {
70
85
  throw new TypeError(`${where}: randomFactor must be a finite number of at least 0, got ${describe(s.randomFactor)}`);
71
86
  }
72
87
  checkInt(s.resetAfterMs, `${where}: resetAfterMs`);
88
+ if (s.minDelayFor !== undefined && typeof s.minDelayFor !== 'function') {
89
+ throw new TypeError(`${where}: minDelayFor must be a function, got ${describe(s.minDelayFor)}`);
90
+ }
73
91
  return;
74
92
  default:
75
93
  throw new TypeError(`${where}: unknown supervisor strategy type ${describe(s.type)}`);
@@ -77,6 +95,32 @@ export function checkStrategy(value, where) {
77
95
  }
78
96
  /** A history with no failures in it. */
79
97
  export const NO_FAILURES = Object.freeze({ times: [], count: 0, backoffs: 0 });
98
+ const NO_MINIMUM = Object.freeze({ ms: 0 });
99
+ /**
100
+ * Asks a backoff strategy's `minDelayFor` about a failure. It runs the user's code, so it's kept
101
+ * out of {@link decide}, and it never throws: a throw or a bad return comes back as a problem for
102
+ * the cell to log, with no minimum, so a broken reader can't break supervision.
103
+ */
104
+ export function minimumDelay(strategy, failure) {
105
+ if (strategy.type !== 'backoff' || strategy.minDelayFor === undefined)
106
+ return NO_MINIMUM;
107
+ let ms;
108
+ try {
109
+ ms = strategy.minDelayFor(failure);
110
+ }
111
+ catch (error) {
112
+ return { ms: 0, problem: 'minDelayFor threw; using the backoff alone', error };
113
+ }
114
+ if (ms === undefined)
115
+ return NO_MINIMUM;
116
+ if (typeof ms !== 'number' || !Number.isSafeInteger(ms) || ms < 0) {
117
+ return {
118
+ ms: 0,
119
+ problem: `minDelayFor must return a non-negative integer or undefined, got ${describe(ms)}; using the backoff alone`,
120
+ };
121
+ }
122
+ return { ms };
123
+ }
80
124
  /**
81
125
  * Decides what to do about a failure, and returns the history to keep for the next one. Pure,
82
126
  * apart from drawing from `random`, and only for backoff. Limits and resets are worked out from
@@ -109,7 +153,8 @@ export function decide(strategy, history, facts) {
109
153
  case 'backoff': {
110
154
  const ranLongEnough = facts.now - facts.startedAt >= strategy.resetAfterMs;
111
155
  const n = ranLongEnough ? 0 : history.backoffs;
112
- const base = Math.min(strategy.maxMs, strategy.minMs * 2 ** n);
156
+ // The minimum isn't capped by maxMs: a server's retry-after wins over our own guess.
157
+ const base = Math.max(Math.min(strategy.maxMs, strategy.minMs * 2 ** n), facts.minDelayMs);
113
158
  const delayMs = Math.round(base * (1 + facts.random() * strategy.randomFactor));
114
159
  return {
115
160
  decision: { directive: 'restart', attempt: n + 1, delayMs },
package/dist/system.d.ts CHANGED
@@ -14,6 +14,12 @@ export interface SystemHandle {
14
14
  * isn't counted, because the scheduler completes it (decision 0010).
15
15
  */
16
16
  busy(): number;
17
+ /**
18
+ * How many `pipeToSelf` promises with a signal are still pending. They aren't busy work, since
19
+ * their signal ends them, but `settle` gives them a turn to arrive if they already have
20
+ * (decision 0038).
21
+ */
22
+ boundedPipes(): number;
17
23
  /**
18
24
  * The actors that are busy now, each with the time on this system's scheduler when it became
19
25
  * busy, for Rehearsal's stall check. An actor that's busy again straight after settling counts
package/dist/system.js CHANGED
@@ -69,6 +69,7 @@ export function createSystem(opts = {}) {
69
69
  const cellOf = (ref) => typeof ref === 'object' && ref !== null ? cells.get(ref) : undefined;
70
70
  const watchTargetOf = (ref) => cellOf(ref) ?? resolveWatch?.(ref);
71
71
  let busy = 0;
72
+ let bounded = 0;
72
73
  // By path. A cell can wait on more than one promise at once, through pipeToSelf.
73
74
  const busyByPath = new Map();
74
75
  let terminating = false;
@@ -152,6 +153,9 @@ export function createSystem(opts = {}) {
152
153
  busyByPath.delete(path);
153
154
  }
154
155
  },
156
+ trackBounded: (delta) => {
157
+ bounded += delta;
158
+ },
155
159
  terminating: (path) => terminating && (systemStopping || !isSystemPath(path)),
156
160
  cellOf,
157
161
  watchTargetOf,
@@ -302,6 +306,7 @@ export function createSystem(opts = {}) {
302
306
  return {
303
307
  system,
304
308
  busy: () => busy,
309
+ boundedPipes: () => bounded,
305
310
  busyActors: () => [...busyByPath].map(([path, { since }]) => ({ path, since })),
306
311
  pendingAsks: () => asker.pending(),
307
312
  makeRef,
@@ -34,7 +34,8 @@ export interface TestKit {
34
34
  probe<M>(name?: string): TestProbe<M>;
35
35
  /**
36
36
  * Runs everything that can happen without time passing: queued work, due timers and actors'
37
- * messages, until nothing is left.
37
+ * messages, until nothing is left. It waits for async handlers and piped promises, but not for
38
+ * a pipe with a signal, which only gets one event-loop turn to arrive (`PipeOptions`).
38
39
  * @throws SettleTimeoutError if actors are still busy after 1,000 real event-loop ticks.
39
40
  */
40
41
  settle(): Promise<void>;
@@ -35,9 +35,12 @@ export function createTestKit(opts = {}) {
35
35
  const probeNames = new Set();
36
36
  let generated = 0;
37
37
  const settle = async () => {
38
+ let yielded = false;
38
39
  for (let ticks = 0;; ticks++) {
39
- scheduler.runReady();
40
- if (handle.busy() === 0)
40
+ const ran = scheduler.runReady();
41
+ // A pipe with a signal ends when its signal aborts, so settle doesn't wait for it. It gets
42
+ // one event-loop turn, so a promise that has already settled still arrives (decision 0038).
43
+ if (handle.busy() === 0 && (handle.boundedPipes() === 0 || (yielded && ran === 0)))
41
44
  return;
42
45
  if (ticks >= MAX_TICKS) {
43
46
  // An ask only time can complete is the likeliest culprit when one is pending.
@@ -50,6 +53,7 @@ export function createTestKit(opts = {}) {
50
53
  // Async receive runs on real promises, so let one real event-loop turn pass. This is the
51
54
  // one place the testkit uses real time (decision 0003).
52
55
  await new Promise((resolve) => setTimeout(resolve, 0));
56
+ yielded = true;
53
57
  }
54
58
  };
55
59
  return {
package/dist/types.d.ts CHANGED
@@ -56,6 +56,31 @@ export type Result<T> = {
56
56
  readonly ok: false;
57
57
  readonly error: unknown;
58
58
  };
59
+ /**
60
+ * What `pipeToSelf` needs from an `AbortSignal`, so the core needs no DOM or Node types. Every
61
+ * runtime's `AbortSignal` fits it (decision 0038).
62
+ */
63
+ export interface PipeSignal {
64
+ /** Whether it has aborted already. */
65
+ readonly aborted: boolean;
66
+ /** Why it aborted: what the pipe delivers as its error. */
67
+ readonly reason: unknown;
68
+ /** Adds the listener the pipe waits on. */
69
+ addEventListener(type: 'abort', listener: () => void): void;
70
+ /** Removes it, once the promise has settled first. */
71
+ removeEventListener(type: 'abort', listener: () => void): void;
72
+ }
73
+ /** Options for `pipeToSelf`. */
74
+ export interface PipeOptions {
75
+ /**
76
+ * Ends the pipe when it aborts: the actor gets `map({ ok: false, error: signal.reason })` at
77
+ * once, without waiting for the promise, and whatever the promise does later is ignored. A pipe
78
+ * with a signal doesn't count as busy for the testkit's `settle`, so `advance` lets time pass
79
+ * while it's pending. Abort it from one of the actor's timers or from its `postStop`, so
80
+ * something on the scheduler always ends it (decision 0038).
81
+ */
82
+ readonly signal?: PipeSignal | undefined;
83
+ }
59
84
  /**
60
85
  * Keyed timers that send the actor a message. They belong to one incarnation: every timer is
61
86
  * cancelled when the actor stops or restarts, and a stale context's timer methods do nothing.
@@ -135,10 +160,13 @@ export interface ActorContext<M> {
135
160
  * Waits for `promise` without holding the mailbox, then sends the actor `map(result)`. `map`
136
161
  * runs inside the actor when that message is taken, so a mapper that throws is a failure for
137
162
  * supervision. If the actor has stopped by then, the raw `Result` becomes a dead letter. Unlike
138
- * timers, a result still arrives after a restart, as a `self.tell` would.
139
- * @throws TypeError if `map` isn't a function.
163
+ * timers, a result still arrives after a restart, as a `self.tell` would. With `opts.signal`,
164
+ * the signal aborting ends the pipe early, and the pipe isn't busy work for `settle`
165
+ * ({@link PipeOptions}).
166
+ * @throws TypeError if `map` isn't a function, or `opts` has an unknown key or a `signal` that
167
+ * isn't an abort signal.
140
168
  */
141
- pipeToSelf<T>(promise: PromiseLike<T>, map: (result: Result<T>) => M): void;
169
+ pipeToSelf<T>(promise: PromiseLike<T>, map: (result: Result<T>) => M, opts?: PipeOptions): void;
142
170
  }
143
171
  /** A lifecycle event, delivered to `onSignal`. */
144
172
  export type Signal =
@@ -241,7 +269,8 @@ export type SystemEvent = Timestamped<{
241
269
  }
242
270
  /**
243
271
  * An actor is about to run `initial` again. `attempt` counts restarts from 1, since the
244
- * restart window or the backoff last reset. `delayMs` is the backoff it waited, 0 for a restart.
272
+ * restart window or the backoff last reset. `delayMs` is the backoff it waited, including any
273
+ * minimum its failure set through `minDelayFor`, and 0 for a restart.
245
274
  */
246
275
  | {
247
276
  readonly type: 'restarted';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kylewillett/troupe",
3
- "version": "0.3.0",
3
+ "version": "0.3.2",
4
4
  "description": "Typed actors for TypeScript: supervision, event-sourced persistent actors, and cluster sharding.",
5
5
  "license": "MIT",
6
6
  "author": "Kyle Willett",