@kylewillett/troupe 0.3.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,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.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
+
5
11
  ## 0.3.0 (2026-11-24)
6
12
 
7
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**.
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.
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,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';
@@ -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
  }
@@ -787,3 +828,22 @@ function isThenable(value) {
787
828
  value !== null &&
788
829
  typeof value.then === 'function');
789
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
+ }
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';
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 =
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kylewillett/troupe",
3
- "version": "0.3.0",
3
+ "version": "0.3.1",
4
4
  "description": "Typed actors for TypeScript: supervision, event-sourced persistent actors, and cluster sharding.",
5
5
  "license": "MIT",
6
6
  "author": "Kyle Willett",