@operad-io/engine 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/LICENSE +21 -0
- package/README.md +11 -2
- package/config.schema.json +188 -0
- package/keys.schema.json +12 -0
- package/package.json +22 -4
- package/src/config/config.ts +627 -0
- package/src/config/index.ts +1 -0
- package/src/flow/define-flow.ts +57 -0
- package/src/flow/index.ts +5 -0
- package/src/flow/load.ts +41 -0
- package/src/flow/types.ts +107 -0
- package/src/flow/validate.ts +296 -0
- package/src/http/address.ts +142 -0
- package/src/http/index.ts +25 -0
- package/src/http/link.ts +20 -0
- package/src/http/server.ts +920 -0
- package/src/http/token.ts +90 -0
- package/src/index.ts +18 -0
- package/src/kernel/decide.ts +689 -0
- package/src/kernel/index.ts +3 -0
- package/src/kernel/state.ts +275 -0
- package/src/kernel/types.ts +366 -0
- package/src/log/errors.ts +77 -0
- package/src/log/facts.ts +50 -0
- package/src/log/index.ts +6 -0
- package/src/log/json-value.ts +67 -0
- package/src/log/open-log.ts +17 -0
- package/src/log/schema.ts +5 -0
- package/src/log/secret.ts +30 -0
- package/src/log/sqlite.ts +1011 -0
- package/src/log/types.ts +230 -0
- package/src/loop/code-watch.ts +486 -0
- package/src/loop/index.ts +3 -0
- package/src/loop/older-code.ts +58 -0
- package/src/loop/serve.ts +483 -0
- package/src/markdown.ts +451 -0
- package/src/notify/index.ts +10 -0
- package/src/notify/notify.ts +256 -0
- package/src/platform/file-lock.ts +385 -0
- package/src/platform/index.ts +13 -0
- package/src/platform/load.ts +18 -0
- package/src/platform/process-group.ts +675 -0
- package/src/platform/process-watch.ts +152 -0
- package/src/platform/sqlite-open.ts +104 -0
- package/src/platform/step-reap.ts +668 -0
- package/src/platform/watch.ts +158 -0
- package/src/platform/worker-reports.ts +34 -0
- package/src/plugin/action-schema.ts +550 -0
- package/src/plugin/declared-flows.ts +74 -0
- package/src/plugin/define-plugin.ts +12 -0
- package/src/plugin/errors.ts +73 -0
- package/src/plugin/filters.ts +46 -0
- package/src/plugin/harness.ts +50 -0
- package/src/plugin/home.ts +13 -0
- package/src/plugin/index.ts +65 -0
- package/src/plugin/install.ts +268 -0
- package/src/plugin/keys.ts +63 -0
- package/src/plugin/load.ts +256 -0
- package/src/plugin/logger.ts +30 -0
- package/src/plugin/object-facts.ts +132 -0
- package/src/plugin/open-store.ts +32 -0
- package/src/plugin/paging.ts +133 -0
- package/src/plugin/registry.ts +1786 -0
- package/src/plugin/secrets.ts +141 -0
- package/src/plugin/semver.ts +110 -0
- package/src/plugin/settings.ts +64 -0
- package/src/plugin/sqlite-store.ts +756 -0
- package/src/plugin/store.ts +318 -0
- package/src/plugin/types.ts +1243 -0
- package/src/plugin/usage.ts +157 -0
- package/src/plugin/validate.ts +1028 -0
- package/src/runner/answer.ts +156 -0
- package/src/runner/ask.ts +483 -0
- package/src/runner/cancel.ts +51 -0
- package/src/runner/errors.ts +20 -0
- package/src/runner/grants.ts +92 -0
- package/src/runner/index.ts +33 -0
- package/src/runner/limits.ts +403 -0
- package/src/runner/lock.ts +140 -0
- package/src/runner/runner.ts +1175 -0
- package/src/runner/service.ts +184 -0
- package/src/runner/step-worker.ts +303 -0
- package/src/testing/clock.ts +67 -0
- package/src/testing/index.ts +90 -0
- package/src/testing/types.ts +116 -0
- package/src/testing/world.ts +369 -0
- package/src/trigger/cron.ts +193 -0
- package/src/trigger/index.ts +32 -0
- package/src/trigger/kernel.ts +1221 -0
- package/src/trigger/rules.ts +300 -0
- package/src/trigger/store.ts +233 -0
- package/src/trigger/types.ts +156 -0
- package/src/util.ts +50 -0
- package/src/views/history.ts +634 -0
- package/src/views/index.ts +7 -0
- package/src/views/pending.ts +209 -0
- package/src/views/presentation.ts +2609 -0
- package/src/views/running.ts +255 -0
- package/src/views/settings.ts +452 -0
- package/src/views/types.ts +72 -0
- package/src/views/uploads.ts +228 -0
- package/triggers.schema.json +48 -0
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
/** The shapes `@operad-io/engine/testing` takes and returns. */
|
|
2
|
+
|
|
3
|
+
import type { FlowDefinition } from "../flow/types.ts";
|
|
4
|
+
import type { Fact } from "../log/types.ts";
|
|
5
|
+
import type { JsonValue } from "../log/types.ts";
|
|
6
|
+
import type { PluginDefinition, PluginStore } from "../plugin/types.ts";
|
|
7
|
+
import type { TriggerResult } from "../trigger/types.ts";
|
|
8
|
+
import type { Clock } from "../platform/index.ts";
|
|
9
|
+
|
|
10
|
+
/** A clock the test moves. Timers fire only when `advance` passes them. */
|
|
11
|
+
export interface FakeClock extends Clock {
|
|
12
|
+
/** The time now, in milliseconds. Starts at the value given to `fakeClock`. */
|
|
13
|
+
now(): number;
|
|
14
|
+
/** Moves time forward and fires every timer that falls due, in order. */
|
|
15
|
+
advance(ms: number): void;
|
|
16
|
+
/** How many timers are set and not yet fired or cleared. */
|
|
17
|
+
readonly pending: number;
|
|
18
|
+
/** Resolves once at least one timer is set. */
|
|
19
|
+
whenTimer(): Promise<void>;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* The plugin a test runs: the path or package name of its module (steps then
|
|
24
|
+
* run in a worker, as under `serve`), or its definition, which can only run
|
|
25
|
+
* with `inProcess: true`.
|
|
26
|
+
*/
|
|
27
|
+
export type PluginUnderTest = PluginDefinition | string;
|
|
28
|
+
|
|
29
|
+
/** What a world is made of. */
|
|
30
|
+
export interface WorldOptions {
|
|
31
|
+
/** The plugin's `config.json` section (`ctx.settings`). */
|
|
32
|
+
readonly settings?: Readonly<Record<string, JsonValue>> | undefined;
|
|
33
|
+
/** The plugin's secrets (`ctx.secrets`). */
|
|
34
|
+
readonly secrets?: Readonly<Record<string, string>> | undefined;
|
|
35
|
+
readonly clock?: FakeClock | undefined;
|
|
36
|
+
/**
|
|
37
|
+
* Run steps in this process against an in-memory store: faster, not isolated.
|
|
38
|
+
* A step then shares module state with the test and may return values a
|
|
39
|
+
* worker could not hand back, so it can pass here and fail under `serve`.
|
|
40
|
+
* Needed when the plugin is given as a definition.
|
|
41
|
+
*/
|
|
42
|
+
readonly inProcess?: boolean | undefined;
|
|
43
|
+
/** Objects to start from; only with `inProcess`. Default: `memoryStore()`. */
|
|
44
|
+
readonly store?: PluginStore | undefined;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export interface RunFlowOptions extends WorldOptions {
|
|
48
|
+
/** The object the run is about. Default: `<first object type>:1`. */
|
|
49
|
+
readonly object?: { readonly type: string; readonly id: string } | undefined;
|
|
50
|
+
/** Fixed JSON the flow starts with (`ctx.params`). */
|
|
51
|
+
readonly params?: JsonValue | undefined;
|
|
52
|
+
/** The access profile (`ctx.access`). */
|
|
53
|
+
readonly access?: JsonValue | undefined;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export type FlowRunStatus = "ended" | "waiting_person" | "blocked";
|
|
57
|
+
|
|
58
|
+
export type FlowEnd = "done" | "failed" | "cancelled";
|
|
59
|
+
|
|
60
|
+
/** What a run is waiting for a person to answer. */
|
|
61
|
+
export interface FlowWait {
|
|
62
|
+
readonly id: string;
|
|
63
|
+
readonly prompt: string;
|
|
64
|
+
readonly choices: readonly string[];
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** One run, as it stood when `runFlow`, `answer` or `resume` returned. */
|
|
68
|
+
export interface FlowRun {
|
|
69
|
+
readonly runId: string;
|
|
70
|
+
readonly flow: string;
|
|
71
|
+
readonly status: FlowRunStatus;
|
|
72
|
+
readonly end: FlowEnd | undefined;
|
|
73
|
+
readonly wait: FlowWait | undefined;
|
|
74
|
+
readonly facts: readonly Fact[];
|
|
75
|
+
readonly history: readonly string[];
|
|
76
|
+
readonly store: PluginStore;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export interface EmitOptions {
|
|
80
|
+
/** The idempotency key. Default: a fresh one for each event of a world. */
|
|
81
|
+
readonly key?: string | undefined;
|
|
82
|
+
/** The object the event is about, as `<type>:<id>`. */
|
|
83
|
+
readonly object?: string | undefined;
|
|
84
|
+
readonly summary?: string | undefined;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export interface EmitResult {
|
|
88
|
+
/** True when this event started a run: a rule matched and it was not a repeat. */
|
|
89
|
+
readonly started: boolean;
|
|
90
|
+
readonly result: TriggerResult;
|
|
91
|
+
/** The run the event started, taken to its end or first wait. */
|
|
92
|
+
readonly run: FlowRun | undefined;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* One log, store, kernel and clock that several calls share, so a repeated
|
|
97
|
+
* event key is a repeat and a run that ends can start the next one.
|
|
98
|
+
*/
|
|
99
|
+
export interface TestWorld {
|
|
100
|
+
readonly store: PluginStore;
|
|
101
|
+
/** Starts `flow` and runs the world until nothing more can happen. */
|
|
102
|
+
runFlow(
|
|
103
|
+
flow: string | FlowDefinition,
|
|
104
|
+
options?: Pick<RunFlowOptions, "object" | "params" | "access">,
|
|
105
|
+
): Promise<FlowRun>;
|
|
106
|
+
/** Sends an event through the plugin's rules, as a source plugin would. */
|
|
107
|
+
emit(
|
|
108
|
+
source: string,
|
|
109
|
+
type: string,
|
|
110
|
+
data?: JsonValue,
|
|
111
|
+
options?: EmitOptions,
|
|
112
|
+
): Promise<EmitResult>;
|
|
113
|
+
/** Every run of the world, in the order they started. */
|
|
114
|
+
runs(): Promise<readonly FlowRun[]>;
|
|
115
|
+
close(): Promise<void>;
|
|
116
|
+
}
|
|
@@ -0,0 +1,369 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One isolated world for a test: a log, a store, a registry holding the plugin
|
|
3
|
+
* under test, and the kernel. It is made of the engine's own parts, and it is
|
|
4
|
+
* driven by the same pass `serve` makes: tick, apply recorded answers, start
|
|
5
|
+
* runs, give every run a runner. A test's calls record what a person or a
|
|
6
|
+
* source would and then let that pass run until nothing changes.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { mkdtemp, rm } from "node:fs/promises";
|
|
10
|
+
import { tmpdir } from "node:os";
|
|
11
|
+
import { join } from "node:path";
|
|
12
|
+
import type { FlowDefinition } from "../flow/types.ts";
|
|
13
|
+
import { openLog } from "../log/open-log.ts";
|
|
14
|
+
import { SQLITE_FILE_NAME } from "../log/sqlite.ts";
|
|
15
|
+
import type { Fact, JsonValue, LogBackend } from "../log/types.ts";
|
|
16
|
+
import { SqlitePluginStore } from "../plugin/sqlite-store.ts";
|
|
17
|
+
import { loadPlugin } from "../plugin/load.ts";
|
|
18
|
+
import { PluginRegistry } from "../plugin/registry.ts";
|
|
19
|
+
import { FileSecretStore } from "../plugin/secrets.ts";
|
|
20
|
+
import { MemoryPluginStore } from "../plugin/store.ts";
|
|
21
|
+
import type { PluginDefinition, PluginStore } from "../plugin/types.ts";
|
|
22
|
+
import { serveOnce } from "../loop/serve.ts";
|
|
23
|
+
import { recordAnswer } from "../runner/answer.ts";
|
|
24
|
+
import { Runner } from "../runner/runner.ts";
|
|
25
|
+
import { parseObjectKey, readState } from "../runner/service.ts";
|
|
26
|
+
import { Kernel } from "../trigger/kernel.ts";
|
|
27
|
+
import { loadTriggerRules } from "../trigger/rules.ts";
|
|
28
|
+
import { readStoredStart, readStoredTrigger } from "../trigger/store.ts";
|
|
29
|
+
import { formatHistoryEntry, historyEntries } from "../views/history.ts";
|
|
30
|
+
import type {
|
|
31
|
+
EmitOptions,
|
|
32
|
+
EmitResult,
|
|
33
|
+
FlowRun,
|
|
34
|
+
FlowRunStatus,
|
|
35
|
+
PluginUnderTest,
|
|
36
|
+
RunFlowOptions,
|
|
37
|
+
TestWorld,
|
|
38
|
+
WorldOptions,
|
|
39
|
+
} from "./types.ts";
|
|
40
|
+
|
|
41
|
+
/** A pass that keeps changing the log this many times is a loop, not a test. */
|
|
42
|
+
const MAX_PASSES = 200;
|
|
43
|
+
|
|
44
|
+
interface World {
|
|
45
|
+
readonly root: string;
|
|
46
|
+
readonly storeRoot: string;
|
|
47
|
+
readonly home: string;
|
|
48
|
+
readonly plugin: PluginDefinition;
|
|
49
|
+
readonly log: LogBackend;
|
|
50
|
+
readonly registry: PluginRegistry;
|
|
51
|
+
readonly kernel: Kernel;
|
|
52
|
+
readonly store: PluginStore;
|
|
53
|
+
readonly options: WorldOptions;
|
|
54
|
+
readonly now: () => number;
|
|
55
|
+
events: number;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const worlds = new Set<World>();
|
|
59
|
+
const worldOf = new WeakMap<FlowRun, World>();
|
|
60
|
+
|
|
61
|
+
/** An empty in-memory object store. */
|
|
62
|
+
export function memoryStore(): PluginStore {
|
|
63
|
+
return new MemoryPluginStore({ root: join(tmpdir(), "operad-testing-memory") });
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function isDefinition(plugin: PluginUnderTest): plugin is PluginDefinition {
|
|
67
|
+
return typeof plugin !== "string";
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
async function createWorld(
|
|
71
|
+
plugin: PluginUnderTest,
|
|
72
|
+
options: WorldOptions,
|
|
73
|
+
): Promise<World> {
|
|
74
|
+
if (isDefinition(plugin) && options.inProcess !== true) {
|
|
75
|
+
throw new Error(
|
|
76
|
+
"a plugin given as a definition can only run in this process: pass its module path " +
|
|
77
|
+
"to run its steps in a worker as `serve` does, or set inProcess: true",
|
|
78
|
+
);
|
|
79
|
+
}
|
|
80
|
+
if (options.store !== undefined && options.inProcess !== true) {
|
|
81
|
+
throw new Error("a store of your own needs inProcess: true; a worker opens its own");
|
|
82
|
+
}
|
|
83
|
+
const root = await mkdtemp(join(tmpdir(), "operad-testing-"));
|
|
84
|
+
const home = join(root, "home");
|
|
85
|
+
const storeRoot = join(root, "store");
|
|
86
|
+
const clock = options.clock;
|
|
87
|
+
const now = clock === undefined ? () => Date.now() : () => clock.now();
|
|
88
|
+
let log: LogBackend | undefined;
|
|
89
|
+
try {
|
|
90
|
+
const definition = isDefinition(plugin)
|
|
91
|
+
? plugin
|
|
92
|
+
: ((await loadPlugin(plugin, home)) as PluginDefinition);
|
|
93
|
+
const store: PluginStore =
|
|
94
|
+
options.inProcess === true
|
|
95
|
+
? (options.store ?? memoryStore())
|
|
96
|
+
: new SqlitePluginStore({ root: storeRoot });
|
|
97
|
+
for (const [name, value] of Object.entries(options.secrets ?? {})) {
|
|
98
|
+
await new FileSecretStore({ home, plugin: definition.name }).set(name, value);
|
|
99
|
+
}
|
|
100
|
+
log = openLog({ backend: "sqlite", path: join(storeRoot, SQLITE_FILE_NAME) });
|
|
101
|
+
const onLog = (message: string): void => {
|
|
102
|
+
console.error(message);
|
|
103
|
+
};
|
|
104
|
+
const registry = new PluginRegistry([definition], {
|
|
105
|
+
home,
|
|
106
|
+
cwd: home,
|
|
107
|
+
storeRoot,
|
|
108
|
+
store,
|
|
109
|
+
clock: now,
|
|
110
|
+
settings:
|
|
111
|
+
options.settings === undefined ? {} : { [definition.name]: options.settings },
|
|
112
|
+
...(options.inProcess === true || isDefinition(plugin) ? {} : { sources: [plugin] }),
|
|
113
|
+
onLog,
|
|
114
|
+
});
|
|
115
|
+
const refusal = registry.refusals().find((item) => item.plugin === definition.name);
|
|
116
|
+
if (refusal !== undefined) throw new Error(refusal.message);
|
|
117
|
+
const rules = await loadTriggerRules({ home, registry, onLog });
|
|
118
|
+
const kernel = new Kernel({ log, registry, home, storeRoot, rules, clock: now, onLog });
|
|
119
|
+
const world: World = {
|
|
120
|
+
root,
|
|
121
|
+
storeRoot,
|
|
122
|
+
home,
|
|
123
|
+
plugin: definition,
|
|
124
|
+
log,
|
|
125
|
+
registry,
|
|
126
|
+
kernel,
|
|
127
|
+
store,
|
|
128
|
+
options,
|
|
129
|
+
now,
|
|
130
|
+
events: 0,
|
|
131
|
+
};
|
|
132
|
+
worlds.add(world);
|
|
133
|
+
return world;
|
|
134
|
+
} catch (error) {
|
|
135
|
+
await log?.close();
|
|
136
|
+
await rm(root, { recursive: true, force: true });
|
|
137
|
+
throw error;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
async function closeWorld(world: World): Promise<void> {
|
|
142
|
+
if (!worlds.delete(world)) return;
|
|
143
|
+
await world.log.close();
|
|
144
|
+
await rm(world.root, { recursive: true, force: true });
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** Closes every world made so far and removes its scratch directory. */
|
|
148
|
+
export async function cleanup(): Promise<void> {
|
|
149
|
+
for (const world of [...worlds]) await closeWorld(world);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function flowNamed(world: World, flow: string | FlowDefinition): FlowDefinition {
|
|
153
|
+
const name = typeof flow === "string" ? flow : flow.name;
|
|
154
|
+
const found = world.registry.flow(name);
|
|
155
|
+
if (found === undefined) throw new Error(`the plugin has no flow "${name}"`);
|
|
156
|
+
return found.flow;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** What a run is doing, as one string: it changes whenever the run moves. */
|
|
160
|
+
async function signature(world: World): Promise<string> {
|
|
161
|
+
const runs = await world.log.runs();
|
|
162
|
+
return JSON.stringify(runs.map((run) => [run.runId, run.lastSeq, run.active]));
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** Gives one run a runner, as the process `serve` starts for it would. */
|
|
166
|
+
async function runnerFor(world: World, runId: string, recover: boolean): Promise<void> {
|
|
167
|
+
const run = (await world.log.runs()).find((item) => item.runId === runId);
|
|
168
|
+
if (run === undefined) throw new Error(`no run "${runId}"`);
|
|
169
|
+
const found = world.registry.flow(run.flow);
|
|
170
|
+
if (found === undefined) throw new Error(`flow "${run.flow}" is not loaded`);
|
|
171
|
+
const object = parseObjectKey(run.object);
|
|
172
|
+
world.kernel.adoptStart(run);
|
|
173
|
+
const startInput = readStoredStart(world.storeRoot, runId);
|
|
174
|
+
const trigger = readStoredTrigger(world.storeRoot, runId);
|
|
175
|
+
const clock = world.options.clock;
|
|
176
|
+
const runner = new Runner({
|
|
177
|
+
log: world.log,
|
|
178
|
+
flow: found.flow,
|
|
179
|
+
runId,
|
|
180
|
+
registry: world.registry,
|
|
181
|
+
lockRoot: world.storeRoot,
|
|
182
|
+
clock: world.now,
|
|
183
|
+
recover,
|
|
184
|
+
...(clock === undefined ? {} : { timers: clock }),
|
|
185
|
+
...(run.access === undefined ? {} : { access: run.access }),
|
|
186
|
+
...(object === undefined ? {} : { object }),
|
|
187
|
+
...(startInput === undefined ? {} : { startInput }),
|
|
188
|
+
...(trigger === undefined ? {} : { trigger }),
|
|
189
|
+
onEnded: async (endedRunId, state) => {
|
|
190
|
+
await world.kernel.emitRunEnd(endedRunId, state);
|
|
191
|
+
},
|
|
192
|
+
emit: async (pluginName, event) => {
|
|
193
|
+
await world.kernel.emitStep(runId, pluginName, event, run.object);
|
|
194
|
+
},
|
|
195
|
+
});
|
|
196
|
+
await runner.run();
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Makes the passes `serve` makes until one changes nothing: answers recorded
|
|
201
|
+
* since the last pass are applied, every run that can move gets a runner, and
|
|
202
|
+
* a run that ends can start the next through the rules.
|
|
203
|
+
*/
|
|
204
|
+
async function settle(world: World): Promise<void> {
|
|
205
|
+
for (let pass = 0; pass < MAX_PASSES; pass += 1) {
|
|
206
|
+
const before = await signature(world);
|
|
207
|
+
const runners: Promise<void>[] = [];
|
|
208
|
+
await serveOnce({
|
|
209
|
+
log: world.log,
|
|
210
|
+
registry: world.registry,
|
|
211
|
+
kernel: world.kernel,
|
|
212
|
+
lockRoot: world.storeRoot,
|
|
213
|
+
storeRoot: world.storeRoot,
|
|
214
|
+
home: world.home,
|
|
215
|
+
clock: world.now,
|
|
216
|
+
spawnRun: (runId, options) => {
|
|
217
|
+
runners.push(runnerFor(world, runId, options.recover));
|
|
218
|
+
},
|
|
219
|
+
});
|
|
220
|
+
await Promise.all(runners);
|
|
221
|
+
if ((await signature(world)) === before) return;
|
|
222
|
+
}
|
|
223
|
+
throw new Error(`the runs were still changing after ${MAX_PASSES} passes`);
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
async function snapshot(world: World, runId: string): Promise<FlowRun> {
|
|
227
|
+
const facts: Fact[] = [];
|
|
228
|
+
for await (const fact of world.log.read(runId)) facts.push(fact);
|
|
229
|
+
const state = await readState(world.log, runId);
|
|
230
|
+
const history: string[] = [];
|
|
231
|
+
for await (const entry of historyEntries(world.log.read(runId))) {
|
|
232
|
+
history.push(formatHistoryEntry(entry));
|
|
233
|
+
}
|
|
234
|
+
const info = (await world.log.runs()).find((item) => item.runId === runId);
|
|
235
|
+
const status: FlowRunStatus =
|
|
236
|
+
state.status === "ended"
|
|
237
|
+
? "ended"
|
|
238
|
+
: state.status === "waiting_person"
|
|
239
|
+
? "waiting_person"
|
|
240
|
+
: "blocked";
|
|
241
|
+
const run: FlowRun = {
|
|
242
|
+
runId,
|
|
243
|
+
flow: info?.flow ?? "",
|
|
244
|
+
status,
|
|
245
|
+
end: state.endedStatus ?? undefined,
|
|
246
|
+
wait:
|
|
247
|
+
state.wait === null || status !== "waiting_person"
|
|
248
|
+
? undefined
|
|
249
|
+
: { id: state.wait.id, prompt: state.wait.prompt, choices: state.wait.choices },
|
|
250
|
+
facts,
|
|
251
|
+
history,
|
|
252
|
+
store: world.store,
|
|
253
|
+
};
|
|
254
|
+
worldOf.set(run, world);
|
|
255
|
+
return run;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
function worldFor(run: FlowRun): World {
|
|
259
|
+
const world = worldOf.get(run);
|
|
260
|
+
if (world === undefined) throw new Error("this run was not made by the testing package");
|
|
261
|
+
return world;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
async function runFlowIn(
|
|
265
|
+
world: World,
|
|
266
|
+
flow: string | FlowDefinition,
|
|
267
|
+
options: Pick<RunFlowOptions, "object" | "params" | "access">,
|
|
268
|
+
): Promise<FlowRun> {
|
|
269
|
+
const definition = flowNamed(world, flow);
|
|
270
|
+
const first = world.plugin.objects?.[0];
|
|
271
|
+
const object =
|
|
272
|
+
options.object !== undefined
|
|
273
|
+
? `${options.object.type}:${options.object.id}`
|
|
274
|
+
: first !== undefined
|
|
275
|
+
? `${first.name}:1`
|
|
276
|
+
: `flow:${world.plugin.name}/${definition.name}`;
|
|
277
|
+
const started = await world.kernel.start({
|
|
278
|
+
flow: definition.name,
|
|
279
|
+
object,
|
|
280
|
+
...(options.params === undefined ? {} : { params: options.params }),
|
|
281
|
+
...(options.access === undefined ? {} : { access: options.access }),
|
|
282
|
+
});
|
|
283
|
+
if (started.kind !== "started") {
|
|
284
|
+
throw new Error(`the flow "${definition.name}" did not start (${started.kind})`);
|
|
285
|
+
}
|
|
286
|
+
await settle(world);
|
|
287
|
+
return snapshot(world, started.runId);
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
async function emitIn(
|
|
291
|
+
world: World,
|
|
292
|
+
source: string,
|
|
293
|
+
type: string,
|
|
294
|
+
data: JsonValue | undefined,
|
|
295
|
+
options: EmitOptions,
|
|
296
|
+
): Promise<EmitResult> {
|
|
297
|
+
world.events += 1;
|
|
298
|
+
const result = await world.kernel.receive({
|
|
299
|
+
source,
|
|
300
|
+
type,
|
|
301
|
+
key: options.key ?? `testing-${world.events}`,
|
|
302
|
+
hops: 0,
|
|
303
|
+
...(options.object === undefined ? {} : { object: options.object }),
|
|
304
|
+
...(options.summary === undefined ? {} : { summary: options.summary }),
|
|
305
|
+
...(data === undefined ? {} : { data }),
|
|
306
|
+
});
|
|
307
|
+
await settle(world);
|
|
308
|
+
const run =
|
|
309
|
+
result.runId === undefined ? undefined : await snapshot(world, result.runId);
|
|
310
|
+
return { started: result.kind === "started" && !result.duplicate, result, run };
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/** Answers the wait the run is in, then lets the world run on. */
|
|
314
|
+
export async function answerRunWait(
|
|
315
|
+
run: FlowRun,
|
|
316
|
+
waitId: string,
|
|
317
|
+
choice: string,
|
|
318
|
+
note: string | undefined,
|
|
319
|
+
): Promise<FlowRun> {
|
|
320
|
+
const world = worldFor(run);
|
|
321
|
+
const state = await readState(world.log, run.runId);
|
|
322
|
+
if (state.status !== "waiting_person" || state.wait === null) {
|
|
323
|
+
throw new Error(`run ${run.runId} is not waiting for a person`);
|
|
324
|
+
}
|
|
325
|
+
if (state.wait.id !== waitId) {
|
|
326
|
+
throw new Error(
|
|
327
|
+
`run ${run.runId}: the wait "${waitId}" is not the one it is in ("${state.wait.id}")`,
|
|
328
|
+
);
|
|
329
|
+
}
|
|
330
|
+
// What the CLI and a plugin action do: record the answer. The pass applies it.
|
|
331
|
+
await recordAnswer({
|
|
332
|
+
log: world.log,
|
|
333
|
+
runId: run.runId,
|
|
334
|
+
choice,
|
|
335
|
+
...(note === undefined ? {} : { note }),
|
|
336
|
+
actor: { via: "testing", id: "test" },
|
|
337
|
+
});
|
|
338
|
+
await settle(world);
|
|
339
|
+
return snapshot(world, run.runId);
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
/** Lets the world run on, for example after the clock passed a time wait. */
|
|
343
|
+
export async function resumeRun(run: FlowRun): Promise<FlowRun> {
|
|
344
|
+
const world = worldFor(run);
|
|
345
|
+
await settle(world);
|
|
346
|
+
return snapshot(world, run.runId);
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
export async function testWorld(
|
|
350
|
+
plugin: PluginUnderTest,
|
|
351
|
+
options: WorldOptions = {},
|
|
352
|
+
): Promise<TestWorld> {
|
|
353
|
+
const world = await createWorld(plugin, options);
|
|
354
|
+
return {
|
|
355
|
+
store: world.store,
|
|
356
|
+
runFlow: (flow, runOptions = {}) => runFlowIn(world, flow, runOptions),
|
|
357
|
+
emit: (source, type, data, emitOptions = {}) =>
|
|
358
|
+
emitIn(world, source, type, data, emitOptions),
|
|
359
|
+
async runs() {
|
|
360
|
+
const runs = await world.log.runs();
|
|
361
|
+
return Promise.all(
|
|
362
|
+
[...runs]
|
|
363
|
+
.sort((left, right) => left.startedAt - right.startedAt)
|
|
364
|
+
.map((run) => snapshot(world, run.runId)),
|
|
365
|
+
);
|
|
366
|
+
},
|
|
367
|
+
close: () => closeWorld(world),
|
|
368
|
+
};
|
|
369
|
+
}
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A five-field cron expression, evaluated in the machine's local time zone.
|
|
3
|
+
*
|
|
4
|
+
* Fields are minute, hour, day of month, month and day of week. Each accepts
|
|
5
|
+
* `*`, a number, a range `a-b`, a step like `*` with `/n`, and comma lists.
|
|
6
|
+
* The day fields follow the usual rule: when both are restricted, either may
|
|
7
|
+
* match; when one is `*`, the other must match.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
export interface CronField {
|
|
11
|
+
readonly values: ReadonlySet<number>;
|
|
12
|
+
readonly restricted: boolean;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface CronSchedule {
|
|
16
|
+
readonly minute: CronField;
|
|
17
|
+
readonly hour: CronField;
|
|
18
|
+
readonly day: CronField;
|
|
19
|
+
readonly month: CronField;
|
|
20
|
+
readonly weekday: CronField;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export class CronError extends Error {
|
|
24
|
+
constructor(message: string) {
|
|
25
|
+
super(message);
|
|
26
|
+
this.name = "CronError";
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function parseNumber(text: string, min: number, max: number, field: string): number {
|
|
31
|
+
if (!/^\d+$/.test(text)) {
|
|
32
|
+
throw new CronError(`${field}: "${text}" is not a number`);
|
|
33
|
+
}
|
|
34
|
+
const value = Number(text);
|
|
35
|
+
if (value < min || value > max) {
|
|
36
|
+
throw new CronError(`${field}: ${value} is outside ${min}..${max}`);
|
|
37
|
+
}
|
|
38
|
+
return value;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function parseField(text: string, min: number, max: number, field: string): CronField {
|
|
42
|
+
if (text.length === 0) throw new CronError(`${field}: must not be empty`);
|
|
43
|
+
const values = new Set<number>();
|
|
44
|
+
let restricted = false;
|
|
45
|
+
|
|
46
|
+
for (const part of text.split(",")) {
|
|
47
|
+
if (part.length === 0) throw new CronError(`${field}: has an empty list item`);
|
|
48
|
+
const [range, stepText, extra] = part.split("/");
|
|
49
|
+
if (extra !== undefined) {
|
|
50
|
+
throw new CronError(`${field}: "${part}" has too many "/" parts`);
|
|
51
|
+
}
|
|
52
|
+
const step = stepText === undefined ? 1 : parseNumber(stepText, 1, max, `${field} step`);
|
|
53
|
+
if (stepText !== undefined) restricted = true;
|
|
54
|
+
|
|
55
|
+
let start: number;
|
|
56
|
+
let end: number;
|
|
57
|
+
if (range === "*") {
|
|
58
|
+
start = min;
|
|
59
|
+
end = max;
|
|
60
|
+
} else if (range !== undefined && range.includes("-")) {
|
|
61
|
+
const [left, right, more] = range.split("-");
|
|
62
|
+
if (more !== undefined || left === undefined || right === undefined) {
|
|
63
|
+
throw new CronError(`${field}: "${part}" is not a valid range`);
|
|
64
|
+
}
|
|
65
|
+
start = parseNumber(left, min, max, field);
|
|
66
|
+
end = parseNumber(right, min, max, field);
|
|
67
|
+
if (start > end) throw new CronError(`${field}: "${part}" is an empty range`);
|
|
68
|
+
restricted = true;
|
|
69
|
+
} else {
|
|
70
|
+
start = parseNumber(range ?? "", min, max, field);
|
|
71
|
+
end = start;
|
|
72
|
+
restricted = true;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
for (let value = start; value <= end; value += step) values.add(value);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
if (field === "day of week" && values.has(7)) values.add(0);
|
|
79
|
+
|
|
80
|
+
if (values.size === 0) throw new CronError(`${field}: matches no value`);
|
|
81
|
+
return { values, restricted };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const MONTH_NAMES = [
|
|
85
|
+
"jan",
|
|
86
|
+
"feb",
|
|
87
|
+
"mar",
|
|
88
|
+
"apr",
|
|
89
|
+
"may",
|
|
90
|
+
"jun",
|
|
91
|
+
"jul",
|
|
92
|
+
"aug",
|
|
93
|
+
"sep",
|
|
94
|
+
"oct",
|
|
95
|
+
"nov",
|
|
96
|
+
"dec",
|
|
97
|
+
] as const;
|
|
98
|
+
|
|
99
|
+
const WEEKDAY_NAMES = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"] as const;
|
|
100
|
+
|
|
101
|
+
function expandNames(text: string, names: readonly string[], min: number): string {
|
|
102
|
+
return text.replace(/[a-zA-Z]{3}/g, (name) => {
|
|
103
|
+
const index = names.indexOf(name.toLowerCase() as never);
|
|
104
|
+
if (index < 0) throw new CronError(`unknown name "${name}"`);
|
|
105
|
+
return String(index + min);
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Parses five fields; a schedule with seconds or years is refused. */
|
|
110
|
+
export function parseCron(expression: string): CronSchedule {
|
|
111
|
+
if (typeof expression !== "string") {
|
|
112
|
+
throw new CronError("schedule: must be a string");
|
|
113
|
+
}
|
|
114
|
+
const fields = expression.trim().split(/\s+/);
|
|
115
|
+
if (fields.length !== 5) {
|
|
116
|
+
throw new CronError(
|
|
117
|
+
`schedule: expected five fields (minute hour day month weekday), got ${fields.length}`,
|
|
118
|
+
);
|
|
119
|
+
}
|
|
120
|
+
const [minute, hour, day, month, weekday] = fields as [
|
|
121
|
+
string,
|
|
122
|
+
string,
|
|
123
|
+
string,
|
|
124
|
+
string,
|
|
125
|
+
string,
|
|
126
|
+
];
|
|
127
|
+
return {
|
|
128
|
+
minute: parseField(minute, 0, 59, "minute"),
|
|
129
|
+
hour: parseField(hour, 0, 23, "hour"),
|
|
130
|
+
day: parseField(day, 1, 31, "day of month"),
|
|
131
|
+
month: parseField(expandNames(month, MONTH_NAMES, 1), 1, 12, "month"),
|
|
132
|
+
weekday: parseField(expandNames(weekday, WEEKDAY_NAMES, 0), 0, 7, "day of week"),
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function weekdayValue(date: Date): number {
|
|
137
|
+
return date.getDay();
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** True when the local date falls on the schedule. */
|
|
141
|
+
export function cronMatches(schedule: CronSchedule, date: Date): boolean {
|
|
142
|
+
if (!schedule.minute.values.has(date.getMinutes())) return false;
|
|
143
|
+
if (!schedule.hour.values.has(date.getHours())) return false;
|
|
144
|
+
if (!schedule.month.values.has(date.getMonth() + 1)) return false;
|
|
145
|
+
|
|
146
|
+
const weekday = weekdayValue(date);
|
|
147
|
+
const dayMatches = schedule.day.values.has(date.getDate());
|
|
148
|
+
const weekdayMatches = schedule.weekday.values.has(weekday);
|
|
149
|
+
if (!schedule.day.restricted && !schedule.weekday.restricted) return true;
|
|
150
|
+
if (!schedule.day.restricted) return weekdayMatches;
|
|
151
|
+
if (!schedule.weekday.restricted) return dayMatches;
|
|
152
|
+
// Both day fields are restricted: either one matching is enough.
|
|
153
|
+
return dayMatches || weekdayMatches;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** The start of the minute `time` is in, in milliseconds. */
|
|
157
|
+
export function minuteStart(time: number): number {
|
|
158
|
+
return time - (time % 60_000);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* The latest scheduled minute at or before `time`, looking back at most
|
|
163
|
+
* `limitDays`. Returns the minute start, or null when none matches.
|
|
164
|
+
*/
|
|
165
|
+
export function latestCronMinute(
|
|
166
|
+
schedule: CronSchedule,
|
|
167
|
+
time: number,
|
|
168
|
+
limitDays = 366 * 2,
|
|
169
|
+
): number | null {
|
|
170
|
+
let candidate = minuteStart(time);
|
|
171
|
+
const limit = candidate - limitDays * 24 * 60 * 60_000;
|
|
172
|
+
while (candidate >= limit) {
|
|
173
|
+
if (cronMatches(schedule, new Date(candidate))) return candidate;
|
|
174
|
+
candidate -= 60_000;
|
|
175
|
+
}
|
|
176
|
+
return null;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** Every scheduled minute in `(after, until]`, oldest first. Kept small by callers. */
|
|
180
|
+
export function cronMinutesBetween(
|
|
181
|
+
schedule: CronSchedule,
|
|
182
|
+
after: number,
|
|
183
|
+
until: number,
|
|
184
|
+
): number[] {
|
|
185
|
+
const result: number[] = [];
|
|
186
|
+
let candidate = minuteStart(after) + 60_000;
|
|
187
|
+
const end = minuteStart(until);
|
|
188
|
+
while (candidate <= end) {
|
|
189
|
+
if (cronMatches(schedule, new Date(candidate))) result.push(candidate);
|
|
190
|
+
candidate += 60_000;
|
|
191
|
+
}
|
|
192
|
+
return result;
|
|
193
|
+
}
|