@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.
Files changed (97) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/LICENSE +21 -0
  3. package/README.md +380 -2
  4. package/dist/actor.d.ts +13 -0
  5. package/dist/actor.js +14 -0
  6. package/dist/ask.d.ts +39 -0
  7. package/dist/ask.js +135 -0
  8. package/dist/backstage/encode.d.ts +36 -0
  9. package/dist/backstage/encode.js +183 -0
  10. package/dist/backstage/index.d.ts +4 -0
  11. package/dist/backstage/index.js +4 -0
  12. package/dist/backstage/requests.d.ts +8 -0
  13. package/dist/backstage/requests.js +137 -0
  14. package/dist/backstage/source.d.ts +10 -0
  15. package/dist/backstage/source.js +143 -0
  16. package/dist/backstage/types.d.ts +135 -0
  17. package/dist/backstage/types.js +3 -0
  18. package/dist/backstage-ui/assets/index-Bg0MCiqs.css +1 -0
  19. package/dist/backstage-ui/assets/index-CeefBsDh.js +9 -0
  20. package/dist/backstage-ui/index.html +13 -0
  21. package/dist/cell.d.ts +129 -0
  22. package/dist/cell.js +763 -0
  23. package/dist/checks.d.ts +9 -0
  24. package/dist/checks.js +25 -0
  25. package/dist/dispatcher.d.ts +36 -0
  26. package/dist/dispatcher.js +65 -0
  27. package/dist/errors.d.ts +37 -0
  28. package/dist/errors.js +41 -0
  29. package/dist/events.d.ts +37 -0
  30. package/dist/events.js +88 -0
  31. package/dist/index.d.ts +7 -0
  32. package/dist/index.js +7 -0
  33. package/dist/internal.d.ts +81 -0
  34. package/dist/internal.js +36 -0
  35. package/dist/logger.d.ts +31 -0
  36. package/dist/logger.js +56 -0
  37. package/dist/names.d.ts +20 -0
  38. package/dist/names.js +50 -0
  39. package/dist/node/backstage/index.d.ts +1 -0
  40. package/dist/node/backstage/index.js +2 -0
  41. package/dist/node/backstage/server.d.ts +60 -0
  42. package/dist/node/backstage/server.js +342 -0
  43. package/dist/node/sqlite/index.d.ts +1 -0
  44. package/dist/node/sqlite/index.js +2 -0
  45. package/dist/node/sqlite/schema.d.ts +2 -0
  46. package/dist/node/sqlite/schema.js +36 -0
  47. package/dist/node/sqlite/schema.sql +32 -0
  48. package/dist/node/sqlite/sqlite.d.ts +24 -0
  49. package/dist/node/sqlite/sqlite.js +183 -0
  50. package/dist/persistence/actor.d.ts +158 -0
  51. package/dist/persistence/actor.js +454 -0
  52. package/dist/persistence/backend.d.ts +32 -0
  53. package/dist/persistence/backend.js +96 -0
  54. package/dist/persistence/errors.d.ts +60 -0
  55. package/dist/persistence/errors.js +82 -0
  56. package/dist/persistence/index.d.ts +6 -0
  57. package/dist/persistence/index.js +5 -0
  58. package/dist/persistence/json.d.ts +7 -0
  59. package/dist/persistence/json.js +75 -0
  60. package/dist/persistence/memory.d.ts +18 -0
  61. package/dist/persistence/memory.js +143 -0
  62. package/dist/persistence/postgres/index.d.ts +1 -0
  63. package/dist/persistence/postgres/index.js +3 -0
  64. package/dist/persistence/postgres/postgres.d.ts +66 -0
  65. package/dist/persistence/postgres/postgres.js +236 -0
  66. package/dist/persistence/postgres/schema.d.ts +12 -0
  67. package/dist/persistence/postgres/schema.js +57 -0
  68. package/dist/persistence/postgres/schema.sql +35 -0
  69. package/dist/persistence/projection.d.ts +48 -0
  70. package/dist/persistence/projection.js +102 -0
  71. package/dist/persistence/standard-schema.d.ts +63 -0
  72. package/dist/persistence/standard-schema.js +7 -0
  73. package/dist/persistence/types.d.ts +73 -0
  74. package/dist/persistence/types.js +3 -0
  75. package/dist/queue.d.ts +11 -0
  76. package/dist/queue.js +31 -0
  77. package/dist/scheduler.d.ts +24 -0
  78. package/dist/scheduler.js +23 -0
  79. package/dist/supervision.d.ts +91 -0
  80. package/dist/supervision.js +120 -0
  81. package/dist/system.d.ts +28 -0
  82. package/dist/system.js +216 -0
  83. package/dist/testkit/index.d.ts +4 -0
  84. package/dist/testkit/index.js +4 -0
  85. package/dist/testkit/kit.d.ts +63 -0
  86. package/dist/testkit/kit.js +93 -0
  87. package/dist/testkit/manual-scheduler.d.ts +58 -0
  88. package/dist/testkit/manual-scheduler.js +187 -0
  89. package/dist/testkit/probe.d.ts +50 -0
  90. package/dist/testkit/probe.js +124 -0
  91. package/dist/testkit/random.d.ts +11 -0
  92. package/dist/testkit/random.js +23 -0
  93. package/dist/timers.d.ts +37 -0
  94. package/dist/timers.js +110 -0
  95. package/dist/types.d.ts +364 -0
  96. package/dist/types.js +1 -0
  97. package/package.json +112 -4
@@ -0,0 +1,36 @@
1
+ /** A JSON value, as every Backstage frame and response is made of. */
2
+ export type WireValue = null | boolean | number | string | readonly WireValue[] | {
3
+ readonly [key: string]: WireValue;
4
+ };
5
+ /** How far `encode` goes before it cuts. Tuned against the demo's states in T3 (decision 0021). */
6
+ export declare const LIMITS: Readonly<{
7
+ /** Containers nested this deep are shown; one more is cut. */
8
+ depth: 8;
9
+ /** Items of one array, or keys of one object. */
10
+ items: 200;
11
+ /** Characters of one string. */
12
+ string: 2000;
13
+ /** Values in one call, so a wide and deep value can't take long however it's shaped. */
14
+ total: 10000;
15
+ }>;
16
+ /**
17
+ * Turns any value into a JSON value, for a wire or a UI (decision 0021). Never throws.
18
+ *
19
+ * - A JSON value is itself, except that object keys starting with `$` gain one more `$`, so the
20
+ * markers below can't be forged. Unescape a key by dropping its first `$`.
21
+ * - An actor ref, meaning anything with a string `path` and `tell` and `ask` functions, is
22
+ * `{ $ref: path }`.
23
+ * - An `Error` is `{ $error: { name, message } }`.
24
+ * - `undefined` is left out of objects and is `null` in arrays. On its own it's
25
+ * `{ $value: "undefined" }`.
26
+ * - A non-finite number, a `bigint`, a function, a symbol, a `Map`, a `Set`, a `Date` or any other
27
+ * class instance is `{ $value: "..." }`, a short description such as `"Map(3)"`.
28
+ * - A value already on the path from the root is `{ $cycle: true }`.
29
+ * - Past 8 levels of containers, a container is `{ $truncated: n }`, with `n` its items. An array
30
+ * past 200 items ends with `{ $truncated: n }`, and an object past 200 keys has a `$truncated: n`
31
+ * key, `n` being how many were left out. A string past 2,000 characters is
32
+ * `{ $string: "<the first 2,000>", $truncated: n }`. After 10,000 values in one call, the rest
33
+ * are cut the same way.
34
+ * - A value whose reading throws, such as a revoked proxy, is `{ $value: "unreadable" }`.
35
+ */
36
+ export declare function encode(value: unknown): WireValue;
@@ -0,0 +1,183 @@
1
+ // The wire encoding (decision 0021). Messages and states can hold anything, and a wire carries only
2
+ // JSON, so `encode` turns any value into a JSON value with markers for what JSON can't say. It runs
3
+ // on every event while Backstage is attached, so it walks once, allocates only its output, and
4
+ // never throws: an inspector must never break the system it watches.
5
+ /** How far `encode` goes before it cuts. Tuned against the demo's states in T3 (decision 0021). */
6
+ export const LIMITS = Object.freeze({
7
+ /** Containers nested this deep are shown; one more is cut. */
8
+ depth: 8,
9
+ /** Items of one array, or keys of one object. */
10
+ items: 200,
11
+ /** Characters of one string. */
12
+ string: 2000,
13
+ /** Values in one call, so a wide and deep value can't take long however it's shaped. */
14
+ total: 10_000,
15
+ });
16
+ /** What a value becomes when reading it throws. */
17
+ const UNREADABLE = Object.freeze({ $value: 'unreadable' });
18
+ /**
19
+ * Turns any value into a JSON value, for a wire or a UI (decision 0021). Never throws.
20
+ *
21
+ * - A JSON value is itself, except that object keys starting with `$` gain one more `$`, so the
22
+ * markers below can't be forged. Unescape a key by dropping its first `$`.
23
+ * - An actor ref, meaning anything with a string `path` and `tell` and `ask` functions, is
24
+ * `{ $ref: path }`.
25
+ * - An `Error` is `{ $error: { name, message } }`.
26
+ * - `undefined` is left out of objects and is `null` in arrays. On its own it's
27
+ * `{ $value: "undefined" }`.
28
+ * - A non-finite number, a `bigint`, a function, a symbol, a `Map`, a `Set`, a `Date` or any other
29
+ * class instance is `{ $value: "..." }`, a short description such as `"Map(3)"`.
30
+ * - A value already on the path from the root is `{ $cycle: true }`.
31
+ * - Past 8 levels of containers, a container is `{ $truncated: n }`, with `n` its items. An array
32
+ * past 200 items ends with `{ $truncated: n }`, and an object past 200 keys has a `$truncated: n`
33
+ * key, `n` being how many were left out. A string past 2,000 characters is
34
+ * `{ $string: "<the first 2,000>", $truncated: n }`. After 10,000 values in one call, the rest
35
+ * are cut the same way.
36
+ * - A value whose reading throws, such as a revoked proxy, is `{ $value: "unreadable" }`.
37
+ */
38
+ export function encode(value) {
39
+ const encoded = new Encoder().at(value, 0);
40
+ return encoded === undefined ? { $value: 'undefined' } : encoded;
41
+ }
42
+ /** One `encode` call: the containers on the current path, and what's left of the budget. */
43
+ class Encoder {
44
+ #path = new Set();
45
+ #left = LIMITS.total;
46
+ /** `value` encoded, or `undefined` for `undefined`, which a container leaves out or nulls. */
47
+ at(value, depth) {
48
+ this.#left -= 1;
49
+ switch (typeof value) {
50
+ case 'undefined':
51
+ return undefined;
52
+ case 'boolean':
53
+ return value;
54
+ case 'string':
55
+ return string(value);
56
+ case 'number':
57
+ if (Number.isFinite(value))
58
+ return value === 0 ? 0 : value; // -0 isn't JSON
59
+ return { $value: String(value) };
60
+ case 'bigint':
61
+ return { $value: `${String(value)}n` };
62
+ case 'symbol':
63
+ return { $value: clip(value.toString()) };
64
+ case 'function':
65
+ return { $value: functionName(value) };
66
+ case 'object':
67
+ if (value === null)
68
+ return null;
69
+ return this.#object(value, depth);
70
+ }
71
+ }
72
+ #object(value, depth) {
73
+ if (this.#path.has(value))
74
+ return { $cycle: true };
75
+ this.#path.add(value);
76
+ try {
77
+ return this.#container(value, depth);
78
+ }
79
+ catch {
80
+ // A throwing getter, a proxy trap or a revoked proxy. The rest of the value still encodes.
81
+ return UNREADABLE;
82
+ }
83
+ finally {
84
+ this.#path.delete(value);
85
+ }
86
+ }
87
+ #container(value, depth) {
88
+ const ref = refPath(value);
89
+ if (ref !== undefined)
90
+ return { $ref: clip(ref) };
91
+ if (value instanceof Error) {
92
+ // Either can be set to anything at runtime.
93
+ const { name, message } = value;
94
+ return { $error: { name: clip(String(name)), message: clip(String(message)) } };
95
+ }
96
+ if (Array.isArray(value))
97
+ return this.#array(value, depth);
98
+ const proto = Object.getPrototypeOf(value);
99
+ if (proto !== Object.prototype && proto !== null)
100
+ return { $value: describeInstance(value) };
101
+ return this.#plain(value, depth);
102
+ }
103
+ #array(items, depth) {
104
+ const length = items.length;
105
+ if (depth >= LIMITS.depth)
106
+ return { $truncated: length };
107
+ const out = [];
108
+ const shown = Math.min(length, LIMITS.items);
109
+ for (let i = 0; i < shown; i++) {
110
+ if (this.#left <= 0)
111
+ break;
112
+ out.push(this.at(items[i], depth + 1) ?? null);
113
+ }
114
+ if (out.length < length)
115
+ out.push({ $truncated: length - out.length });
116
+ return out;
117
+ }
118
+ #plain(record, depth) {
119
+ const keys = Object.keys(record);
120
+ if (depth >= LIMITS.depth)
121
+ return { $truncated: keys.length };
122
+ const out = {};
123
+ const shown = Math.min(keys.length, LIMITS.items);
124
+ let seen = 0;
125
+ for (; seen < shown; seen++) {
126
+ if (this.#left <= 0)
127
+ break;
128
+ const key = keys[seen]; // seen < keys.length
129
+ const encoded = this.at(record[key], depth + 1);
130
+ if (encoded !== undefined)
131
+ define(out, key.startsWith('$') ? `$${key}` : key, encoded);
132
+ }
133
+ if (seen < keys.length)
134
+ define(out, '$truncated', keys.length - seen);
135
+ return out;
136
+ }
137
+ }
138
+ /** Sets an own property, so a `__proto__` key is data, as `JSON.parse` makes it. */
139
+ function define(out, key, value) {
140
+ Object.defineProperty(out, key, { value, enumerable: true, writable: true, configurable: true });
141
+ }
142
+ function string(value) {
143
+ if (value.length <= LIMITS.string)
144
+ return value;
145
+ return { $string: value.slice(0, LIMITS.string), $truncated: value.length - LIMITS.string };
146
+ }
147
+ /** Short text for a description, which is never itself cut with a marker. */
148
+ function clip(text) {
149
+ return text.length <= LIMITS.string ? text : `${text.slice(0, LIMITS.string)}…`;
150
+ }
151
+ /**
152
+ * The path of an actor ref, by shape rather than by brand, so a remote ref that implements
153
+ * `ActorRef` in milestone 4 encodes the same way.
154
+ */
155
+ function refPath(value) {
156
+ const { path, tell, ask } = value;
157
+ if (typeof path === 'string' && typeof tell === 'function' && typeof ask === 'function') {
158
+ return path;
159
+ }
160
+ return undefined;
161
+ }
162
+ function functionName(fn) {
163
+ let name;
164
+ try {
165
+ name = fn.name;
166
+ }
167
+ catch {
168
+ name = '';
169
+ }
170
+ return typeof name === 'string' && name !== '' ? clip(`function ${name}`) : 'function';
171
+ }
172
+ function describeInstance(value) {
173
+ if (value instanceof Map)
174
+ return `Map(${String(value.size)})`;
175
+ if (value instanceof Set)
176
+ return `Set(${String(value.size)})`;
177
+ if (value instanceof Date) {
178
+ return Number.isNaN(value.getTime()) ? 'Date(invalid)' : `Date(${value.toISOString()})`;
179
+ }
180
+ const ctor = value.constructor;
181
+ const name = typeof ctor === 'function' ? ctor.name : '';
182
+ return name === '' ? 'object' : clip(name);
183
+ }
@@ -0,0 +1,4 @@
1
+ export { backstage } from './source.js';
2
+ export { encode } from './encode.js';
3
+ export type { WireValue } from './encode.js';
4
+ export type { ActorInfo, ActorStatus, BackstageError, BackstageOptions, BackstageRequest, BackstageResponse, BackstageSource, Frame, TimelineEvent, WireEvent, } from './types.js';
@@ -0,0 +1,4 @@
1
+ // The /backstage entry point: the inspector protocol, the wire encoding and the in-process source.
2
+ // It runs in any runtime (decision 0004). Backstage only watches (decision 0021).
3
+ export { backstage } from './source.js';
4
+ export { encode } from './encode.js';
@@ -0,0 +1,8 @@
1
+ import type { SystemInspection } from '../internal.js';
2
+ import type { BackstageResponse } from './types.js';
3
+ /** The most events one `timeline` response holds, and the page size for finding the end. */
4
+ export declare const MAX_TIMELINE = 256;
5
+ /** Answers `req` from `inspection`. Never rejects. */
6
+ export declare function answer(inspection: SystemInspection, req: unknown): Promise<BackstageResponse>;
7
+ /** An error response for `error`. */
8
+ export declare function failure(error: unknown): BackstageResponse;
@@ -0,0 +1,137 @@
1
+ // Answers Backstage's requests. Each reads either the live tree or the journal, never changes
2
+ // anything, and turns every failure into an error response (decision 0021). History comes from the
3
+ // journal, never from the live actor, so it reads the same for an entity on another node.
4
+ import { describe } from '../checks.js';
5
+ import { encode } from './encode.js';
6
+ /** The most events one `timeline` response holds, and the page size for finding the end. */
7
+ export const MAX_TIMELINE = 256;
8
+ /** A request that can't be answered, with the name its response carries. */
9
+ class RequestError extends Error {
10
+ constructor(name, message) {
11
+ super(message);
12
+ this.name = name;
13
+ }
14
+ }
15
+ const KEYS = {
16
+ state: ['type', 'path'],
17
+ timeline: ['type', 'path', 'fromSeq', 'limit'],
18
+ stateAt: ['type', 'path', 'seq'],
19
+ };
20
+ /** Answers `req` from `inspection`. Never rejects. */
21
+ export async function answer(inspection, req) {
22
+ try {
23
+ return await dispatch(inspection, req);
24
+ }
25
+ catch (error) {
26
+ return failure(error);
27
+ }
28
+ }
29
+ /** An error response for `error`. */
30
+ export function failure(error) {
31
+ if (error instanceof Error) {
32
+ // Either can be set to anything at runtime.
33
+ const { name, message } = error;
34
+ return { ok: false, error: { name: String(name), message: String(message) } };
35
+ }
36
+ return { ok: false, error: { name: 'Error', message: describe(error) } };
37
+ }
38
+ async function dispatch(inspection, req) {
39
+ const { type, path } = checkRequest(req);
40
+ switch (type) {
41
+ case 'state': {
42
+ return { ok: true, type, path, state: encode(cellAt(inspection, path).state) };
43
+ }
44
+ case 'timeline': {
45
+ const { fromSeq, limit } = req;
46
+ checkSeq(fromSeq, 'fromSeq', 1);
47
+ checkSeq(limit, 'limit', 1);
48
+ if (limit > MAX_TIMELINE) {
49
+ throw new RangeError(`timeline: limit must be at most ${String(MAX_TIMELINE)}, got ${String(limit)}`);
50
+ }
51
+ return timeline(path, persistentAt(inspection, path), fromSeq, limit);
52
+ }
53
+ case 'stateAt': {
54
+ const { seq } = req;
55
+ checkSeq(seq, 'seq', 0);
56
+ const state = await persistentAt(inspection, path).stateAt(seq);
57
+ return { ok: true, type, path, seq, state: encode(state) };
58
+ }
59
+ }
60
+ }
61
+ async function timeline(path, hook, fromSeq, limit) {
62
+ const { journal } = hook.persistence;
63
+ const id = hook.persistenceId;
64
+ const page = await journal.read(id, fromSeq, limit);
65
+ const last = page.at(-1);
66
+ let lastSeq;
67
+ if (last === undefined)
68
+ lastSeq = await lastSeqAfter(hook, 0);
69
+ else
70
+ lastSeq = page.length < limit ? last.seq : await lastSeqAfter(hook, last.seq);
71
+ // One past the end is an empty page, so an inspector can ask for what comes next.
72
+ if (fromSeq > lastSeq + 1) {
73
+ throw new RangeError(`timeline: fromSeq ${String(fromSeq)} is past ${id}'s last event, ${String(lastSeq)}`);
74
+ }
75
+ return { ok: true, type: 'timeline', path, persistenceId: id, events: page.map(toWire), lastSeq };
76
+ }
77
+ /** The stream's last sequence number, reading on from `after`, which is known to exist (or 0). */
78
+ async function lastSeqAfter(hook, after) {
79
+ let last = after;
80
+ for (;;) {
81
+ const page = await hook.persistence.journal.read(hook.persistenceId, last + 1, MAX_TIMELINE);
82
+ const end = page.at(-1);
83
+ if (end === undefined)
84
+ return last;
85
+ last = end.seq;
86
+ if (page.length < MAX_TIMELINE)
87
+ return last;
88
+ }
89
+ }
90
+ function toWire(e) {
91
+ return {
92
+ seq: e.seq,
93
+ offset: e.offset,
94
+ event: encode(e.event),
95
+ version: e.version,
96
+ tags: [...e.tags],
97
+ timestamp: e.timestamp,
98
+ };
99
+ }
100
+ function cellAt(inspection, path) {
101
+ const cell = inspection.walk().find((c) => c.path === path);
102
+ if (cell === undefined)
103
+ throw new RequestError('NotFoundError', `no live actor at ${path}`);
104
+ return cell;
105
+ }
106
+ function persistentAt(inspection, path) {
107
+ const hook = cellAt(inspection, path).persistent;
108
+ if (hook === undefined) {
109
+ throw new RequestError('NotPersistentError', `${path} is not a persistent actor`);
110
+ }
111
+ return hook;
112
+ }
113
+ function checkRequest(req) {
114
+ if (typeof req !== 'object' || req === null || Array.isArray(req)) {
115
+ throw new TypeError('a request must be an object');
116
+ }
117
+ const { type, path } = req;
118
+ const keys = typeof type === 'string' && Object.hasOwn(KEYS, type) ? KEYS[type] : undefined;
119
+ if (keys === undefined) {
120
+ throw new TypeError(`a request's type must be state, timeline or stateAt, got ${describe(type)}`);
121
+ }
122
+ for (const key of Object.keys(req)) {
123
+ if (!keys.includes(key))
124
+ throw new TypeError(`${String(type)}: unknown field "${key}"`);
125
+ }
126
+ if (typeof path !== 'string') {
127
+ throw new TypeError(`${String(type)}: path must be a string, got ${describe(path)}`);
128
+ }
129
+ return { type: type, path };
130
+ }
131
+ function checkSeq(value, what, min) {
132
+ if (typeof value !== 'number' || !Number.isSafeInteger(value)) {
133
+ throw new TypeError(`${what} must be an integer, got ${describe(value)}`);
134
+ }
135
+ if (value < min)
136
+ throw new RangeError(`${what} must be at least ${String(min)}, got ${String(value)}`);
137
+ }
@@ -0,0 +1,10 @@
1
+ import type { ActorSystem } from '../types.js';
2
+ import type { BackstageOptions, BackstageSource } from './types.js';
3
+ /**
4
+ * Attaches an inspector to a system. Runs in any runtime. It subscribes with `{ messages: true }`,
5
+ * so message events are on until {@link BackstageSource.close}. Backstage only watches: nothing it
6
+ * offers changes the system (decision 0021).
7
+ * @throws TypeError unless `system` was made by `createActorSystem`, and `opts.history` is a
8
+ * non-negative integer.
9
+ */
10
+ export declare function backstage(system: ActorSystem, opts?: BackstageOptions): BackstageSource;
@@ -0,0 +1,143 @@
1
+ // The in-process source: Backstage attached to a system in the same runtime. It subscribes with
2
+ // message events on, encodes each event once as it happens (a message may change afterwards), and
3
+ // keeps a ring of lifecycle events so a page opened after a crash still shows it (decision 0021).
4
+ import { checkInt, checkKeys } from '../checks.js';
5
+ import { inspectSystem } from '../internal.js';
6
+ import { encode } from './encode.js';
7
+ import { answer, failure } from './requests.js';
8
+ const OPTIONS = new Set(['history']);
9
+ const DEFAULT_HISTORY = 500;
10
+ /** The events a new connection's history keeps. Message events aren't: the UI keeps its own. */
11
+ const LIFECYCLE = new Set([
12
+ 'spawned',
13
+ 'stopped',
14
+ 'failed',
15
+ 'restarted',
16
+ 'persisted',
17
+ 'recovered',
18
+ 'deadLetter',
19
+ ]);
20
+ /**
21
+ * Attaches an inspector to a system. Runs in any runtime. It subscribes with `{ messages: true }`,
22
+ * so message events are on until {@link BackstageSource.close}. Backstage only watches: nothing it
23
+ * offers changes the system (decision 0021).
24
+ * @throws TypeError unless `system` was made by `createActorSystem`, and `opts.history` is a
25
+ * non-negative integer.
26
+ */
27
+ export function backstage(system, opts) {
28
+ const limit = checkOptions(opts);
29
+ const inspection = inspectSystem(system);
30
+ const history = new Ring(limit);
31
+ // Copy on write, so a listener that disconnects during delivery doesn't skip its neighbour.
32
+ let listeners = [];
33
+ let closed = false;
34
+ const deliver = (frame, to) => {
35
+ for (const listener of to) {
36
+ try {
37
+ listener(frame);
38
+ }
39
+ catch (error) {
40
+ inspection.log.error('a Backstage connection threw; skipped it', { error });
41
+ }
42
+ }
43
+ };
44
+ const unsubscribe = system.events.subscribe((event) => {
45
+ const lifecycle = LIFECYCLE.has(event.type);
46
+ // Nobody connected and nothing to keep: skip the encoding.
47
+ if (!lifecycle && listeners.length === 0)
48
+ return;
49
+ const wire = encodeEvent(event);
50
+ if (lifecycle)
51
+ history.push(wire);
52
+ deliver({ type: 'event', event: wire }, listeners);
53
+ }, { messages: true });
54
+ return Object.freeze({
55
+ connect(listener) {
56
+ if (typeof listener !== 'function') {
57
+ throw new TypeError('backstage.connect: listener must be a function');
58
+ }
59
+ if (closed)
60
+ throw new Error('backstage.connect: the source is closed');
61
+ listeners = [...listeners, listener];
62
+ const hello = {
63
+ type: 'hello',
64
+ protocol: 1,
65
+ system: system.name,
66
+ now: inspection.scheduler.now(),
67
+ actors: inspection.walk().map(actorInfo),
68
+ history: history.items(),
69
+ };
70
+ deliver(hello, [listener]);
71
+ let connected = true;
72
+ return () => {
73
+ if (!connected)
74
+ return;
75
+ connected = false;
76
+ listeners = listeners.filter((l) => l !== listener);
77
+ };
78
+ },
79
+ request(req) {
80
+ if (closed) {
81
+ const error = new Error('the source is closed');
82
+ error.name = 'ClosedError';
83
+ return Promise.resolve(failure(error));
84
+ }
85
+ return answer(inspection, req);
86
+ },
87
+ close() {
88
+ if (closed)
89
+ return;
90
+ closed = true;
91
+ listeners = [];
92
+ unsubscribe();
93
+ },
94
+ });
95
+ }
96
+ function checkOptions(opts) {
97
+ if (opts === undefined)
98
+ return DEFAULT_HISTORY;
99
+ checkKeys(opts, OPTIONS, 'backstage');
100
+ const { history = DEFAULT_HISTORY } = opts;
101
+ checkInt(history, 'backstage: history', { min: 0 });
102
+ return history;
103
+ }
104
+ function actorInfo(cell) {
105
+ const { path, status, depth, persistent } = cell;
106
+ return persistent === undefined
107
+ ? { path, status, depth }
108
+ : { path, status, depth, persistenceId: persistent.persistenceId };
109
+ }
110
+ /**
111
+ * Encodes each field on its own, so a message gets the full depth limit. `undefined` fields are
112
+ * left out, as JSON would.
113
+ */
114
+ function encodeEvent(event) {
115
+ const out = {};
116
+ for (const [key, value] of Object.entries(event)) {
117
+ if (value !== undefined)
118
+ out[key] = encode(value);
119
+ }
120
+ return out;
121
+ }
122
+ /** The last `capacity` items pushed, oldest first. */
123
+ class Ring {
124
+ #items = [];
125
+ #capacity;
126
+ #start = 0;
127
+ constructor(capacity) {
128
+ this.#capacity = capacity;
129
+ }
130
+ push(item) {
131
+ if (this.#capacity === 0)
132
+ return;
133
+ if (this.#items.length < this.#capacity) {
134
+ this.#items.push(item);
135
+ return;
136
+ }
137
+ this.#items[this.#start] = item;
138
+ this.#start = (this.#start + 1) % this.#capacity;
139
+ }
140
+ items() {
141
+ return [...this.#items.slice(this.#start), ...this.#items.slice(0, this.#start)];
142
+ }
143
+ }
@@ -0,0 +1,135 @@
1
+ import type { SystemEvent } from '../types.js';
2
+ import type { WireValue } from './encode.js';
3
+ /** Options for {@link backstage}. */
4
+ export interface BackstageOptions {
5
+ /** How many lifecycle events to keep for a new connection's history. Default 500. */
6
+ history?: number;
7
+ }
8
+ /** An inspector's view of one system: a stream of frames, and requests that only read. */
9
+ export interface BackstageSource {
10
+ /**
11
+ * Calls `listener` with a `hello` frame at once, then an `event` frame for every event. Every
12
+ * connection gets the same frame objects, so don't change them. A listener that throws is
13
+ * logged to the system's logger and skipped.
14
+ * @returns A function that ends the connection.
15
+ * @throws TypeError unless `listener` is a function.
16
+ * @throws Error once the source is closed.
17
+ */
18
+ connect(listener: (frame: Frame) => void): () => void;
19
+ /**
20
+ * Answers one request. Read-only: nothing it does changes the system. Never rejects: a request
21
+ * that can't be answered gets an error response.
22
+ */
23
+ request(req: BackstageRequest): Promise<BackstageResponse>;
24
+ /** Unsubscribes from the system, which turns message events off unless something else wants them. Every connection ends. */
25
+ close(): void;
26
+ }
27
+ /** Where an actor is in its life. `starting` covers a persistent actor's recovery. */
28
+ export type ActorStatus = 'starting' | 'running' | 'restarting' | 'stopping';
29
+ /** One live actor, as a `hello` lists it. Its state is a `state` request away. */
30
+ export interface ActorInfo {
31
+ /** Its path, such as `/user/box-office/hamlet`. */
32
+ readonly path: string;
33
+ /** Where it is in its life. */
34
+ readonly status: ActorStatus;
35
+ /** How many messages wait in its mailbox. */
36
+ readonly depth: number;
37
+ /** Its persistence id, when it's a persistent actor, which `timeline` and `stateAt` need. */
38
+ readonly persistenceId?: string;
39
+ }
40
+ type Wire<E> = E extends unknown ? {
41
+ readonly [K in keyof E]: unknown extends E[K] ? WireValue : E[K];
42
+ } : never;
43
+ /** A {@link SystemEvent} with what it carries (messages, errors) encoded as {@link WireValue}s. */
44
+ export type WireEvent = Wire<SystemEvent>;
45
+ /** What a source sends a connection. */
46
+ export type Frame = {
47
+ readonly type: 'hello';
48
+ /** The protocol's version. */
49
+ readonly protocol: 1;
50
+ /** The system's name. */
51
+ readonly system: string;
52
+ /** The system scheduler's time when the frame was made. */
53
+ readonly now: number;
54
+ /** Every live actor under `/user`, each parent before its children. */
55
+ readonly actors: readonly ActorInfo[];
56
+ /** Lifecycle events since the source attached, oldest first, at most `history`. */
57
+ readonly history: readonly WireEvent[];
58
+ } | {
59
+ readonly type: 'event';
60
+ readonly event: WireEvent;
61
+ };
62
+ /** A question for a source. None of them changes anything. */
63
+ export type BackstageRequest =
64
+ /** An actor's current state. */
65
+ {
66
+ readonly type: 'state';
67
+ readonly path: string;
68
+ }
69
+ /** A persistent actor's stored events from `fromSeq`, at most `limit`, up to 256. */
70
+ | {
71
+ readonly type: 'timeline';
72
+ readonly path: string;
73
+ readonly fromSeq: number;
74
+ readonly limit: number;
75
+ }
76
+ /** A persistent actor's state after event `seq`, read from its journal. */
77
+ | {
78
+ readonly type: 'stateAt';
79
+ readonly path: string;
80
+ readonly seq: number;
81
+ };
82
+ /** One event of a persistent actor's journal, as a `timeline` response gives it. */
83
+ export interface TimelineEvent {
84
+ /** Its place in the stream: 1, 2, 3, ... */
85
+ readonly seq: number;
86
+ /** Its place in the whole journal. */
87
+ readonly offset: number;
88
+ /** The event as stored, before any upcasting, encoded. */
89
+ readonly event: WireValue;
90
+ /** Its schema version as stored. */
91
+ readonly version: number;
92
+ /** Its tags. */
93
+ readonly tags: readonly string[];
94
+ /** The backend's wall-clock ms when it was appended. For people, never for ordering. */
95
+ readonly timestamp: number;
96
+ }
97
+ /** Why a request got no answer. */
98
+ export interface BackstageError {
99
+ /**
100
+ * `TypeError` for a request that isn't one, `RangeError` for a number out of range or a `seq`
101
+ * past the end, `NotFoundError` for a path with no live actor, `NotPersistentError` for a
102
+ * `timeline` or `stateAt` of a plain actor, `ClosedError` once the source is closed. Otherwise
103
+ * the name of what the journal rejected with.
104
+ */
105
+ readonly name: string;
106
+ /** What went wrong, for people. */
107
+ readonly message: string;
108
+ }
109
+ /** A source's answer to a {@link BackstageRequest}. */
110
+ export type BackstageResponse = {
111
+ readonly ok: true;
112
+ readonly type: 'state';
113
+ readonly path: string;
114
+ /** The state, encoded. A persistent actor's is its `{ seq, state }`. */
115
+ readonly state: WireValue;
116
+ } | {
117
+ readonly ok: true;
118
+ readonly type: 'timeline';
119
+ readonly path: string;
120
+ readonly persistenceId: string;
121
+ readonly events: readonly TimelineEvent[];
122
+ /** The stream's last sequence number when it was read, 0 for an empty one. */
123
+ readonly lastSeq: number;
124
+ } | {
125
+ readonly ok: true;
126
+ readonly type: 'stateAt';
127
+ readonly path: string;
128
+ readonly seq: number;
129
+ /** The state after event `seq`, encoded. */
130
+ readonly state: WireValue;
131
+ } | {
132
+ readonly ok: false;
133
+ readonly error: BackstageError;
134
+ };
135
+ export {};
@@ -0,0 +1,3 @@
1
+ // The Backstage protocol (decision 0021): JSON frames from a source to an inspector, and read-only
2
+ // requests back. Refs travel as paths, so milestone 4 can send all of it from another node.
3
+ export {};