@kylewillett/troupe 0.1.1 → 0.3.0

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.
Files changed (106) hide show
  1. package/CHANGELOG.md +26 -1
  2. package/README.md +134 -4
  3. package/dist/ask.d.ts +5 -1
  4. package/dist/ask.js +16 -0
  5. package/dist/backstage/index.d.ts +2 -1
  6. package/dist/backstage/index.js +1 -0
  7. package/dist/backstage/source.d.ts +1 -1
  8. package/dist/backstage/source.js +65 -2
  9. package/dist/backstage/types.d.ts +65 -4
  10. package/dist/backstage/types.js +2 -1
  11. package/dist/backstage-ui/assets/index-CG896RLZ.css +1 -0
  12. package/dist/backstage-ui/assets/index-DF_Xnc1u.js +9 -0
  13. package/dist/backstage-ui/index.html +2 -2
  14. package/dist/cell.d.ts +19 -16
  15. package/dist/cell.js +46 -20
  16. package/dist/checks.d.ts +10 -0
  17. package/dist/checks.js +34 -2
  18. package/dist/cluster/index.d.ts +6 -0
  19. package/dist/cluster/index.js +4 -0
  20. package/dist/cluster/leases.d.ts +37 -0
  21. package/dist/cluster/leases.js +132 -0
  22. package/dist/cluster/membership.d.ts +100 -0
  23. package/dist/cluster/membership.js +559 -0
  24. package/dist/cluster/memory.d.ts +31 -0
  25. package/dist/cluster/memory.js +187 -0
  26. package/dist/cluster/placement.d.ts +10 -0
  27. package/dist/cluster/placement.js +30 -0
  28. package/dist/cluster/postgres/index.d.ts +1 -0
  29. package/dist/cluster/postgres/index.js +3 -0
  30. package/dist/cluster/postgres/schema.d.ts +7 -0
  31. package/dist/cluster/postgres/schema.js +33 -0
  32. package/dist/cluster/postgres/schema.sql +18 -0
  33. package/dist/cluster/postgres/store.d.ts +28 -0
  34. package/dist/cluster/postgres/store.js +124 -0
  35. package/dist/cluster/region.d.ts +103 -0
  36. package/dist/cluster/region.js +843 -0
  37. package/dist/cluster/remoting.d.ts +79 -0
  38. package/dist/cluster/remoting.js +755 -0
  39. package/dist/cluster/shard-memory.d.ts +14 -0
  40. package/dist/cluster/shard-memory.js +92 -0
  41. package/dist/cluster/shard-store.d.ts +62 -0
  42. package/dist/cluster/shard-store.js +36 -0
  43. package/dist/cluster/shard.d.ts +54 -0
  44. package/dist/cluster/shard.js +278 -0
  45. package/dist/cluster/sharding.d.ts +116 -0
  46. package/dist/cluster/sharding.js +286 -0
  47. package/dist/cluster/table.d.ts +29 -0
  48. package/dist/cluster/table.js +74 -0
  49. package/dist/cluster/timed-store.d.ts +4 -0
  50. package/dist/cluster/timed-store.js +19 -0
  51. package/dist/cluster/transport.d.ts +29 -0
  52. package/dist/cluster/transport.js +4 -0
  53. package/dist/cluster/wire.d.ts +90 -0
  54. package/dist/cluster/wire.js +177 -0
  55. package/dist/hash.d.ts +7 -0
  56. package/dist/hash.js +25 -0
  57. package/dist/index.d.ts +1 -0
  58. package/dist/index.js +1 -0
  59. package/dist/internal.d.ts +139 -2
  60. package/dist/internal.js +12 -1
  61. package/dist/json.d.ts +44 -0
  62. package/dist/json.js +143 -0
  63. package/dist/node/cluster/frames.d.ts +31 -0
  64. package/dist/node/cluster/frames.js +73 -0
  65. package/dist/node/cluster/index.d.ts +1 -0
  66. package/dist/node/cluster/index.js +3 -0
  67. package/dist/node/cluster/tcp.d.ts +101 -0
  68. package/dist/node/cluster/tcp.js +416 -0
  69. package/dist/persistence/actor.d.ts +9 -0
  70. package/dist/persistence/actor.js +21 -10
  71. package/dist/persistence/backend.d.ts +1 -10
  72. package/dist/persistence/backend.js +4 -34
  73. package/dist/persistence/errors.d.ts +19 -0
  74. package/dist/persistence/errors.js +22 -0
  75. package/dist/persistence/index.d.ts +1 -1
  76. package/dist/persistence/index.js +1 -1
  77. package/dist/persistence/postgres/index.d.ts +2 -1
  78. package/dist/persistence/postgres/index.js +1 -1
  79. package/dist/persistence/postgres/pool.d.ts +44 -0
  80. package/dist/persistence/postgres/pool.js +65 -0
  81. package/dist/persistence/postgres/postgres.d.ts +1 -33
  82. package/dist/persistence/postgres/postgres.js +4 -63
  83. package/dist/persistence/projection.d.ts +6 -0
  84. package/dist/persistence/projection.js +21 -5
  85. package/dist/rehearsal/clock.d.ts +54 -0
  86. package/dist/rehearsal/clock.js +203 -0
  87. package/dist/rehearsal/database.d.ts +116 -0
  88. package/dist/rehearsal/database.js +349 -0
  89. package/dist/rehearsal/loop.d.ts +57 -0
  90. package/dist/rehearsal/loop.js +153 -0
  91. package/dist/rehearsal/network.d.ts +120 -0
  92. package/dist/rehearsal/network.js +524 -0
  93. package/dist/rehearsal/ranges.d.ts +8 -0
  94. package/dist/rehearsal/ranges.js +27 -0
  95. package/dist/rehearsal/yield.d.ts +9 -0
  96. package/dist/rehearsal/yield.js +24 -0
  97. package/dist/system.d.ts +13 -1
  98. package/dist/system.js +204 -25
  99. package/dist/timeout.d.ts +8 -0
  100. package/dist/timeout.js +26 -0
  101. package/dist/types.d.ts +86 -3
  102. package/package.json +21 -2
  103. package/dist/backstage-ui/assets/index-Bg0MCiqs.css +0 -1
  104. package/dist/backstage-ui/assets/index-CeefBsDh.js +0 -9
  105. package/dist/persistence/json.d.ts +0 -7
  106. package/dist/persistence/json.js +0 -75
package/dist/system.js CHANGED
@@ -4,7 +4,7 @@ import { checkInt, checkKeys, describe } from './checks.js';
4
4
  import { Dispatcher } from './dispatcher.js';
5
5
  import { ActorSystemTerminatedError, NotAChildError } from './errors.js';
6
6
  import { EventBus } from './events.js';
7
- import { INSPECT } from './internal.js';
7
+ import { HOOKS, INSPECT, } from './internal.js';
8
8
  import { consoleLogger, isLogger, safeLogger } from './logger.js';
9
9
  import { childPath, Names } from './names.js';
10
10
  import { realScheduler } from './scheduler.js';
@@ -23,6 +23,8 @@ const STOP = supervise.stop();
23
23
  const MAILBOX_OPTIONS = new Set(['capacity']);
24
24
  const SYSTEM_NAME = /^[a-z0-9-]+$/;
25
25
  const USER_PATH = '/user';
26
+ const SYSTEM_PATH = '/system';
27
+ const TEMP_PATH = '/temp';
26
28
  /**
27
29
  * Creates an actor system, the root of an actor hierarchy.
28
30
  * @throws TypeError for options that can't be used, unknown fields included.
@@ -62,26 +64,71 @@ export function createSystem(opts = {}) {
62
64
  const asker = new Asker({ events, systemName: name, defaultTimeoutMs: askTimeoutMs, setTimer });
63
65
  const makeRef = (path, tell) => asker.ref(path, tell);
64
66
  const cells = new WeakMap();
67
+ // Remoting's, for remote refs (decision 0026). Undefined for a system with no cluster.
68
+ let resolveWatch;
69
+ const cellOf = (ref) => typeof ref === 'object' && ref !== null ? cells.get(ref) : undefined;
70
+ const watchTargetOf = (ref) => cellOf(ref) ?? resolveWatch?.(ref);
65
71
  let busy = 0;
72
+ // By path. A cell can wait on more than one promise at once, through pipeToSelf.
73
+ const busyByPath = new Map();
66
74
  let terminating = false;
75
+ // Set once terminate() has stopped /user and every onTerminate task has settled: from then,
76
+ // actors under /system stop and take no more messages.
77
+ let systemStopping = false;
78
+ const terminateTasks = [];
79
+ let tasksRun = false;
67
80
  let resolveTerminated;
68
81
  const whenTerminated = new Promise((resolve) => {
69
82
  resolveTerminated = resolve;
70
83
  });
71
- // The parent of every top-level actor. terminate() stops it like any other parent.
72
- const guardian = {
73
- path: USER_PATH,
74
- names: new Names(),
75
- childCells: new Map(),
76
- removeChild(child) {
77
- this.childCells.delete(child.name);
78
- this.names.release(child.name);
79
- // The last stopped event is published right after this returns, before anyone awaiting
80
- // whenTerminated can run.
81
- if (terminating && this.childCells.size === 0)
84
+ // The parents of every top-level actor: the user's, and the system's own under /system, which
85
+ // the cluster uses (decision 0025). terminate() stops /user first, then /system, so a user
86
+ // actor's last messages can still go through the cluster.
87
+ const guardian = guardianAt(USER_PATH, () => {
88
+ if (terminating)
89
+ stopSystemActors();
90
+ });
91
+ const systemGuardian = guardianAt(SYSTEM_PATH, () => {
92
+ if (terminating)
93
+ checkTerminated();
94
+ });
95
+ // The last stopped event is published right after a removeChild returns, before anyone
96
+ // awaiting whenTerminated can run.
97
+ const checkTerminated = () => {
98
+ if (!systemStopping)
99
+ return;
100
+ if (guardian.childCells.size === 0 && systemGuardian.childCells.size === 0) {
101
+ resolveTerminated();
102
+ }
103
+ };
104
+ // Once /user is empty, the onTerminate tasks run, such as the cluster's graceful leave, which
105
+ // hands shards off while /system still works. Only then does /system stop.
106
+ const stopSystemActors = () => {
107
+ if (guardian.childCells.size > 0 || tasksRun)
108
+ return;
109
+ tasksRun = true;
110
+ const stopSystem = () => {
111
+ systemStopping = true;
112
+ if (systemGuardian.childCells.size === 0)
82
113
  resolveTerminated();
83
- },
114
+ for (const child of [...systemGuardian.childCells.values()])
115
+ child.requestStop();
116
+ };
117
+ if (terminateTasks.length === 0) {
118
+ stopSystem();
119
+ return;
120
+ }
121
+ const running = terminateTasks.map(async (task) => {
122
+ try {
123
+ await task();
124
+ }
125
+ catch (error) {
126
+ log.error('terminate: a termination task failed', { error });
127
+ }
128
+ });
129
+ void Promise.all(running).then(stopSystem);
84
130
  };
131
+ const isSystemPath = (path) => path === SYSTEM_PATH || path.startsWith(`${SYSTEM_PATH}/`);
85
132
  const host = {
86
133
  dispatcher,
87
134
  events,
@@ -92,13 +139,24 @@ export function createSystem(opts = {}) {
92
139
  setTimer,
93
140
  makeRef,
94
141
  onAskSettled: (promise, listener) => asker.onSettled(promise, listener),
95
- trackBusy: (delta) => {
142
+ trackBusy: (path, delta) => {
96
143
  busy += delta;
144
+ const entry = busyByPath.get(path);
145
+ if (delta === 1) {
146
+ if (entry === undefined)
147
+ busyByPath.set(path, { count: 1, since: now() });
148
+ else
149
+ entry.count++;
150
+ }
151
+ else if (entry !== undefined && --entry.count === 0) {
152
+ busyByPath.delete(path);
153
+ }
97
154
  },
98
- terminating: () => terminating,
99
- cellOf: (ref) => (typeof ref === 'object' && ref !== null ? cells.get(ref) : undefined),
155
+ terminating: (path) => terminating && (systemStopping || !isSystemPath(path)),
156
+ cellOf,
157
+ watchTargetOf,
100
158
  spawn(parent, def, childName, spawnOpts) {
101
- if (terminating) {
159
+ if (terminating && (systemStopping || !isSystemPath(parent.path))) {
102
160
  throw new ActorSystemTerminatedError(`system "${name}" is terminating, so it can't spawn`);
103
161
  }
104
162
  checkDef(def);
@@ -113,10 +171,27 @@ export function createSystem(opts = {}) {
113
171
  return cell.ref;
114
172
  },
115
173
  };
174
+ let clusterView;
175
+ const clusterListeners = new Set();
116
176
  const inspection = Object.freeze({
117
177
  scheduler,
118
178
  log,
119
- walk: () => walk(guardian.childCells, []),
179
+ walk: () => {
180
+ const out = walk(guardian.childCells, []);
181
+ const sharding = systemGuardian.childCells.get('sharding');
182
+ return sharding === undefined ? out : walk(sharding.childCells, out);
183
+ },
184
+ cluster: () => clusterView,
185
+ onClusterChange(listener) {
186
+ // A wrapper per call, so adding one listener twice gives two subscriptions.
187
+ const own = () => {
188
+ listener();
189
+ };
190
+ clusterListeners.add(own);
191
+ return () => {
192
+ clusterListeners.delete(own);
193
+ };
194
+ },
120
195
  });
121
196
  const system = {
122
197
  name,
@@ -139,31 +214,135 @@ export function createSystem(opts = {}) {
139
214
  // Pending asks fail now, so an actor awaiting one in an async receive can still stop.
140
215
  asker.terminate();
141
216
  if (guardian.childCells.size === 0)
142
- resolveTerminated();
217
+ stopSystemActors();
143
218
  for (const child of [...guardian.childCells.values()])
144
219
  child.requestStop();
145
220
  return whenTerminated;
146
221
  },
147
222
  };
148
- // Not enumerable, so spreading or logging a system doesn't show it.
223
+ const hooks = Object.freeze({
224
+ scheduler,
225
+ random,
226
+ log,
227
+ spawnSystem(def, childName, spawnOpts, parent) {
228
+ if (parent === undefined)
229
+ return host.spawn(systemGuardian, def, childName, spawnOpts);
230
+ const cell = cellOf(parent);
231
+ if (cell === undefined || cell.terminated || !cell.ref.path.startsWith(`${SYSTEM_PATH}/`)) {
232
+ throw new TypeError('spawnSystem: parent must be a live actor under /system');
233
+ }
234
+ return host.spawn(cell, def, childName, spawnOpts);
235
+ },
236
+ lookup(path) {
237
+ if (path.startsWith(`${TEMP_PATH}/`))
238
+ return asker.temp(path);
239
+ const root = path.startsWith(`${USER_PATH}/`)
240
+ ? guardian
241
+ : path.startsWith(`${SYSTEM_PATH}/`)
242
+ ? systemGuardian
243
+ : undefined;
244
+ return root === undefined ? undefined : find(root, path.slice(root.path.length + 1));
245
+ },
246
+ owns: (ref) => asker.owns(ref),
247
+ makeRef,
248
+ publish: (body) => {
249
+ events.publish(body);
250
+ },
251
+ deadLetter(recipient, message, reason) {
252
+ events.publish({ type: 'deadLetter', recipient, message, reason });
253
+ },
254
+ watchTarget: watchTargetOf,
255
+ setWatchResolver(resolve) {
256
+ if (resolveWatch !== undefined)
257
+ throw new Error('a watch resolver is already installed');
258
+ resolveWatch = resolve;
259
+ },
260
+ sender: () => host.senderOverride ?? dispatcher.current?.path,
261
+ stopWhenIdle(ref) {
262
+ const cell = cellOf(ref);
263
+ if (cell === undefined)
264
+ throw new TypeError('stopWhenIdle: the ref is not an actor of this system');
265
+ cell.stopWhenIdle();
266
+ },
267
+ onTerminate(task) {
268
+ if (tasksRun)
269
+ throw new Error('onTerminate: the system has already stopped /user');
270
+ terminateTasks.push(task);
271
+ },
272
+ setCluster(view) {
273
+ if (clusterView !== undefined)
274
+ throw new Error('a cluster view is already set');
275
+ clusterView = view;
276
+ return () => {
277
+ for (const listener of [...clusterListeners]) {
278
+ try {
279
+ listener();
280
+ }
281
+ catch (error) {
282
+ log.error('a cluster view listener threw; skipped it', { error });
283
+ }
284
+ }
285
+ };
286
+ },
287
+ tellFrom(ref, message, from) {
288
+ const outer = host.senderOverride;
289
+ host.senderOverride = from;
290
+ try {
291
+ ref.tell(message);
292
+ }
293
+ finally {
294
+ host.senderOverride = outer;
295
+ }
296
+ },
297
+ });
298
+ // Not enumerable, so spreading or logging a system doesn't show them.
149
299
  Object.defineProperty(system, INSPECT, { value: inspection });
300
+ Object.defineProperty(system, HOOKS, { value: hooks });
150
301
  Object.freeze(system);
151
302
  return {
152
303
  system,
153
304
  busy: () => busy,
305
+ busyActors: () => [...busyByPath].map(([path, { since }]) => ({ path, since })),
154
306
  pendingAsks: () => asker.pending(),
155
307
  makeRef,
156
308
  watch(ref, watcher) {
157
- const cell = host.cellOf(ref);
158
- if (cell === undefined)
309
+ const target = watchTargetOf(ref);
310
+ if (target === undefined) {
159
311
  throw new TypeError('watch: the ref is not an actor of this system');
160
- if (cell.terminated)
161
- watcher.notifyTerminated(cell);
312
+ }
313
+ if (target.terminated)
314
+ watcher.notifyTerminated(target);
162
315
  else
163
- cell.watchers.add(watcher);
316
+ target.addWatcher(watcher);
317
+ },
318
+ };
319
+ }
320
+ /** A guardian: the parent of top-level actors at `path`. `onEmpty` runs when its last child goes. */
321
+ function guardianAt(path, onEmpty) {
322
+ return {
323
+ path,
324
+ names: new Names(),
325
+ childCells: new Map(),
326
+ removeChild(child) {
327
+ this.childCells.delete(child.name);
328
+ this.names.release(child.name);
329
+ if (this.childCells.size === 0)
330
+ onEmpty();
164
331
  },
165
332
  };
166
333
  }
334
+ /** The ref of the cell at `relative`, a path such as `a/b` below `root`, if it hasn't terminated. */
335
+ function find(root, relative) {
336
+ let children = root.childCells;
337
+ let cell;
338
+ for (const name of relative.split('/')) {
339
+ cell = children.get(name);
340
+ if (cell === undefined)
341
+ return undefined;
342
+ children = cell.childCells;
343
+ }
344
+ return cell?.ref;
345
+ }
167
346
  /** Every cell under `cells`, depth first, each parent before its children in spawn order. */
168
347
  function walk(cells, out) {
169
348
  for (const cell of cells.values()) {
@@ -0,0 +1,8 @@
1
+ /** Schedules `task` after `delayMs`, and returns a function that cancels it. */
2
+ export type SetTimer = (task: () => void, delayMs: number) => () => void;
3
+ /**
4
+ * Settles as `call` does, or rejects with `timedOut()` once `ms` have passed on `setTimer`,
5
+ * whichever comes first. An answer that comes after the timeout is dropped: the outcome stays
6
+ * unknown to the caller, which settles it by recovery, never by a late reply.
7
+ */
8
+ export declare function withTimeout<T>(call: PromiseLike<T>, ms: number, setTimer: SetTimer, timedOut: () => Error): Promise<T>;
@@ -0,0 +1,26 @@
1
+ // Timeouts on calls the framework makes to a store (decision 0036). A call that never settles
2
+ // would hold its caller for good: a persistent actor's mailbox, a projection's poll, a shard's
3
+ // handoff. The timer runs on the caller's scheduler (decision 0003), so virtual time reaches it.
4
+ // Never exported.
5
+ /**
6
+ * Settles as `call` does, or rejects with `timedOut()` once `ms` have passed on `setTimer`,
7
+ * whichever comes first. An answer that comes after the timeout is dropped: the outcome stays
8
+ * unknown to the caller, which settles it by recovery, never by a late reply.
9
+ */
10
+ export function withTimeout(call, ms, setTimer, timedOut) {
11
+ // A promise settles once, so whichever comes second, the answer or the timeout, does nothing.
12
+ return new Promise((resolve, reject) => {
13
+ const cancel = setTimer(() => {
14
+ reject(timedOut());
15
+ }, ms);
16
+ Promise.resolve(call).then((value) => {
17
+ cancel();
18
+ resolve(value);
19
+ }, (error) => {
20
+ cancel();
21
+ // The call's own reason, passed on as it came, whatever it is.
22
+ // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors
23
+ reject(error);
24
+ });
25
+ });
26
+ }
package/dist/types.d.ts CHANGED
@@ -3,13 +3,19 @@ import type { Scheduler } from './scheduler.js';
3
3
  import type { SupervisorStrategy } from './supervision.js';
4
4
  /**
5
5
  * A handle for sending messages to one actor. It's the only way to reach an actor: you never hold
6
- * the actor itself, which is what lets a ref point at another process in milestone 4.
6
+ * the actor itself, which is what lets a ref point at an actor on another node.
7
7
  *
8
8
  * `tell` is a property, not a method, so `ActorRef` is contravariant in `M`: a ref that accepts
9
9
  * more messages can stand in for one that accepts fewer, never the other way round.
10
10
  */
11
11
  export interface ActorRef<M> {
12
- /** Where the actor lives in the hierarchy, for example `/user/box-office`. */
12
+ /**
13
+ * Where the actor lives. A local actor's path is its place in the hierarchy, such as
14
+ * `/user/box-office`. An actor on another node in a cluster has the full form, its cluster,
15
+ * node address and uid, then the path, such as `troupe://festival@node-2:2552#17/user/crowd`,
16
+ * so two refs with the same path are the same actor. An entity ref's path is
17
+ * `/sharding/<type>/<id>`, the same on every node, wherever the entity lives.
18
+ */
13
19
  readonly path: string;
14
20
  /**
15
21
  * Sends `msg` to the actor's mailbox and returns at once. Never throws: a message that can't be
@@ -38,6 +44,8 @@ export interface AskOptions {
38
44
  /** How long to wait for the reply, in ms. Default: the system's `askTimeoutMs`. */
39
45
  timeoutMs?: number;
40
46
  }
47
+ /** Why a message became a dead letter. See the `deadLetter` event. */
48
+ export type DeadLetterReason = 'mailboxFull' | 'stopped' | 'askCompleted' | 'terminated' | 'unreachable' | 'unserializable' | 'invalid';
41
49
  /** A ref to an actor of any protocol, for watching, stopping and comparing. */
42
50
  export type AnyRef = ActorRef<never>;
43
51
  /** How a promise settled, as `pipeToSelf` delivers it. */
@@ -301,6 +309,77 @@ export type SystemEvent = Timestamped<{
301
309
  readonly stateChanged: boolean;
302
310
  /** Present, and true, for a cancelled timer's message, which no handler saw. */
303
311
  readonly skipped?: true;
312
+ }
313
+ /**
314
+ * In a cluster, a member joined, in this node's view: this node itself once it's in the
315
+ * cluster, or another node it has learned of (decision 0028). A member is one incarnation of a
316
+ * node: its address and its uid, new on every start.
317
+ */
318
+ | {
319
+ readonly type: 'memberUp';
320
+ readonly address: string;
321
+ readonly uid: number;
322
+ }
323
+ /** In a cluster, a member began leaving gracefully. Placement stops using it. */
324
+ | {
325
+ readonly type: 'memberLeaving';
326
+ readonly address: string;
327
+ readonly uid: number;
328
+ }
329
+ /**
330
+ * In a cluster, a member was downed, by this node or another, after being unreachable too long.
331
+ * Messages to it are `unreachable` dead letters, and watches on its actors signal `terminated`.
332
+ * It stays in the table, as `down`, until a new incarnation at its address replaces it.
333
+ */
334
+ | {
335
+ readonly type: 'memberDown';
336
+ readonly address: string;
337
+ readonly uid: number;
338
+ }
339
+ /**
340
+ * In a cluster, a member is gone from this node's table: it left, or a new incarnation at its
341
+ * address replaced it.
342
+ */
343
+ | {
344
+ readonly type: 'memberRemoved';
345
+ readonly address: string;
346
+ readonly uid: number;
347
+ }
348
+ /**
349
+ * In a cluster, this node stopped hearing a member's heartbeats, or started again. Each node's
350
+ * own view, never gossiped.
351
+ */
352
+ | {
353
+ readonly type: 'reachability';
354
+ readonly address: string;
355
+ readonly uid: number;
356
+ readonly reachable: boolean;
357
+ }
358
+ /**
359
+ * In a cluster, this node acquired the lease on a shard of an entity type and started it
360
+ * (decision 0030). `node` is this node's holder name, `<address>#<uid>`. `token` goes up by one
361
+ * every time the lease changes hands, so a history can tell one ownership from the next.
362
+ */
363
+ | {
364
+ readonly type: 'shardAcquired';
365
+ readonly entityType: string;
366
+ readonly shard: number;
367
+ readonly node: string;
368
+ readonly token: number;
369
+ }
370
+ /**
371
+ * In a cluster, this node stopped owning a shard. `leaseLost`: its lease ran out by this node's
372
+ * clock, before it could be renewed, and its entities are stopping. Otherwise its entities have
373
+ * stopped and the lease is being given up: `leaving`, as the node leaves or terminates,
374
+ * `downed`, as it leaves because it was downed, or `handoff`, to move the shard to another node.
375
+ */
376
+ | {
377
+ readonly type: 'shardReleased';
378
+ readonly entityType: string;
379
+ readonly shard: number;
380
+ readonly node: string;
381
+ readonly token: number;
382
+ readonly reason: 'handoff' | 'leaving' | 'leaseLost' | 'downed';
304
383
  } | {
305
384
  readonly type: 'deadLetter';
306
385
  readonly recipient: string;
@@ -314,8 +393,12 @@ export type SystemEvent = Timestamped<{
314
393
  * `mailboxFull`: a bounded mailbox was full. `stopped`: the actor was stopping or had
315
394
  * stopped. `askCompleted`: a reply to an `ask` that had already been answered or had timed
316
395
  * out. `terminated`: the system was terminating.
396
+ *
397
+ * In a cluster: `unreachable`: its node couldn't be reached, or was down. `unserializable`:
398
+ * the message wasn't JSON plus refs, or was too big to send. `invalid`: the message failed
399
+ * its entity type's schema.
317
400
  */
318
- readonly reason: 'mailboxFull' | 'stopped' | 'askCompleted' | 'terminated';
401
+ readonly reason: DeadLetterReason;
319
402
  }>;
320
403
  /** The system's events, delivered synchronously, in order, as they happen. */
321
404
  export interface EventStream {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kylewillett/troupe",
3
- "version": "0.1.1",
4
- "description": "Typed actors for TypeScript: supervision, event-sourced persistent actors, and (later) cluster sharding.",
3
+ "version": "0.3.0",
4
+ "description": "Typed actors for TypeScript: supervision, event-sourced persistent actors, and cluster sharding.",
5
5
  "license": "MIT",
6
6
  "author": "Kyle Willett",
7
7
  "homepage": "https://troupe.kylewillett.com/",
@@ -19,6 +19,8 @@
19
19
  "akka",
20
20
  "supervision",
21
21
  "event-sourcing",
22
+ "cluster",
23
+ "sharding",
22
24
  "typescript"
23
25
  ],
24
26
  "type": "module",
@@ -62,6 +64,18 @@
62
64
  "./backstage/server": {
63
65
  "types": "./dist/node/backstage/index.d.ts",
64
66
  "import": "./dist/node/backstage/index.js"
67
+ },
68
+ "./cluster": {
69
+ "types": "./dist/cluster/index.d.ts",
70
+ "import": "./dist/cluster/index.js"
71
+ },
72
+ "./cluster/postgres": {
73
+ "types": "./dist/cluster/postgres/index.d.ts",
74
+ "import": "./dist/cluster/postgres/index.js"
75
+ },
76
+ "./cluster/tcp": {
77
+ "types": "./dist/node/cluster/index.d.ts",
78
+ "import": "./dist/node/cluster/index.js"
65
79
  }
66
80
  },
67
81
  "sideEffects": false,
@@ -73,11 +87,16 @@
73
87
  "test": "vitest run --project unit",
74
88
  "test:watch": "vitest --project unit",
75
89
  "test:integration": "vitest run --project integration",
90
+ "test:cluster": "npm run build && vitest run --project multiprocess",
76
91
  "coverage": "vitest run --coverage --project unit --project integration",
77
92
  "postgres:up": "docker compose -f docker-compose.test.yml up -d --wait",
78
93
  "postgres:down": "docker compose -f docker-compose.test.yml down",
79
94
  "example": "npm run build && node examples/box-office/main.ts",
80
95
  "example:backstage": "npm run build && node examples/backstage/main.ts",
96
+ "cluster:up": "docker compose -f docker-compose.cluster.yml up -d --build --wait && npm run cluster:logs",
97
+ "cluster:logs": "docker compose -f docker-compose.cluster.yml logs -f -t --no-color | node examples/cluster/narrate.ts",
98
+ "cluster:down": "docker compose -f docker-compose.cluster.yml down -v",
99
+ "cluster:smoke": "node scripts/cluster-smoke.ts",
81
100
  "bench": "node --expose-gc bench/run.ts",
82
101
  "demo:dev": "vite --config demo/vite.config.ts",
83
102
  "demo:build": "vite build --config demo/vite.config.ts",
@@ -1 +0,0 @@
1
- .backstage{--bs-bg:#fff;--bs-panel:#faf9fc;--bs-fg:#1c1b22;--bs-muted:#5d5b66;--bs-line:#e3e1ea;--bs-accent:#7a2e3a;--bs-select:#f3e6e8;--bs-changed:#f6dfa4;--bs-running:#2f7d4f;--bs-starting:#2b63b5;--bs-restarting:#b86e00;--bs-stopped:#8f8c99;--bs-error:#b3261e;--bs-bar:#c9768a;--bs-flow:#7a2e3a;--bs-mono:ui-monospace, "SF Mono", Menlo, Consolas, monospace;color:var(--bs-fg);min-width:0;container-type:inline-size}.bs-grid{grid-template-columns:minmax(19rem,1fr) minmax(0,1.25fr) minmax(0,1.25fr);align-items:start;gap:1rem;display:grid}@media (prefers-color-scheme:dark){.backstage{--bs-bg:#17161c;--bs-panel:#1e1d24;--bs-fg:#ecebf1;--bs-muted:#a3a1ad;--bs-line:#2f2d38;--bs-accent:#d77a88;--bs-select:#3a2328;--bs-changed:#5b4714;--bs-running:#6fcf97;--bs-starting:#8ab4f8;--bs-restarting:#f2b04c;--bs-stopped:#6d6a78;--bs-error:#f2b8b5;--bs-bar:#b0566c;--bs-flow:#e8a0ab}}.backstage h2{margin:0 0 .25rem;font-size:1.05rem}.backstage h3{margin:.25rem 0;font-size:1rem}.backstage h4{text-transform:uppercase;letter-spacing:.04em;color:var(--bs-muted);margin:1rem 0 .35rem;font-size:.85rem}.bs-panel{background:var(--bs-panel);border:1px solid var(--bs-line);border-radius:8px;min-width:0;padding:.75rem}.bs-explain{margin:0 0 .25rem;font-size:.9rem}.bs-more{color:var(--bs-muted);margin-bottom:.5rem;font-size:.85rem}.bs-more summary{cursor:pointer}.bs-more p{margin:.25rem 0}.bs-empty,.bs-note{color:var(--bs-muted);font-size:.85rem}.bs-error{color:var(--bs-error);font-size:.9rem}.bs-path{font-family:var(--bs-mono);color:var(--bs-muted);overflow-wrap:anywhere;font-size:.8rem;font-weight:400}.bs-summary{margin:0 0 .5rem;font-size:.9rem}.bs-tabs{display:none}.bs-tree{min-height:30px;max-height:34rem;position:relative;overflow:hidden auto}.bs-flows{pointer-events:none;position:absolute;top:0;left:0}.bs-flow{fill:none;stroke:var(--bs-flow);stroke-width:1.5px;animation:.7s ease-out forwards bs-flow}@keyframes bs-flow{0%{opacity:1}to{opacity:0}}.bs-tree-list{margin:0;padding:0;list-style:none}.bs-row{cursor:pointer;white-space:nowrap;border-radius:4px;align-items:center;gap:.4rem;height:30px;padding-right:.25rem;font-size:.9rem;animation:.3s ease-out bs-appear;display:flex}.bs-row:hover{background:var(--bs-line)}.bs-row:focus-visible{outline:2px solid var(--bs-accent);outline-offset:-2px}.bs-row.bs-selected{background:var(--bs-select)}@keyframes bs-appear{0%{opacity:0;transform:translate(-6px)}}.bs-dot{background:var(--bs-running);border-radius:50%;flex:none;width:.6rem;height:.6rem}.bs-starting .bs-dot{background:var(--bs-starting)}.bs-restarting .bs-dot,.bs-stopping .bs-dot{background:var(--bs-restarting);animation:.6s ease-in-out infinite alternate bs-pulse}.bs-stopped{animation:1.5s ease-in forwards bs-fade}.bs-stopped .bs-dot{background:var(--bs-stopped)}@keyframes bs-pulse{to{transform:scale(1.5)}}@keyframes bs-fade{to{opacity:.25}}.bs-name{text-overflow:ellipsis;overflow:hidden}.bs-phase{color:var(--bs-restarting);font-size:.75rem}.bs-stopped .bs-phase{color:var(--bs-stopped)}.bs-failures{color:var(--bs-error);font-size:.75rem}.bs-tag{border:1px solid var(--bs-line);color:var(--bs-muted);border-radius:999px;padding:0 .3rem;font-size:.7rem}.bs-mailbox{flex:none;align-items:center;gap:.3rem;margin-left:auto;display:flex}.bs-bar{background:var(--bs-line);border-radius:999px;width:4rem;height:.45rem;overflow:hidden}.bs-fill{background:var(--bs-bar);height:100%;transition:width .12s linear;display:block}.bs-depth{text-align:right;font-variant-numeric:tabular-nums;width:1.6rem;color:var(--bs-muted);font-size:.8rem}.bs-value{font-family:var(--bs-mono);background:var(--bs-bg);border:1px solid var(--bs-line);white-space:pre-wrap;overflow-wrap:anywhere;border-radius:6px;max-height:18rem;margin:0;padding:.5rem;font-size:.8rem;line-height:1.45;overflow:auto}.bs-entries{padding-left:1.2em;display:block}.bs-entry{display:block}.bs-key{color:var(--bs-muted)}.bs-string{color:var(--bs-running)}.bs-number,.bs-boolean{color:var(--bs-starting)}.bs-null{color:var(--bs-stopped)}.bs-chip{font-family:var(--bs-mono);border:1px solid var(--bs-line);background:var(--bs-panel);border-radius:4px;padding:0 .35rem;font-size:.75rem}.bs-chip-ref{color:var(--bs-accent)}.bs-chip-error{color:var(--bs-error)}.bs-chip-cut,.bs-chip-cycle,.bs-chip-value{color:var(--bs-muted)}.bs-changed{background:var(--bs-changed);color:inherit;outline:1px solid var(--bs-restarting);border-radius:3px}.bs-changed.bs-block{vertical-align:top;display:inline-block}.bs-removed{color:var(--bs-muted);text-decoration:line-through}.bs-chart{margin:0}.bs-chart svg{width:100%;height:56px;display:block}.bs-chart figcaption{color:var(--bs-muted);font-size:.75rem}.bs-axis{stroke:var(--bs-line)}.bs-line{fill:none;stroke:var(--bs-bar);stroke-width:2px}.bs-scroll{overflow-x:auto}.bs-messages{border-collapse:collapse;font-variant-numeric:tabular-nums;width:100%;font-size:.8rem}.bs-messages th,.bs-messages td{text-align:left;border-bottom:1px solid var(--bs-line);white-space:nowrap;padding:.15rem .4rem .15rem 0}.bs-messages th{color:var(--bs-muted);font-weight:600}.bs-message code{font-family:var(--bs-mono);font-size:.75rem}.bs-outcome-failed td,.bs-outcome-dropped td{color:var(--bs-error)}.bs-outcome-waiting td,.bs-outcome-skipped td{color:var(--bs-muted)}.bs-failure-list{margin:0;padding-left:1.5rem;font-size:.85rem}.bs-failure-list time{font-variant-numeric:tabular-nums;color:var(--bs-muted)}.bs-scrubber{align-items:center;gap:.5rem;margin:.5rem 0;display:flex}.bs-scrubber input{accent-color:var(--bs-accent);flex:1;min-width:0}.backstage button{font:inherit;color:inherit}.bs-scrubber button{border:1px solid var(--bs-line);background:var(--bs-bg);cursor:pointer;border-radius:6px;padding:.2rem .7rem}.bs-scrubber button[aria-pressed=true]{background:var(--bs-accent);border-color:var(--bs-accent);color:var(--bs-bg)}.bs-events{max-height:16rem;margin:0;padding:0;list-style:none;overflow-y:auto}.bs-event{text-align:left;cursor:pointer;background:0 0;border:none;border-radius:4px;align-items:center;gap:.5rem;width:100%;padding:.15rem .25rem;font-size:.8rem;display:flex}.bs-event:hover{background:var(--bs-line)}.bs-event[aria-current=true]{background:var(--bs-select)}.bs-event code{font-family:var(--bs-mono);text-overflow:ellipsis;white-space:nowrap;flex:1;min-width:0;font-size:.75rem;overflow:hidden}.bs-seq{text-align:right;font-variant-numeric:tabular-nums;width:2.5rem;color:var(--bs-muted);flex:none}.bs-event time{color:var(--bs-muted);font-variant-numeric:tabular-nums;flex:none}@media (prefers-reduced-motion:reduce){.bs-row,.bs-flow,.bs-restarting .bs-dot,.bs-stopping .bs-dot{animation:none}.bs-stopped{opacity:.4;animation:none}}@container (width<=68rem){.bs-grid{grid-template-columns:minmax(18rem,1fr) minmax(0,1.4fr)}.bs-panel-tree{grid-row:span 2}}@container (width<=40rem){.bs-grid{display:block}.bs-tabs{gap:.25rem;margin-bottom:.5rem;display:flex}.bs-tabs button{border:1px solid var(--bs-line);background:var(--bs-panel);cursor:pointer;border-radius:6px;flex:1;padding:.5rem}.bs-tabs button[aria-selected=true]{background:var(--bs-accent);border-color:var(--bs-accent);color:var(--bs-bg)}.bs-panel:not(.bs-active){display:none}.bs-tree{max-height:none}}:root{--bg:#fff;--fg:#1c1b22;--muted:#5d5b66;--line:#e3e1ea;--live:#2f7d4f;--warn:#b86e00;--lightningcss-light:initial;--lightningcss-dark: ;color-scheme:light dark;font-family:system-ui,-apple-system,Segoe UI,sans-serif;line-height:1.5}@media (prefers-color-scheme:dark){:root{--lightningcss-light: ;--lightningcss-dark:initial;--bg:#17161c;--fg:#ecebf1;--muted:#a3a1ad;--line:#2f2d38;--live:#7fcf9c;--warn:#f0b45a}}*{box-sizing:border-box}body{background:var(--bg);color:var(--fg);margin:0}main{max-width:120rem;margin:0 auto;padding:1rem 1rem 3rem}.bar{border-bottom:1px solid var(--line);flex-wrap:wrap;align-items:baseline;gap:.25rem 1rem;margin-bottom:1rem;padding-bottom:.75rem;display:flex}h1{margin:0;font-size:1.5rem}.status{color:var(--muted);margin:0}.status-open{color:var(--live)}.status-reconnecting,.status-closed{color:var(--warn)}