@operad-io/engine 0.0.0-stage → 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- 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 +85 -0
- package/src/index.ts +16 -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 +635 -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 +1783 -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 +1236 -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 +1212 -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 +2551 -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
- package/README.md +0 -3
|
@@ -0,0 +1,1212 @@
|
|
|
1
|
+
/** The one entry point that starts runs, and the rules that point events at it. */
|
|
2
|
+
|
|
3
|
+
import { readFileSync } from "node:fs";
|
|
4
|
+
import type { KernelState, StartInput } from "../kernel/types.ts";
|
|
5
|
+
import { inputIdFor } from "../log/facts.ts";
|
|
6
|
+
import { ActiveRunError, SeqConflictError } from "../log/errors.ts";
|
|
7
|
+
import type {
|
|
8
|
+
InputOutcome,
|
|
9
|
+
InputRecord,
|
|
10
|
+
JsonValue,
|
|
11
|
+
LogBackend,
|
|
12
|
+
RunInfo,
|
|
13
|
+
} from "../log/types.ts";
|
|
14
|
+
import type { PluginRegistry } from "../plugin/registry.ts";
|
|
15
|
+
import type { SourceHandle } from "../plugin/types.ts";
|
|
16
|
+
import { messageOf, StartRefusedError } from "../plugin/errors.ts";
|
|
17
|
+
import { endRunDirectly, readState } from "../runner/service.ts";
|
|
18
|
+
import { TriggerStore } from "./store.ts";
|
|
19
|
+
import {
|
|
20
|
+
MAX_TRIGGER_HOPS,
|
|
21
|
+
type RefusedStart,
|
|
22
|
+
type StartRequest,
|
|
23
|
+
type StartResult,
|
|
24
|
+
type StepEvent,
|
|
25
|
+
type TriggerCandidate,
|
|
26
|
+
type TriggerEvent,
|
|
27
|
+
type TriggerResult,
|
|
28
|
+
type TriggerRule,
|
|
29
|
+
type TriggerView,
|
|
30
|
+
} from "./types.ts";
|
|
31
|
+
import { isRecord } from "../util.ts";
|
|
32
|
+
|
|
33
|
+
/** One decision per input: what the event would do. */
|
|
34
|
+
const ROUTE = "route";
|
|
35
|
+
/** A second decision per candidate input: how a person resolved it. */
|
|
36
|
+
const RESOLVE = "resolve";
|
|
37
|
+
|
|
38
|
+
export interface KernelOptions {
|
|
39
|
+
readonly log: LogBackend;
|
|
40
|
+
readonly registry: PluginRegistry;
|
|
41
|
+
readonly home: string;
|
|
42
|
+
/** The store root: event files and the trigger metadata live under it. */
|
|
43
|
+
readonly storeRoot: string;
|
|
44
|
+
readonly rules?: readonly TriggerRule[] | undefined;
|
|
45
|
+
readonly clock?: (() => number) | undefined;
|
|
46
|
+
readonly onLog?: ((message: string) => void) | undefined;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function objectOf(event: TriggerEvent): string | undefined {
|
|
50
|
+
return typeof event.object === "string" && event.object.length > 0
|
|
51
|
+
? event.object
|
|
52
|
+
: undefined;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** A string field of a fact payload, if it is a non-empty string. */
|
|
56
|
+
function field(payload: JsonValue, name: string): string | undefined {
|
|
57
|
+
if (!isRecord(payload)) return undefined;
|
|
58
|
+
const value = payload[name];
|
|
59
|
+
return typeof value === "string" && value.length > 0 ? value : undefined;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function payloadOf(outcome: InputOutcome): Record<string, JsonValue> {
|
|
63
|
+
return isRecord(outcome.payload) ? outcome.payload : {};
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** The value a claimed decision carries, such as `started` or `dismissed`. */
|
|
67
|
+
function valueOf(outcome: InputOutcome): string | undefined {
|
|
68
|
+
return field(outcome.payload, "value");
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** The event a recorded input payload carries, if it carries one. */
|
|
72
|
+
function eventFromPayload(payload: JsonValue): TriggerEvent | undefined {
|
|
73
|
+
if (!isRecord(payload)) return undefined;
|
|
74
|
+
const source = payload.source;
|
|
75
|
+
const key = payload.key;
|
|
76
|
+
const type = payload.type;
|
|
77
|
+
if (
|
|
78
|
+
typeof source !== "string" ||
|
|
79
|
+
typeof key !== "string" ||
|
|
80
|
+
typeof type !== "string" ||
|
|
81
|
+
source.length === 0 ||
|
|
82
|
+
key.length === 0 ||
|
|
83
|
+
type.length === 0
|
|
84
|
+
) {
|
|
85
|
+
return undefined;
|
|
86
|
+
}
|
|
87
|
+
const hops =
|
|
88
|
+
typeof payload.hops === "number" && Number.isInteger(payload.hops) && payload.hops >= 0
|
|
89
|
+
? payload.hops
|
|
90
|
+
: 0;
|
|
91
|
+
const summary = readSummary(payload.summaryFile);
|
|
92
|
+
return {
|
|
93
|
+
source,
|
|
94
|
+
key,
|
|
95
|
+
type,
|
|
96
|
+
hops,
|
|
97
|
+
...(typeof payload.object === "string" ? { object: payload.object } : {}),
|
|
98
|
+
...(typeof payload.link === "string" ? { link: payload.link } : {}),
|
|
99
|
+
...(summary === undefined ? {} : { summary }),
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** The first line of an event's summary file, kept short for the history. */
|
|
104
|
+
function readSummary(path: unknown): string | undefined {
|
|
105
|
+
if (typeof path !== "string") return undefined;
|
|
106
|
+
try {
|
|
107
|
+
const first = readFileSync(path, "utf8").split("\n")[0]?.trim() ?? "";
|
|
108
|
+
return first.length === 0 ? undefined : first.slice(0, 300);
|
|
109
|
+
} catch {
|
|
110
|
+
return undefined;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** What a step sees of a recorded event: paths to files, never their text. */
|
|
115
|
+
function viewFromPayload(payload: JsonValue): TriggerView | undefined {
|
|
116
|
+
const event = eventFromPayload(payload);
|
|
117
|
+
if (event === undefined || !isRecord(payload)) return undefined;
|
|
118
|
+
return {
|
|
119
|
+
source: event.source,
|
|
120
|
+
key: event.key,
|
|
121
|
+
type: event.type,
|
|
122
|
+
...(event.link === undefined ? {} : { link: event.link }),
|
|
123
|
+
hops: event.hops,
|
|
124
|
+
...(typeof payload.summaryFile === "string"
|
|
125
|
+
? { summary: payload.summaryFile }
|
|
126
|
+
: {}),
|
|
127
|
+
...(typeof payload.dataFile === "string" ? { data: payload.dataFile } : {}),
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** The last step result in a state, as a small summary for the run-end event. */
|
|
132
|
+
function lastStepSummary(state: KernelState): JsonValue {
|
|
133
|
+
const entries = Object.entries(state.results);
|
|
134
|
+
const last = entries[entries.length - 1];
|
|
135
|
+
if (last === undefined) return null;
|
|
136
|
+
const [effectId, value] = last;
|
|
137
|
+
return { step: effectId.split(":")[0] ?? effectId, result: value.result };
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Starts one run through the kernel entry, for callers that do not keep a
|
|
142
|
+
* `Kernel` around. The first four fields are the request; the rest is the
|
|
143
|
+
* environment the kernel needs.
|
|
144
|
+
*/
|
|
145
|
+
export async function start(
|
|
146
|
+
options: StartRequest & KernelOptions,
|
|
147
|
+
): Promise<StartResult> {
|
|
148
|
+
const kernel = new Kernel(options);
|
|
149
|
+
return kernel.start({
|
|
150
|
+
flow: options.flow,
|
|
151
|
+
object: options.object,
|
|
152
|
+
...(options.params === undefined ? {} : { params: options.params }),
|
|
153
|
+
...(options.trigger === undefined ? {} : { trigger: options.trigger }),
|
|
154
|
+
...(options.inputId === undefined ? {} : { inputId: options.inputId }),
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
export class Kernel {
|
|
159
|
+
readonly log: LogBackend;
|
|
160
|
+
readonly registry: PluginRegistry;
|
|
161
|
+
readonly home: string;
|
|
162
|
+
readonly storeRoot: string;
|
|
163
|
+
readonly store: TriggerStore;
|
|
164
|
+
readonly rules: readonly TriggerRule[];
|
|
165
|
+
readonly clock: () => number;
|
|
166
|
+
private readonly onLog: (message: string) => void;
|
|
167
|
+
private readonly runningSources: {
|
|
168
|
+
readonly plugin: string;
|
|
169
|
+
readonly handle: SourceHandle;
|
|
170
|
+
}[] = [];
|
|
171
|
+
/** One in-flight route per input, so same-process callers share a decision. */
|
|
172
|
+
private readonly routing = new Map<string, Promise<TriggerResult>>();
|
|
173
|
+
/** Where `recoverUnrouted` has read the inputs and the outcomes up to. */
|
|
174
|
+
private inputPosition = 0;
|
|
175
|
+
private outcomeSeq = 0;
|
|
176
|
+
/** Events and started candidates whose side effect is not finished yet. */
|
|
177
|
+
private readonly unrouted = new Map<string, InputRecord>();
|
|
178
|
+
private readonly unstarted = new Map<string, InputOutcome>();
|
|
179
|
+
|
|
180
|
+
constructor(options: KernelOptions) {
|
|
181
|
+
this.log = options.log;
|
|
182
|
+
this.registry = options.registry;
|
|
183
|
+
this.home = options.home;
|
|
184
|
+
this.storeRoot = options.storeRoot;
|
|
185
|
+
this.rules = options.rules ?? [];
|
|
186
|
+
this.clock = options.clock ?? (() => Date.now());
|
|
187
|
+
this.onLog = options.onLog ?? ((message) => console.error(message));
|
|
188
|
+
this.store = new TriggerStore({
|
|
189
|
+
root: `${options.storeRoot}/triggers`,
|
|
190
|
+
clock: this.clock,
|
|
191
|
+
});
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** The event a run sees, from the store written when the run started. */
|
|
195
|
+
triggerForRun(runId: string): TriggerView | undefined {
|
|
196
|
+
return this.store.readRunTrigger(runId);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Starts one run. When a trigger is given, its `source`+`key` is recorded
|
|
201
|
+
* first and the run's start fact points at that input; a repeated event
|
|
202
|
+
* returns the first result and starts nothing.
|
|
203
|
+
*/
|
|
204
|
+
async start(request: StartRequest): Promise<StartResult> {
|
|
205
|
+
const found = this.registry.flow(request.flow);
|
|
206
|
+
if (found === undefined) {
|
|
207
|
+
throw new Error(`flow "${request.flow}" is not loaded`);
|
|
208
|
+
}
|
|
209
|
+
if (typeof request.object !== "string" || request.object.length === 0) {
|
|
210
|
+
throw new Error("start: object must be a non-empty string");
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// An input a route or a candidate already claimed: realise that claim,
|
|
214
|
+
// never a second one. The log's first decision is the result.
|
|
215
|
+
if (request.inputId !== undefined) {
|
|
216
|
+
const inputId = request.inputId;
|
|
217
|
+
const input = await this.findInput(inputId);
|
|
218
|
+
const claimed = await this.outcome(inputId, ROUTE);
|
|
219
|
+
if (claimed === undefined) {
|
|
220
|
+
await this.claimRoute(inputId, {
|
|
221
|
+
value: "started",
|
|
222
|
+
flow: request.flow,
|
|
223
|
+
object: request.object,
|
|
224
|
+
...(request.params === undefined ? {} : { params: request.params }),
|
|
225
|
+
...(request.access === undefined ? {} : { access: request.access }),
|
|
226
|
+
});
|
|
227
|
+
}
|
|
228
|
+
return this.startResultFor(inputId, input);
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
const given = request.trigger;
|
|
232
|
+
if (given === undefined) {
|
|
233
|
+
const realized = await this.realizeStart(
|
|
234
|
+
undefined,
|
|
235
|
+
request.flow,
|
|
236
|
+
request.params,
|
|
237
|
+
request.object,
|
|
238
|
+
undefined,
|
|
239
|
+
request.access,
|
|
240
|
+
);
|
|
241
|
+
return { kind: "started", runId: realized.runId, duplicate: false };
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
if (
|
|
245
|
+
!isRecord(given) ||
|
|
246
|
+
typeof given.source !== "string" ||
|
|
247
|
+
typeof given.key !== "string" ||
|
|
248
|
+
typeof given.type !== "string"
|
|
249
|
+
) {
|
|
250
|
+
throw new Error("start: trigger needs a source, a key and a type");
|
|
251
|
+
}
|
|
252
|
+
const hops = given.hops ?? 0;
|
|
253
|
+
const event: TriggerEvent = { ...given, hops };
|
|
254
|
+
const prepared = this.prepareEvent(event);
|
|
255
|
+
const recorded = await this.log.recordInput(
|
|
256
|
+
null,
|
|
257
|
+
event.source,
|
|
258
|
+
event.key,
|
|
259
|
+
prepared.payload,
|
|
260
|
+
);
|
|
261
|
+
const inputId = recorded.inputId;
|
|
262
|
+
const input = await this.findInput(inputId);
|
|
263
|
+
|
|
264
|
+
const claimed = await this.outcome(inputId, ROUTE);
|
|
265
|
+
if (claimed === undefined) {
|
|
266
|
+
await this.claimRoute(inputId, {
|
|
267
|
+
value: "started",
|
|
268
|
+
flow: request.flow,
|
|
269
|
+
object: request.object,
|
|
270
|
+
...(request.params === undefined ? {} : { params: request.params }),
|
|
271
|
+
...(request.access === undefined ? {} : { access: request.access }),
|
|
272
|
+
});
|
|
273
|
+
}
|
|
274
|
+
return this.startResultFor(inputId, input, recorded.duplicate);
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/**
|
|
278
|
+
* Restores the start metadata of a run whose creator died between creating
|
|
279
|
+
* the run and writing it. `serve` does this before it spawns a child, so the
|
|
280
|
+
* child starts from the same input and sees the same event.
|
|
281
|
+
*/
|
|
282
|
+
adoptStart(run: RunInfo): boolean {
|
|
283
|
+
if (this.store.readRunStart(run.runId) !== undefined) return false;
|
|
284
|
+
const pending = this.store.pendingStart(run.flow, run.object, run.startedAt);
|
|
285
|
+
if (pending === undefined) return false;
|
|
286
|
+
if (pending.view !== undefined) {
|
|
287
|
+
this.store.writeRunTrigger(run.runId, pending.view);
|
|
288
|
+
}
|
|
289
|
+
this.store.writeRunStart(run.runId, pending.start);
|
|
290
|
+
this.store.dropPendingStart(pending.id);
|
|
291
|
+
return true;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/** Sends one outside event through the rules. */
|
|
295
|
+
async receive(event: TriggerEvent): Promise<TriggerResult> {
|
|
296
|
+
event = { ...event, hops: event.hops ?? 0 };
|
|
297
|
+
if (
|
|
298
|
+
typeof event.source !== "string" ||
|
|
299
|
+
event.source.length === 0 ||
|
|
300
|
+
typeof event.key !== "string" ||
|
|
301
|
+
event.key.length === 0 ||
|
|
302
|
+
typeof event.type !== "string" ||
|
|
303
|
+
event.type.length === 0
|
|
304
|
+
) {
|
|
305
|
+
throw new Error("event: source, key and type must be non-empty strings");
|
|
306
|
+
}
|
|
307
|
+
if (!Number.isInteger(event.hops) || event.hops < 0) {
|
|
308
|
+
throw new Error("event: hops must be a non-negative integer");
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
const prepared = this.prepareEvent(event);
|
|
312
|
+
const recorded = await this.log.recordInput(
|
|
313
|
+
null,
|
|
314
|
+
event.source,
|
|
315
|
+
event.key,
|
|
316
|
+
prepared.payload,
|
|
317
|
+
);
|
|
318
|
+
return this.route(recorded.inputId, recorded.duplicate);
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/**
|
|
322
|
+
* Routes one event the log already recorded. The claim is written before any
|
|
323
|
+
* side effect, so concurrent callers agree on one decision; the side effect
|
|
324
|
+
* is idempotent on the input id, so a crash between the two is finished by
|
|
325
|
+
* the next pass.
|
|
326
|
+
*/
|
|
327
|
+
private async route(
|
|
328
|
+
inputId: string,
|
|
329
|
+
duplicate: boolean,
|
|
330
|
+
known?: InputRecord,
|
|
331
|
+
): Promise<TriggerResult> {
|
|
332
|
+
const inflight = this.routing.get(inputId);
|
|
333
|
+
if (inflight !== undefined) {
|
|
334
|
+
const result = await inflight;
|
|
335
|
+
return duplicate ? { ...result, duplicate: true } : result;
|
|
336
|
+
}
|
|
337
|
+
const work = this.routeOnce(inputId, known);
|
|
338
|
+
this.routing.set(inputId, work);
|
|
339
|
+
try {
|
|
340
|
+
const result = await work;
|
|
341
|
+
return duplicate ? { ...result, duplicate: true } : result;
|
|
342
|
+
} finally {
|
|
343
|
+
this.routing.delete(inputId);
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/** The work behind one route, shared by concurrent callers. */
|
|
348
|
+
private async routeOnce(
|
|
349
|
+
inputId: string,
|
|
350
|
+
known?: InputRecord,
|
|
351
|
+
): Promise<TriggerResult> {
|
|
352
|
+
const input = known ?? (await this.findInput(inputId));
|
|
353
|
+
if (input === undefined) {
|
|
354
|
+
throw new Error(`input "${inputId}" is not recorded`);
|
|
355
|
+
}
|
|
356
|
+
const event = eventFromPayload(input.payload);
|
|
357
|
+
if (event === undefined) {
|
|
358
|
+
throw new Error(`input "${inputId}" carries no event`);
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
let claimed = await this.outcome(inputId, ROUTE);
|
|
362
|
+
if (claimed === undefined) {
|
|
363
|
+
claimed = await this.claimRoute(
|
|
364
|
+
inputId,
|
|
365
|
+
await this.routeDecision(inputId, event),
|
|
366
|
+
);
|
|
367
|
+
}
|
|
368
|
+
return this.realizeRoute(inputId, input, event, claimed, false);
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
/**
|
|
372
|
+
* Claims the route decision. The first write wins; every concurrent caller
|
|
373
|
+
* and every retry after a crash reads the same stored decision.
|
|
374
|
+
*/
|
|
375
|
+
private async claimRoute(
|
|
376
|
+
inputId: string,
|
|
377
|
+
payload: Record<string, JsonValue>,
|
|
378
|
+
): Promise<InputOutcome> {
|
|
379
|
+
const recorded = await this.log.recordOutcome(inputId, ROUTE, payload);
|
|
380
|
+
return recorded.outcome;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
/** What one recorded event would do, before the claim is written. */
|
|
384
|
+
private async routeDecision(
|
|
385
|
+
inputId: string,
|
|
386
|
+
event: TriggerEvent,
|
|
387
|
+
): Promise<Record<string, JsonValue>> {
|
|
388
|
+
// A run the log says this input started is the decision, even when the
|
|
389
|
+
// process died before it could write one.
|
|
390
|
+
const started = await this.startedRun(inputId);
|
|
391
|
+
if (started !== undefined) {
|
|
392
|
+
return {
|
|
393
|
+
value: "started",
|
|
394
|
+
flow: started.flow,
|
|
395
|
+
object: started.object,
|
|
396
|
+
};
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
if (event.hops > MAX_TRIGGER_HOPS) {
|
|
400
|
+
return {
|
|
401
|
+
value: "skipped",
|
|
402
|
+
reason: `the chain is ${event.hops} hops deep; at most ${MAX_TRIGGER_HOPS} are followed`,
|
|
403
|
+
...(event.object === undefined ? {} : { object: event.object }),
|
|
404
|
+
};
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
const rule = this.match(event);
|
|
408
|
+
if (rule === undefined) {
|
|
409
|
+
return {
|
|
410
|
+
value: "none",
|
|
411
|
+
...(event.object === undefined ? {} : { object: event.object }),
|
|
412
|
+
};
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
const object = this.resolveObject(rule, event);
|
|
416
|
+
if (object === undefined) {
|
|
417
|
+
return {
|
|
418
|
+
value: "none",
|
|
419
|
+
reason: "the rule takes the event's object, but the event has none",
|
|
420
|
+
};
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
const active = await this.activeRun(rule.start.flow, object);
|
|
424
|
+
if (active !== undefined) {
|
|
425
|
+
if (active.startInputId === inputId) {
|
|
426
|
+
return { value: "started", flow: rule.start.flow, object };
|
|
427
|
+
}
|
|
428
|
+
return {
|
|
429
|
+
value: "in_run",
|
|
430
|
+
runId: active.runId,
|
|
431
|
+
flow: active.flow,
|
|
432
|
+
object: active.object,
|
|
433
|
+
};
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
if (rule.mode === "observe") {
|
|
437
|
+
return { value: "observed", flow: rule.start.flow, object };
|
|
438
|
+
}
|
|
439
|
+
if (rule.mode === "candidate") {
|
|
440
|
+
return {
|
|
441
|
+
value: "candidate",
|
|
442
|
+
flow: rule.start.flow,
|
|
443
|
+
object,
|
|
444
|
+
...(rule.start.params === undefined ? {} : { params: rule.start.params }),
|
|
445
|
+
};
|
|
446
|
+
}
|
|
447
|
+
return {
|
|
448
|
+
value: "started",
|
|
449
|
+
flow: rule.start.flow,
|
|
450
|
+
object,
|
|
451
|
+
...(rule.start.params === undefined ? {} : { params: rule.start.params }),
|
|
452
|
+
};
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
/** Finishes the side effect a claimed route decision names. */
|
|
456
|
+
private async realizeRoute(
|
|
457
|
+
inputId: string,
|
|
458
|
+
input: InputRecord,
|
|
459
|
+
event: TriggerEvent,
|
|
460
|
+
outcome: InputOutcome,
|
|
461
|
+
duplicate: boolean,
|
|
462
|
+
): Promise<TriggerResult> {
|
|
463
|
+
const value = valueOf(outcome);
|
|
464
|
+
const flow = field(outcome.payload, "flow");
|
|
465
|
+
const object = field(outcome.payload, "object");
|
|
466
|
+
const base = {
|
|
467
|
+
inputId,
|
|
468
|
+
duplicate,
|
|
469
|
+
...(flow === undefined ? {} : { flow }),
|
|
470
|
+
...(object === undefined ? {} : { object }),
|
|
471
|
+
};
|
|
472
|
+
|
|
473
|
+
switch (value) {
|
|
474
|
+
case "started": {
|
|
475
|
+
if (flow === undefined || object === undefined) {
|
|
476
|
+
return { kind: "recorded", ...base };
|
|
477
|
+
}
|
|
478
|
+
const params = payloadOf(outcome).params;
|
|
479
|
+
const realized = await this.realizeStart(
|
|
480
|
+
inputId,
|
|
481
|
+
flow,
|
|
482
|
+
params,
|
|
483
|
+
object,
|
|
484
|
+
input,
|
|
485
|
+
);
|
|
486
|
+
return {
|
|
487
|
+
kind: realized.kind === "active" ? "active" : "started",
|
|
488
|
+
...base,
|
|
489
|
+
runId: realized.runId,
|
|
490
|
+
};
|
|
491
|
+
}
|
|
492
|
+
case "in_run": {
|
|
493
|
+
const runId = field(outcome.payload, "runId");
|
|
494
|
+
if (runId !== undefined) {
|
|
495
|
+
await this.ensureRunFact(
|
|
496
|
+
runId,
|
|
497
|
+
"trigger_received",
|
|
498
|
+
{
|
|
499
|
+
source: event.source,
|
|
500
|
+
type: event.type,
|
|
501
|
+
key: event.key,
|
|
502
|
+
...(event.summary === undefined ? {} : { summary: event.summary }),
|
|
503
|
+
...(event.link === undefined ? {} : { link: event.link }),
|
|
504
|
+
hops: event.hops,
|
|
505
|
+
},
|
|
506
|
+
inputId,
|
|
507
|
+
);
|
|
508
|
+
}
|
|
509
|
+
return {
|
|
510
|
+
kind: "active",
|
|
511
|
+
...base,
|
|
512
|
+
...(runId === undefined ? {} : { runId }),
|
|
513
|
+
};
|
|
514
|
+
}
|
|
515
|
+
case "observed":
|
|
516
|
+
await this.ensureObservedFact(
|
|
517
|
+
inputId,
|
|
518
|
+
flow ?? "a flow",
|
|
519
|
+
object ?? "an object",
|
|
520
|
+
);
|
|
521
|
+
return { kind: "observed", ...base };
|
|
522
|
+
case "candidate":
|
|
523
|
+
return { kind: "candidate", ...base, pendingId: inputId };
|
|
524
|
+
case "skipped":
|
|
525
|
+
return {
|
|
526
|
+
kind: "skipped",
|
|
527
|
+
...base,
|
|
528
|
+
reason:
|
|
529
|
+
field(outcome.payload, "reason") ?? "the event was not followed",
|
|
530
|
+
};
|
|
531
|
+
default:
|
|
532
|
+
return { kind: "recorded", ...base };
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
/** The candidates still waiting for a person, oldest first. */
|
|
537
|
+
async candidates(): Promise<readonly TriggerCandidate[]> {
|
|
538
|
+
const inputs = new Map<string, InputRecord>();
|
|
539
|
+
for await (const input of this.log.readInputs()) {
|
|
540
|
+
inputs.set(input.inputId, input);
|
|
541
|
+
}
|
|
542
|
+
const resolved = new Set<string>();
|
|
543
|
+
const routes: InputOutcome[] = [];
|
|
544
|
+
for await (const outcome of this.log.readOutcomes()) {
|
|
545
|
+
if (outcome.kind === RESOLVE) resolved.add(outcome.inputId);
|
|
546
|
+
if (outcome.kind === ROUTE && valueOf(outcome) === "candidate") {
|
|
547
|
+
routes.push(outcome);
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
const list: TriggerCandidate[] = [];
|
|
551
|
+
for (const outcome of routes) {
|
|
552
|
+
if (resolved.has(outcome.inputId)) continue;
|
|
553
|
+
const candidate = this.candidateFrom(outcome, inputs.get(outcome.inputId));
|
|
554
|
+
if (candidate !== undefined) list.push(candidate);
|
|
555
|
+
}
|
|
556
|
+
return list.sort(
|
|
557
|
+
(left, right) =>
|
|
558
|
+
left.at - right.at || left.pendingId.localeCompare(right.pendingId),
|
|
559
|
+
);
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
/**
|
|
563
|
+
* Events the rules sent to a flow that cannot start now. Nothing is stored
|
|
564
|
+
* for them: they are read from the route decisions, so they leave this list
|
|
565
|
+
* when the plugin is enabled and the start goes through.
|
|
566
|
+
*/
|
|
567
|
+
async refusedStarts(): Promise<readonly RefusedStart[]> {
|
|
568
|
+
const list: RefusedStart[] = [];
|
|
569
|
+
const runs = await this.log.runs();
|
|
570
|
+
const resolvedStarts = new Set<string>();
|
|
571
|
+
const outcomes: InputOutcome[] = [];
|
|
572
|
+
for await (const outcome of this.log.readOutcomes()) {
|
|
573
|
+
outcomes.push(outcome);
|
|
574
|
+
if (outcome.kind === RESOLVE && valueOf(outcome) === "started") {
|
|
575
|
+
resolvedStarts.add(outcome.inputId);
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
for (const outcome of outcomes) {
|
|
579
|
+
// A route that starts, or a candidate a person already chose to start.
|
|
580
|
+
if (
|
|
581
|
+
outcome.kind !== ROUTE ||
|
|
582
|
+
!(
|
|
583
|
+
valueOf(outcome) === "started" ||
|
|
584
|
+
(valueOf(outcome) === "candidate" && resolvedStarts.has(outcome.inputId))
|
|
585
|
+
)
|
|
586
|
+
) {
|
|
587
|
+
continue;
|
|
588
|
+
}
|
|
589
|
+
const flow = field(outcome.payload, "flow");
|
|
590
|
+
const object = field(outcome.payload, "object");
|
|
591
|
+
if (flow === undefined || object === undefined) continue;
|
|
592
|
+
if (runs.some((run) => run.startInputId === outcome.inputId)) continue;
|
|
593
|
+
const reason = this.registry.startProblem(flow);
|
|
594
|
+
if (reason !== undefined) {
|
|
595
|
+
list.push({ inputId: outcome.inputId, flow, object, reason });
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
return list;
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
/** Cancels a candidate without starting it. */
|
|
602
|
+
async dismiss(pendingId: string): Promise<TriggerCandidate> {
|
|
603
|
+
const route = await this.outcome(pendingId, ROUTE);
|
|
604
|
+
if (route === undefined) {
|
|
605
|
+
throw new Error(`no pending item "${pendingId}"`);
|
|
606
|
+
}
|
|
607
|
+
if (valueOf(route) !== "candidate") {
|
|
608
|
+
throw new Error(
|
|
609
|
+
`pending item "${pendingId}" is already ${valueOf(route) ?? "resolved"}`,
|
|
610
|
+
);
|
|
611
|
+
}
|
|
612
|
+
const input = await this.findInput(pendingId);
|
|
613
|
+
const candidate = this.candidateFrom(route, input);
|
|
614
|
+
if (candidate === undefined) {
|
|
615
|
+
throw new Error(`no pending item "${pendingId}"`);
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
const recorded = await this.log.recordOutcome(
|
|
619
|
+
pendingId,
|
|
620
|
+
RESOLVE,
|
|
621
|
+
{ value: "dismissed", pendingId },
|
|
622
|
+
);
|
|
623
|
+
const resolved = valueOf(recorded.outcome);
|
|
624
|
+
if (resolved === "started") {
|
|
625
|
+
const started = await this.startedRun(pendingId);
|
|
626
|
+
const runId = field(recorded.outcome.payload, "runId") ?? started?.runId;
|
|
627
|
+
throw new Error(
|
|
628
|
+
`pending item "${pendingId}" is already started${runId === undefined ? "" : ` as ${runId}`}`,
|
|
629
|
+
);
|
|
630
|
+
}
|
|
631
|
+
if (resolved !== "dismissed") {
|
|
632
|
+
throw new Error(
|
|
633
|
+
`pending item "${pendingId}" is already ${resolved ?? "resolved"}`,
|
|
634
|
+
);
|
|
635
|
+
}
|
|
636
|
+
return { ...candidate, status: "dismissed" };
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
/** Starts a candidate through the same entry every other start uses. */
|
|
640
|
+
async startCandidate(pendingId: string): Promise<StartResult> {
|
|
641
|
+
const route = await this.outcome(pendingId, ROUTE);
|
|
642
|
+
if (route === undefined) {
|
|
643
|
+
throw new Error(`no pending item "${pendingId}"`);
|
|
644
|
+
}
|
|
645
|
+
if (valueOf(route) !== "candidate") {
|
|
646
|
+
throw new Error(
|
|
647
|
+
`pending item "${pendingId}" is already ${valueOf(route) ?? "resolved"}`,
|
|
648
|
+
);
|
|
649
|
+
}
|
|
650
|
+
const input = await this.findInput(pendingId);
|
|
651
|
+
const candidate = this.candidateFrom(route, input);
|
|
652
|
+
if (candidate === undefined) {
|
|
653
|
+
throw new Error(`no pending item "${pendingId}"`);
|
|
654
|
+
}
|
|
655
|
+
// Refused before the person's choice is recorded, so the candidate stays
|
|
656
|
+
// pending and can be started once the plugin is enabled.
|
|
657
|
+
const problem = this.registry.startProblem(candidate.flow);
|
|
658
|
+
if (problem !== undefined) throw new StartRefusedError(problem);
|
|
659
|
+
|
|
660
|
+
const recorded = await this.log.recordOutcome(
|
|
661
|
+
pendingId,
|
|
662
|
+
RESOLVE,
|
|
663
|
+
{
|
|
664
|
+
value: "started",
|
|
665
|
+
flow: candidate.flow,
|
|
666
|
+
object: candidate.object,
|
|
667
|
+
},
|
|
668
|
+
);
|
|
669
|
+
const resolved = valueOf(recorded.outcome);
|
|
670
|
+
if (resolved === "dismissed") {
|
|
671
|
+
throw new Error(`pending item "${pendingId}" is already dismissed`);
|
|
672
|
+
}
|
|
673
|
+
if (resolved !== "started") {
|
|
674
|
+
throw new Error(
|
|
675
|
+
`pending item "${pendingId}" is already ${resolved ?? "resolved"}`,
|
|
676
|
+
);
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
const realized = await this.realizeStart(
|
|
680
|
+
pendingId,
|
|
681
|
+
candidate.flow,
|
|
682
|
+
candidate.params,
|
|
683
|
+
candidate.object,
|
|
684
|
+
input,
|
|
685
|
+
);
|
|
686
|
+
return {
|
|
687
|
+
kind: realized.kind === "active" ? "active" : "started",
|
|
688
|
+
runId: realized.runId,
|
|
689
|
+
duplicate: recorded.duplicate,
|
|
690
|
+
};
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
/** Ends a run whose flow cannot be found, with a reason that names it. */
|
|
694
|
+
async failRun(runId: string, reason: string): Promise<void> {
|
|
695
|
+
const ended = await endRunDirectly(this.log, runId, "failed", reason);
|
|
696
|
+
if (ended === undefined || ended.status !== "ended") return;
|
|
697
|
+
await this.emitRunEnd(runId, ended);
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
/** Emits the event that ends a run, once per run id. */
|
|
701
|
+
async emitRunEnd(runId: string, state: KernelState): Promise<void> {
|
|
702
|
+
const status = state.endedStatus;
|
|
703
|
+
if (status === null) return;
|
|
704
|
+
const runs = await this.log.runs();
|
|
705
|
+
const run = runs.find((candidate) => candidate.runId === runId);
|
|
706
|
+
if (run === undefined) return;
|
|
707
|
+
const type = `run.${status}`;
|
|
708
|
+
const event: TriggerEvent = {
|
|
709
|
+
source: "operad",
|
|
710
|
+
key: runId,
|
|
711
|
+
type,
|
|
712
|
+
object: run.object,
|
|
713
|
+
hops: state.hops + 1,
|
|
714
|
+
data: {
|
|
715
|
+
result: status,
|
|
716
|
+
summary: lastStepSummary(state),
|
|
717
|
+
},
|
|
718
|
+
};
|
|
719
|
+
// Record the event before ending the run: a crash in between leaves the
|
|
720
|
+
// run active, and the next pass records the same event again (the input
|
|
721
|
+
// store dedupes source+key). A run that is still active would receive the
|
|
722
|
+
// event instead of the rule starting a run on the same object, so the run
|
|
723
|
+
// is ended before the event goes back through the rules.
|
|
724
|
+
const prepared = this.prepareEvent(event);
|
|
725
|
+
const recorded = await this.log.recordInput(
|
|
726
|
+
null,
|
|
727
|
+
event.source,
|
|
728
|
+
event.key,
|
|
729
|
+
prepared.payload,
|
|
730
|
+
);
|
|
731
|
+
const inputId = recorded.inputId;
|
|
732
|
+
await this.log.endRun(runId);
|
|
733
|
+
try {
|
|
734
|
+
await this.route(inputId, recorded.duplicate);
|
|
735
|
+
} catch (error) {
|
|
736
|
+
this.onLog(`run ${runId}: run-end event failed: ${messageOf(error)}`);
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
/**
|
|
741
|
+
* Routes every recorded event whose side effect may not be finished. `serve`
|
|
742
|
+
* calls this once per pass, so a crash anywhere in receiving an event is
|
|
743
|
+
* picked up on the next start. The claim is the guard: routing again can
|
|
744
|
+
* never double a run or a fact.
|
|
745
|
+
*/
|
|
746
|
+
async recoverUnrouted(): Promise<void> {
|
|
747
|
+
// Only what was recorded since the last pass is read; an event whose
|
|
748
|
+
// routing failed stays in `unrouted` and is tried again each pass.
|
|
749
|
+
const fresh = await this.log.readInputsAfter(this.inputPosition);
|
|
750
|
+
for (const input of fresh.inputs) {
|
|
751
|
+
if (input.runId !== null) continue;
|
|
752
|
+
if (eventFromPayload(input.payload) === undefined) continue;
|
|
753
|
+
this.unrouted.set(input.inputId, input);
|
|
754
|
+
}
|
|
755
|
+
for (const [inputId, input] of [...this.unrouted]) {
|
|
756
|
+
try {
|
|
757
|
+
await this.route(inputId, true, input);
|
|
758
|
+
this.unrouted.delete(inputId);
|
|
759
|
+
} catch (error) {
|
|
760
|
+
this.onLog(
|
|
761
|
+
`trigger ${inputId}: event routing failed: ${messageOf(error)}`,
|
|
762
|
+
);
|
|
763
|
+
}
|
|
764
|
+
}
|
|
765
|
+
this.inputPosition = fresh.position;
|
|
766
|
+
|
|
767
|
+
// A candidate a person started, whose run the process never created.
|
|
768
|
+
const resolves = await this.log.readOutcomesAfter(this.outcomeSeq);
|
|
769
|
+
for (const outcome of resolves) {
|
|
770
|
+
this.outcomeSeq = Math.max(this.outcomeSeq, outcome.seq);
|
|
771
|
+
if (outcome.kind === RESOLVE && valueOf(outcome) === "started") {
|
|
772
|
+
this.unstarted.set(outcome.inputId, outcome);
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
for (const [inputId, outcome] of [...this.unstarted]) {
|
|
776
|
+
const route = await this.outcome(inputId, ROUTE);
|
|
777
|
+
if (route === undefined || valueOf(route) !== "candidate") {
|
|
778
|
+
this.unstarted.delete(inputId);
|
|
779
|
+
continue;
|
|
780
|
+
}
|
|
781
|
+
const input = await this.findInput(inputId);
|
|
782
|
+
const candidate = this.candidateFrom(route, input);
|
|
783
|
+
if (candidate === undefined) {
|
|
784
|
+
this.unstarted.delete(inputId);
|
|
785
|
+
continue;
|
|
786
|
+
}
|
|
787
|
+
try {
|
|
788
|
+
await this.realizeStart(
|
|
789
|
+
outcome.inputId,
|
|
790
|
+
candidate.flow,
|
|
791
|
+
candidate.params,
|
|
792
|
+
candidate.object,
|
|
793
|
+
input,
|
|
794
|
+
);
|
|
795
|
+
this.unstarted.delete(inputId);
|
|
796
|
+
} catch (error) {
|
|
797
|
+
this.onLog(
|
|
798
|
+
`trigger ${outcome.inputId}: candidate start failed: ${messageOf(error)}`,
|
|
799
|
+
);
|
|
800
|
+
}
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
/** Handles an event a step emitted; the run scopes the key and sets hops. */
|
|
805
|
+
async emitStep(
|
|
806
|
+
runId: string,
|
|
807
|
+
plugin: string,
|
|
808
|
+
event: StepEvent,
|
|
809
|
+
object: string | undefined,
|
|
810
|
+
): Promise<TriggerResult> {
|
|
811
|
+
if (!event.type.startsWith(`${plugin}.`)) {
|
|
812
|
+
throw new Error(
|
|
813
|
+
`emit: type "${event.type}" must begin with "${plugin}."`,
|
|
814
|
+
);
|
|
815
|
+
}
|
|
816
|
+
const state = await readState(this.log, runId);
|
|
817
|
+
const eventObject = event.object ?? object;
|
|
818
|
+
const trigger: TriggerEvent = {
|
|
819
|
+
source: "operad",
|
|
820
|
+
key: `${runId}:${event.key}`,
|
|
821
|
+
type: event.type,
|
|
822
|
+
...(eventObject === undefined ? {} : { object: eventObject }),
|
|
823
|
+
...(event.summary === undefined ? {} : { summary: event.summary }),
|
|
824
|
+
...(event.data === undefined ? {} : { data: event.data }),
|
|
825
|
+
hops: state.hops + 1,
|
|
826
|
+
};
|
|
827
|
+
const result = await this.receive(trigger);
|
|
828
|
+
if (result.kind === "skipped" && result.reason !== undefined) {
|
|
829
|
+
await this.recordSkip(runId, trigger, result.reason, result.inputId);
|
|
830
|
+
}
|
|
831
|
+
return result;
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
/** Starts every loaded source; a broken one is logged and skipped. */
|
|
835
|
+
async startSources(): Promise<void> {
|
|
836
|
+
const running = await this.registry.startSources({
|
|
837
|
+
rules: this.rules,
|
|
838
|
+
clock: this.clock,
|
|
839
|
+
emit: async (event) => {
|
|
840
|
+
await this.receive(event);
|
|
841
|
+
},
|
|
842
|
+
});
|
|
843
|
+
this.runningSources.push(...running);
|
|
844
|
+
}
|
|
845
|
+
|
|
846
|
+
/** Stops every source. A source that throws while stopping is logged. */
|
|
847
|
+
async stopSources(): Promise<void> {
|
|
848
|
+
const running = this.runningSources.splice(0);
|
|
849
|
+
for (const source of running) {
|
|
850
|
+
try {
|
|
851
|
+
await source.handle.stop();
|
|
852
|
+
} catch (error) {
|
|
853
|
+
this.onLog(
|
|
854
|
+
`plugin "${source.plugin}": stop failed: ${messageOf(error)}`,
|
|
855
|
+
);
|
|
856
|
+
}
|
|
857
|
+
}
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
private match(event: TriggerEvent): TriggerRule | undefined {
|
|
861
|
+
return this.rules.find((rule) => {
|
|
862
|
+
if (rule.source !== event.source || rule.type !== event.type) return false;
|
|
863
|
+
return this.resolveObject(rule, event) !== undefined;
|
|
864
|
+
});
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
private resolveObject(
|
|
868
|
+
rule: TriggerRule,
|
|
869
|
+
event: TriggerEvent,
|
|
870
|
+
): string | undefined {
|
|
871
|
+
if (rule.object === "$event.object") return objectOf(event);
|
|
872
|
+
return rule.object;
|
|
873
|
+
}
|
|
874
|
+
|
|
875
|
+
private async activeRun(
|
|
876
|
+
flow: string,
|
|
877
|
+
object: string,
|
|
878
|
+
): Promise<RunInfo | undefined> {
|
|
879
|
+
const active = await this.log.runs({ active: true });
|
|
880
|
+
return active.find((run) => run.flow === flow && run.object === object);
|
|
881
|
+
}
|
|
882
|
+
|
|
883
|
+
/** Appends a run fact once per input id; a sequence conflict is retried. */
|
|
884
|
+
private async ensureRunFact(
|
|
885
|
+
runId: string,
|
|
886
|
+
kind: string,
|
|
887
|
+
payload: JsonValue,
|
|
888
|
+
inputId: string | undefined,
|
|
889
|
+
): Promise<void> {
|
|
890
|
+
if (inputId === undefined) return;
|
|
891
|
+
for (let attempt = 0; attempt < 8; attempt += 1) {
|
|
892
|
+
// Read the sequence first, then look for the fact: a write that lands
|
|
893
|
+
// between the two is seen by the scan, and a write after it makes the
|
|
894
|
+
// append conflict, so two processes cannot both add the fact.
|
|
895
|
+
const state = await readState(this.log, runId);
|
|
896
|
+
if (state.status === "ended") return;
|
|
897
|
+
let found = false;
|
|
898
|
+
for await (const fact of this.log.read(runId)) {
|
|
899
|
+
if (fact.cause === inputId && fact.kind === kind) {
|
|
900
|
+
found = true;
|
|
901
|
+
break;
|
|
902
|
+
}
|
|
903
|
+
}
|
|
904
|
+
if (found) return;
|
|
905
|
+
try {
|
|
906
|
+
await this.log.append(runId, state.lastSeq, [
|
|
907
|
+
{ kind, payload, cause: inputId },
|
|
908
|
+
]);
|
|
909
|
+
return;
|
|
910
|
+
} catch (error) {
|
|
911
|
+
if (error instanceof SeqConflictError) continue;
|
|
912
|
+
throw error;
|
|
913
|
+
}
|
|
914
|
+
}
|
|
915
|
+
this.onLog(`run ${runId}: could not record ${kind} after a sequence conflict`);
|
|
916
|
+
}
|
|
917
|
+
|
|
918
|
+
/** Writes the "would start" fact once per input id, enforced by the log. */
|
|
919
|
+
private async ensureObservedFact(
|
|
920
|
+
inputId: string,
|
|
921
|
+
flow: string,
|
|
922
|
+
object: string,
|
|
923
|
+
): Promise<void> {
|
|
924
|
+
await this.log.appendGlobal(
|
|
925
|
+
{
|
|
926
|
+
kind: "trigger_observed",
|
|
927
|
+
payload: {
|
|
928
|
+
inputId,
|
|
929
|
+
flow,
|
|
930
|
+
object,
|
|
931
|
+
reason: `would start ${flow} on ${object}`,
|
|
932
|
+
},
|
|
933
|
+
cause: inputId,
|
|
934
|
+
},
|
|
935
|
+
`trigger_observed:${inputId}`,
|
|
936
|
+
);
|
|
937
|
+
}
|
|
938
|
+
|
|
939
|
+
private async recordSkip(
|
|
940
|
+
runId: string,
|
|
941
|
+
event: TriggerEvent,
|
|
942
|
+
reason: string,
|
|
943
|
+
inputId: string | undefined,
|
|
944
|
+
): Promise<void> {
|
|
945
|
+
try {
|
|
946
|
+
await this.ensureRunFact(
|
|
947
|
+
runId,
|
|
948
|
+
"trigger_skipped",
|
|
949
|
+
{
|
|
950
|
+
source: event.source,
|
|
951
|
+
type: event.type,
|
|
952
|
+
key: event.key,
|
|
953
|
+
hops: event.hops,
|
|
954
|
+
reason,
|
|
955
|
+
},
|
|
956
|
+
inputId,
|
|
957
|
+
);
|
|
958
|
+
} catch (error) {
|
|
959
|
+
this.onLog(
|
|
960
|
+
`run ${runId}: could not record a skipped event: ${messageOf(error)}`,
|
|
961
|
+
);
|
|
962
|
+
}
|
|
963
|
+
}
|
|
964
|
+
|
|
965
|
+
/**
|
|
966
|
+
* Writes the event's summary and data files and returns the payload the log
|
|
967
|
+
* keeps: the event fields, with file paths instead of the text itself.
|
|
968
|
+
*/
|
|
969
|
+
private prepareEvent(event: TriggerEvent): {
|
|
970
|
+
readonly inputId: string;
|
|
971
|
+
readonly payload: JsonValue;
|
|
972
|
+
readonly view: TriggerView;
|
|
973
|
+
} {
|
|
974
|
+
const inputId = inputIdFor(event.source, event.key);
|
|
975
|
+
const paths = this.store.eventPaths(inputId);
|
|
976
|
+
const view = this.store.writeEventFiles(inputId, event);
|
|
977
|
+
const payload: JsonValue = {
|
|
978
|
+
source: event.source,
|
|
979
|
+
key: event.key,
|
|
980
|
+
type: event.type,
|
|
981
|
+
hops: event.hops,
|
|
982
|
+
...(event.object === undefined ? {} : { object: event.object }),
|
|
983
|
+
...(event.link === undefined ? {} : { link: event.link }),
|
|
984
|
+
...(event.summary === undefined ? {} : { summaryFile: paths.summary }),
|
|
985
|
+
...(event.data === undefined ? {} : { dataFile: paths.data }),
|
|
986
|
+
};
|
|
987
|
+
return { inputId, payload, view };
|
|
988
|
+
}
|
|
989
|
+
|
|
990
|
+
private async findInput(inputId: string): Promise<InputRecord | undefined> {
|
|
991
|
+
return this.log.findInput(inputId);
|
|
992
|
+
}
|
|
993
|
+
|
|
994
|
+
private async outcome(
|
|
995
|
+
inputId: string,
|
|
996
|
+
kind: string,
|
|
997
|
+
): Promise<InputOutcome | undefined> {
|
|
998
|
+
return this.log.readOutcome(inputId, kind);
|
|
999
|
+
}
|
|
1000
|
+
|
|
1001
|
+
/** A result for an input whose route decision is already claimed. */
|
|
1002
|
+
private async startResultFor(
|
|
1003
|
+
inputId: string,
|
|
1004
|
+
input: InputRecord | undefined,
|
|
1005
|
+
duplicate = true,
|
|
1006
|
+
): Promise<StartResult> {
|
|
1007
|
+
const claimed = await this.outcome(inputId, ROUTE);
|
|
1008
|
+
if (claimed === undefined) {
|
|
1009
|
+
throw new Error(`input "${inputId}" has no route decision`);
|
|
1010
|
+
}
|
|
1011
|
+
const value = valueOf(claimed);
|
|
1012
|
+
const flow = field(claimed.payload, "flow");
|
|
1013
|
+
const object = field(claimed.payload, "object");
|
|
1014
|
+
switch (value) {
|
|
1015
|
+
case "started": {
|
|
1016
|
+
if (flow === undefined || object === undefined) {
|
|
1017
|
+
return { kind: "recorded", duplicate };
|
|
1018
|
+
}
|
|
1019
|
+
const params = payloadOf(claimed).params;
|
|
1020
|
+
const access = payloadOf(claimed).access;
|
|
1021
|
+
const realized = await this.realizeStart(
|
|
1022
|
+
inputId,
|
|
1023
|
+
flow,
|
|
1024
|
+
params,
|
|
1025
|
+
object,
|
|
1026
|
+
input,
|
|
1027
|
+
access,
|
|
1028
|
+
);
|
|
1029
|
+
return {
|
|
1030
|
+
kind: realized.kind === "active" ? "active" : "started",
|
|
1031
|
+
runId: realized.runId,
|
|
1032
|
+
duplicate,
|
|
1033
|
+
};
|
|
1034
|
+
}
|
|
1035
|
+
case "in_run": {
|
|
1036
|
+
const runId = field(claimed.payload, "runId");
|
|
1037
|
+
return runId === undefined
|
|
1038
|
+
? { kind: "recorded", duplicate }
|
|
1039
|
+
: { kind: "active", runId, duplicate };
|
|
1040
|
+
}
|
|
1041
|
+
case "candidate":
|
|
1042
|
+
return { kind: "candidate", pendingId: inputId, duplicate };
|
|
1043
|
+
case "observed":
|
|
1044
|
+
return { kind: "observed", duplicate };
|
|
1045
|
+
case "skipped":
|
|
1046
|
+
return {
|
|
1047
|
+
kind: "skipped",
|
|
1048
|
+
reason:
|
|
1049
|
+
field(claimed.payload, "reason") ?? "the event was not followed",
|
|
1050
|
+
duplicate,
|
|
1051
|
+
};
|
|
1052
|
+
default:
|
|
1053
|
+
return { kind: "recorded", duplicate };
|
|
1054
|
+
}
|
|
1055
|
+
}
|
|
1056
|
+
|
|
1057
|
+
/**
|
|
1058
|
+
* Creates the run for an input at most once. The start files are written
|
|
1059
|
+
* after the run exists, so a recovered run restores them from its pending
|
|
1060
|
+
* start before a child takes over.
|
|
1061
|
+
*/
|
|
1062
|
+
private async realizeStart(
|
|
1063
|
+
inputId: string | undefined,
|
|
1064
|
+
flow: string,
|
|
1065
|
+
params: JsonValue | undefined,
|
|
1066
|
+
object: string,
|
|
1067
|
+
input: InputRecord | undefined,
|
|
1068
|
+
access?: JsonValue,
|
|
1069
|
+
): Promise<{ readonly kind: "started" | "active"; readonly runId: string }> {
|
|
1070
|
+
if (inputId !== undefined) {
|
|
1071
|
+
const existing = await this.startedRun(inputId);
|
|
1072
|
+
if (existing !== undefined) {
|
|
1073
|
+
this.ensureStartFiles(existing, inputId, params, object, input, access);
|
|
1074
|
+
return { kind: "started", runId: existing.runId };
|
|
1075
|
+
}
|
|
1076
|
+
}
|
|
1077
|
+
|
|
1078
|
+
// Nothing is written for a refused start: the claimed event stays
|
|
1079
|
+
// unrealised and is tried again once the plugin is enabled.
|
|
1080
|
+
const problem = this.registry.startProblem(flow);
|
|
1081
|
+
if (problem !== undefined) throw new StartRefusedError(problem);
|
|
1082
|
+
|
|
1083
|
+
const view = input === undefined ? undefined : viewFromPayload(input.payload);
|
|
1084
|
+
const event: TriggerEvent | undefined =
|
|
1085
|
+
view === undefined
|
|
1086
|
+
? undefined
|
|
1087
|
+
: {
|
|
1088
|
+
source: view.source,
|
|
1089
|
+
key: view.key,
|
|
1090
|
+
type: view.type,
|
|
1091
|
+
hops: view.hops,
|
|
1092
|
+
...(view.link === undefined ? {} : { link: view.link }),
|
|
1093
|
+
};
|
|
1094
|
+
const start: StartInput = {
|
|
1095
|
+
kind: "start",
|
|
1096
|
+
...(params === undefined ? {} : { params }),
|
|
1097
|
+
...(access === undefined ? {} : { access }),
|
|
1098
|
+
hops: view?.hops ?? 0,
|
|
1099
|
+
...(event === undefined
|
|
1100
|
+
? {}
|
|
1101
|
+
: { trigger: { source: event.source, type: event.type, key: event.key } }),
|
|
1102
|
+
...(inputId === undefined ? {} : { inputId }),
|
|
1103
|
+
};
|
|
1104
|
+
|
|
1105
|
+
const pendingId = this.store.writePendingStart({
|
|
1106
|
+
flow,
|
|
1107
|
+
object,
|
|
1108
|
+
...(inputId === undefined ? {} : { inputId }),
|
|
1109
|
+
start,
|
|
1110
|
+
...(view === undefined ? {} : { view }),
|
|
1111
|
+
});
|
|
1112
|
+
|
|
1113
|
+
let info: RunInfo;
|
|
1114
|
+
try {
|
|
1115
|
+
info = await this.log.startRun(flow, object, inputId ?? null, access);
|
|
1116
|
+
} catch (error) {
|
|
1117
|
+
if (error instanceof ActiveRunError) {
|
|
1118
|
+
// This start created no run; the record must not be adopted later.
|
|
1119
|
+
this.store.dropPendingStart(pendingId);
|
|
1120
|
+
const active = (await this.log.runs()).find(
|
|
1121
|
+
(run) => run.runId === error.runId,
|
|
1122
|
+
);
|
|
1123
|
+
if (active !== undefined) {
|
|
1124
|
+
if (inputId !== undefined && active.startInputId === inputId) {
|
|
1125
|
+
this.ensureStartFiles(active, inputId, params, object, input, access);
|
|
1126
|
+
return { kind: "started", runId: active.runId };
|
|
1127
|
+
}
|
|
1128
|
+
if (event !== undefined && inputId !== undefined) {
|
|
1129
|
+
await this.ensureRunFact(
|
|
1130
|
+
active.runId,
|
|
1131
|
+
"trigger_received",
|
|
1132
|
+
{
|
|
1133
|
+
source: event.source,
|
|
1134
|
+
type: event.type,
|
|
1135
|
+
key: event.key,
|
|
1136
|
+
...(event.summary === undefined ? {} : { summary: event.summary }),
|
|
1137
|
+
...(event.link === undefined ? {} : { link: event.link }),
|
|
1138
|
+
hops: event.hops,
|
|
1139
|
+
},
|
|
1140
|
+
inputId,
|
|
1141
|
+
);
|
|
1142
|
+
}
|
|
1143
|
+
return { kind: "active", runId: active.runId };
|
|
1144
|
+
}
|
|
1145
|
+
}
|
|
1146
|
+
throw error;
|
|
1147
|
+
}
|
|
1148
|
+
|
|
1149
|
+
// `start.json` is the commit point: it is written last, so a crash before
|
|
1150
|
+
// it lets `adoptStart` redo both files.
|
|
1151
|
+
if (view !== undefined) this.store.writeRunTrigger(info.runId, view);
|
|
1152
|
+
this.store.writeRunStart(info.runId, start);
|
|
1153
|
+
this.store.dropPendingStart(pendingId);
|
|
1154
|
+
return { kind: "started", runId: info.runId };
|
|
1155
|
+
}
|
|
1156
|
+
|
|
1157
|
+
/** Writes a run's start files if they are missing, from its pending start. */
|
|
1158
|
+
private ensureStartFiles(
|
|
1159
|
+
run: RunInfo,
|
|
1160
|
+
inputId: string,
|
|
1161
|
+
params: JsonValue | undefined,
|
|
1162
|
+
object: string,
|
|
1163
|
+
input: InputRecord | undefined,
|
|
1164
|
+
access?: JsonValue,
|
|
1165
|
+
): void {
|
|
1166
|
+
if (this.store.readRunStart(run.runId) !== undefined) return;
|
|
1167
|
+
if (this.adoptStart(run)) return;
|
|
1168
|
+
const view = input === undefined ? undefined : viewFromPayload(input.payload);
|
|
1169
|
+
const start: StartInput = {
|
|
1170
|
+
kind: "start",
|
|
1171
|
+
...(params === undefined ? {} : { params }),
|
|
1172
|
+
...(access === undefined ? {} : { access }),
|
|
1173
|
+
hops: view?.hops ?? 0,
|
|
1174
|
+
...(view === undefined
|
|
1175
|
+
? {}
|
|
1176
|
+
: { trigger: { source: view.source, type: view.type, key: view.key } }),
|
|
1177
|
+
inputId,
|
|
1178
|
+
};
|
|
1179
|
+
if (view !== undefined) this.store.writeRunTrigger(run.runId, view);
|
|
1180
|
+
this.store.writeRunStart(run.runId, start);
|
|
1181
|
+
}
|
|
1182
|
+
|
|
1183
|
+
/** The run the log says this input started, if any. */
|
|
1184
|
+
private async startedRun(inputId: string): Promise<RunInfo | undefined> {
|
|
1185
|
+
const runs = await this.log.runs();
|
|
1186
|
+
return runs.find((run) => run.startInputId === inputId);
|
|
1187
|
+
}
|
|
1188
|
+
|
|
1189
|
+
/** A candidate from a route outcome and the input it points at. */
|
|
1190
|
+
private candidateFrom(
|
|
1191
|
+
outcome: InputOutcome,
|
|
1192
|
+
input: InputRecord | undefined,
|
|
1193
|
+
): TriggerCandidate | undefined {
|
|
1194
|
+
if (valueOf(outcome) !== "candidate" || input === undefined) return undefined;
|
|
1195
|
+
const event = eventFromPayload(input.payload);
|
|
1196
|
+
if (event === undefined) return undefined;
|
|
1197
|
+
const flow = field(outcome.payload, "flow");
|
|
1198
|
+
const object = field(outcome.payload, "object");
|
|
1199
|
+
if (flow === undefined || object === undefined) return undefined;
|
|
1200
|
+
const params = payloadOf(outcome).params;
|
|
1201
|
+
return {
|
|
1202
|
+
pendingId: outcome.inputId,
|
|
1203
|
+
inputId: outcome.inputId,
|
|
1204
|
+
flow,
|
|
1205
|
+
...(params === undefined ? {} : { params }),
|
|
1206
|
+
object,
|
|
1207
|
+
event,
|
|
1208
|
+
status: "pending",
|
|
1209
|
+
at: outcome.time,
|
|
1210
|
+
};
|
|
1211
|
+
}
|
|
1212
|
+
}
|