@kylewillett/troupe 0.3.1 → 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,12 @@
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
+
5
11
  ## 0.3.1 (2026-11-24)
6
12
 
7
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.
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
 
package/dist/cell.js CHANGED
@@ -4,7 +4,7 @@ import { INTERNALS, persistentHookOf, START, } from './internal.js';
4
4
  import { safeLogger } from './logger.js';
5
5
  import { Names } from './names.js';
6
6
  import { Queue } from './queue.js';
7
- import { decide, NO_FAILURES, } from './supervision.js';
7
+ import { decide, minimumDelay, NO_FAILURES, } from './supervision.js';
8
8
  import { TimerEnvelope, TimerTable, timersFor } from './timers.js';
9
9
  /** A settled `pipeToSelf` promise in the mailbox. Its mapper runs when it's dequeued. */
10
10
  class PipeEnvelope {
@@ -623,11 +623,17 @@ export class Cell {
623
623
  }
624
624
  /** Hands a failure to the strategy, then publishes and logs what it decided. */
625
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
+ }
626
631
  const { decision, history } = decide(this.#strategy, this.#history, {
627
632
  now: this.#host.now(),
628
633
  startedAt: this.#startedAt,
629
634
  inInitial,
630
635
  random: () => this.#host.random(),
636
+ minDelayMs: minimum.ms,
631
637
  });
632
638
  this.#history = history;
633
639
  const { directive } = decision;
@@ -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/types.d.ts CHANGED
@@ -269,7 +269,8 @@ export type SystemEvent = Timestamped<{
269
269
  }
270
270
  /**
271
271
  * An actor is about to run `initial` again. `attempt` counts restarts from 1, since the
272
- * 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.
273
274
  */
274
275
  | {
275
276
  readonly type: 'restarted';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kylewillett/troupe",
3
- "version": "0.3.1",
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",