@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
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { checkInt, checkKeys, describe } from './checks.js';
|
|
2
|
+
const RESTART_OPTIONS = new Set(['maxRestarts', 'withinMs']);
|
|
3
|
+
const BACKOFF_OPTIONS = new Set(['minMs', 'maxMs', 'randomFactor', 'resetAfterMs']);
|
|
4
|
+
/** Builds supervisor strategies. Each one checks its options and throws `TypeError` for bad ones. */
|
|
5
|
+
export const supervise = Object.freeze({
|
|
6
|
+
/** Stop the actor, with `failure` set on `terminated` and on the `stopped` event. The default. */
|
|
7
|
+
stop() {
|
|
8
|
+
return Object.freeze({ type: 'stop' });
|
|
9
|
+
},
|
|
10
|
+
/** Keep the actor's state, drop the message that failed, and carry on with the next one. */
|
|
11
|
+
resume() {
|
|
12
|
+
return Object.freeze({ type: 'resume' });
|
|
13
|
+
},
|
|
14
|
+
/**
|
|
15
|
+
* Run `preRestart`, stop the children, and run `initial` again. The mailbox, the ref and the
|
|
16
|
+
* actor's watchers carry over.
|
|
17
|
+
* @param opts.maxRestarts The most restarts within `withinMs`. One more failure stops the
|
|
18
|
+
* actor. Default `Infinity`.
|
|
19
|
+
* @param opts.withinMs The rolling window that `maxRestarts` counts over, in ms. Default
|
|
20
|
+
* `Infinity`.
|
|
21
|
+
*/
|
|
22
|
+
restart(opts = {}) {
|
|
23
|
+
checkKeys(opts, RESTART_OPTIONS, 'supervise.restart');
|
|
24
|
+
const { maxRestarts = Infinity, withinMs = Infinity } = opts;
|
|
25
|
+
return checked({ type: 'restart', maxRestarts, withinMs }, 'supervise.restart');
|
|
26
|
+
},
|
|
27
|
+
/**
|
|
28
|
+
* Restart, as {@link supervise.restart} does, but wait first. Restart number `n`, counting from
|
|
29
|
+
* 0, waits `min(maxMs, minMs * 2^n) * (1 + random() * randomFactor)` ms, rounded. `n` goes back
|
|
30
|
+
* to 0 once the actor has run for `resetAfterMs` without failing.
|
|
31
|
+
* @param opts.randomFactor Jitter, so actors that failed together don't restart together.
|
|
32
|
+
* Default 0.2.
|
|
33
|
+
* @param opts.resetAfterMs Default `maxMs`.
|
|
34
|
+
*/
|
|
35
|
+
restartWithBackoff(opts) {
|
|
36
|
+
checkKeys(opts, BACKOFF_OPTIONS, 'supervise.restartWithBackoff');
|
|
37
|
+
const { minMs, maxMs, randomFactor = 0.2, resetAfterMs = maxMs } = opts;
|
|
38
|
+
return checked({ type: 'backoff', minMs, maxMs, randomFactor, resetAfterMs }, 'supervise.restartWithBackoff');
|
|
39
|
+
},
|
|
40
|
+
});
|
|
41
|
+
function checked(strategy, where) {
|
|
42
|
+
checkStrategy(strategy, where);
|
|
43
|
+
return Object.freeze(strategy);
|
|
44
|
+
}
|
|
45
|
+
/** Checks a strategy, including one built by hand rather than by {@link supervise}. */
|
|
46
|
+
export function checkStrategy(value, where) {
|
|
47
|
+
if (typeof value !== 'object' || value === null) {
|
|
48
|
+
throw new TypeError(`${where}: a supervisor strategy must be an object`);
|
|
49
|
+
}
|
|
50
|
+
const s = value;
|
|
51
|
+
switch (s.type) {
|
|
52
|
+
case 'stop':
|
|
53
|
+
case 'resume':
|
|
54
|
+
checkKeys(s, new Set(['type']), where);
|
|
55
|
+
return;
|
|
56
|
+
case 'restart':
|
|
57
|
+
checkKeys(s, new Set(['type', ...RESTART_OPTIONS]), where);
|
|
58
|
+
checkInt(s.maxRestarts, `${where}: maxRestarts`, { min: 0, infinite: true });
|
|
59
|
+
checkInt(s.withinMs, `${where}: withinMs`, { infinite: true });
|
|
60
|
+
return;
|
|
61
|
+
case 'backoff':
|
|
62
|
+
checkKeys(s, new Set(['type', ...BACKOFF_OPTIONS]), where);
|
|
63
|
+
checkInt(s.minMs, `${where}: minMs`);
|
|
64
|
+
checkInt(s.maxMs, `${where}: maxMs`);
|
|
65
|
+
if (s.maxMs < s.minMs) {
|
|
66
|
+
throw new TypeError(`${where}: maxMs must be at least minMs`);
|
|
67
|
+
}
|
|
68
|
+
if (typeof s.randomFactor !== 'number' ||
|
|
69
|
+
!(s.randomFactor >= 0 && s.randomFactor < Infinity)) {
|
|
70
|
+
throw new TypeError(`${where}: randomFactor must be a finite number of at least 0, got ${describe(s.randomFactor)}`);
|
|
71
|
+
}
|
|
72
|
+
checkInt(s.resetAfterMs, `${where}: resetAfterMs`);
|
|
73
|
+
return;
|
|
74
|
+
default:
|
|
75
|
+
throw new TypeError(`${where}: unknown supervisor strategy type ${describe(s.type)}`);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
/** A history with no failures in it. */
|
|
79
|
+
export const NO_FAILURES = Object.freeze({ times: [], count: 0, backoffs: 0 });
|
|
80
|
+
/**
|
|
81
|
+
* Decides what to do about a failure, and returns the history to keep for the next one. Pure,
|
|
82
|
+
* apart from drawing from `random`, and only for backoff. Limits and resets are worked out from
|
|
83
|
+
* failure times when a failure happens, so no timer is needed to track them.
|
|
84
|
+
*/
|
|
85
|
+
export function decide(strategy, history, facts) {
|
|
86
|
+
switch (strategy.type) {
|
|
87
|
+
case 'stop':
|
|
88
|
+
return { decision: { directive: 'stop' }, history };
|
|
89
|
+
case 'resume':
|
|
90
|
+
// With no state to keep, there's nothing to resume.
|
|
91
|
+
return { decision: { directive: facts.inInitial ? 'stop' : 'resume' }, history };
|
|
92
|
+
case 'restart': {
|
|
93
|
+
const { now } = facts;
|
|
94
|
+
let next;
|
|
95
|
+
let count;
|
|
96
|
+
if (strategy.withinMs === Infinity) {
|
|
97
|
+
count = history.count + 1;
|
|
98
|
+
next = { ...history, count };
|
|
99
|
+
}
|
|
100
|
+
else {
|
|
101
|
+
const times = [...history.times.filter((t) => now - t < strategy.withinMs), now];
|
|
102
|
+
count = times.length;
|
|
103
|
+
next = { ...history, times };
|
|
104
|
+
}
|
|
105
|
+
if (count > strategy.maxRestarts)
|
|
106
|
+
return { decision: { directive: 'stop' }, history: next };
|
|
107
|
+
return { decision: { directive: 'restart', attempt: count, delayMs: 0 }, history: next };
|
|
108
|
+
}
|
|
109
|
+
case 'backoff': {
|
|
110
|
+
const ranLongEnough = facts.now - facts.startedAt >= strategy.resetAfterMs;
|
|
111
|
+
const n = ranLongEnough ? 0 : history.backoffs;
|
|
112
|
+
const base = Math.min(strategy.maxMs, strategy.minMs * 2 ** n);
|
|
113
|
+
const delayMs = Math.round(base * (1 + facts.random() * strategy.randomFactor));
|
|
114
|
+
return {
|
|
115
|
+
decision: { directive: 'restart', attempt: n + 1, delayMs },
|
|
116
|
+
history: { ...history, backoffs: n + 1 },
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
}
|
package/dist/system.d.ts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { type Watcher } from './cell.js';
|
|
2
|
+
import type { ActorRef, ActorSystem, ActorSystemOptions, AnyRef } from './types.js';
|
|
3
|
+
/** The parts of a system that the testkit needs and the public API hides. */
|
|
4
|
+
export interface SystemHandle {
|
|
5
|
+
readonly system: ActorSystem;
|
|
6
|
+
/**
|
|
7
|
+
* How many async handlers and `pipeToSelf` promises are still waiting to settle. A piped ask
|
|
8
|
+
* isn't counted, because the scheduler completes it (decision 0010).
|
|
9
|
+
*/
|
|
10
|
+
busy(): number;
|
|
11
|
+
/** How many asks are waiting for a reply or their timeout. */
|
|
12
|
+
pendingAsks(): number;
|
|
13
|
+
/** Makes a ref whose `ask` works like any actor's, for probes. */
|
|
14
|
+
readonly makeRef: <M>(path: string, tell: (msg: M) => void) => ActorRef<M>;
|
|
15
|
+
/**
|
|
16
|
+
* Watches `ref` for a probe, as `ctx.watch` does for an actor: `watcher` is told once, when the
|
|
17
|
+
* actor terminates, or at once if it already has.
|
|
18
|
+
* @throws TypeError if `ref` isn't an actor of this system.
|
|
19
|
+
*/
|
|
20
|
+
watch(ref: AnyRef, watcher: Watcher): void;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Creates an actor system, the root of an actor hierarchy.
|
|
24
|
+
* @throws TypeError for options that can't be used, unknown fields included.
|
|
25
|
+
*/
|
|
26
|
+
export declare function createActorSystem(opts?: ActorSystemOptions): ActorSystem;
|
|
27
|
+
/** {@link createActorSystem}, plus the internals the testkit reads. Not exported publicly. */
|
|
28
|
+
export declare function createSystem(opts?: ActorSystemOptions): SystemHandle;
|
package/dist/system.js
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
import { Asker } from './ask.js';
|
|
2
|
+
import { Cell } from './cell.js';
|
|
3
|
+
import { checkInt, checkKeys, describe } from './checks.js';
|
|
4
|
+
import { Dispatcher } from './dispatcher.js';
|
|
5
|
+
import { ActorSystemTerminatedError, NotAChildError } from './errors.js';
|
|
6
|
+
import { EventBus } from './events.js';
|
|
7
|
+
import { INSPECT } from './internal.js';
|
|
8
|
+
import { consoleLogger, isLogger, safeLogger } from './logger.js';
|
|
9
|
+
import { childPath, Names } from './names.js';
|
|
10
|
+
import { realScheduler } from './scheduler.js';
|
|
11
|
+
import { checkStrategy, supervise } from './supervision.js';
|
|
12
|
+
const SYSTEM_OPTIONS = new Set([
|
|
13
|
+
'name',
|
|
14
|
+
'scheduler',
|
|
15
|
+
'random',
|
|
16
|
+
'logger',
|
|
17
|
+
'askTimeoutMs',
|
|
18
|
+
'throughput',
|
|
19
|
+
'yieldAfter',
|
|
20
|
+
]);
|
|
21
|
+
const SPAWN_OPTIONS = new Set(['mailbox', 'supervision']);
|
|
22
|
+
const STOP = supervise.stop();
|
|
23
|
+
const MAILBOX_OPTIONS = new Set(['capacity']);
|
|
24
|
+
const SYSTEM_NAME = /^[a-z0-9-]+$/;
|
|
25
|
+
const USER_PATH = '/user';
|
|
26
|
+
/**
|
|
27
|
+
* Creates an actor system, the root of an actor hierarchy.
|
|
28
|
+
* @throws TypeError for options that can't be used, unknown fields included.
|
|
29
|
+
*/
|
|
30
|
+
export function createActorSystem(opts) {
|
|
31
|
+
return createSystem(opts).system;
|
|
32
|
+
}
|
|
33
|
+
/** {@link createActorSystem}, plus the internals the testkit reads. Not exported publicly. */
|
|
34
|
+
export function createSystem(opts = {}) {
|
|
35
|
+
checkKeys(opts, SYSTEM_OPTIONS, 'createActorSystem');
|
|
36
|
+
const { name = 'troupe', scheduler = realScheduler(),
|
|
37
|
+
// The one place the core draws on real chance (decision 0003).
|
|
38
|
+
// eslint-disable-next-line no-restricted-properties
|
|
39
|
+
random = Math.random, logger = consoleLogger('warn'), askTimeoutMs = 5000, throughput = 10, yieldAfter = 1000, } = opts;
|
|
40
|
+
if (typeof name !== 'string' || !SYSTEM_NAME.test(name)) {
|
|
41
|
+
throw new TypeError(`createActorSystem: name must be lower-case letters, digits and "-", got ${describe(name)}`);
|
|
42
|
+
}
|
|
43
|
+
if (!isScheduler(scheduler)) {
|
|
44
|
+
throw new TypeError('createActorSystem: scheduler must have now, runSoon and setTimer methods');
|
|
45
|
+
}
|
|
46
|
+
if (typeof random !== 'function') {
|
|
47
|
+
throw new TypeError(`createActorSystem: random must be a function, got ${describe(random)}`);
|
|
48
|
+
}
|
|
49
|
+
if (!isLogger(logger)) {
|
|
50
|
+
throw new TypeError('createActorSystem: logger must have debug, info, warn and error methods');
|
|
51
|
+
}
|
|
52
|
+
checkInt(askTimeoutMs, 'createActorSystem: askTimeoutMs');
|
|
53
|
+
checkInt(throughput, 'createActorSystem: throughput');
|
|
54
|
+
checkInt(yieldAfter, 'createActorSystem: yieldAfter');
|
|
55
|
+
const log = safeLogger(logger);
|
|
56
|
+
const now = () => scheduler.now();
|
|
57
|
+
const dispatcher = new Dispatcher(scheduler, throughput, yieldAfter);
|
|
58
|
+
const events = new EventBus(now, log, (on) => {
|
|
59
|
+
dispatcher.trackCurrent = on;
|
|
60
|
+
});
|
|
61
|
+
const setTimer = (task, delayMs) => scheduler.setTimer(task, delayMs);
|
|
62
|
+
const asker = new Asker({ events, systemName: name, defaultTimeoutMs: askTimeoutMs, setTimer });
|
|
63
|
+
const makeRef = (path, tell) => asker.ref(path, tell);
|
|
64
|
+
const cells = new WeakMap();
|
|
65
|
+
let busy = 0;
|
|
66
|
+
let terminating = false;
|
|
67
|
+
let resolveTerminated;
|
|
68
|
+
const whenTerminated = new Promise((resolve) => {
|
|
69
|
+
resolveTerminated = resolve;
|
|
70
|
+
});
|
|
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
|
+
resolveTerminated();
|
|
83
|
+
},
|
|
84
|
+
};
|
|
85
|
+
const host = {
|
|
86
|
+
dispatcher,
|
|
87
|
+
events,
|
|
88
|
+
log,
|
|
89
|
+
senderOverride: undefined,
|
|
90
|
+
now,
|
|
91
|
+
random,
|
|
92
|
+
setTimer,
|
|
93
|
+
makeRef,
|
|
94
|
+
onAskSettled: (promise, listener) => asker.onSettled(promise, listener),
|
|
95
|
+
trackBusy: (delta) => {
|
|
96
|
+
busy += delta;
|
|
97
|
+
},
|
|
98
|
+
terminating: () => terminating,
|
|
99
|
+
cellOf: (ref) => (typeof ref === 'object' && ref !== null ? cells.get(ref) : undefined),
|
|
100
|
+
spawn(parent, def, childName, spawnOpts) {
|
|
101
|
+
if (terminating) {
|
|
102
|
+
throw new ActorSystemTerminatedError(`system "${name}" is terminating, so it can't spawn`);
|
|
103
|
+
}
|
|
104
|
+
checkDef(def);
|
|
105
|
+
const { capacity, supervision } = checkSpawnOptions(spawnOpts);
|
|
106
|
+
const claimed = parent.names.claim(childName, parent.path);
|
|
107
|
+
const path = childPath(parent.path, claimed);
|
|
108
|
+
const cell = new Cell(claimed, path, def, host, { capacity, supervision }, parent);
|
|
109
|
+
cells.set(cell.ref, cell);
|
|
110
|
+
parent.childCells.set(claimed, cell);
|
|
111
|
+
events.publish({ type: 'spawned', path });
|
|
112
|
+
cell.start();
|
|
113
|
+
return cell.ref;
|
|
114
|
+
},
|
|
115
|
+
};
|
|
116
|
+
const inspection = Object.freeze({
|
|
117
|
+
scheduler,
|
|
118
|
+
log,
|
|
119
|
+
walk: () => walk(guardian.childCells, []),
|
|
120
|
+
});
|
|
121
|
+
const system = {
|
|
122
|
+
name,
|
|
123
|
+
events,
|
|
124
|
+
whenTerminated,
|
|
125
|
+
spawn(def, childName, spawnOpts) {
|
|
126
|
+
return host.spawn(guardian, def, childName, spawnOpts);
|
|
127
|
+
},
|
|
128
|
+
stop(ref) {
|
|
129
|
+
const cell = host.cellOf(ref);
|
|
130
|
+
if (cell?.parent !== guardian) {
|
|
131
|
+
throw new NotAChildError(`${describeRef(ref)} is not a top-level actor of "${name}"`);
|
|
132
|
+
}
|
|
133
|
+
cell.requestStop();
|
|
134
|
+
},
|
|
135
|
+
terminate() {
|
|
136
|
+
if (terminating)
|
|
137
|
+
return whenTerminated;
|
|
138
|
+
terminating = true;
|
|
139
|
+
// Pending asks fail now, so an actor awaiting one in an async receive can still stop.
|
|
140
|
+
asker.terminate();
|
|
141
|
+
if (guardian.childCells.size === 0)
|
|
142
|
+
resolveTerminated();
|
|
143
|
+
for (const child of [...guardian.childCells.values()])
|
|
144
|
+
child.requestStop();
|
|
145
|
+
return whenTerminated;
|
|
146
|
+
},
|
|
147
|
+
};
|
|
148
|
+
// Not enumerable, so spreading or logging a system doesn't show it.
|
|
149
|
+
Object.defineProperty(system, INSPECT, { value: inspection });
|
|
150
|
+
Object.freeze(system);
|
|
151
|
+
return {
|
|
152
|
+
system,
|
|
153
|
+
busy: () => busy,
|
|
154
|
+
pendingAsks: () => asker.pending(),
|
|
155
|
+
makeRef,
|
|
156
|
+
watch(ref, watcher) {
|
|
157
|
+
const cell = host.cellOf(ref);
|
|
158
|
+
if (cell === undefined)
|
|
159
|
+
throw new TypeError('watch: the ref is not an actor of this system');
|
|
160
|
+
if (cell.terminated)
|
|
161
|
+
watcher.notifyTerminated(cell);
|
|
162
|
+
else
|
|
163
|
+
cell.watchers.add(watcher);
|
|
164
|
+
},
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
/** Every cell under `cells`, depth first, each parent before its children in spawn order. */
|
|
168
|
+
function walk(cells, out) {
|
|
169
|
+
for (const cell of cells.values()) {
|
|
170
|
+
out.push(cell.inspect());
|
|
171
|
+
walk(cell.childCells, out);
|
|
172
|
+
}
|
|
173
|
+
return out;
|
|
174
|
+
}
|
|
175
|
+
function checkDef(def) {
|
|
176
|
+
if (typeof def !== 'object' || def === null) {
|
|
177
|
+
throw new TypeError('spawn: the definition must be an object from actor()');
|
|
178
|
+
}
|
|
179
|
+
const d = def;
|
|
180
|
+
if (!('initial' in d))
|
|
181
|
+
throw new TypeError('spawn: the definition has no initial state');
|
|
182
|
+
if (typeof d.receive !== 'function')
|
|
183
|
+
throw new TypeError('spawn: receive must be a function');
|
|
184
|
+
if (d.onSignal !== undefined && typeof d.onSignal !== 'function') {
|
|
185
|
+
throw new TypeError('spawn: onSignal must be a function when it is set');
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
function describeRef(ref) {
|
|
189
|
+
const path = typeof ref === 'object' && ref !== null ? ref.path : ref;
|
|
190
|
+
return typeof path === 'string' ? path : 'that ref';
|
|
191
|
+
}
|
|
192
|
+
function checkSpawnOptions(opts) {
|
|
193
|
+
if (opts === undefined)
|
|
194
|
+
return { capacity: Infinity, supervision: STOP };
|
|
195
|
+
checkKeys(opts, SPAWN_OPTIONS, 'spawn');
|
|
196
|
+
const { mailbox, supervision = STOP } = opts;
|
|
197
|
+
checkStrategy(supervision, 'spawn: supervision');
|
|
198
|
+
return { capacity: checkCapacity(mailbox), supervision };
|
|
199
|
+
}
|
|
200
|
+
function checkCapacity(mailbox) {
|
|
201
|
+
if (mailbox === undefined)
|
|
202
|
+
return Infinity;
|
|
203
|
+
checkKeys(mailbox, MAILBOX_OPTIONS, 'spawn: mailbox');
|
|
204
|
+
if (mailbox.capacity === undefined)
|
|
205
|
+
return Infinity;
|
|
206
|
+
checkInt(mailbox.capacity, 'spawn: mailbox.capacity');
|
|
207
|
+
return mailbox.capacity;
|
|
208
|
+
}
|
|
209
|
+
function isScheduler(value) {
|
|
210
|
+
if (typeof value !== 'object' || value === null)
|
|
211
|
+
return false;
|
|
212
|
+
const v = value;
|
|
213
|
+
return (typeof v.now === 'function' &&
|
|
214
|
+
typeof v.runSoon === 'function' &&
|
|
215
|
+
typeof v.setTimer === 'function');
|
|
216
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { createTestKit, SettleTimeoutError, type LogEntry, type TestKit, type TestKitOptions, } from './kit.js';
|
|
2
|
+
export { ManualScheduler, type ManualSchedulerOptions } from './manual-scheduler.js';
|
|
3
|
+
export type { TestProbe } from './probe.js';
|
|
4
|
+
export { seededRandom } from './random.js';
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import type { LogLevel } from '../logger.js';
|
|
2
|
+
import type { ActorSystem, ActorSystemOptions, SystemEvent } from '../types.js';
|
|
3
|
+
import { ManualScheduler } from './manual-scheduler.js';
|
|
4
|
+
import { TestProbe } from './probe.js';
|
|
5
|
+
/** One entry the kit's logger recorded. */
|
|
6
|
+
export interface LogEntry {
|
|
7
|
+
/** The level it was logged at. */
|
|
8
|
+
readonly level: LogLevel;
|
|
9
|
+
/** The message. */
|
|
10
|
+
readonly msg: string;
|
|
11
|
+
/** The structured fields, when any were given. An actor's entries include its `path`. */
|
|
12
|
+
readonly fields?: Record<string, unknown>;
|
|
13
|
+
}
|
|
14
|
+
/** Options for {@link createTestKit}. */
|
|
15
|
+
export interface TestKitOptions {
|
|
16
|
+
/** The seed for the system's `random`, through {@link seededRandom}. Default 1. */
|
|
17
|
+
seed?: number;
|
|
18
|
+
/** The virtual time to start at, in ms. Default 0. */
|
|
19
|
+
startTime?: number;
|
|
20
|
+
/** Options for the system under test. The kit supplies the scheduler, random and logger. */
|
|
21
|
+
system?: Omit<ActorSystemOptions, 'scheduler' | 'random' | 'logger'>;
|
|
22
|
+
}
|
|
23
|
+
/** An actor system on virtual time, with probes and a record of everything it did. */
|
|
24
|
+
export interface TestKit {
|
|
25
|
+
/** The system under test. */
|
|
26
|
+
readonly system: ActorSystem;
|
|
27
|
+
/** Its scheduler. Prefer `settle` and `advance` to driving it directly. */
|
|
28
|
+
readonly scheduler: ManualScheduler;
|
|
29
|
+
/** Every event the system published, in order. */
|
|
30
|
+
readonly events: readonly SystemEvent[];
|
|
31
|
+
/** Everything the system and its actors logged, at every level. */
|
|
32
|
+
readonly logs: readonly LogEntry[];
|
|
33
|
+
/** Creates a probe at `/temp/probe-<name>`. Names are generated when omitted. */
|
|
34
|
+
probe<M>(name?: string): TestProbe<M>;
|
|
35
|
+
/**
|
|
36
|
+
* Runs everything that can happen without time passing: queued work, due timers and actors'
|
|
37
|
+
* messages, until nothing is left.
|
|
38
|
+
* @throws SettleTimeoutError if actors are still busy after 1,000 real event-loop ticks.
|
|
39
|
+
*/
|
|
40
|
+
settle(): Promise<void>;
|
|
41
|
+
/**
|
|
42
|
+
* Moves virtual time forward by `ms`. Timers fire in order of due time, then of creation, with
|
|
43
|
+
* the clock set to each one's due time, and the kit settles after each due time. Timers that
|
|
44
|
+
* are set along the way fire too, if they fall due within `ms`. Ends settled, with the clock
|
|
45
|
+
* `ms` later than it started.
|
|
46
|
+
* @throws TypeError if `ms` isn't a non-negative integer.
|
|
47
|
+
* @throws SettleTimeoutError as `settle` does.
|
|
48
|
+
*/
|
|
49
|
+
advance(ms: number): Promise<void>;
|
|
50
|
+
/** Terminates the system, then settles until every actor has stopped. */
|
|
51
|
+
shutdown(): Promise<void>;
|
|
52
|
+
}
|
|
53
|
+
/** Thrown by `settle` when actors stay busy, for example awaiting a promise that never settles. */
|
|
54
|
+
export declare class SettleTimeoutError extends Error {
|
|
55
|
+
/** Always `"SettleTimeoutError"`, so the error can be recognized without `instanceof`. */
|
|
56
|
+
readonly name = "SettleTimeoutError";
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Creates an actor system on a {@link ManualScheduler} and a {@link seededRandom}, with a logger
|
|
60
|
+
* that records into `kit.logs`. Nothing runs until you call `settle`.
|
|
61
|
+
* @throws TypeError if `seed` isn't a safe integer.
|
|
62
|
+
*/
|
|
63
|
+
export declare function createTestKit(opts?: TestKitOptions): TestKit;
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { checkInt } from '../checks.js';
|
|
2
|
+
import { ActorNameError } from '../errors.js';
|
|
3
|
+
import { createSystem } from '../system.js';
|
|
4
|
+
import { ManualScheduler } from './manual-scheduler.js';
|
|
5
|
+
import { TestProbe } from './probe.js';
|
|
6
|
+
import { seededRandom } from './random.js';
|
|
7
|
+
/** Thrown by `settle` when actors stay busy, for example awaiting a promise that never settles. */
|
|
8
|
+
export class SettleTimeoutError extends Error {
|
|
9
|
+
/** Always `"SettleTimeoutError"`, so the error can be recognized without `instanceof`. */
|
|
10
|
+
name = 'SettleTimeoutError';
|
|
11
|
+
}
|
|
12
|
+
const MAX_TICKS = 1000;
|
|
13
|
+
const PROBE_NAME = /^[A-Za-z0-9][A-Za-z0-9._~-]{0,63}$/;
|
|
14
|
+
/**
|
|
15
|
+
* Creates an actor system on a {@link ManualScheduler} and a {@link seededRandom}, with a logger
|
|
16
|
+
* that records into `kit.logs`. Nothing runs until you call `settle`.
|
|
17
|
+
* @throws TypeError if `seed` isn't a safe integer.
|
|
18
|
+
*/
|
|
19
|
+
export function createTestKit(opts = {}) {
|
|
20
|
+
const random = seededRandom(opts.seed ?? 1);
|
|
21
|
+
const scheduler = new ManualScheduler(opts.startTime === undefined ? {} : { startTime: opts.startTime });
|
|
22
|
+
const logs = [];
|
|
23
|
+
const record = (level) => (msg, fields) => {
|
|
24
|
+
logs.push(fields === undefined ? { level, msg } : { level, msg, fields });
|
|
25
|
+
};
|
|
26
|
+
const logger = {
|
|
27
|
+
debug: record('debug'),
|
|
28
|
+
info: record('info'),
|
|
29
|
+
warn: record('warn'),
|
|
30
|
+
error: record('error'),
|
|
31
|
+
};
|
|
32
|
+
const handle = createSystem({ ...opts.system, scheduler, random, logger });
|
|
33
|
+
const events = [];
|
|
34
|
+
handle.system.events.subscribe((event) => events.push(event));
|
|
35
|
+
const probeNames = new Set();
|
|
36
|
+
let generated = 0;
|
|
37
|
+
const settle = async () => {
|
|
38
|
+
for (let ticks = 0;; ticks++) {
|
|
39
|
+
scheduler.runReady();
|
|
40
|
+
if (handle.busy() === 0)
|
|
41
|
+
return;
|
|
42
|
+
if (ticks >= MAX_TICKS) {
|
|
43
|
+
// An ask only time can complete is the likeliest culprit when one is pending.
|
|
44
|
+
const hint = handle.pendingAsks() > 0
|
|
45
|
+
? 'is one awaiting an ask that only times out as time passes? Pipe it with pipeToSelf'
|
|
46
|
+
: 'is one awaiting a promise that never settles?';
|
|
47
|
+
throw new SettleTimeoutError(`settle: ${String(handle.busy())} actor(s) still busy after ${String(MAX_TICKS)} ` +
|
|
48
|
+
`ticks; ${hint}`);
|
|
49
|
+
}
|
|
50
|
+
// Async receive runs on real promises, so let one real event-loop turn pass. This is the
|
|
51
|
+
// one place the testkit uses real time (decision 0003).
|
|
52
|
+
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
return {
|
|
56
|
+
system: handle.system,
|
|
57
|
+
scheduler,
|
|
58
|
+
events,
|
|
59
|
+
logs,
|
|
60
|
+
probe(name) {
|
|
61
|
+
const chosen = name ?? String(++generated);
|
|
62
|
+
if (!PROBE_NAME.test(chosen))
|
|
63
|
+
throw new ActorNameError(`probe name "${chosen}" is invalid`);
|
|
64
|
+
const full = `probe-${chosen}`;
|
|
65
|
+
if (probeNames.has(full))
|
|
66
|
+
throw new ActorNameError(`probe name "${chosen}" is already taken`);
|
|
67
|
+
probeNames.add(full);
|
|
68
|
+
return new TestProbe(`/temp/${full}`, full, handle);
|
|
69
|
+
},
|
|
70
|
+
settle,
|
|
71
|
+
async advance(ms) {
|
|
72
|
+
checkInt(ms, 'advance: ms', { min: 0 });
|
|
73
|
+
const target = scheduler.now() + ms;
|
|
74
|
+
await settle();
|
|
75
|
+
for (;;) {
|
|
76
|
+
const next = scheduler.nextTimerAt();
|
|
77
|
+
if (next === undefined || next > target)
|
|
78
|
+
break;
|
|
79
|
+
// Settling ran everything already due, so `next` is in the future. This runs every timer
|
|
80
|
+
// due then, and what they queue, with the clock at `next`. The settle after it lets async
|
|
81
|
+
// work they started finish before time moves on.
|
|
82
|
+
scheduler.advanceTo(next);
|
|
83
|
+
await settle();
|
|
84
|
+
}
|
|
85
|
+
scheduler.advanceTo(target);
|
|
86
|
+
},
|
|
87
|
+
async shutdown() {
|
|
88
|
+
const terminated = handle.system.terminate();
|
|
89
|
+
await settle();
|
|
90
|
+
await terminated;
|
|
91
|
+
},
|
|
92
|
+
};
|
|
93
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import type { Scheduler } from '../scheduler.js';
|
|
2
|
+
/** Options for {@link ManualScheduler}. */
|
|
3
|
+
export interface ManualSchedulerOptions {
|
|
4
|
+
/** The virtual time to start at, in ms. Default 0. */
|
|
5
|
+
startTime?: number;
|
|
6
|
+
/**
|
|
7
|
+
* How many tasks and timers one {@link ManualScheduler.runReady} may run, without time moving,
|
|
8
|
+
* before the scheduler decides something is re-queuing itself forever and throws a
|
|
9
|
+
* `RangeError`. Default 100,000.
|
|
10
|
+
*/
|
|
11
|
+
maxSteps?: number;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* A scheduler on virtual time, for tests and simulation (decision 0003). Nothing runs on its
|
|
15
|
+
* own: queued tasks and due timers run only when you call {@link ManualScheduler.runReady} or
|
|
16
|
+
* {@link ManualScheduler.advanceTo}, and time moves only through `advanceTo`.
|
|
17
|
+
*
|
|
18
|
+
* Queued tasks always run before timers, and timers run in order of due time, then of creation.
|
|
19
|
+
* An error thrown by a task comes out of the call that ran it. The task has already left the
|
|
20
|
+
* queue, so the scheduler stays usable.
|
|
21
|
+
*/
|
|
22
|
+
export declare class ManualScheduler implements Scheduler {
|
|
23
|
+
#private;
|
|
24
|
+
constructor(opts?: ManualSchedulerOptions);
|
|
25
|
+
/** The current virtual time, in ms. While a timer runs, this is its due time. */
|
|
26
|
+
now(): number;
|
|
27
|
+
/** Queues `task`. It runs at the next {@link ManualScheduler.runReady} or `advanceTo`. */
|
|
28
|
+
runSoon(task: () => void): void;
|
|
29
|
+
/**
|
|
30
|
+
* Schedules `task` at `now() + delayMs` of virtual time. A negative or `NaN` delay counts as 0,
|
|
31
|
+
* as `setTimeout` treats it.
|
|
32
|
+
* @returns A function that cancels the timer. It stops a timer that's already due as long as it
|
|
33
|
+
* hasn't run yet.
|
|
34
|
+
*/
|
|
35
|
+
setTimer(task: () => void, delayMs: number): () => void;
|
|
36
|
+
/**
|
|
37
|
+
* Runs queued tasks and due timers, without moving time, until none are left. Tasks go first,
|
|
38
|
+
* so the tasks a timer queues run before the next timer.
|
|
39
|
+
* @returns How many tasks and timers ran.
|
|
40
|
+
* @throws RangeError after `maxSteps` in one call, which means something re-queues itself
|
|
41
|
+
* without end.
|
|
42
|
+
*/
|
|
43
|
+
runReady(): number;
|
|
44
|
+
/**
|
|
45
|
+
* Moves virtual time forward to `time`, running everything that falls due on the way. Before
|
|
46
|
+
* each timer runs, `now()` is set to its due time. Timers scheduled along the way also run if
|
|
47
|
+
* they fall due by `time`. Ends with `now() === time`.
|
|
48
|
+
* @throws RangeError if `time` is earlier than `now()`, because virtual time never goes back.
|
|
49
|
+
*/
|
|
50
|
+
advanceTo(time: number): void;
|
|
51
|
+
/**
|
|
52
|
+
* The due time of the earliest timer that hasn't run or been cancelled, or `undefined` when none
|
|
53
|
+
* is scheduled. It can be earlier than `now()` for a timer that's due but hasn't run yet.
|
|
54
|
+
*/
|
|
55
|
+
nextTimerAt(): number | undefined;
|
|
56
|
+
/** How many timers are scheduled and not yet run or cancelled. */
|
|
57
|
+
pendingTimers(): number;
|
|
58
|
+
}
|