@kylewillett/troupe 0.0.0-stage → 0.1.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.
- package/CHANGELOG.md +36 -0
- package/LICENSE +21 -0
- package/README.md +376 -2
- package/dist/actor.d.ts +13 -0
- package/dist/actor.js +14 -0
- package/dist/ask.d.ts +39 -0
- package/dist/ask.js +135 -0
- package/dist/backstage/encode.d.ts +36 -0
- package/dist/backstage/encode.js +183 -0
- package/dist/backstage/index.d.ts +4 -0
- package/dist/backstage/index.js +4 -0
- package/dist/backstage/requests.d.ts +8 -0
- package/dist/backstage/requests.js +137 -0
- package/dist/backstage/source.d.ts +10 -0
- package/dist/backstage/source.js +143 -0
- package/dist/backstage/types.d.ts +135 -0
- package/dist/backstage/types.js +3 -0
- package/dist/backstage-ui/assets/index-Bg0MCiqs.css +1 -0
- package/dist/backstage-ui/assets/index-CeefBsDh.js +9 -0
- package/dist/backstage-ui/index.html +13 -0
- package/dist/cell.d.ts +129 -0
- package/dist/cell.js +763 -0
- package/dist/checks.d.ts +9 -0
- package/dist/checks.js +25 -0
- package/dist/dispatcher.d.ts +36 -0
- package/dist/dispatcher.js +65 -0
- package/dist/errors.d.ts +37 -0
- package/dist/errors.js +41 -0
- package/dist/events.d.ts +37 -0
- package/dist/events.js +88 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +7 -0
- package/dist/internal.d.ts +81 -0
- package/dist/internal.js +36 -0
- package/dist/logger.d.ts +31 -0
- package/dist/logger.js +56 -0
- package/dist/names.d.ts +20 -0
- package/dist/names.js +50 -0
- package/dist/node/backstage/index.d.ts +1 -0
- package/dist/node/backstage/index.js +2 -0
- package/dist/node/backstage/server.d.ts +60 -0
- package/dist/node/backstage/server.js +342 -0
- package/dist/node/sqlite/index.d.ts +1 -0
- package/dist/node/sqlite/index.js +2 -0
- package/dist/node/sqlite/schema.d.ts +2 -0
- package/dist/node/sqlite/schema.js +36 -0
- package/dist/node/sqlite/schema.sql +32 -0
- package/dist/node/sqlite/sqlite.d.ts +24 -0
- package/dist/node/sqlite/sqlite.js +183 -0
- package/dist/persistence/actor.d.ts +158 -0
- package/dist/persistence/actor.js +454 -0
- package/dist/persistence/backend.d.ts +32 -0
- package/dist/persistence/backend.js +96 -0
- package/dist/persistence/errors.d.ts +60 -0
- package/dist/persistence/errors.js +82 -0
- package/dist/persistence/index.d.ts +6 -0
- package/dist/persistence/index.js +5 -0
- package/dist/persistence/json.d.ts +7 -0
- package/dist/persistence/json.js +75 -0
- package/dist/persistence/memory.d.ts +18 -0
- package/dist/persistence/memory.js +143 -0
- package/dist/persistence/postgres/index.d.ts +1 -0
- package/dist/persistence/postgres/index.js +3 -0
- package/dist/persistence/postgres/postgres.d.ts +66 -0
- package/dist/persistence/postgres/postgres.js +236 -0
- package/dist/persistence/postgres/schema.d.ts +12 -0
- package/dist/persistence/postgres/schema.js +57 -0
- package/dist/persistence/postgres/schema.sql +35 -0
- package/dist/persistence/projection.d.ts +48 -0
- package/dist/persistence/projection.js +102 -0
- package/dist/persistence/standard-schema.d.ts +63 -0
- package/dist/persistence/standard-schema.js +7 -0
- package/dist/persistence/types.d.ts +73 -0
- package/dist/persistence/types.js +3 -0
- package/dist/queue.d.ts +11 -0
- package/dist/queue.js +31 -0
- package/dist/scheduler.d.ts +24 -0
- package/dist/scheduler.js +23 -0
- package/dist/supervision.d.ts +91 -0
- package/dist/supervision.js +120 -0
- package/dist/system.d.ts +28 -0
- package/dist/system.js +216 -0
- package/dist/testkit/index.d.ts +4 -0
- package/dist/testkit/index.js +4 -0
- package/dist/testkit/kit.d.ts +63 -0
- package/dist/testkit/kit.js +93 -0
- package/dist/testkit/manual-scheduler.d.ts +58 -0
- package/dist/testkit/manual-scheduler.js +187 -0
- package/dist/testkit/probe.d.ts +50 -0
- package/dist/testkit/probe.js +124 -0
- package/dist/testkit/random.d.ts +11 -0
- package/dist/testkit/random.js +23 -0
- package/dist/timers.d.ts +37 -0
- package/dist/timers.js +110 -0
- package/dist/types.d.ts +364 -0
- package/dist/types.js +1 -0
- package/package.json +110 -4
package/dist/checks.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/** Throws unless `opts` is a plain object whose keys are all in `allowed`. */
|
|
2
|
+
export declare function checkKeys(opts: unknown, allowed: ReadonlySet<string>, where: string): void;
|
|
3
|
+
/** Throws unless `value` is a safe integer of at least `min` (1 by default), or `Infinity` when allowed. */
|
|
4
|
+
export declare function checkInt(value: unknown, what: string, { min, infinite }?: {
|
|
5
|
+
min?: number;
|
|
6
|
+
infinite?: boolean;
|
|
7
|
+
}): void;
|
|
8
|
+
/** Renders a bad value for an error message. */
|
|
9
|
+
export declare function describe(value: unknown): string;
|
package/dist/checks.js
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
// Option checks shared by createActorSystem, spawn and supervise. Each throws TypeError, so a bad
|
|
2
|
+
// option fails where it's passed in, never later.
|
|
3
|
+
/** Throws unless `opts` is a plain object whose keys are all in `allowed`. */
|
|
4
|
+
export function checkKeys(opts, allowed, where) {
|
|
5
|
+
if (typeof opts !== 'object' || opts === null || Array.isArray(opts)) {
|
|
6
|
+
throw new TypeError(`${where}: options must be an object`);
|
|
7
|
+
}
|
|
8
|
+
for (const key of Object.keys(opts)) {
|
|
9
|
+
if (!allowed.has(key))
|
|
10
|
+
throw new TypeError(`${where}: unknown option "${key}"`);
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
/** Throws unless `value` is a safe integer of at least `min` (1 by default), or `Infinity` when allowed. */
|
|
14
|
+
export function checkInt(value, what, { min = 1, infinite = false } = {}) {
|
|
15
|
+
if (infinite && value === Infinity)
|
|
16
|
+
return;
|
|
17
|
+
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < min) {
|
|
18
|
+
const kind = min === 0 ? 'a non-negative integer' : 'a positive integer';
|
|
19
|
+
throw new TypeError(`${what} must be ${kind}${infinite ? ' or Infinity' : ''}, got ${describe(value)}`);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
/** Renders a bad value for an error message. */
|
|
23
|
+
export function describe(value) {
|
|
24
|
+
return typeof value === 'string' ? `"${value}"` : String(value);
|
|
25
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { Scheduler } from './scheduler.js';
|
|
2
|
+
/** Something the dispatcher can give a turn to: in practice, an actor's cell. */
|
|
3
|
+
export interface Runnable {
|
|
4
|
+
/** The actor's path, for the sender of what it sends during its turn (decision 0020). */
|
|
5
|
+
readonly path?: string;
|
|
6
|
+
/**
|
|
7
|
+
* Runs up to `max` steps synchronously.
|
|
8
|
+
* @returns How many steps ran.
|
|
9
|
+
*/
|
|
10
|
+
run(max: number): number;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Shares the one thread among every actor (decision 0007). It keeps a FIFO ready queue and gives
|
|
14
|
+
* each runnable up to `throughput` steps per turn. It wakes on a microtask (`runSoon`), and after
|
|
15
|
+
* `yieldAfter` steps in a row it yields with a zero-delay timer, a macrotask, so I/O and timers
|
|
16
|
+
* get a turn even while actors message each other without end.
|
|
17
|
+
*
|
|
18
|
+
* Runnables decide when they're ready, and must not schedule themselves twice: the dispatcher
|
|
19
|
+
* trusts them.
|
|
20
|
+
*/
|
|
21
|
+
export declare class Dispatcher {
|
|
22
|
+
#private;
|
|
23
|
+
/**
|
|
24
|
+
* The runnable whose turn this is, while one is running and `trackCurrent` is on. A cell's turn
|
|
25
|
+
* is the only code that runs inside a drain, so whatever it sends, it sent (decision 0020).
|
|
26
|
+
*/
|
|
27
|
+
current: Runnable | undefined;
|
|
28
|
+
/**
|
|
29
|
+
* Whether to keep `current`. Only message events need it, and storing a pointer every turn
|
|
30
|
+
* costs a GC write barrier, so the system turns this on only while someone wants them.
|
|
31
|
+
*/
|
|
32
|
+
trackCurrent: boolean;
|
|
33
|
+
constructor(scheduler: Scheduler, throughput: number, yieldAfter: number);
|
|
34
|
+
/** Puts `runnable` at the back of the ready queue, and wakes the dispatcher if it's idle. */
|
|
35
|
+
schedule(runnable: Runnable): void;
|
|
36
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { Queue } from './queue.js';
|
|
2
|
+
/**
|
|
3
|
+
* Shares the one thread among every actor (decision 0007). It keeps a FIFO ready queue and gives
|
|
4
|
+
* each runnable up to `throughput` steps per turn. It wakes on a microtask (`runSoon`), and after
|
|
5
|
+
* `yieldAfter` steps in a row it yields with a zero-delay timer, a macrotask, so I/O and timers
|
|
6
|
+
* get a turn even while actors message each other without end.
|
|
7
|
+
*
|
|
8
|
+
* Runnables decide when they're ready, and must not schedule themselves twice: the dispatcher
|
|
9
|
+
* trusts them.
|
|
10
|
+
*/
|
|
11
|
+
export class Dispatcher {
|
|
12
|
+
#scheduler;
|
|
13
|
+
#throughput;
|
|
14
|
+
#yieldAfter;
|
|
15
|
+
#ready = new Queue();
|
|
16
|
+
#running = false;
|
|
17
|
+
#wakePending = false;
|
|
18
|
+
/**
|
|
19
|
+
* The runnable whose turn this is, while one is running and `trackCurrent` is on. A cell's turn
|
|
20
|
+
* is the only code that runs inside a drain, so whatever it sends, it sent (decision 0020).
|
|
21
|
+
*/
|
|
22
|
+
current;
|
|
23
|
+
/**
|
|
24
|
+
* Whether to keep `current`. Only message events need it, and storing a pointer every turn
|
|
25
|
+
* costs a GC write barrier, so the system turns this on only while someone wants them.
|
|
26
|
+
*/
|
|
27
|
+
trackCurrent = false;
|
|
28
|
+
constructor(scheduler, throughput, yieldAfter) {
|
|
29
|
+
this.#scheduler = scheduler;
|
|
30
|
+
this.#throughput = throughput;
|
|
31
|
+
this.#yieldAfter = yieldAfter;
|
|
32
|
+
}
|
|
33
|
+
/** Puts `runnable` at the back of the ready queue, and wakes the dispatcher if it's idle. */
|
|
34
|
+
schedule(runnable) {
|
|
35
|
+
this.#ready.push(runnable);
|
|
36
|
+
if (this.#running || this.#wakePending)
|
|
37
|
+
return;
|
|
38
|
+
this.#wakePending = true;
|
|
39
|
+
this.#scheduler.runSoon(this.#drain);
|
|
40
|
+
}
|
|
41
|
+
#drain = () => {
|
|
42
|
+
this.#wakePending = false;
|
|
43
|
+
this.#running = true;
|
|
44
|
+
let ran = 0;
|
|
45
|
+
try {
|
|
46
|
+
while (ran < this.#yieldAfter) {
|
|
47
|
+
const next = this.#ready.shift();
|
|
48
|
+
if (next === undefined)
|
|
49
|
+
break;
|
|
50
|
+
if (this.trackCurrent)
|
|
51
|
+
this.current = next;
|
|
52
|
+
ran += next.run(Math.min(this.#throughput, this.#yieldAfter - ran));
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
finally {
|
|
56
|
+
this.#running = false;
|
|
57
|
+
this.current = undefined;
|
|
58
|
+
}
|
|
59
|
+
if (this.#ready.size > 0) {
|
|
60
|
+
// Out of budget with work left: yield to the event loop, then carry on.
|
|
61
|
+
this.#wakePending = true;
|
|
62
|
+
this.#scheduler.setTimer(this.#drain, 0);
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
}
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Thrown by `spawn` for a name that's invalid, reserved (it starts with `$`), or already used by
|
|
3
|
+
* a sibling that hasn't terminated yet.
|
|
4
|
+
*/
|
|
5
|
+
export declare class ActorNameError extends Error {
|
|
6
|
+
/** Always `"ActorNameError"`, so the error can be recognized without `instanceof`. */
|
|
7
|
+
readonly name = "ActorNameError";
|
|
8
|
+
}
|
|
9
|
+
/** Thrown by `ctx.stop(ref)` and `system.stop(ref)` when `ref` is neither self nor a child. */
|
|
10
|
+
export declare class NotAChildError extends Error {
|
|
11
|
+
/** Always `"NotAChildError"`, so the error can be recognized without `instanceof`. */
|
|
12
|
+
readonly name = "NotAChildError";
|
|
13
|
+
}
|
|
14
|
+
/** Thrown by `ctx.spawn` once the actor is stopping or has stopped. */
|
|
15
|
+
export declare class ActorStoppedError extends Error {
|
|
16
|
+
/** Always `"ActorStoppedError"`, so the error can be recognized without `instanceof`. */
|
|
17
|
+
readonly name = "ActorStoppedError";
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Thrown by `spawn` once `system.terminate()` has been called. Also the reason every pending and
|
|
21
|
+
* later `ask` rejects.
|
|
22
|
+
*/
|
|
23
|
+
export declare class ActorSystemTerminatedError extends Error {
|
|
24
|
+
/** Always `"ActorSystemTerminatedError"`, so the error can be recognized without `instanceof`. */
|
|
25
|
+
readonly name = "ActorSystemTerminatedError";
|
|
26
|
+
}
|
|
27
|
+
/** The reason an `ask` rejects when no reply arrives within its timeout. */
|
|
28
|
+
export declare class AskTimeoutError extends Error {
|
|
29
|
+
/** Always `"AskTimeoutError"`, so the error can be recognized without `instanceof`. */
|
|
30
|
+
readonly name = "AskTimeoutError";
|
|
31
|
+
/** The path of the actor that was asked. */
|
|
32
|
+
readonly target: string;
|
|
33
|
+
/** How long the ask waited, in ms. */
|
|
34
|
+
readonly timeoutMs: number;
|
|
35
|
+
/** @internal `ask` creates these. */
|
|
36
|
+
constructor(target: string, timeoutMs: number);
|
|
37
|
+
}
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Thrown by `spawn` for a name that's invalid, reserved (it starts with `$`), or already used by
|
|
3
|
+
* a sibling that hasn't terminated yet.
|
|
4
|
+
*/
|
|
5
|
+
export class ActorNameError extends Error {
|
|
6
|
+
/** Always `"ActorNameError"`, so the error can be recognized without `instanceof`. */
|
|
7
|
+
name = 'ActorNameError';
|
|
8
|
+
}
|
|
9
|
+
/** Thrown by `ctx.stop(ref)` and `system.stop(ref)` when `ref` is neither self nor a child. */
|
|
10
|
+
export class NotAChildError extends Error {
|
|
11
|
+
/** Always `"NotAChildError"`, so the error can be recognized without `instanceof`. */
|
|
12
|
+
name = 'NotAChildError';
|
|
13
|
+
}
|
|
14
|
+
/** Thrown by `ctx.spawn` once the actor is stopping or has stopped. */
|
|
15
|
+
export class ActorStoppedError extends Error {
|
|
16
|
+
/** Always `"ActorStoppedError"`, so the error can be recognized without `instanceof`. */
|
|
17
|
+
name = 'ActorStoppedError';
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Thrown by `spawn` once `system.terminate()` has been called. Also the reason every pending and
|
|
21
|
+
* later `ask` rejects.
|
|
22
|
+
*/
|
|
23
|
+
export class ActorSystemTerminatedError extends Error {
|
|
24
|
+
/** Always `"ActorSystemTerminatedError"`, so the error can be recognized without `instanceof`. */
|
|
25
|
+
name = 'ActorSystemTerminatedError';
|
|
26
|
+
}
|
|
27
|
+
/** The reason an `ask` rejects when no reply arrives within its timeout. */
|
|
28
|
+
export class AskTimeoutError extends Error {
|
|
29
|
+
/** Always `"AskTimeoutError"`, so the error can be recognized without `instanceof`. */
|
|
30
|
+
name = 'AskTimeoutError';
|
|
31
|
+
/** The path of the actor that was asked. */
|
|
32
|
+
target;
|
|
33
|
+
/** How long the ask waited, in ms. */
|
|
34
|
+
timeoutMs;
|
|
35
|
+
/** @internal `ask` creates these. */
|
|
36
|
+
constructor(target, timeoutMs) {
|
|
37
|
+
super(`ask to ${target} got no reply within ${String(timeoutMs)} ms`);
|
|
38
|
+
this.target = target;
|
|
39
|
+
this.timeoutMs = timeoutMs;
|
|
40
|
+
}
|
|
41
|
+
}
|
package/dist/events.d.ts
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { Logger } from './logger.js';
|
|
2
|
+
import type { EventStream, SystemEvent } from './types.js';
|
|
3
|
+
type Untimed<E> = E extends unknown ? Omit<E, 'seq' | 'at'> : never;
|
|
4
|
+
/** An event before the bus stamps it with `seq` and `at`. */
|
|
5
|
+
export type EventBody = Untimed<SystemEvent>;
|
|
6
|
+
/** The bodies of message events, which go only to listeners that asked for them (decision 0020). */
|
|
7
|
+
export type MessageEventBody = Extract<EventBody, {
|
|
8
|
+
type: 'delivered' | 'processed';
|
|
9
|
+
}>;
|
|
10
|
+
type Listener = (event: SystemEvent) => void;
|
|
11
|
+
/**
|
|
12
|
+
* Delivers system events to listeners, synchronously and in order, so the order a listener sees
|
|
13
|
+
* is the order things happened (decision 0003).
|
|
14
|
+
*
|
|
15
|
+
* Message events go only to listeners that subscribed with `{ messages: true }`. Cells check
|
|
16
|
+
* {@link EventBus.messages} before building one, so while no listener wants them they cost one
|
|
17
|
+
* check per message (decision 0020). Every event takes the next `seq`, whoever receives it.
|
|
18
|
+
*/
|
|
19
|
+
export declare class EventBus implements EventStream {
|
|
20
|
+
#private;
|
|
21
|
+
/** @param onMessages Called whenever {@link EventBus.messages} changes. */
|
|
22
|
+
constructor(now: () => number, log: Logger, onMessages?: (on: boolean) => void);
|
|
23
|
+
/**
|
|
24
|
+
* True while at least one listener wants message events. A plain field rather than a getter,
|
|
25
|
+
* since every message reads it (decision 0020). Only the bus writes it.
|
|
26
|
+
*/
|
|
27
|
+
messages: boolean;
|
|
28
|
+
subscribe(listener: Listener, opts?: {
|
|
29
|
+
messages?: boolean;
|
|
30
|
+
}): () => void;
|
|
31
|
+
/** The id for the next message that gets a `delivered`. */
|
|
32
|
+
nextMessageId(): number;
|
|
33
|
+
publish(body: EventBody): void;
|
|
34
|
+
/** Publishes a message event to the listeners that asked for them. */
|
|
35
|
+
publishMessage(body: MessageEventBody): void;
|
|
36
|
+
}
|
|
37
|
+
export {};
|
package/dist/events.js
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { checkKeys, describe } from './checks.js';
|
|
2
|
+
const SUBSCRIBE_OPTIONS = new Set(['messages']);
|
|
3
|
+
/**
|
|
4
|
+
* Delivers system events to listeners, synchronously and in order, so the order a listener sees
|
|
5
|
+
* is the order things happened (decision 0003).
|
|
6
|
+
*
|
|
7
|
+
* Message events go only to listeners that subscribed with `{ messages: true }`. Cells check
|
|
8
|
+
* {@link EventBus.messages} before building one, so while no listener wants them they cost one
|
|
9
|
+
* check per message (decision 0020). Every event takes the next `seq`, whoever receives it.
|
|
10
|
+
*/
|
|
11
|
+
export class EventBus {
|
|
12
|
+
// Copy on write, so a listener that unsubscribes during delivery doesn't skip its neighbour.
|
|
13
|
+
#listeners = [];
|
|
14
|
+
#messageListeners = [];
|
|
15
|
+
#seq = 0;
|
|
16
|
+
#messageId = 0;
|
|
17
|
+
#now;
|
|
18
|
+
#log;
|
|
19
|
+
#onMessages;
|
|
20
|
+
/** @param onMessages Called whenever {@link EventBus.messages} changes. */
|
|
21
|
+
constructor(now, log, onMessages = () => { }) {
|
|
22
|
+
this.#now = now;
|
|
23
|
+
this.#log = log;
|
|
24
|
+
this.#onMessages = onMessages;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* True while at least one listener wants message events. A plain field rather than a getter,
|
|
28
|
+
* since every message reads it (decision 0020). Only the bus writes it.
|
|
29
|
+
*/
|
|
30
|
+
messages = false;
|
|
31
|
+
subscribe(listener, opts) {
|
|
32
|
+
if (typeof listener !== 'function') {
|
|
33
|
+
throw new TypeError('events.subscribe: listener must be a function');
|
|
34
|
+
}
|
|
35
|
+
const messages = checkSubscribeOptions(opts);
|
|
36
|
+
const entry = { listener };
|
|
37
|
+
this.#listeners = [...this.#listeners, entry];
|
|
38
|
+
if (messages) {
|
|
39
|
+
this.#messageListeners = [...this.#messageListeners, entry];
|
|
40
|
+
this.#setMessages(true);
|
|
41
|
+
}
|
|
42
|
+
return () => {
|
|
43
|
+
this.#listeners = this.#listeners.filter((l) => l !== entry);
|
|
44
|
+
if (messages) {
|
|
45
|
+
this.#messageListeners = this.#messageListeners.filter((l) => l !== entry);
|
|
46
|
+
this.#setMessages(this.#messageListeners.length > 0);
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
#setMessages(on) {
|
|
51
|
+
if (this.messages === on)
|
|
52
|
+
return;
|
|
53
|
+
this.messages = on;
|
|
54
|
+
this.#onMessages(on);
|
|
55
|
+
}
|
|
56
|
+
/** The id for the next message that gets a `delivered`. */
|
|
57
|
+
nextMessageId() {
|
|
58
|
+
return ++this.#messageId;
|
|
59
|
+
}
|
|
60
|
+
publish(body) {
|
|
61
|
+
this.#deliver(this.#listeners, body);
|
|
62
|
+
}
|
|
63
|
+
/** Publishes a message event to the listeners that asked for them. */
|
|
64
|
+
publishMessage(body) {
|
|
65
|
+
this.#deliver(this.#messageListeners, body);
|
|
66
|
+
}
|
|
67
|
+
#deliver(entries, body) {
|
|
68
|
+
const event = { ...body, seq: ++this.#seq, at: this.#now() };
|
|
69
|
+
for (const entry of entries) {
|
|
70
|
+
try {
|
|
71
|
+
entry.listener(event);
|
|
72
|
+
}
|
|
73
|
+
catch (error) {
|
|
74
|
+
this.#log.error('an event listener threw; skipped it', { error, event: event.type });
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
function checkSubscribeOptions(opts) {
|
|
80
|
+
if (opts === undefined)
|
|
81
|
+
return false;
|
|
82
|
+
checkKeys(opts, SUBSCRIBE_OPTIONS, 'events.subscribe');
|
|
83
|
+
const { messages } = opts;
|
|
84
|
+
if (messages !== undefined && typeof messages !== 'boolean') {
|
|
85
|
+
throw new TypeError(`events.subscribe: messages must be a boolean, got ${describe(messages)}`);
|
|
86
|
+
}
|
|
87
|
+
return messages === true;
|
|
88
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export { actor } from './actor.js';
|
|
2
|
+
export { ActorNameError, ActorStoppedError, ActorSystemTerminatedError, AskTimeoutError, NotAChildError, } from './errors.js';
|
|
3
|
+
export { consoleLogger, silentLogger, type Logger, type LogLevel } from './logger.js';
|
|
4
|
+
export { realScheduler, type Scheduler } from './scheduler.js';
|
|
5
|
+
export { supervise, type SupervisorStrategy } from './supervision.js';
|
|
6
|
+
export { createActorSystem } from './system.js';
|
|
7
|
+
export type { ActorContext, ActorDef, ActorRef, ActorSystem, ActorSystemOptions, AnyRef, AskOptions, EventStream, Result, Signal, SpawnOptions, SystemEvent, Timers, } from './types.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
// Public API. Export only from here and from testkit/index.ts.
|
|
2
|
+
export { actor } from './actor.js';
|
|
3
|
+
export { ActorNameError, ActorStoppedError, ActorSystemTerminatedError, AskTimeoutError, NotAChildError, } from './errors.js';
|
|
4
|
+
export { consoleLogger, silentLogger } from './logger.js';
|
|
5
|
+
export { realScheduler } from './scheduler.js';
|
|
6
|
+
export { supervise } from './supervision.js';
|
|
7
|
+
export { createActorSystem } from './system.js';
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import type { EventBody } from './events.js';
|
|
2
|
+
import type { Logger } from './logger.js';
|
|
3
|
+
import type { Persistence } from './persistence/types.js';
|
|
4
|
+
import type { Scheduler } from './scheduler.js';
|
|
5
|
+
import type { ActorContext, ActorSystem } from './types.js';
|
|
6
|
+
/**
|
|
7
|
+
* An optional async step on an `ActorDef`, run after `initial` and before any message. It gets the
|
|
8
|
+
* state `initial` made and returns the state to start with. The cell holds its mailbox until it
|
|
9
|
+
* settles, and a rejection is a failure in the actor's start, the same as a throw in `initial`.
|
|
10
|
+
*/
|
|
11
|
+
export declare const START: unique symbol;
|
|
12
|
+
/** What a cell offers its own `ctx`, beyond the public `ActorContext`. */
|
|
13
|
+
export declare const INTERNALS: unique symbol;
|
|
14
|
+
/** The start hook's shape. */
|
|
15
|
+
export type StartHook<M, S> = (state: S, ctx: ActorContext<M>) => Promise<S>;
|
|
16
|
+
/** An `ActorDef` that may carry a start hook. */
|
|
17
|
+
export interface WithStart<M, S> {
|
|
18
|
+
readonly [START]?: StartHook<M, S>;
|
|
19
|
+
}
|
|
20
|
+
/** What `ctx[INTERNALS]` holds. */
|
|
21
|
+
export interface CellInternals {
|
|
22
|
+
/** Publishes a system event, stamped by the system's bus. */
|
|
23
|
+
publish(body: EventBody): void;
|
|
24
|
+
/**
|
|
25
|
+
* Counts `promise` as busy work until it settles, without holding the mailbox, so the testkit's
|
|
26
|
+
* `settle` waits for it. The caller handles its rejection. Persistent actors' snapshot saves.
|
|
27
|
+
*/
|
|
28
|
+
track(promise: PromiseLike<unknown>): void;
|
|
29
|
+
/**
|
|
30
|
+
* Runs `fn` with this actor as the sender of every `tell` in it, for code that runs after an
|
|
31
|
+
* `await` on the actor's behalf: a persistent actor's effect steps (decision 0020).
|
|
32
|
+
*/
|
|
33
|
+
asSender<T>(fn: () => T): T;
|
|
34
|
+
}
|
|
35
|
+
/** The internals of a `ctx` the system made. */
|
|
36
|
+
export declare function internalsOf(ctx: object): CellInternals;
|
|
37
|
+
/** The inspection hook on a system the core made. */
|
|
38
|
+
export declare const INSPECT: unique symbol;
|
|
39
|
+
/** The inspection hook on a persistent actor's definition. */
|
|
40
|
+
export declare const PERSISTENT: unique symbol;
|
|
41
|
+
/**
|
|
42
|
+
* Where an actor is in its life. `starting` covers the time before `initial` has run, and a
|
|
43
|
+
* persistent actor's recovery.
|
|
44
|
+
*/
|
|
45
|
+
export type ActorStatus = 'starting' | 'running' | 'restarting' | 'stopping';
|
|
46
|
+
/** What the tree walk shows of one live actor. Read-only: nothing here changes the actor. */
|
|
47
|
+
export interface CellInspection {
|
|
48
|
+
readonly path: string;
|
|
49
|
+
readonly status: ActorStatus;
|
|
50
|
+
/** How many messages wait in its mailbox. */
|
|
51
|
+
readonly depth: number;
|
|
52
|
+
/** Its current state, the object itself. `undefined` before `initial` has returned. */
|
|
53
|
+
readonly state: unknown;
|
|
54
|
+
/** Its definition's persistent hook, when it's a persistent actor. */
|
|
55
|
+
readonly persistent: PersistentHook | undefined;
|
|
56
|
+
}
|
|
57
|
+
/** What `system[INSPECT]` holds. */
|
|
58
|
+
export interface SystemInspection {
|
|
59
|
+
/** The scheduler the system runs on. */
|
|
60
|
+
readonly scheduler: Scheduler;
|
|
61
|
+
/** The system's logger, wrapped so it never throws. For an inspector's own failures. */
|
|
62
|
+
readonly log: Logger;
|
|
63
|
+
/** Every live actor under `/user`, depth first, each parent before its children in spawn order. */
|
|
64
|
+
walk(): CellInspection[];
|
|
65
|
+
}
|
|
66
|
+
/** What a persistent actor's definition offers an inspector, without touching a live actor. */
|
|
67
|
+
export interface PersistentHook {
|
|
68
|
+
readonly persistenceId: string;
|
|
69
|
+
readonly persistence: Persistence;
|
|
70
|
+
/**
|
|
71
|
+
* The state after event `seq`, folded from the journal's events 1 to `seq` as recovery folds
|
|
72
|
+
* them, with no snapshot. `stateAt(0)` is the initial state.
|
|
73
|
+
* @throws TypeError, as a rejection, unless `seq` is a non-negative integer.
|
|
74
|
+
* @throws RangeError, as a rejection, when `seq` is past the journal's last event.
|
|
75
|
+
*/
|
|
76
|
+
stateAt(seq: number): Promise<unknown>;
|
|
77
|
+
}
|
|
78
|
+
/** The inspection hook of a system the core made. */
|
|
79
|
+
export declare function inspectSystem(system: ActorSystem): SystemInspection;
|
|
80
|
+
/** The persistent hook of a definition, if it's a persistent actor's. */
|
|
81
|
+
export declare function persistentHookOf(def: object): PersistentHook | undefined;
|
package/dist/internal.js
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
// Hooks between the core and the package's other entry points. None of this is public API: the
|
|
2
|
+
// symbols are exported only to the package's own modules, never from an entry point, so user
|
|
3
|
+
// actors can't reach them. Persistent actors use them to recover before any message (milestone 2),
|
|
4
|
+
// and Backstage uses them to read what the public API doesn't show (milestone 3).
|
|
5
|
+
/**
|
|
6
|
+
* An optional async step on an `ActorDef`, run after `initial` and before any message. It gets the
|
|
7
|
+
* state `initial` made and returns the state to start with. The cell holds its mailbox until it
|
|
8
|
+
* settles, and a rejection is a failure in the actor's start, the same as a throw in `initial`.
|
|
9
|
+
*/
|
|
10
|
+
export const START = Symbol('troupe.start');
|
|
11
|
+
/** What a cell offers its own `ctx`, beyond the public `ActorContext`. */
|
|
12
|
+
export const INTERNALS = Symbol('troupe.internals');
|
|
13
|
+
/** The internals of a `ctx` the system made. */
|
|
14
|
+
export function internalsOf(ctx) {
|
|
15
|
+
const internals = ctx[INTERNALS];
|
|
16
|
+
if (internals === undefined) {
|
|
17
|
+
throw new TypeError('this context was not made by an actor system');
|
|
18
|
+
}
|
|
19
|
+
return internals;
|
|
20
|
+
}
|
|
21
|
+
/** The inspection hook on a system the core made. */
|
|
22
|
+
export const INSPECT = Symbol('troupe.inspect');
|
|
23
|
+
/** The inspection hook on a persistent actor's definition. */
|
|
24
|
+
export const PERSISTENT = Symbol('troupe.persistent');
|
|
25
|
+
/** The inspection hook of a system the core made. */
|
|
26
|
+
export function inspectSystem(system) {
|
|
27
|
+
const inspection = system[INSPECT];
|
|
28
|
+
if (inspection === undefined) {
|
|
29
|
+
throw new TypeError('this system was not made by createActorSystem');
|
|
30
|
+
}
|
|
31
|
+
return inspection;
|
|
32
|
+
}
|
|
33
|
+
/** The persistent hook of a definition, if it's a persistent actor's. */
|
|
34
|
+
export function persistentHookOf(def) {
|
|
35
|
+
return def[PERSISTENT];
|
|
36
|
+
}
|
package/dist/logger.d.ts
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/** Log levels, from most to least verbose. */
|
|
2
|
+
export type LogLevel = 'debug' | 'info' | 'warn' | 'error';
|
|
3
|
+
/**
|
|
4
|
+
* Where the system and `ctx.log` write. Pass your own to `createActorSystem` to route Troupe's
|
|
5
|
+
* logs into your logging library. A logger that throws never affects an actor.
|
|
6
|
+
*/
|
|
7
|
+
export interface Logger {
|
|
8
|
+
/** Fine detail, for following what an actor does step by step. */
|
|
9
|
+
debug(msg: string, fields?: Record<string, unknown>): void;
|
|
10
|
+
/** Routine news worth keeping. */
|
|
11
|
+
info(msg: string, fields?: Record<string, unknown>): void;
|
|
12
|
+
/** Something unexpected that didn't fail anything. */
|
|
13
|
+
warn(msg: string, fields?: Record<string, unknown>): void;
|
|
14
|
+
/** A failure, such as an actor or an event listener that threw. */
|
|
15
|
+
error(msg: string, fields?: Record<string, unknown>): void;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* A logger that writes to `console`, at `level` and above.
|
|
19
|
+
* @param level The lowest level to write. Default `"warn"`.
|
|
20
|
+
* @throws TypeError for an unknown level.
|
|
21
|
+
*/
|
|
22
|
+
export declare function consoleLogger(level?: LogLevel): Logger;
|
|
23
|
+
/** A logger that discards everything. */
|
|
24
|
+
export declare const silentLogger: Logger;
|
|
25
|
+
/** True if `value` has the four logging methods. */
|
|
26
|
+
export declare function isLogger(value: unknown): value is Logger;
|
|
27
|
+
/**
|
|
28
|
+
* Wraps a caller's logger so it can never throw into the system, and optionally adds fields to
|
|
29
|
+
* every entry, as `ctx.log` adds `{ path }`.
|
|
30
|
+
*/
|
|
31
|
+
export declare function safeLogger(logger: Logger, extra?: Record<string, unknown>): Logger;
|
package/dist/logger.js
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
const LEVELS = ['debug', 'info', 'warn', 'error'];
|
|
2
|
+
/**
|
|
3
|
+
* A logger that writes to `console`, at `level` and above.
|
|
4
|
+
* @param level The lowest level to write. Default `"warn"`.
|
|
5
|
+
* @throws TypeError for an unknown level.
|
|
6
|
+
*/
|
|
7
|
+
export function consoleLogger(level = 'warn') {
|
|
8
|
+
const min = LEVELS.indexOf(level);
|
|
9
|
+
if (min === -1) {
|
|
10
|
+
// JSON.stringify, because at runtime a JavaScript caller can pass anything here.
|
|
11
|
+
throw new TypeError(`consoleLogger: level must be one of ${LEVELS.join(', ')}, got ${JSON.stringify(level)}`);
|
|
12
|
+
}
|
|
13
|
+
const at = (lvl) => (msg, fields) => {
|
|
14
|
+
if (LEVELS.indexOf(lvl) < min)
|
|
15
|
+
return;
|
|
16
|
+
if (fields === undefined)
|
|
17
|
+
console[lvl](`[troupe] ${msg}`);
|
|
18
|
+
else
|
|
19
|
+
console[lvl](`[troupe] ${msg}`, fields);
|
|
20
|
+
};
|
|
21
|
+
return { debug: at('debug'), info: at('info'), warn: at('warn'), error: at('error') };
|
|
22
|
+
}
|
|
23
|
+
const noop = () => { };
|
|
24
|
+
/** A logger that discards everything. */
|
|
25
|
+
export const silentLogger = Object.freeze({
|
|
26
|
+
debug: noop,
|
|
27
|
+
info: noop,
|
|
28
|
+
warn: noop,
|
|
29
|
+
error: noop,
|
|
30
|
+
});
|
|
31
|
+
/** True if `value` has the four logging methods. */
|
|
32
|
+
export function isLogger(value) {
|
|
33
|
+
if (typeof value !== 'object' || value === null)
|
|
34
|
+
return false;
|
|
35
|
+
const v = value;
|
|
36
|
+
return LEVELS.every((lvl) => typeof v[lvl] === 'function');
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Wraps a caller's logger so it can never throw into the system, and optionally adds fields to
|
|
40
|
+
* every entry, as `ctx.log` adds `{ path }`.
|
|
41
|
+
*/
|
|
42
|
+
export function safeLogger(logger, extra) {
|
|
43
|
+
const at = (lvl) => (msg, fields) => {
|
|
44
|
+
try {
|
|
45
|
+
const merged = extra === undefined ? fields : { ...extra, ...fields };
|
|
46
|
+
if (merged === undefined)
|
|
47
|
+
logger[lvl](msg);
|
|
48
|
+
else
|
|
49
|
+
logger[lvl](msg, merged);
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
// A broken logger must not break an actor, and there's nowhere left to report it.
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
return { debug: at('debug'), info: at('info'), warn: at('warn'), error: at('error') };
|
|
56
|
+
}
|
package/dist/names.d.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/** Whether `value` matches the actor name pattern. Persistence tags use it too. */
|
|
2
|
+
export declare function isValidName(value: unknown): value is string;
|
|
3
|
+
/**
|
|
4
|
+
* The names in use under one parent, and the counter for generated names (`$1`, `$2`, ...).
|
|
5
|
+
* Generated names start with `$`, which a caller can't pass in, so they never clash with chosen
|
|
6
|
+
* ones.
|
|
7
|
+
*/
|
|
8
|
+
export declare class Names {
|
|
9
|
+
#private;
|
|
10
|
+
/**
|
|
11
|
+
* Checks `name` and claims it, or generates one when it's `undefined`.
|
|
12
|
+
* @param parentPath For error messages.
|
|
13
|
+
* @throws ActorNameError for an invalid, reserved or taken name.
|
|
14
|
+
*/
|
|
15
|
+
claim(name: unknown, parentPath: string): string;
|
|
16
|
+
/** Frees `name` for reuse, once its actor has terminated. Generated names are never reused. */
|
|
17
|
+
release(name: string): void;
|
|
18
|
+
}
|
|
19
|
+
/** Joins a parent path and a child name. */
|
|
20
|
+
export declare function childPath(parentPath: string, name: string): string;
|
package/dist/names.js
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { ActorNameError } from './errors.js';
|
|
2
|
+
// URL-safe, so paths can go on the wire unescaped in milestone 4.
|
|
3
|
+
const NAME = /^[A-Za-z0-9][A-Za-z0-9._~-]{0,63}$/;
|
|
4
|
+
/** Whether `value` matches the actor name pattern. Persistence tags use it too. */
|
|
5
|
+
export function isValidName(value) {
|
|
6
|
+
return typeof value === 'string' && NAME.test(value);
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* The names in use under one parent, and the counter for generated names (`$1`, `$2`, ...).
|
|
10
|
+
* Generated names start with `$`, which a caller can't pass in, so they never clash with chosen
|
|
11
|
+
* ones.
|
|
12
|
+
*/
|
|
13
|
+
export class Names {
|
|
14
|
+
#taken = new Set();
|
|
15
|
+
#generated = 0;
|
|
16
|
+
/**
|
|
17
|
+
* Checks `name` and claims it, or generates one when it's `undefined`.
|
|
18
|
+
* @param parentPath For error messages.
|
|
19
|
+
* @throws ActorNameError for an invalid, reserved or taken name.
|
|
20
|
+
*/
|
|
21
|
+
claim(name, parentPath) {
|
|
22
|
+
if (name === undefined) {
|
|
23
|
+
const generated = `$${String(++this.#generated)}`;
|
|
24
|
+
this.#taken.add(generated);
|
|
25
|
+
return generated;
|
|
26
|
+
}
|
|
27
|
+
if (typeof name !== 'string') {
|
|
28
|
+
throw new ActorNameError(`actor name must be a string, got ${typeof name}`);
|
|
29
|
+
}
|
|
30
|
+
if (name.startsWith('$')) {
|
|
31
|
+
throw new ActorNameError(`actor name "${name}" is reserved: names starting with "$" are generated`);
|
|
32
|
+
}
|
|
33
|
+
if (!NAME.test(name)) {
|
|
34
|
+
throw new ActorNameError(`actor name "${name}" is invalid: use 1 to 64 letters, digits, ".", "_", "~" or "-", starting with a letter or digit`);
|
|
35
|
+
}
|
|
36
|
+
if (this.#taken.has(name)) {
|
|
37
|
+
throw new ActorNameError(`actor name "${name}" is already taken under ${parentPath}`);
|
|
38
|
+
}
|
|
39
|
+
this.#taken.add(name);
|
|
40
|
+
return name;
|
|
41
|
+
}
|
|
42
|
+
/** Frees `name` for reuse, once its actor has terminated. Generated names are never reused. */
|
|
43
|
+
release(name) {
|
|
44
|
+
this.#taken.delete(name);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
/** Joins a parent path and a child name. */
|
|
48
|
+
export function childPath(parentPath, name) {
|
|
49
|
+
return parentPath === '/' ? `/${name}` : `${parentPath}/${name}`;
|
|
50
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { serveBackstage, type BackstageServer, type BackstageServerOptions } from './server.js';
|