@kylewillett/troupe 0.0.0-stage → 0.1.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 +40 -0
- package/LICENSE +21 -0
- package/README.md +380 -2
- package/dist/actor.d.ts +13 -0
- package/dist/actor.js +14 -0
- package/dist/ask.d.ts +39 -0
- package/dist/ask.js +135 -0
- package/dist/backstage/encode.d.ts +36 -0
- package/dist/backstage/encode.js +183 -0
- package/dist/backstage/index.d.ts +4 -0
- package/dist/backstage/index.js +4 -0
- package/dist/backstage/requests.d.ts +8 -0
- package/dist/backstage/requests.js +137 -0
- package/dist/backstage/source.d.ts +10 -0
- package/dist/backstage/source.js +143 -0
- package/dist/backstage/types.d.ts +135 -0
- package/dist/backstage/types.js +3 -0
- package/dist/backstage-ui/assets/index-Bg0MCiqs.css +1 -0
- package/dist/backstage-ui/assets/index-CeefBsDh.js +9 -0
- package/dist/backstage-ui/index.html +13 -0
- package/dist/cell.d.ts +129 -0
- package/dist/cell.js +763 -0
- package/dist/checks.d.ts +9 -0
- package/dist/checks.js +25 -0
- package/dist/dispatcher.d.ts +36 -0
- package/dist/dispatcher.js +65 -0
- package/dist/errors.d.ts +37 -0
- package/dist/errors.js +41 -0
- package/dist/events.d.ts +37 -0
- package/dist/events.js +88 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +7 -0
- package/dist/internal.d.ts +81 -0
- package/dist/internal.js +36 -0
- package/dist/logger.d.ts +31 -0
- package/dist/logger.js +56 -0
- package/dist/names.d.ts +20 -0
- package/dist/names.js +50 -0
- package/dist/node/backstage/index.d.ts +1 -0
- package/dist/node/backstage/index.js +2 -0
- package/dist/node/backstage/server.d.ts +60 -0
- package/dist/node/backstage/server.js +342 -0
- package/dist/node/sqlite/index.d.ts +1 -0
- package/dist/node/sqlite/index.js +2 -0
- package/dist/node/sqlite/schema.d.ts +2 -0
- package/dist/node/sqlite/schema.js +36 -0
- package/dist/node/sqlite/schema.sql +32 -0
- package/dist/node/sqlite/sqlite.d.ts +24 -0
- package/dist/node/sqlite/sqlite.js +183 -0
- package/dist/persistence/actor.d.ts +158 -0
- package/dist/persistence/actor.js +454 -0
- package/dist/persistence/backend.d.ts +32 -0
- package/dist/persistence/backend.js +96 -0
- package/dist/persistence/errors.d.ts +60 -0
- package/dist/persistence/errors.js +82 -0
- package/dist/persistence/index.d.ts +6 -0
- package/dist/persistence/index.js +5 -0
- package/dist/persistence/json.d.ts +7 -0
- package/dist/persistence/json.js +75 -0
- package/dist/persistence/memory.d.ts +18 -0
- package/dist/persistence/memory.js +143 -0
- package/dist/persistence/postgres/index.d.ts +1 -0
- package/dist/persistence/postgres/index.js +3 -0
- package/dist/persistence/postgres/postgres.d.ts +66 -0
- package/dist/persistence/postgres/postgres.js +236 -0
- package/dist/persistence/postgres/schema.d.ts +12 -0
- package/dist/persistence/postgres/schema.js +57 -0
- package/dist/persistence/postgres/schema.sql +35 -0
- package/dist/persistence/projection.d.ts +48 -0
- package/dist/persistence/projection.js +102 -0
- package/dist/persistence/standard-schema.d.ts +63 -0
- package/dist/persistence/standard-schema.js +7 -0
- package/dist/persistence/types.d.ts +73 -0
- package/dist/persistence/types.js +3 -0
- package/dist/queue.d.ts +11 -0
- package/dist/queue.js +31 -0
- package/dist/scheduler.d.ts +24 -0
- package/dist/scheduler.js +23 -0
- package/dist/supervision.d.ts +91 -0
- package/dist/supervision.js +120 -0
- package/dist/system.d.ts +28 -0
- package/dist/system.js +216 -0
- package/dist/testkit/index.d.ts +4 -0
- package/dist/testkit/index.js +4 -0
- package/dist/testkit/kit.d.ts +63 -0
- package/dist/testkit/kit.js +93 -0
- package/dist/testkit/manual-scheduler.d.ts +58 -0
- package/dist/testkit/manual-scheduler.js +187 -0
- package/dist/testkit/probe.d.ts +50 -0
- package/dist/testkit/probe.js +124 -0
- package/dist/testkit/random.d.ts +11 -0
- package/dist/testkit/random.js +23 -0
- package/dist/timers.d.ts +37 -0
- package/dist/timers.js +110 -0
- package/dist/types.d.ts +364 -0
- package/dist/types.js +1 -0
- package/package.json +112 -4
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
This project follows [Semantic Versioning](https://semver.org/). Under 0.x, a minor version can break the API, and it will in milestone 4. Each design choice behind these entries has a record in [docs/decisions](https://github.com/Fours/troupe/tree/main/docs/decisions).
|
|
4
|
+
|
|
5
|
+
## 0.1.1 (2026-11-23)
|
|
6
|
+
|
|
7
|
+
- The package's `homepage` is the demo site, <https://troupe.kylewillett.com/>, and the README links to the demo and to the design write-up, "How Troupe works", there. No code changed.
|
|
8
|
+
|
|
9
|
+
## 0.1.0 (2026-11-22)
|
|
10
|
+
|
|
11
|
+
The first published version. ESM only, for Node 22.18 or later, with no runtime dependencies. Everything but the SQLite backend and the Backstage server runs on any JavaScript runtime.
|
|
12
|
+
|
|
13
|
+
### Actors (`@kylewillett/troupe`)
|
|
14
|
+
|
|
15
|
+
- `actor({ initial, receive, onSignal })`: an actor is a plain-value state and a reducer, with one message type that its refs are checked against. It handles one message at a time, async `receive` included.
|
|
16
|
+
- `createActorSystem()`: a hierarchy under `/user`, with `spawn`, `stop`, death watch with `terminated` signals, and `terminate()`, which stops children before their parents.
|
|
17
|
+
- `ref.tell` never throws: a message that can't be delivered, to a stopped actor or a full bounded mailbox, becomes a `deadLetter` event. `ref.ask` replies through a temporary ref under `/temp`, and rejects with `AskTimeoutError` after `timeoutMs`.
|
|
18
|
+
- Supervision, chosen by the parent at spawn: `supervise.stop()`, `resume()`, `restart({ maxRestarts, withinMs })` and `restartWithBackoff({ minMs, maxMs, randomFactor, resetAfterMs })`. A restart is a new incarnation, with `preRestart` first.
|
|
19
|
+
- Keyed single and periodic timers that belong to one incarnation, and `pipeToSelf` for promises.
|
|
20
|
+
- A shared dispatcher that gives each actor a turn of `throughput` messages and yields to the host every `yieldAfter`.
|
|
21
|
+
- The event stream: `failed`, `restarted`, `deadLetter`, and, for persistent actors, `persisted` and `recovered`. `delivered` and `processed` events, with mailbox depth and a best-effort sender, go only to listeners that pass `{ messages: true }`.
|
|
22
|
+
- Time, scheduling and chance are injected: `scheduler` and `random` options, and `realScheduler()`, whose `now()` is whole milliseconds.
|
|
23
|
+
|
|
24
|
+
### The testkit (`/testkit`)
|
|
25
|
+
|
|
26
|
+
- `createTestKit({ seed })`: a system on virtual time (`ManualScheduler`) and seeded chance (`seededRandom`), with `settle()`, `advance(ms)`, and every event and log line recorded.
|
|
27
|
+
- `kit.probe()`: a `TestProbe` whose ref records what it's sent, with `expectMessage`, `expectNoMessage`, `watch` and `expectTerminated`.
|
|
28
|
+
|
|
29
|
+
### Persistence (`/persistence`, `/persistence/sqlite`, `/persistence/postgres`)
|
|
30
|
+
|
|
31
|
+
- `persistentActor`: commands return effects (`persist`, `reply` and `none`, with `thenReply`, `thenRun` and `thenStop` chained after a persist), and the mailbox waits while a write is in flight. On start and restart it recovers from its latest snapshot and the events after it, then gets `recoveryCompleted`.
|
|
32
|
+
- Snapshots (`snapshots: { every, version }`), tags on events, schemas through Standard Schema, and versioned events with upcasters. Events and state are checked as JSON when they're written.
|
|
33
|
+
- A sequence check on every append, so a second writer to the same stream fails with `JournalConflictError` instead of forking it.
|
|
34
|
+
- `projection`: reads events by tag and keeps its offset, at least once.
|
|
35
|
+
- Three backends that pass one contract suite: `inMemoryPersistence()`, `sqlitePersistence()` on Node's `node:sqlite`, and `postgresPersistence()` on a `pg`-compatible pool it never imports. Each ships its table SQL in `dist/`.
|
|
36
|
+
|
|
37
|
+
### Backstage (`/backstage`, `/backstage/server`)
|
|
38
|
+
|
|
39
|
+
- `backstage(system)`: an in-process source of the inspector protocol, which is JSON frames with refs as paths: a `hello` with the actor tree and recent history, then events, plus requests for an actor's state, a persistent actor's timeline, and its state at any sequence number. `encode()` is the wire encoding for messages and state. Backstage only watches.
|
|
40
|
+
- `serveBackstage(system)`: serves the Backstage UI, which ships built in the package, on `127.0.0.1:7070`, and streams the system to it with server-sent events. It refuses requests whose `Host` header doesn't name the address it serves.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Kyle Willett
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,381 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Troupe
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Typed actors for TypeScript, in the spirit of Akka: hierarchies, supervision, `ask`, timers, a testkit that runs on virtual time, and event-sourced persistent actors on an in-memory, SQLite or Postgres journal. Cluster sharding comes next.
|
|
4
|
+
|
|
5
|
+
> **Status:** 0.x, so a minor version can change the API, and milestone 4 will. See the [changelog](CHANGELOG.md), the [roadmap](docs/roadmap.md), and the specs for [milestone 1](docs/milestone-1.md), [milestone 2](docs/milestone-2.md) and [milestone 3](docs/milestone-3.md).
|
|
6
|
+
|
|
7
|
+
**[See it run](https://troupe.kylewillett.com/):** opening night at a box office, a Troupe system running live in your browser with no backend, inspected by Backstage. Crash a show and watch it restart and recover from its journal, take the journal down, and scrub a show's events back through time.
|
|
8
|
+
|
|
9
|
+
**[How it works](https://troupe.kylewillett.com/how-it-works/):** the design write-up, "How Troupe works", tells the [decision records](docs/decisions/) as one story, from actors as a state and a reducer to the benchmark's numbers, and links every claim to its record.
|
|
10
|
+
|
|
11
|
+
- **Typed:** each actor has one message type, and refs are checked against it.
|
|
12
|
+
- **No runtime dependencies**, and the core runs on any JavaScript runtime, not only Node.
|
|
13
|
+
- **Deterministic tests:** time, scheduling and chance are injected, so the testkit replays a run exactly from a seed.
|
|
14
|
+
|
|
15
|
+
## Install
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
npm install @kylewillett/troupe
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
It needs Node 22.18 or later, and is ESM only. Each release is published from CI with [npm provenance](https://docs.npmjs.com/generating-provenance-statements), which ties it to the commit and the workflow run that built it ([0024](docs/decisions/0024-publish-from-ci-with-provenance.md)). It's one package with several entry points:
|
|
22
|
+
|
|
23
|
+
| Entry point | What it has | Runs on |
|
|
24
|
+
| --- | --- | --- |
|
|
25
|
+
| `@kylewillett/troupe` | actors, systems, supervision, `ask`, timers | any runtime |
|
|
26
|
+
| `@kylewillett/troupe/testkit` | virtual time, seeded random, probes | any runtime |
|
|
27
|
+
| `@kylewillett/troupe/persistence` | persistent actors, projections, the in-memory backend | any runtime |
|
|
28
|
+
| `@kylewillett/troupe/persistence/sqlite` | the SQLite backend, on `node:sqlite` | Node |
|
|
29
|
+
| `@kylewillett/troupe/persistence/postgres` | the Postgres backend, on your own `pg` pool | any runtime with a pool |
|
|
30
|
+
| `@kylewillett/troupe/backstage` | Backstage, the inspector: its protocol and an in-process source | any runtime |
|
|
31
|
+
| `@kylewillett/troupe/backstage/server` | `serveBackstage`, the inspector's UI over HTTP | Node |
|
|
32
|
+
|
|
33
|
+
None of them has a runtime dependency.
|
|
34
|
+
|
|
35
|
+
## Quick start
|
|
36
|
+
|
|
37
|
+
An actor is a state plus a reducer. `receive` takes the current state and one message, and returns the next state.
|
|
38
|
+
|
|
39
|
+
```ts
|
|
40
|
+
import { actor, createActorSystem, type ActorRef } from '@kylewillett/troupe';
|
|
41
|
+
|
|
42
|
+
type CounterMsg = { type: 'inc'; by: number } | { type: 'get'; replyTo: ActorRef<number> };
|
|
43
|
+
|
|
44
|
+
const counter = actor<CounterMsg, number>({
|
|
45
|
+
initial: 0,
|
|
46
|
+
receive(count, msg) {
|
|
47
|
+
switch (msg.type) {
|
|
48
|
+
case 'inc':
|
|
49
|
+
return count + msg.by;
|
|
50
|
+
case 'get':
|
|
51
|
+
msg.replyTo.tell(count);
|
|
52
|
+
return count;
|
|
53
|
+
}
|
|
54
|
+
},
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
const system = createActorSystem();
|
|
58
|
+
const ref = system.spawn(counter, 'counter');
|
|
59
|
+
ref.tell({ type: 'inc', by: 2 });
|
|
60
|
+
console.log(await ref.ask<number>((replyTo) => ({ type: 'get', replyTo }))); // 2
|
|
61
|
+
await system.terminate();
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
## Defining actors
|
|
65
|
+
|
|
66
|
+
`actor({ initial, receive, onSignal })` returns a definition, which you can spawn as many times as you like.
|
|
67
|
+
|
|
68
|
+
- **`initial`** is the starting state, or a function `(ctx) => state`. It runs when the actor starts and again on every restart, so it's also where an actor spawns its children and starts its timers.
|
|
69
|
+
- **`receive(state, msg, ctx)`** returns the next state, either directly or as a promise.
|
|
70
|
+
- **`onSignal(state, signal, ctx)`** is optional. It handles `preRestart`, `postStop`, and `terminated` for actors this one watches.
|
|
71
|
+
|
|
72
|
+
**State is a plain value:** data, not functions or class instances. Refs carry functions, so keep them out of state too: a parent finds its children with `ctx.child(name)`. Persistent actors snapshot state, and the milestone 3 inspector displays it, so this rule matters.
|
|
73
|
+
|
|
74
|
+
Protocols are discriminated unions, and TypeScript checks that `receive` handles every case. There's no "unhandled message".
|
|
75
|
+
|
|
76
|
+
An actor runs **one message at a time**. If `receive` returns a promise, the actor's next message waits until the promise settles, while other actors carry on.
|
|
77
|
+
|
|
78
|
+
## `tell` and `ask`
|
|
79
|
+
|
|
80
|
+
- **`ref.tell(msg)`** sends a message and returns at once. It never throws. A message that can't be delivered, because the actor has stopped or its bounded mailbox is full, becomes a dead letter on the event stream.
|
|
81
|
+
- **`ref.ask(build, { timeoutMs })`** sends a request and returns a promise of the reply. `build` gets a temporary `replyTo` ref and returns the message to send. Write the reply type, as in `ask<number>(...)`, because TypeScript can't infer it from the protocol. If no reply comes within `timeoutMs` (default 5,000), the promise rejects with `AskTimeoutError`. Asking a stopped actor times out too, rather than failing fast, so that local refs behave like remote ones will.
|
|
82
|
+
|
|
83
|
+
Messages from one sender to one receiver arrive in the order they were sent.
|
|
84
|
+
|
|
85
|
+
## The hierarchy
|
|
86
|
+
|
|
87
|
+
Actors spawned with `system.spawn` live under `/user`. An actor's children live under its path, as in `/user/box-office/hamlet`.
|
|
88
|
+
|
|
89
|
+
```ts
|
|
90
|
+
const parent = actor<never, null>({
|
|
91
|
+
initial: (ctx) => {
|
|
92
|
+
const child = ctx.spawn(counter, 'counter');
|
|
93
|
+
ctx.watch(child);
|
|
94
|
+
return null;
|
|
95
|
+
},
|
|
96
|
+
receive: (state) => state,
|
|
97
|
+
onSignal(state, signal, ctx) {
|
|
98
|
+
if (signal.type === 'terminated') ctx.log.info('child stopped', { child: signal.ref.path });
|
|
99
|
+
return state;
|
|
100
|
+
},
|
|
101
|
+
});
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
- **`ctx.stop()`** stops the actor itself, and `ctx.stop(child)` stops one of its children. Stopping recurses: an actor stops its children first, waits for them, runs `postStop`, and then terminates.
|
|
105
|
+
- **`ctx.watch(ref)`** delivers a `terminated` signal when that actor stops. It works on any actor, not only children. If the actor stopped because it failed, the signal carries the `failure`.
|
|
106
|
+
- **`system.terminate()`** stops everything, and resolves once the last actor has stopped.
|
|
107
|
+
|
|
108
|
+
## Supervision
|
|
109
|
+
|
|
110
|
+
When an actor fails, its parent's strategy decides what happens. A failure is a throw or a rejected promise in `initial`, `receive`, `onSignal` or a `pipeToSelf` mapper. The parent chooses the strategy when it spawns the child:
|
|
111
|
+
|
|
112
|
+
```ts
|
|
113
|
+
import { supervise } from '@kylewillett/troupe';
|
|
114
|
+
|
|
115
|
+
ctx.spawn(show, 'hamlet', {
|
|
116
|
+
supervision: supervise.restartWithBackoff({ minMs: 200, maxMs: 5_000 }),
|
|
117
|
+
});
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
| Strategy | What happens |
|
|
121
|
+
| --- | --- |
|
|
122
|
+
| `supervise.stop()` (the default) | The actor stops, and watchers get `terminated` with the `failure`. |
|
|
123
|
+
| `supervise.resume()` | The actor keeps its state, drops the message that failed, and carries on. |
|
|
124
|
+
| `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. |
|
|
125
|
+
| `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. |
|
|
126
|
+
|
|
127
|
+
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`.
|
|
128
|
+
|
|
129
|
+
## Timers and `pipeToSelf`
|
|
130
|
+
|
|
131
|
+
```ts
|
|
132
|
+
type SessionMsg =
|
|
133
|
+
| { type: 'touch' }
|
|
134
|
+
| { type: 'idle' }
|
|
135
|
+
| { type: 'load'; id: string }
|
|
136
|
+
| { type: 'loaded'; result: Result<string> };
|
|
137
|
+
|
|
138
|
+
const session = actor<SessionMsg, { lastLoaded?: string }>({
|
|
139
|
+
initial: (ctx) => {
|
|
140
|
+
ctx.timers.startSingle('idle', { type: 'idle' }, 60_000);
|
|
141
|
+
return {};
|
|
142
|
+
},
|
|
143
|
+
receive(state, msg, ctx) {
|
|
144
|
+
switch (msg.type) {
|
|
145
|
+
case 'touch':
|
|
146
|
+
ctx.timers.startSingle('idle', { type: 'idle' }, 60_000); // replaces the old timer
|
|
147
|
+
return state;
|
|
148
|
+
case 'idle':
|
|
149
|
+
ctx.stop();
|
|
150
|
+
return state;
|
|
151
|
+
case 'load':
|
|
152
|
+
ctx.pipeToSelf(fetchProfile(msg.id), (result) => ({ type: 'loaded', result }));
|
|
153
|
+
return state;
|
|
154
|
+
case 'loaded':
|
|
155
|
+
return msg.result.ok ? { lastLoaded: msg.result.value } : state;
|
|
156
|
+
}
|
|
157
|
+
},
|
|
158
|
+
});
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
- **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.
|
|
162
|
+
- **`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.
|
|
163
|
+
|
|
164
|
+
## The testkit
|
|
165
|
+
|
|
166
|
+
`@kylewillett/troupe/testkit` runs a system on virtual time, with a seeded random. Tests run instantly, and the same seed gives the same run.
|
|
167
|
+
|
|
168
|
+
```ts
|
|
169
|
+
import { createTestKit } from '@kylewillett/troupe/testkit';
|
|
170
|
+
|
|
171
|
+
const kit = createTestKit({ seed: 1 });
|
|
172
|
+
const probe = kit.probe<number>('replies');
|
|
173
|
+
const ref = kit.system.spawn(counter, 'counter');
|
|
174
|
+
|
|
175
|
+
ref.tell({ type: 'inc', by: 2 });
|
|
176
|
+
ref.tell({ type: 'get', replyTo: probe.ref });
|
|
177
|
+
await kit.settle();
|
|
178
|
+
probe.expectMessage(2);
|
|
179
|
+
|
|
180
|
+
await kit.advance(60_000); // fires every timer due in the next minute, in order
|
|
181
|
+
await kit.shutdown();
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
- **`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.
|
|
185
|
+
- **`kit.advance(ms)`** moves virtual time forward. It fires timers in order, and settles at each due time.
|
|
186
|
+
- **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.
|
|
187
|
+
- **`kit.events`** and **`kit.logs`** record everything the system published and logged.
|
|
188
|
+
|
|
189
|
+
## Persistent actors
|
|
190
|
+
|
|
191
|
+
`@kylewillett/troupe/persistence` adds event sourcing. A persistent actor doesn't change its state directly. It turns each command into events, the journal stores them, and only then are they applied to the state. On start and on every restart, the actor replays its events to get its state back, so a crash, a restart or a new process loses nothing that was written.
|
|
192
|
+
|
|
193
|
+
### Defining one
|
|
194
|
+
|
|
195
|
+
```ts
|
|
196
|
+
import { createActorSystem, type ActorRef } from '@kylewillett/troupe';
|
|
197
|
+
import { inMemoryPersistence, persistentActor } from '@kylewillett/troupe/persistence';
|
|
198
|
+
|
|
199
|
+
type Receipt = { ok: true; balance: number } | { ok: false; reason: string };
|
|
200
|
+
type AccountCmd =
|
|
201
|
+
| { type: 'deposit'; amount: number; replyTo: ActorRef<Receipt> }
|
|
202
|
+
| { type: 'withdraw'; amount: number; replyTo: ActorRef<Receipt> };
|
|
203
|
+
type AccountEvent = { type: 'deposited'; amount: number } | { type: 'withdrawn'; amount: number };
|
|
204
|
+
|
|
205
|
+
const persistence = inMemoryPersistence();
|
|
206
|
+
|
|
207
|
+
const account = (id: string) =>
|
|
208
|
+
persistentActor<AccountCmd, AccountEvent, { balance: number }>({
|
|
209
|
+
id: `account-${id}`,
|
|
210
|
+
persistence,
|
|
211
|
+
initial: { balance: 0 },
|
|
212
|
+
onCommand(state, cmd, { persist, reply }) {
|
|
213
|
+
const receipt = (s: { balance: number }): Receipt => ({ ok: true, balance: s.balance });
|
|
214
|
+
switch (cmd.type) {
|
|
215
|
+
case 'deposit':
|
|
216
|
+
return persist({ type: 'deposited', amount: cmd.amount }).thenReply(cmd.replyTo, receipt);
|
|
217
|
+
case 'withdraw':
|
|
218
|
+
if (cmd.amount > state.balance) {
|
|
219
|
+
return reply(cmd.replyTo, { ok: false, reason: 'insufficient funds' });
|
|
220
|
+
}
|
|
221
|
+
return persist({ type: 'withdrawn', amount: cmd.amount }).thenReply(cmd.replyTo, receipt);
|
|
222
|
+
}
|
|
223
|
+
},
|
|
224
|
+
onEvent(state, event) {
|
|
225
|
+
return event.type === 'deposited'
|
|
226
|
+
? { balance: state.balance + event.amount }
|
|
227
|
+
: { balance: state.balance - event.amount };
|
|
228
|
+
},
|
|
229
|
+
});
|
|
230
|
+
|
|
231
|
+
const system = createActorSystem();
|
|
232
|
+
const alice = system.spawn(account('alice'), 'alice');
|
|
233
|
+
await alice.ask<Receipt>((replyTo) => ({ type: 'deposit', amount: 10, replyTo })); // balance 10
|
|
234
|
+
```
|
|
235
|
+
|
|
236
|
+
`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.
|
|
237
|
+
|
|
238
|
+
### Effects
|
|
239
|
+
|
|
240
|
+
`onCommand` is synchronous and can't change the state. It returns an effect, built from its context:
|
|
241
|
+
|
|
242
|
+
- **`persist(...events)`** appends the events, applies them with `onEvent`, and then runs the steps chained after it.
|
|
243
|
+
- **`reply(to, message)`** persists nothing and replies at once. **`none()`** does nothing.
|
|
244
|
+
- **`.thenReply(to, (state) => message)`** replies with the state after the events. **`.thenRun((state) => ...)`** runs a side effect, such as starting a timer. **`.thenStop()`** stops the actor once the events are written.
|
|
245
|
+
|
|
246
|
+
Steps run in the order you chain them. While a persist is in flight, the actor's mailbox waits, so the next command sees the state the last one left. A rejected append applies nothing: the actor fails, and a restart recovers what the journal really holds. Every successful append publishes a `persisted` event.
|
|
247
|
+
|
|
248
|
+
### Recovery, snapshots, and why `onEvent` must be pure
|
|
249
|
+
|
|
250
|
+
When the actor starts or restarts, it reads its stream and folds each event through `onEvent`. Commands sent meanwhile wait in the mailbox. Then `onSignal` gets `recoveryCompleted`, and the system publishes a `recovered` event with the last sequence number.
|
|
251
|
+
|
|
252
|
+
Because every recovery replays every event, **`onEvent` must be pure**: no I/O, no timers, no replies, no randomness or clock reads, and no throwing for an event it has accepted before. Anything else would happen again on every replay. Side effects belong in `thenRun` and `thenReply`, which run once, after the write. Timers don't survive a restart, so start the ones your state implies in `onSignal` on `recoveryCompleted`.
|
|
253
|
+
|
|
254
|
+
Long streams make recovery slow. `snapshots: { every: 100 }` saves the state after any persist that crosses a multiple of 100, and recovery starts from the latest snapshot and replays only the events after it. Snapshots are a shortcut, never the source of truth: events are never deleted, and recovery replays everything when it can't use a snapshot. Bump `snapshots.version` whenever the state's shape changes, and recovery ignores the old ones. A snapshot that fails to save or load logs a warning, and the actor carries on.
|
|
255
|
+
|
|
256
|
+
### Backends
|
|
257
|
+
|
|
258
|
+
```ts
|
|
259
|
+
import { inMemoryPersistence } from '@kylewillett/troupe/persistence';
|
|
260
|
+
import { sqlitePersistence } from '@kylewillett/troupe/persistence/sqlite';
|
|
261
|
+
import { postgresPersistence } from '@kylewillett/troupe/persistence/postgres';
|
|
262
|
+
import pg from 'pg';
|
|
263
|
+
|
|
264
|
+
const memory = inMemoryPersistence();
|
|
265
|
+
const sqlite = sqlitePersistence({ path: 'app.db' }); // or ':memory:'
|
|
266
|
+
const postgres = postgresPersistence({ pool: new pg.Pool(), schema: 'troupe' });
|
|
267
|
+
await postgres.setup();
|
|
268
|
+
```
|
|
269
|
+
|
|
270
|
+
- **In-memory** runs anywhere, and is what tests use. It forgets everything when the process exits.
|
|
271
|
+
- **SQLite** uses Node's built-in `node:sqlite`, so it adds no dependency. It's Node only. On Node 22, `node:sqlite` is experimental, and the first load prints an `ExperimentalWarning`. Node 24 and later don't. Calls are synchronous under the hood, and `close()` closes the file.
|
|
272
|
+
- **Postgres** runs on a pool you pass in. Troupe never imports `pg`: anything with `pg`'s `query` and `connect` works. Call **`setup()`** once, on start, to create the tables. It's safe to run every time. Each `schema` is a separate journal, so two apps can share a database. If you manage migrations yourself, the tables' SQL ships as `dist/persistence/postgres/schema.sql`. The SQLite backend ships its own as `dist/node/sqlite/schema.sql`.
|
|
273
|
+
|
|
274
|
+
Every backend passes the same contract suite, so an actor behaves the same on each one.
|
|
275
|
+
|
|
276
|
+
### Schemas and upcasters
|
|
277
|
+
|
|
278
|
+
Events live for as long as your data does, so their shape will change. `events` adds runtime checks and versions:
|
|
279
|
+
|
|
280
|
+
```ts
|
|
281
|
+
import { z } from 'zod';
|
|
282
|
+
|
|
283
|
+
const Event = z.discriminatedUnion('type', [
|
|
284
|
+
z.object({ type: z.literal('deposited'), amount: z.number().int().positive(), memo: z.string() }),
|
|
285
|
+
z.object({ type: z.literal('withdrawn'), amount: z.number().int().positive(), memo: z.string() }),
|
|
286
|
+
]);
|
|
287
|
+
|
|
288
|
+
persistentActor({
|
|
289
|
+
// ...
|
|
290
|
+
events: {
|
|
291
|
+
schema: Event,
|
|
292
|
+
version: 2,
|
|
293
|
+
// Version 1 events had no memo.
|
|
294
|
+
upcasters: { 1: (event) => ({ ...(event as object), memo: '' }) },
|
|
295
|
+
},
|
|
296
|
+
});
|
|
297
|
+
```
|
|
298
|
+
|
|
299
|
+
- Any [Standard Schema](https://standardschema.dev) library works, such as Zod or Valibot, sync or async. The schema checks each event before the append, so a bad event is never written, and again on recovery. A failure is an `EventValidationError` with the schema's issues.
|
|
300
|
+
- New events are stored at `version`. On recovery, a stored event runs through one upcaster per version step, from its own version up, and then through the schema. `upcasters[n]` turns a version-n event into a version-(n + 1) one, and they must cover every step from 1 to `version - 1`.
|
|
301
|
+
- An event stored at a higher version than the actor knows fails recovery with `EventVersionError`, so old code never misreads new data.
|
|
302
|
+
|
|
303
|
+
### Tags and projections
|
|
304
|
+
|
|
305
|
+
`tags(event)` labels events, and a projection follows one tag across every entity, in the order the journal stored them. It's how you build read models, such as a sales report from every show.
|
|
306
|
+
|
|
307
|
+
```ts
|
|
308
|
+
import { supervise } from '@kylewillett/troupe';
|
|
309
|
+
import { projection } from '@kylewillett/troupe/persistence';
|
|
310
|
+
|
|
311
|
+
system.spawn(
|
|
312
|
+
projection({ name: 'deposits', persistence, tag: 'account', handle: (e) => report.record(e) }),
|
|
313
|
+
'deposits',
|
|
314
|
+
{ supervision: supervise.restartWithBackoff({ minMs: 200, maxMs: 5_000 }) },
|
|
315
|
+
);
|
|
316
|
+
```
|
|
317
|
+
|
|
318
|
+
The projection reads a batch, hands each event to `handle` in turn, and then saves its offset in the backend's offset store. A new projection with the same name starts after the saved offset. When a batch comes back short, it waits `pollMs` before it reads again.
|
|
319
|
+
|
|
320
|
+
Delivery is **at least once**. If `handle` fails, or the process dies before the offset is saved, the projection restarts from the last saved offset, and that batch runs again. So `handle` must be safe to repeat: make it idempotent, for example by upserting keyed on the event's `persistenceId` and `seq`, or by recording the last `offset` it applied. `handle` gets the event as it was stored, not upcast or checked, since a tag can span entity types.
|
|
321
|
+
|
|
322
|
+
### Two writers, and why backoff suits persistent actors
|
|
323
|
+
|
|
324
|
+
An entity's events must form one stream. If two actors with the same `id` both write, perhaps from two processes on one database, the stream could fork. It can't, because every append says which sequence number it follows, and the journal rejects a stale one with **`JournalConflictError`**. The loser's command is dropped, and the actor fails like any other.
|
|
325
|
+
|
|
326
|
+
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.
|
|
327
|
+
|
|
328
|
+
## Pitfalls
|
|
329
|
+
|
|
330
|
+
- **Don't await an `ask` inside `receive` to an actor that might ask you back.** An async `receive` holds the mailbox until it settles. If the other actor asks this one in turn, neither can answer until the ask times out. Use `pipeToSelf` for requests between actors: the mailbox stays open while the reply is on its way. Under the testkit, a piped ask also runs entirely on virtual time ([0010](docs/decisions/0010-piped-asks-stay-on-the-scheduler.md)). An awaited ask that can only time out makes `settle` throw.
|
|
331
|
+
- **Timers keep a Node process alive.** A system with active timers stops Node from exiting until you call `system.terminate()`, which cancels them.
|
|
332
|
+
|
|
333
|
+
## Backstage
|
|
334
|
+
|
|
335
|
+
Backstage is an inspector for a running system: the live actor tree with each mailbox's depth, the selected actor's state, messages and failures, and a persistent actor's journal, which you can scrub back through to see its state after any event. It only watches. Nothing in it can send a message or stop an actor ([0021](docs/decisions/0021-backstage-only-watches.md)).
|
|
336
|
+
|
|
337
|
+
In Node, `serveBackstage` serves it on localhost:
|
|
338
|
+
|
|
339
|
+
```ts
|
|
340
|
+
import { serveBackstage } from '@kylewillett/troupe/backstage/server';
|
|
341
|
+
|
|
342
|
+
const backstage = await serveBackstage(system); // { port: 7070, host: '127.0.0.1' } by default
|
|
343
|
+
console.log(`Backstage: ${backstage.url}`);
|
|
344
|
+
// ...
|
|
345
|
+
await backstage.close();
|
|
346
|
+
```
|
|
347
|
+
|
|
348
|
+
Open the URL in a browser. The UI ships in the package, so it needs nothing else and works offline. `port: 0` picks a free port. It streams the system with server-sent events, and reconnects by itself if the process restarts ([0023](docs/decisions/0023-backstage-server-uses-sse.md)).
|
|
349
|
+
|
|
350
|
+
> **Backstage shows every message and every state.** Keep it on a loopback address, as it is by default. Binding `host` to anything else shows them to whoever can reach that address. On loopback, it refuses requests whose `Host` header isn't a name for the address it serves, which stops other sites in your browser from reaching it through DNS rebinding, and it sends no CORS headers.
|
|
351
|
+
|
|
352
|
+
`npm run example:backstage` builds the package and runs [examples/backstage](examples/backstage): the demo's opening night on real time and SQLite, with Backstage on <http://127.0.0.1:7070/>. Ten seconds in, `hamlet` gets a bad request, so there's a crash and a restart to look at.
|
|
353
|
+
|
|
354
|
+
## The box office example
|
|
355
|
+
|
|
356
|
+
`npm run example` builds the package and runs [examples/box-office](examples/box-office) on real time, on a SQLite file at `.troupe/box-office.db`, which it deletes at the start of each run so the story repeats. A box office actor spawns one show per production, and each show is a persistent actor whose events are `held`, `confirmed` and `released`. Customers hold seats with `ask`, and holds expire on a timer unless they're confirmed.
|
|
357
|
+
|
|
358
|
+
A malformed request crashes `hamlet`, which restarts with backoff and recovers its holds from the journal, so Carol's confirm still succeeds. Then the system terminates, a new one opens the same file, and every show comes back with its sales.
|
|
359
|
+
|
|
360
|
+
One thing doesn't come back exactly: a recovered hold gets a fresh timer for the full hold time, because holds don't remember how long they had left. Durable timers are a later idea. [test/examples/box-office.test.ts](test/examples/box-office.test.ts) runs the same story under the testkit, with two systems sharing one in-memory backend.
|
|
361
|
+
|
|
362
|
+
## Development
|
|
363
|
+
|
|
364
|
+
```bash
|
|
365
|
+
npm install
|
|
366
|
+
npm run lint && npm run typecheck && npm test && npm run build
|
|
367
|
+
```
|
|
368
|
+
|
|
369
|
+
The Postgres tests need a database. `npm run postgres:up` starts one on port 5440 with Docker, or you can point `TROUPE_POSTGRES_URL` at your own.
|
|
370
|
+
|
|
371
|
+
```bash
|
|
372
|
+
npm run postgres:up
|
|
373
|
+
npm run test:integration && npm run coverage
|
|
374
|
+
npm run postgres:down
|
|
375
|
+
```
|
|
376
|
+
|
|
377
|
+
Design decisions are recorded in [docs/decisions](docs/decisions/README.md).
|
|
378
|
+
|
|
379
|
+
## License
|
|
380
|
+
|
|
381
|
+
MIT
|
package/dist/actor.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { ActorDef } from './types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Defines an actor: an initial state and a reducer (decision 0001). Returns the definition
|
|
4
|
+
* unchanged. It exists so TypeScript infers and checks the message type `M` and the state type `S`
|
|
5
|
+
* in one place.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* const counter = actor<CounterMsg, number>({
|
|
9
|
+
* initial: 0,
|
|
10
|
+
* receive: (count, msg) => (msg.type === 'inc' ? count + msg.by : count),
|
|
11
|
+
* });
|
|
12
|
+
*/
|
|
13
|
+
export declare function actor<M, S>(def: ActorDef<M, S>): ActorDef<M, S>;
|
package/dist/actor.js
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Defines an actor: an initial state and a reducer (decision 0001). Returns the definition
|
|
3
|
+
* unchanged. It exists so TypeScript infers and checks the message type `M` and the state type `S`
|
|
4
|
+
* in one place.
|
|
5
|
+
*
|
|
6
|
+
* @example
|
|
7
|
+
* const counter = actor<CounterMsg, number>({
|
|
8
|
+
* initial: 0,
|
|
9
|
+
* receive: (count, msg) => (msg.type === 'inc' ? count + msg.by : count),
|
|
10
|
+
* });
|
|
11
|
+
*/
|
|
12
|
+
export function actor(def) {
|
|
13
|
+
return def;
|
|
14
|
+
}
|
package/dist/ask.d.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { EventBus } from './events.js';
|
|
2
|
+
import type { ActorRef, AskOptions, Result } from './types.js';
|
|
3
|
+
/** What an {@link Asker} needs from its system. */
|
|
4
|
+
export interface AskerHost {
|
|
5
|
+
readonly events: EventBus;
|
|
6
|
+
readonly systemName: string;
|
|
7
|
+
readonly defaultTimeoutMs: number;
|
|
8
|
+
setTimer(task: () => void, delayMs: number): () => void;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Makes refs and runs `ask` for one system (decision 0009). Every ref, whether it belongs to a
|
|
12
|
+
* cell, an ask or a probe, gets its `ask` from here, so asking works the same whatever is behind
|
|
13
|
+
* the ref.
|
|
14
|
+
*
|
|
15
|
+
* An ask's temporary ref, under `/temp`, isn't an actor. It has no mailbox: a reply resolves the
|
|
16
|
+
* promise as soon as it's told. It publishes no `spawned` or `stopped` events.
|
|
17
|
+
*/
|
|
18
|
+
export declare class Asker {
|
|
19
|
+
#private;
|
|
20
|
+
constructor(host: AskerHost);
|
|
21
|
+
/** Freezes `path` and `tell` into a ref, with an `ask` that targets it. */
|
|
22
|
+
ref<M>(path: string, tell: (msg: M) => void): ActorRef<M>;
|
|
23
|
+
/**
|
|
24
|
+
* Rejects every pending ask, and every later one, with `ActorSystemTerminatedError`. It does
|
|
25
|
+
* this at once rather than after `/user` has stopped: an actor whose async `receive` awaits an
|
|
26
|
+
* ask can't stop until that ask settles.
|
|
27
|
+
*/
|
|
28
|
+
terminate(): void;
|
|
29
|
+
/**
|
|
30
|
+
* Calls `listener` synchronously when `promise`, an ask's promise, settles, or at once if it
|
|
31
|
+
* already has. This keeps `pipeToSelf` of an ask on the scheduler, with no promise hop
|
|
32
|
+
* (decision 0010).
|
|
33
|
+
* @returns False, doing nothing, if `promise` isn't one this asker made.
|
|
34
|
+
*/
|
|
35
|
+
onSettled(promise: unknown, listener: (result: Result<unknown>) => void): boolean;
|
|
36
|
+
ask<M, R>(target: ActorRef<M>, build: (replyTo: ActorRef<R>) => M, opts: AskOptions | undefined): Promise<R>;
|
|
37
|
+
/** How many asks are still waiting for a reply or their timeout. */
|
|
38
|
+
pending(): number;
|
|
39
|
+
}
|
package/dist/ask.js
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import { checkInt, checkKeys } from './checks.js';
|
|
2
|
+
import { ActorSystemTerminatedError, AskTimeoutError } from './errors.js';
|
|
3
|
+
const ASK_OPTIONS = new Set(['timeoutMs']);
|
|
4
|
+
const TEMP_PATH = '/temp';
|
|
5
|
+
/**
|
|
6
|
+
* Makes refs and runs `ask` for one system (decision 0009). Every ref, whether it belongs to a
|
|
7
|
+
* cell, an ask or a probe, gets its `ask` from here, so asking works the same whatever is behind
|
|
8
|
+
* the ref.
|
|
9
|
+
*
|
|
10
|
+
* An ask's temporary ref, under `/temp`, isn't an actor. It has no mailbox: a reply resolves the
|
|
11
|
+
* promise as soon as it's told. It publishes no `spawned` or `stopped` events.
|
|
12
|
+
*/
|
|
13
|
+
export class Asker {
|
|
14
|
+
#host;
|
|
15
|
+
// Rejects each ask that's still waiting, for terminate().
|
|
16
|
+
#pending = new Set();
|
|
17
|
+
#outcomes = new WeakMap();
|
|
18
|
+
#generated = 0;
|
|
19
|
+
#terminated = false;
|
|
20
|
+
constructor(host) {
|
|
21
|
+
this.#host = host;
|
|
22
|
+
}
|
|
23
|
+
/** Freezes `path` and `tell` into a ref, with an `ask` that targets it. */
|
|
24
|
+
ref(path, tell) {
|
|
25
|
+
const ref = Object.freeze({
|
|
26
|
+
path,
|
|
27
|
+
tell,
|
|
28
|
+
ask: (build, opts) => this.ask(ref, build, opts),
|
|
29
|
+
});
|
|
30
|
+
return ref;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Rejects every pending ask, and every later one, with `ActorSystemTerminatedError`. It does
|
|
34
|
+
* this at once rather than after `/user` has stopped: an actor whose async `receive` awaits an
|
|
35
|
+
* ask can't stop until that ask settles.
|
|
36
|
+
*/
|
|
37
|
+
terminate() {
|
|
38
|
+
this.#terminated = true;
|
|
39
|
+
for (const reject of [...this.#pending])
|
|
40
|
+
reject(this.#terminatedError());
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Calls `listener` synchronously when `promise`, an ask's promise, settles, or at once if it
|
|
44
|
+
* already has. This keeps `pipeToSelf` of an ask on the scheduler, with no promise hop
|
|
45
|
+
* (decision 0010).
|
|
46
|
+
* @returns False, doing nothing, if `promise` isn't one this asker made.
|
|
47
|
+
*/
|
|
48
|
+
onSettled(promise, listener) {
|
|
49
|
+
const outcome = typeof promise === 'object' && promise !== null && this.#outcomes.get(promise);
|
|
50
|
+
if (!outcome)
|
|
51
|
+
return false;
|
|
52
|
+
if (outcome.result === undefined)
|
|
53
|
+
outcome.listeners.push(listener);
|
|
54
|
+
else
|
|
55
|
+
listener(outcome.result);
|
|
56
|
+
return true;
|
|
57
|
+
}
|
|
58
|
+
ask(target, build, opts) {
|
|
59
|
+
// Checked before anything else, so bad options throw where they're passed in.
|
|
60
|
+
const timeoutMs = this.#timeout(opts);
|
|
61
|
+
if (typeof build !== 'function')
|
|
62
|
+
throw new TypeError('ask: build must be a function');
|
|
63
|
+
if (this.#terminated)
|
|
64
|
+
return Promise.reject(this.#terminatedError());
|
|
65
|
+
const { events } = this.#host;
|
|
66
|
+
const outcome = { result: undefined, listeners: [] };
|
|
67
|
+
const settled = (result) => {
|
|
68
|
+
outcome.result = result;
|
|
69
|
+
for (const listener of outcome.listeners.splice(0))
|
|
70
|
+
listener(result);
|
|
71
|
+
};
|
|
72
|
+
const promise = new Promise((resolve, reject) => {
|
|
73
|
+
const path = `${TEMP_PATH}/$${String(++this.#generated)}`;
|
|
74
|
+
let done = false;
|
|
75
|
+
let cancelTimer = () => { };
|
|
76
|
+
const finish = () => {
|
|
77
|
+
if (done)
|
|
78
|
+
return false;
|
|
79
|
+
done = true;
|
|
80
|
+
cancelTimer();
|
|
81
|
+
this.#pending.delete(fail);
|
|
82
|
+
return true;
|
|
83
|
+
};
|
|
84
|
+
const fail = (error) => {
|
|
85
|
+
if (!finish())
|
|
86
|
+
return;
|
|
87
|
+
reject(error);
|
|
88
|
+
settled({ ok: false, error });
|
|
89
|
+
};
|
|
90
|
+
const replyTo = this.ref(path, (reply) => {
|
|
91
|
+
if (finish()) {
|
|
92
|
+
resolve(reply);
|
|
93
|
+
settled({ ok: true, value: reply });
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
const reason = this.#terminated ? 'terminated' : 'askCompleted';
|
|
97
|
+
events.publish({ type: 'deadLetter', recipient: path, message: reply, reason });
|
|
98
|
+
});
|
|
99
|
+
let msg;
|
|
100
|
+
try {
|
|
101
|
+
msg = build(replyTo);
|
|
102
|
+
}
|
|
103
|
+
catch (error) {
|
|
104
|
+
// Nothing has been sent and no timer set. A reply through a ref that build kept is then
|
|
105
|
+
// an askCompleted dead letter. Throwing from the executor rejects with build's error.
|
|
106
|
+
done = true;
|
|
107
|
+
settled({ ok: false, error });
|
|
108
|
+
throw error;
|
|
109
|
+
}
|
|
110
|
+
cancelTimer = this.#host.setTimer(() => {
|
|
111
|
+
fail(new AskTimeoutError(target.path, timeoutMs));
|
|
112
|
+
}, timeoutMs);
|
|
113
|
+
this.#pending.add(fail);
|
|
114
|
+
target.tell(msg);
|
|
115
|
+
});
|
|
116
|
+
this.#outcomes.set(promise, outcome);
|
|
117
|
+
return promise;
|
|
118
|
+
}
|
|
119
|
+
/** How many asks are still waiting for a reply or their timeout. */
|
|
120
|
+
pending() {
|
|
121
|
+
return this.#pending.size;
|
|
122
|
+
}
|
|
123
|
+
#timeout(opts) {
|
|
124
|
+
if (opts === undefined)
|
|
125
|
+
return this.#host.defaultTimeoutMs;
|
|
126
|
+
checkKeys(opts, ASK_OPTIONS, 'ask');
|
|
127
|
+
if (opts.timeoutMs === undefined)
|
|
128
|
+
return this.#host.defaultTimeoutMs;
|
|
129
|
+
checkInt(opts.timeoutMs, 'ask: timeoutMs');
|
|
130
|
+
return opts.timeoutMs;
|
|
131
|
+
}
|
|
132
|
+
#terminatedError() {
|
|
133
|
+
return new ActorSystemTerminatedError(`system "${this.#host.systemName}" is terminating, so the ask can't complete`);
|
|
134
|
+
}
|
|
135
|
+
}
|