@kylewillett/troupe 0.1.1 → 0.2.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 (81) hide show
  1. package/CHANGELOG.md +16 -1
  2. package/README.md +129 -3
  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 +16 -14
  15. package/dist/cell.js +38 -13
  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 +109 -0
  46. package/dist/cluster/sharding.js +278 -0
  47. package/dist/cluster/table.d.ts +29 -0
  48. package/dist/cluster/table.js +74 -0
  49. package/dist/cluster/transport.d.ts +29 -0
  50. package/dist/cluster/transport.js +4 -0
  51. package/dist/cluster/wire.d.ts +90 -0
  52. package/dist/cluster/wire.js +177 -0
  53. package/dist/hash.d.ts +7 -0
  54. package/dist/hash.js +25 -0
  55. package/dist/internal.d.ts +134 -2
  56. package/dist/internal.js +12 -1
  57. package/dist/json.d.ts +44 -0
  58. package/dist/json.js +143 -0
  59. package/dist/node/cluster/frames.d.ts +31 -0
  60. package/dist/node/cluster/frames.js +73 -0
  61. package/dist/node/cluster/index.d.ts +1 -0
  62. package/dist/node/cluster/index.js +3 -0
  63. package/dist/node/cluster/tcp.d.ts +101 -0
  64. package/dist/node/cluster/tcp.js +416 -0
  65. package/dist/persistence/actor.js +1 -1
  66. package/dist/persistence/backend.d.ts +1 -10
  67. package/dist/persistence/backend.js +4 -34
  68. package/dist/persistence/postgres/index.d.ts +2 -1
  69. package/dist/persistence/postgres/index.js +1 -1
  70. package/dist/persistence/postgres/pool.d.ts +44 -0
  71. package/dist/persistence/postgres/pool.js +65 -0
  72. package/dist/persistence/postgres/postgres.d.ts +1 -33
  73. package/dist/persistence/postgres/postgres.js +4 -63
  74. package/dist/system.d.ts +1 -1
  75. package/dist/system.js +190 -24
  76. package/dist/types.d.ts +86 -3
  77. package/package.json +21 -2
  78. package/dist/backstage-ui/assets/index-Bg0MCiqs.css +0 -1
  79. package/dist/backstage-ui/assets/index-CeefBsDh.js +0 -9
  80. package/dist/persistence/json.d.ts +0 -7
  81. package/dist/persistence/json.js +0 -75
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Something that runs a parameterized query, as `pg`'s pool and clients do. Only `rows` is read.
3
+ */
4
+ export interface PgQueryable {
5
+ /** Runs `text` with `$1`, `$2`, ... bound to `values`. */
6
+ query(text: string, values?: unknown[]): Promise<{
7
+ readonly rows: readonly unknown[];
8
+ }>;
9
+ }
10
+ /** One connection checked out of a {@link PgPool}, as `pg`'s `PoolClient` is. */
11
+ export interface PgPoolClient extends PgQueryable {
12
+ /** Returns the connection to the pool, or with `true` or an error, discards it. */
13
+ release(destroy?: boolean | Error): void;
14
+ }
15
+ /**
16
+ * A pool of Postgres connections, typed by shape so this entry point never imports `pg`
17
+ * (decision 0017). A `pg` `Pool` fits, and so does any pool with the same two methods.
18
+ */
19
+ export interface PgPool extends PgQueryable {
20
+ /** Checks out one connection, for a transaction. */
21
+ connect(): Promise<PgPoolClient>;
22
+ }
23
+ export declare const LOCK_CLASS = 1414681936;
24
+ /** Takes the advisory lock `($1, $2)` until the transaction ends. */
25
+ export declare const LOCK = "SELECT pg_advisory_xact_lock($1, $2)";
26
+ /** Throws unless `pool` has the two methods a {@link PgPool} needs. */
27
+ export declare function checkPool(pool: unknown, where: string): asserts pool is PgPool;
28
+ /**
29
+ * Runs `work` in a read-committed transaction on one connection. Read committed, whatever the
30
+ * database's default, so each statement sees what committed before it, including while this
31
+ * one waited for a lock. A connection whose rollback fails is discarded, not reused.
32
+ */
33
+ export declare function transaction<T>(pool: PgPool, work: (client: PgPoolClient) => Promise<T>): Promise<T>;
34
+ /**
35
+ * A 32-bit FNV-1a hash of `text`, as a signed integer for Postgres's `int4`. Computed here, not by
36
+ * Postgres's undocumented `hashtext`, so every process agrees on it, whatever the server version.
37
+ * A collision only makes two journals share a lock.
38
+ */
39
+ export declare function schemaHash(text: string): number;
40
+ /**
41
+ * A `bigint` column as a JavaScript number. `pg` returns them as strings by default, and other
42
+ * pools may parse them as numbers or bigints. The journal only stores safe integers.
43
+ */
44
+ export declare function toInt(value: unknown): number;
@@ -0,0 +1,65 @@
1
+ // What both Postgres backends share, never exported from an entry point: the pool's shape, the
2
+ // transaction runner, the advisory lock's keys and the integer reader. The journal
3
+ // (/persistence/postgres) and the shard store (/cluster/postgres) run on the same pool (0017).
4
+ import { describe } from '../../checks.js';
5
+ import { fnv1a } from '../../hash.js';
6
+ // The first key of the schema's advisory lock: "TRUP". The second is the schema's hash, so each
7
+ // schema in a database has its own lock. Journal appends take it (decision 0016), and so does
8
+ // every setup(), so two backends setting up one schema at once don't race to create it.
9
+ export const LOCK_CLASS = 0x54525550;
10
+ /** Takes the advisory lock `($1, $2)` until the transaction ends. */
11
+ export const LOCK = 'SELECT pg_advisory_xact_lock($1, $2)';
12
+ /** Throws unless `pool` has the two methods a {@link PgPool} needs. */
13
+ export function checkPool(pool, where) {
14
+ const ok = typeof pool === 'object' &&
15
+ pool !== null &&
16
+ typeof pool.query === 'function' &&
17
+ typeof pool.connect === 'function';
18
+ if (!ok) {
19
+ throw new TypeError(`${where}: pool must have query() and connect(), like pg.Pool`);
20
+ }
21
+ }
22
+ /**
23
+ * Runs `work` in a read-committed transaction on one connection. Read committed, whatever the
24
+ * database's default, so each statement sees what committed before it, including while this
25
+ * one waited for a lock. A connection whose rollback fails is discarded, not reused.
26
+ */
27
+ export async function transaction(pool, work) {
28
+ const client = await pool.connect();
29
+ let result;
30
+ try {
31
+ await client.query('BEGIN ISOLATION LEVEL READ COMMITTED');
32
+ result = await work(client);
33
+ await client.query('COMMIT');
34
+ }
35
+ catch (error) {
36
+ const rolledBack = await client.query('ROLLBACK').then(() => true, () => false);
37
+ client.release(!rolledBack);
38
+ throw error;
39
+ }
40
+ client.release();
41
+ return result;
42
+ }
43
+ /**
44
+ * A 32-bit FNV-1a hash of `text`, as a signed integer for Postgres's `int4`. Computed here, not by
45
+ * Postgres's undocumented `hashtext`, so every process agrees on it, whatever the server version.
46
+ * A collision only makes two journals share a lock.
47
+ */
48
+ export function schemaHash(text) {
49
+ return fnv1a(text) | 0;
50
+ }
51
+ /**
52
+ * A `bigint` column as a JavaScript number. `pg` returns them as strings by default, and other
53
+ * pools may parse them as numbers or bigints. The journal only stores safe integers.
54
+ */
55
+ export function toInt(value) {
56
+ const n = typeof value === 'string' || typeof value === 'bigint'
57
+ ? Number(value)
58
+ : typeof value === 'number'
59
+ ? value
60
+ : NaN;
61
+ if (!Number.isSafeInteger(n)) {
62
+ throw new TypeError(`Postgres: expected an integer from the database, got ${describe(value)}`);
63
+ }
64
+ return n;
65
+ }
@@ -1,26 +1,5 @@
1
1
  import type { Persistence } from '../types.js';
2
- /**
3
- * Something that runs a parameterized query, as `pg`'s pool and clients do. Only `rows` is read.
4
- */
5
- export interface PgQueryable {
6
- /** Runs `text` with `$1`, `$2`, ... bound to `values`. */
7
- query(text: string, values?: unknown[]): Promise<{
8
- readonly rows: readonly unknown[];
9
- }>;
10
- }
11
- /** One connection checked out of a {@link PgPool}, as `pg`'s `PoolClient` is. */
12
- export interface PgPoolClient extends PgQueryable {
13
- /** Returns the connection to the pool, or with `true` or an error, discards it. */
14
- release(destroy?: boolean | Error): void;
15
- }
16
- /**
17
- * A pool of Postgres connections, typed by shape so this entry point never imports `pg`
18
- * (decision 0017). A `pg` `Pool` fits, and so does any pool with the same two methods.
19
- */
20
- export interface PgPool extends PgQueryable {
21
- /** Checks out one connection, for a transaction. */
22
- connect(): Promise<PgPoolClient>;
23
- }
2
+ import { type PgPool } from './pool.js';
24
3
  /** The Postgres backend's stores, which share the caller's pool. */
25
4
  export interface PostgresPersistence extends Required<Persistence> {
26
5
  /**
@@ -53,14 +32,3 @@ export declare function postgresPersistence(opts: {
53
32
  schema?: string;
54
33
  clock?: () => number;
55
34
  }): PostgresPersistence;
56
- /**
57
- * A 32-bit FNV-1a hash of `text`, as a signed integer for Postgres's `int4`. Computed here, not by
58
- * Postgres's undocumented `hashtext`, so every process agrees on it, whatever the server version.
59
- * A collision only makes two journals share a lock.
60
- */
61
- export declare function schemaHash(text: string): number;
62
- /**
63
- * A `bigint` column as a JavaScript number. `pg` returns them as strings by default, and other
64
- * pools may parse them as numbers or bigints. The journal only stores safe integers.
65
- */
66
- export declare function toInt(value: unknown): number;
@@ -1,11 +1,9 @@
1
1
  import { checkKeys, describe } from '../../checks.js';
2
2
  import { checkAppend, checkId, checkOffsetSave, checkRead, checkReadByTag, serializeSnapshot, wallClock, } from '../backend.js';
3
3
  import { JournalConflictError } from '../errors.js';
4
+ import { checkPool, LOCK, LOCK_CLASS, schemaHash, toInt, transaction, } from './pool.js';
4
5
  import { DEFAULT_SCHEMA, isSchemaName, postgresSchemaStatements } from './schema.js';
5
6
  const OPTIONS = new Set(['pool', 'schema', 'clock']);
6
- // The first key of the journal's advisory lock: "TRUP". The second is the schema's hash, so each
7
- // journal in a database has its own lock.
8
- const LOCK_CLASS = 0x54525550;
9
7
  // Postgres's SQLSTATE for a unique violation.
10
8
  const UNIQUE_VIOLATION = '23505';
11
9
  /**
@@ -31,7 +29,7 @@ export function postgresPersistence(opts) {
31
29
  // The default wall clock for timestamps, which never order anything (decision 0015).
32
30
  // eslint-disable-next-line no-restricted-properties
33
31
  const { pool, schema = DEFAULT_SCHEMA, clock = Date.now } = opts;
34
- checkPool(pool);
32
+ checkPool(pool, 'postgresPersistence');
35
33
  if (!isSchemaName(schema)) {
36
34
  throw new TypeError('postgresPersistence: schema must be lower-case letters, digits and _, starting with a ' +
37
35
  `letter or _, at most 63, got ${describe(schema)}`);
@@ -41,7 +39,6 @@ export function postgresPersistence(opts) {
41
39
  const lockKey = schemaHash(schema);
42
40
  const COLUMNS = 'e.persistence_id, e.seq, e.global_offset, e.timestamp, e.version, ' +
43
41
  'e.tags::text AS tags, e.event::text AS event';
44
- const LOCK = 'SELECT pg_advisory_xact_lock($1, $2)';
45
42
  const LAST_SEQ = `SELECT COALESCE(MAX(seq), 0) AS seq FROM ${s}.events WHERE persistence_id = $1`;
46
43
  // One statement for the whole batch, so the lock is held for as few round trips as possible.
47
44
  // ORDER BY n draws the batch's offsets in its order.
@@ -69,25 +66,6 @@ export function postgresPersistence(opts) {
69
66
  const LOAD_OFFSET = `SELECT global_offset FROM ${s}.offsets WHERE name = $1`;
70
67
  const SAVE_OFFSET = `INSERT INTO ${s}.offsets (name, global_offset) VALUES ($1, $2)
71
68
  ON CONFLICT (name) DO UPDATE SET global_offset = excluded.global_offset`;
72
- /**
73
- * Runs `work` in a read-committed transaction on one connection. Read committed, whatever the
74
- * database's default, so each statement sees what committed before it, including while this
75
- * one waited for the lock. A connection whose rollback fails is discarded, not reused.
76
- */
77
- async function transaction(work) {
78
- const client = await pool.connect();
79
- try {
80
- await client.query('BEGIN ISOLATION LEVEL READ COMMITTED');
81
- await work(client);
82
- await client.query('COMMIT');
83
- }
84
- catch (error) {
85
- const rolledBack = await client.query('ROLLBACK').then(() => true, () => false);
86
- client.release(!rolledBack);
87
- throw error;
88
- }
89
- client.release();
90
- }
91
69
  /** Runs one query on the pool, and returns its rows. */
92
70
  async function rows(text, values) {
93
71
  const result = await pool.query(text, values);
@@ -99,7 +77,7 @@ export function postgresPersistence(opts) {
99
77
  const batch = checkAppend(persistenceId, expectedSeq, events);
100
78
  const timestamp = batch.length === 0 ? 0 : now();
101
79
  try {
102
- await transaction(async (client) => {
80
+ await transaction(pool, async (client) => {
103
81
  await client.query(LOCK, [LOCK_CLASS, lockKey]);
104
82
  // The check runs under the lock, so no other writer can append between it and the
105
83
  // insert. This also rejects an expectedSeq ahead of the stream.
@@ -173,7 +151,7 @@ export function postgresPersistence(opts) {
173
151
  async setup() {
174
152
  // Under the journal's lock, so two processes starting at once don't race to create the
175
153
  // same table, which IF NOT EXISTS alone doesn't prevent.
176
- await transaction(async (client) => {
154
+ await transaction(pool, async (client) => {
177
155
  await client.query(LOCK, [LOCK_CLASS, lockKey]);
178
156
  for (const statement of postgresSchemaStatements(schema))
179
157
  await client.query(statement);
@@ -181,43 +159,6 @@ export function postgresPersistence(opts) {
181
159
  },
182
160
  };
183
161
  }
184
- function checkPool(pool) {
185
- const ok = typeof pool === 'object' &&
186
- pool !== null &&
187
- typeof pool.query === 'function' &&
188
- typeof pool.connect === 'function';
189
- if (!ok) {
190
- throw new TypeError('postgresPersistence: pool must have query() and connect(), like pg.Pool');
191
- }
192
- }
193
- /**
194
- * A 32-bit FNV-1a hash of `text`, as a signed integer for Postgres's `int4`. Computed here, not by
195
- * Postgres's undocumented `hashtext`, so every process agrees on it, whatever the server version.
196
- * A collision only makes two journals share a lock.
197
- */
198
- export function schemaHash(text) {
199
- let hash = 0x811c9dc5;
200
- for (let i = 0; i < text.length; i++) {
201
- hash ^= text.charCodeAt(i);
202
- hash = Math.imul(hash, 0x01000193);
203
- }
204
- return hash | 0;
205
- }
206
- /**
207
- * A `bigint` column as a JavaScript number. `pg` returns them as strings by default, and other
208
- * pools may parse them as numbers or bigints. The journal only stores safe integers.
209
- */
210
- export function toInt(value) {
211
- const n = typeof value === 'string' || typeof value === 'bigint'
212
- ? Number(value)
213
- : typeof value === 'number'
214
- ? value
215
- : NaN;
216
- if (!Number.isSafeInteger(n)) {
217
- throw new TypeError(`postgresPersistence: expected an integer from the database, got ${describe(value)}`);
218
- }
219
- return n;
220
- }
221
162
  function isUniqueViolation(error) {
222
163
  return (typeof error === 'object' &&
223
164
  error !== null &&
package/dist/system.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { type Watcher } from './cell.js';
1
+ import { type Watcher } from './internal.js';
2
2
  import type { ActorRef, ActorSystem, ActorSystemOptions, AnyRef } from './types.js';
3
3
  /** The parts of a system that the testkit needs and the public API hides. */
4
4
  export interface SystemHandle {
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,69 @@ 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;
66
72
  let terminating = false;
73
+ // Set once terminate() has stopped /user and every onTerminate task has settled: from then,
74
+ // actors under /system stop and take no more messages.
75
+ let systemStopping = false;
76
+ const terminateTasks = [];
77
+ let tasksRun = false;
67
78
  let resolveTerminated;
68
79
  const whenTerminated = new Promise((resolve) => {
69
80
  resolveTerminated = resolve;
70
81
  });
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)
82
+ // The parents of every top-level actor: the user's, and the system's own under /system, which
83
+ // the cluster uses (decision 0025). terminate() stops /user first, then /system, so a user
84
+ // actor's last messages can still go through the cluster.
85
+ const guardian = guardianAt(USER_PATH, () => {
86
+ if (terminating)
87
+ stopSystemActors();
88
+ });
89
+ const systemGuardian = guardianAt(SYSTEM_PATH, () => {
90
+ if (terminating)
91
+ checkTerminated();
92
+ });
93
+ // The last stopped event is published right after a removeChild returns, before anyone
94
+ // awaiting whenTerminated can run.
95
+ const checkTerminated = () => {
96
+ if (!systemStopping)
97
+ return;
98
+ if (guardian.childCells.size === 0 && systemGuardian.childCells.size === 0) {
99
+ resolveTerminated();
100
+ }
101
+ };
102
+ // Once /user is empty, the onTerminate tasks run, such as the cluster's graceful leave, which
103
+ // hands shards off while /system still works. Only then does /system stop.
104
+ const stopSystemActors = () => {
105
+ if (guardian.childCells.size > 0 || tasksRun)
106
+ return;
107
+ tasksRun = true;
108
+ const stopSystem = () => {
109
+ systemStopping = true;
110
+ if (systemGuardian.childCells.size === 0)
82
111
  resolveTerminated();
83
- },
112
+ for (const child of [...systemGuardian.childCells.values()])
113
+ child.requestStop();
114
+ };
115
+ if (terminateTasks.length === 0) {
116
+ stopSystem();
117
+ return;
118
+ }
119
+ const running = terminateTasks.map(async (task) => {
120
+ try {
121
+ await task();
122
+ }
123
+ catch (error) {
124
+ log.error('terminate: a termination task failed', { error });
125
+ }
126
+ });
127
+ void Promise.all(running).then(stopSystem);
84
128
  };
129
+ const isSystemPath = (path) => path === SYSTEM_PATH || path.startsWith(`${SYSTEM_PATH}/`);
85
130
  const host = {
86
131
  dispatcher,
87
132
  events,
@@ -95,10 +140,11 @@ export function createSystem(opts = {}) {
95
140
  trackBusy: (delta) => {
96
141
  busy += delta;
97
142
  },
98
- terminating: () => terminating,
99
- cellOf: (ref) => (typeof ref === 'object' && ref !== null ? cells.get(ref) : undefined),
143
+ terminating: (path) => terminating && (systemStopping || !isSystemPath(path)),
144
+ cellOf,
145
+ watchTargetOf,
100
146
  spawn(parent, def, childName, spawnOpts) {
101
- if (terminating) {
147
+ if (terminating && (systemStopping || !isSystemPath(parent.path))) {
102
148
  throw new ActorSystemTerminatedError(`system "${name}" is terminating, so it can't spawn`);
103
149
  }
104
150
  checkDef(def);
@@ -113,10 +159,27 @@ export function createSystem(opts = {}) {
113
159
  return cell.ref;
114
160
  },
115
161
  };
162
+ let clusterView;
163
+ const clusterListeners = new Set();
116
164
  const inspection = Object.freeze({
117
165
  scheduler,
118
166
  log,
119
- walk: () => walk(guardian.childCells, []),
167
+ walk: () => {
168
+ const out = walk(guardian.childCells, []);
169
+ const sharding = systemGuardian.childCells.get('sharding');
170
+ return sharding === undefined ? out : walk(sharding.childCells, out);
171
+ },
172
+ cluster: () => clusterView,
173
+ onClusterChange(listener) {
174
+ // A wrapper per call, so adding one listener twice gives two subscriptions.
175
+ const own = () => {
176
+ listener();
177
+ };
178
+ clusterListeners.add(own);
179
+ return () => {
180
+ clusterListeners.delete(own);
181
+ };
182
+ },
120
183
  });
121
184
  const system = {
122
185
  name,
@@ -139,14 +202,90 @@ export function createSystem(opts = {}) {
139
202
  // Pending asks fail now, so an actor awaiting one in an async receive can still stop.
140
203
  asker.terminate();
141
204
  if (guardian.childCells.size === 0)
142
- resolveTerminated();
205
+ stopSystemActors();
143
206
  for (const child of [...guardian.childCells.values()])
144
207
  child.requestStop();
145
208
  return whenTerminated;
146
209
  },
147
210
  };
148
- // Not enumerable, so spreading or logging a system doesn't show it.
211
+ const hooks = Object.freeze({
212
+ scheduler,
213
+ random,
214
+ log,
215
+ spawnSystem(def, childName, spawnOpts, parent) {
216
+ if (parent === undefined)
217
+ return host.spawn(systemGuardian, def, childName, spawnOpts);
218
+ const cell = cellOf(parent);
219
+ if (cell === undefined || cell.terminated || !cell.ref.path.startsWith(`${SYSTEM_PATH}/`)) {
220
+ throw new TypeError('spawnSystem: parent must be a live actor under /system');
221
+ }
222
+ return host.spawn(cell, def, childName, spawnOpts);
223
+ },
224
+ lookup(path) {
225
+ if (path.startsWith(`${TEMP_PATH}/`))
226
+ return asker.temp(path);
227
+ const root = path.startsWith(`${USER_PATH}/`)
228
+ ? guardian
229
+ : path.startsWith(`${SYSTEM_PATH}/`)
230
+ ? systemGuardian
231
+ : undefined;
232
+ return root === undefined ? undefined : find(root, path.slice(root.path.length + 1));
233
+ },
234
+ owns: (ref) => asker.owns(ref),
235
+ makeRef,
236
+ publish: (body) => {
237
+ events.publish(body);
238
+ },
239
+ deadLetter(recipient, message, reason) {
240
+ events.publish({ type: 'deadLetter', recipient, message, reason });
241
+ },
242
+ watchTarget: watchTargetOf,
243
+ setWatchResolver(resolve) {
244
+ if (resolveWatch !== undefined)
245
+ throw new Error('a watch resolver is already installed');
246
+ resolveWatch = resolve;
247
+ },
248
+ sender: () => host.senderOverride ?? dispatcher.current?.path,
249
+ stopWhenIdle(ref) {
250
+ const cell = cellOf(ref);
251
+ if (cell === undefined)
252
+ throw new TypeError('stopWhenIdle: the ref is not an actor of this system');
253
+ cell.stopWhenIdle();
254
+ },
255
+ onTerminate(task) {
256
+ if (tasksRun)
257
+ throw new Error('onTerminate: the system has already stopped /user');
258
+ terminateTasks.push(task);
259
+ },
260
+ setCluster(view) {
261
+ if (clusterView !== undefined)
262
+ throw new Error('a cluster view is already set');
263
+ clusterView = view;
264
+ return () => {
265
+ for (const listener of [...clusterListeners]) {
266
+ try {
267
+ listener();
268
+ }
269
+ catch (error) {
270
+ log.error('a cluster view listener threw; skipped it', { error });
271
+ }
272
+ }
273
+ };
274
+ },
275
+ tellFrom(ref, message, from) {
276
+ const outer = host.senderOverride;
277
+ host.senderOverride = from;
278
+ try {
279
+ ref.tell(message);
280
+ }
281
+ finally {
282
+ host.senderOverride = outer;
283
+ }
284
+ },
285
+ });
286
+ // Not enumerable, so spreading or logging a system doesn't show them.
149
287
  Object.defineProperty(system, INSPECT, { value: inspection });
288
+ Object.defineProperty(system, HOOKS, { value: hooks });
150
289
  Object.freeze(system);
151
290
  return {
152
291
  system,
@@ -154,16 +293,43 @@ export function createSystem(opts = {}) {
154
293
  pendingAsks: () => asker.pending(),
155
294
  makeRef,
156
295
  watch(ref, watcher) {
157
- const cell = host.cellOf(ref);
158
- if (cell === undefined)
296
+ const target = watchTargetOf(ref);
297
+ if (target === undefined) {
159
298
  throw new TypeError('watch: the ref is not an actor of this system');
160
- if (cell.terminated)
161
- watcher.notifyTerminated(cell);
299
+ }
300
+ if (target.terminated)
301
+ watcher.notifyTerminated(target);
162
302
  else
163
- cell.watchers.add(watcher);
303
+ target.addWatcher(watcher);
164
304
  },
165
305
  };
166
306
  }
307
+ /** A guardian: the parent of top-level actors at `path`. `onEmpty` runs when its last child goes. */
308
+ function guardianAt(path, onEmpty) {
309
+ return {
310
+ path,
311
+ names: new Names(),
312
+ childCells: new Map(),
313
+ removeChild(child) {
314
+ this.childCells.delete(child.name);
315
+ this.names.release(child.name);
316
+ if (this.childCells.size === 0)
317
+ onEmpty();
318
+ },
319
+ };
320
+ }
321
+ /** The ref of the cell at `relative`, a path such as `a/b` below `root`, if it hasn't terminated. */
322
+ function find(root, relative) {
323
+ let children = root.childCells;
324
+ let cell;
325
+ for (const name of relative.split('/')) {
326
+ cell = children.get(name);
327
+ if (cell === undefined)
328
+ return undefined;
329
+ children = cell.childCells;
330
+ }
331
+ return cell?.ref;
332
+ }
167
333
  /** Every cell under `cells`, depth first, each parent before its children in spawn order. */
168
334
  function walk(cells, out) {
169
335
  for (const cell of cells.values()) {