@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,483 @@
|
|
|
1
|
+
/** The kernel loop: one per operad home, one child process per run. */
|
|
2
|
+
|
|
3
|
+
import { ActiveRunError, SeqConflictError } from "../log/errors.ts";
|
|
4
|
+
import type { InputRecord, JsonValue, LogBackend } from "../log/types.ts";
|
|
5
|
+
import { StartRefusedError } from "../plugin/errors.ts";
|
|
6
|
+
import type { PluginRegistry } from "../plugin/registry.ts";
|
|
7
|
+
import type { RunLookup, StartRunRequest } from "../plugin/types.ts";
|
|
8
|
+
import type { Input, PersonAnswerInput } from "../kernel/types.ts";
|
|
9
|
+
import { Kernel } from "../trigger/kernel.ts";
|
|
10
|
+
import { loadTriggerRules } from "../trigger/rules.ts";
|
|
11
|
+
import type { TriggerRule } from "../trigger/types.ts";
|
|
12
|
+
import { acquireLock, lockHeld, runLockPath, serveLockPath } from "../runner/lock.ts";
|
|
13
|
+
import type { LockHandle } from "../runner/lock.ts";
|
|
14
|
+
import { StepLimits } from "../runner/limits.ts";
|
|
15
|
+
import { applyInput, objectKey, parseObjectKey, readState } from "../runner/service.ts";
|
|
16
|
+
import { reapStale } from "../platform/step-reap.ts";
|
|
17
|
+
import { isRecord } from "../util.ts";
|
|
18
|
+
|
|
19
|
+
export interface SpawnRunOptions {
|
|
20
|
+
/** The previous process died mid-step; recover before doing anything else. */
|
|
21
|
+
readonly recover: boolean;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export type SpawnRun = (
|
|
25
|
+
runId: string,
|
|
26
|
+
options: SpawnRunOptions,
|
|
27
|
+
) => void | Promise<void>;
|
|
28
|
+
|
|
29
|
+
export interface ServePassOptions {
|
|
30
|
+
readonly log: LogBackend;
|
|
31
|
+
readonly registry: PluginRegistry;
|
|
32
|
+
readonly spawnRun: SpawnRun;
|
|
33
|
+
readonly lockRoot: string;
|
|
34
|
+
readonly clock?: (() => number) | undefined;
|
|
35
|
+
readonly isRunnerAlive?: ((runId: string) => boolean) | undefined;
|
|
36
|
+
readonly isRecentlySpawned?: ((runId: string) => boolean) | undefined;
|
|
37
|
+
readonly shouldStop?: (() => boolean) | undefined;
|
|
38
|
+
/** Where a refused start or recovery is reported. */
|
|
39
|
+
readonly onLog?: ((message: string) => void) | undefined;
|
|
40
|
+
/** When given, every start request goes through this kernel entry point. */
|
|
41
|
+
readonly kernel?: Kernel | undefined;
|
|
42
|
+
/** The operad home; defaults to the registry's home. */
|
|
43
|
+
readonly home?: string | undefined;
|
|
44
|
+
/** Where trigger metadata lives; defaults to `lockRoot`. */
|
|
45
|
+
readonly storeRoot?: string | undefined;
|
|
46
|
+
/** Rules for a kernel built when `kernel` is omitted. */
|
|
47
|
+
readonly rules?: readonly TriggerRule[] | undefined;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export interface ServePassResult {
|
|
51
|
+
readonly started: readonly string[];
|
|
52
|
+
readonly spawned: readonly string[];
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function startObjectKey(request: StartRunRequest): string {
|
|
56
|
+
const key = objectKey(request.object);
|
|
57
|
+
return key === "flow" ? `flow:${request.plugin}/${request.flow}` : key;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** The answer a recorded input carries, or undefined for another input. */
|
|
61
|
+
function recordedAnswer(payload: JsonValue): PersonAnswerInput | undefined {
|
|
62
|
+
if (!isRecord(payload) || payload.kind !== "person_answer") return undefined;
|
|
63
|
+
const waitId = payload.waitId;
|
|
64
|
+
const choice = payload.choice;
|
|
65
|
+
const actor = payload.actor;
|
|
66
|
+
if (
|
|
67
|
+
typeof waitId !== "string" ||
|
|
68
|
+
typeof choice !== "string" ||
|
|
69
|
+
!isRecord(actor) ||
|
|
70
|
+
typeof actor.via !== "string" ||
|
|
71
|
+
typeof actor.id !== "string"
|
|
72
|
+
) {
|
|
73
|
+
return undefined;
|
|
74
|
+
}
|
|
75
|
+
return {
|
|
76
|
+
kind: "person_answer",
|
|
77
|
+
waitId,
|
|
78
|
+
choice,
|
|
79
|
+
...(typeof payload.note === "string" ? { note: payload.note } : {}),
|
|
80
|
+
actor: { via: actor.via, id: actor.id },
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** The kernel facts a plugin's tick may ask about. */
|
|
85
|
+
function runLookup(log: LogBackend): RunLookup {
|
|
86
|
+
return {
|
|
87
|
+
active: async (object) => {
|
|
88
|
+
const runs = await log.runs({ active: true });
|
|
89
|
+
return object === undefined
|
|
90
|
+
? runs
|
|
91
|
+
: runs.filter((run) => run.object === object);
|
|
92
|
+
},
|
|
93
|
+
state: async (runId) => {
|
|
94
|
+
try {
|
|
95
|
+
return await readState(log, runId);
|
|
96
|
+
} catch {
|
|
97
|
+
return undefined;
|
|
98
|
+
}
|
|
99
|
+
},
|
|
100
|
+
lastStep: async (runId) => {
|
|
101
|
+
let step: string | null = null;
|
|
102
|
+
try {
|
|
103
|
+
for await (const fact of log.read(runId)) {
|
|
104
|
+
if (
|
|
105
|
+
fact.kind === "step_entered" &&
|
|
106
|
+
isRecord(fact.payload) &&
|
|
107
|
+
fact.payload.kind !== "end" &&
|
|
108
|
+
typeof fact.payload.step === "string"
|
|
109
|
+
) {
|
|
110
|
+
step = fact.payload.step;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
} catch {
|
|
114
|
+
return null;
|
|
115
|
+
}
|
|
116
|
+
return step;
|
|
117
|
+
},
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
interface AnswerProgress {
|
|
122
|
+
position: number;
|
|
123
|
+
readonly waiting: Map<
|
|
124
|
+
string,
|
|
125
|
+
{ readonly record: InputRecord; readonly input: PersonAnswerInput }
|
|
126
|
+
>;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** What each serving kernel has read of the inputs, and what still waits. */
|
|
130
|
+
const answerProgress = new WeakMap<Kernel, AnswerProgress>();
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Applies answers another process only recorded. The input record is the
|
|
134
|
+
* hand-off: `serve` is the one process that may decide what the answer means
|
|
135
|
+
* and start the step it requests. A repeated record is applied once.
|
|
136
|
+
*/
|
|
137
|
+
async function applyRecordedAnswers(options: {
|
|
138
|
+
readonly log: LogBackend;
|
|
139
|
+
readonly registry: PluginRegistry;
|
|
140
|
+
readonly kernel: Kernel;
|
|
141
|
+
readonly clock: () => number;
|
|
142
|
+
readonly shouldStop?: (() => boolean) | undefined;
|
|
143
|
+
}): Promise<void> {
|
|
144
|
+
// Only the inputs recorded since the last pass are read. An answer stays in
|
|
145
|
+
// `waiting` until it is applied or can no longer be: a run that has ended
|
|
146
|
+
// takes no answer, so the answers of past runs are never looked at again.
|
|
147
|
+
const progress = answerProgress.get(options.kernel) ?? {
|
|
148
|
+
position: 0,
|
|
149
|
+
waiting: new Map<string, { record: InputRecord; input: PersonAnswerInput }>(),
|
|
150
|
+
};
|
|
151
|
+
answerProgress.set(options.kernel, progress);
|
|
152
|
+
const fresh = await options.log.readInputsAfter(progress.position);
|
|
153
|
+
progress.position = fresh.position;
|
|
154
|
+
for (const record of fresh.inputs) {
|
|
155
|
+
if (record.runId === null) continue;
|
|
156
|
+
const input = recordedAnswer(record.payload);
|
|
157
|
+
if (input !== undefined) progress.waiting.set(record.inputId, { record, input });
|
|
158
|
+
}
|
|
159
|
+
if (progress.waiting.size === 0) return;
|
|
160
|
+
|
|
161
|
+
const runs = new Map(
|
|
162
|
+
(await options.log.runs({ active: true })).map((run) => [run.runId, run]),
|
|
163
|
+
);
|
|
164
|
+
const answers = [...progress.waiting.values()];
|
|
165
|
+
const appliedByRun = new Map<string, Set<string>>();
|
|
166
|
+
const appliedFor = async (runId: string): Promise<Set<string>> => {
|
|
167
|
+
const cached = appliedByRun.get(runId);
|
|
168
|
+
if (cached !== undefined) return cached;
|
|
169
|
+
const applied = new Set<string>();
|
|
170
|
+
try {
|
|
171
|
+
for await (const fact of options.log.read(runId)) {
|
|
172
|
+
if (typeof fact.cause === "string") applied.add(fact.cause);
|
|
173
|
+
}
|
|
174
|
+
} catch {
|
|
175
|
+
// A run that cannot be read is left to the runner's own recovery.
|
|
176
|
+
}
|
|
177
|
+
appliedByRun.set(runId, applied);
|
|
178
|
+
return applied;
|
|
179
|
+
};
|
|
180
|
+
|
|
181
|
+
for (const { record, input } of answers) {
|
|
182
|
+
if (options.shouldStop?.() === true) return;
|
|
183
|
+
const runId = record.runId;
|
|
184
|
+
if (runId === null) continue;
|
|
185
|
+
const run = runs.get(runId);
|
|
186
|
+
if (run === undefined) {
|
|
187
|
+
progress.waiting.delete(record.inputId);
|
|
188
|
+
continue;
|
|
189
|
+
}
|
|
190
|
+
const flow = options.registry.flow(run.flow);
|
|
191
|
+
if (flow === undefined) continue;
|
|
192
|
+
const applied = await appliedFor(runId);
|
|
193
|
+
if (applied.has(record.inputId)) {
|
|
194
|
+
progress.waiting.delete(record.inputId);
|
|
195
|
+
continue;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
for (let attempt = 0; ; attempt += 1) {
|
|
199
|
+
let state;
|
|
200
|
+
try {
|
|
201
|
+
state = await readState(options.log, runId);
|
|
202
|
+
} catch {
|
|
203
|
+
break;
|
|
204
|
+
}
|
|
205
|
+
if (
|
|
206
|
+
state.status !== "waiting_person" ||
|
|
207
|
+
state.wait === null ||
|
|
208
|
+
state.wait.id !== input.waitId
|
|
209
|
+
) {
|
|
210
|
+
progress.waiting.delete(record.inputId);
|
|
211
|
+
break;
|
|
212
|
+
}
|
|
213
|
+
const withId: Input = { ...input, inputId: record.inputId };
|
|
214
|
+
try {
|
|
215
|
+
await applyInput(
|
|
216
|
+
options.log,
|
|
217
|
+
flow.flow,
|
|
218
|
+
runId,
|
|
219
|
+
state,
|
|
220
|
+
withId,
|
|
221
|
+
options.clock(),
|
|
222
|
+
"person",
|
|
223
|
+
`answer:${input.waitId}:${input.choice}`,
|
|
224
|
+
{
|
|
225
|
+
beforeEnd: async (endedRunId, ended) => {
|
|
226
|
+
await options.kernel.emitRunEnd(endedRunId, ended);
|
|
227
|
+
},
|
|
228
|
+
},
|
|
229
|
+
);
|
|
230
|
+
applied.add(record.inputId);
|
|
231
|
+
progress.waiting.delete(record.inputId);
|
|
232
|
+
break;
|
|
233
|
+
} catch (error) {
|
|
234
|
+
if (error instanceof SeqConflictError && attempt < 2) continue;
|
|
235
|
+
throw error;
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* One pass: tick every plugin, start the runs they asked for, and give every
|
|
243
|
+
* active run without a live process a child of its own.
|
|
244
|
+
*/
|
|
245
|
+
export async function serveOnce(
|
|
246
|
+
options: ServePassOptions,
|
|
247
|
+
): Promise<ServePassResult> {
|
|
248
|
+
const clock = options.clock ?? (() => Date.now());
|
|
249
|
+
const isRunnerAlive =
|
|
250
|
+
options.isRunnerAlive ??
|
|
251
|
+
((runId: string) => lockHeld(runLockPath(options.lockRoot, runId)));
|
|
252
|
+
const home = options.home ?? options.registry.home;
|
|
253
|
+
let rules = options.rules;
|
|
254
|
+
if (options.kernel === undefined && rules === undefined) {
|
|
255
|
+
try {
|
|
256
|
+
rules = await loadTriggerRules({ home, registry: options.registry });
|
|
257
|
+
} catch {
|
|
258
|
+
// A broken rule file must not stop the loop; the CLI reports it.
|
|
259
|
+
rules = [];
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
const kernel =
|
|
263
|
+
options.kernel ??
|
|
264
|
+
new Kernel({
|
|
265
|
+
log: options.log,
|
|
266
|
+
registry: options.registry,
|
|
267
|
+
home,
|
|
268
|
+
storeRoot: options.storeRoot ?? options.lockRoot,
|
|
269
|
+
rules: rules ?? [],
|
|
270
|
+
});
|
|
271
|
+
const started: string[] = [];
|
|
272
|
+
const spawned: string[] = [];
|
|
273
|
+
|
|
274
|
+
await options.registry.tick(runLookup(options.log));
|
|
275
|
+
const requests = options.registry.takeStartedRuns();
|
|
276
|
+
for (const request of requests) {
|
|
277
|
+
if (options.shouldStop?.() === true) break;
|
|
278
|
+
const object = startObjectKey(request);
|
|
279
|
+
try {
|
|
280
|
+
const result = await kernel.start({
|
|
281
|
+
flow: request.flow,
|
|
282
|
+
object,
|
|
283
|
+
...(request.params === undefined ? {} : { params: request.params }),
|
|
284
|
+
...(request.trigger === undefined ? {} : { trigger: request.trigger }),
|
|
285
|
+
...(request.inputId === undefined ? {} : { inputId: request.inputId }),
|
|
286
|
+
...(request.access === undefined ? {} : { access: request.access }),
|
|
287
|
+
});
|
|
288
|
+
if (result.kind === "started") started.push(result.runId);
|
|
289
|
+
} catch (error) {
|
|
290
|
+
if (error instanceof StartRefusedError) {
|
|
291
|
+
options.onLog?.(`${request.plugin}/${request.flow}: ${error.message}`);
|
|
292
|
+
} else if (!(error instanceof ActiveRunError)) throw error;
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
if (options.shouldStop?.() !== true) {
|
|
297
|
+
await applyRecordedAnswers({
|
|
298
|
+
log: options.log,
|
|
299
|
+
registry: options.registry,
|
|
300
|
+
kernel,
|
|
301
|
+
clock,
|
|
302
|
+
...(options.shouldStop === undefined
|
|
303
|
+
? {}
|
|
304
|
+
: { shouldStop: options.shouldStop }),
|
|
305
|
+
});
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
// Places freed while no process was left to hand them on (a crash after a
|
|
309
|
+
// step's result, a run that ended) go to the next in line before runs are
|
|
310
|
+
// given processes.
|
|
311
|
+
if (options.shouldStop?.() !== true) {
|
|
312
|
+
await new StepLimits({ log: options.log, lockRoot: options.lockRoot }).grant();
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
const active = await options.log.runs({ active: true });
|
|
316
|
+
for (const run of active) {
|
|
317
|
+
if (options.shouldStop?.() === true) break;
|
|
318
|
+
const state = await readState(options.log, run.runId);
|
|
319
|
+
|
|
320
|
+
if (state.status === "ended") {
|
|
321
|
+
// Recording the end event comes first; `emitRunEnd` ends the run before
|
|
322
|
+
// routing it, so a recovered run can start the same flow on the object.
|
|
323
|
+
await kernel.emitRunEnd(run.runId, state);
|
|
324
|
+
continue;
|
|
325
|
+
}
|
|
326
|
+
if (state.status === "waiting_person") continue;
|
|
327
|
+
|
|
328
|
+
// A run no loaded plugin declares has no graph to drive it. It fails now,
|
|
329
|
+
// naming its flow, instead of sitting at starting while a child retries.
|
|
330
|
+
if (options.registry.flow(run.flow) === undefined) {
|
|
331
|
+
const reason = `flow "${run.flow}" is not loaded`;
|
|
332
|
+
options.onLog?.(`run ${run.runId}: ${reason}`);
|
|
333
|
+
await kernel.failRun(run.runId, reason);
|
|
334
|
+
continue;
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
const now = clock();
|
|
338
|
+
if (
|
|
339
|
+
state.effect?.kind === "schedule_wake" &&
|
|
340
|
+
state.effect.due !== null &&
|
|
341
|
+
now < state.effect.due
|
|
342
|
+
) {
|
|
343
|
+
continue;
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
if (isRunnerAlive(run.runId)) continue;
|
|
347
|
+
if (options.isRecentlySpawned?.(run.runId) === true) continue;
|
|
348
|
+
|
|
349
|
+
// A step the flow needs went missing: the run waits for the plugin.
|
|
350
|
+
const problem = options.registry.startProblem(run.flow);
|
|
351
|
+
if (problem !== undefined) {
|
|
352
|
+
options.onLog?.(`run ${run.runId}: ${problem}`);
|
|
353
|
+
continue;
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
// A start that died after creating its run must not become a run with no
|
|
357
|
+
// record of the event that made it: restore the start files first, so the
|
|
358
|
+
// child starts from the intended input and sees the same event.
|
|
359
|
+
kernel.adoptStart(run);
|
|
360
|
+
|
|
361
|
+
await options.spawnRun(run.runId, {
|
|
362
|
+
recover:
|
|
363
|
+
state.status === "running" &&
|
|
364
|
+
state.effect !== null &&
|
|
365
|
+
state.effectStarted === state.effect.id,
|
|
366
|
+
});
|
|
367
|
+
spawned.push(run.runId);
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
// A recorded event whose routing was interrupted is routed again. Outcomes
|
|
371
|
+
// are derived from the log by input id, so a second pass cannot repeat one.
|
|
372
|
+
if (options.shouldStop?.() !== true) {
|
|
373
|
+
await kernel.recoverUnrouted();
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
return { started, spawned };
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
export interface ServeOptions extends Omit<ServePassOptions, "shouldStop"> {
|
|
380
|
+
readonly home: string;
|
|
381
|
+
/** The home lock, when the caller already holds it; `serve` releases it. */
|
|
382
|
+
readonly lock?: LockHandle | undefined;
|
|
383
|
+
/** Called after each pass; it must not wait for slow work. */
|
|
384
|
+
readonly onPass?: (() => void) | undefined;
|
|
385
|
+
readonly intervalMs?: number | undefined;
|
|
386
|
+
readonly signal?: AbortSignal | undefined;
|
|
387
|
+
readonly sleep?:
|
|
388
|
+
| ((ms: number, signal?: AbortSignal) => Promise<void>)
|
|
389
|
+
| undefined;
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
/** Waits `ms`, but a signal abort ends the wait at once. */
|
|
393
|
+
export function sleepUntilAborted(
|
|
394
|
+
ms: number,
|
|
395
|
+
signal?: AbortSignal,
|
|
396
|
+
): Promise<void> {
|
|
397
|
+
return new Promise((resolve) => {
|
|
398
|
+
if (signal?.aborted === true) {
|
|
399
|
+
resolve();
|
|
400
|
+
return;
|
|
401
|
+
}
|
|
402
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
403
|
+
const done = (): void => {
|
|
404
|
+
if (timer !== undefined) clearTimeout(timer);
|
|
405
|
+
signal?.removeEventListener("abort", done);
|
|
406
|
+
resolve();
|
|
407
|
+
};
|
|
408
|
+
timer = setTimeout(done, ms);
|
|
409
|
+
signal?.addEventListener("abort", done, { once: true });
|
|
410
|
+
});
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
/**
|
|
414
|
+
* Runs passes until the signal aborts. A child is never killed: an interrupted
|
|
415
|
+
* loop leaves it running, and the next loop picks the run up again.
|
|
416
|
+
*/
|
|
417
|
+
export async function serve(options: ServeOptions): Promise<void> {
|
|
418
|
+
const lock =
|
|
419
|
+
options.lock ??
|
|
420
|
+
acquireLock(serveLockPath(options.home), {
|
|
421
|
+
clock: options.clock,
|
|
422
|
+
});
|
|
423
|
+
const intervalMs = options.intervalMs ?? 1_000;
|
|
424
|
+
const sleep = options.sleep ?? sleepUntilAborted;
|
|
425
|
+
const clock = options.clock ?? (() => Date.now());
|
|
426
|
+
const spawnedAt = new Map<string, number>();
|
|
427
|
+
let stopped = options.signal?.aborted === true;
|
|
428
|
+
const stop = (): void => {
|
|
429
|
+
stopped = true;
|
|
430
|
+
};
|
|
431
|
+
options.signal?.addEventListener("abort", stop, { once: true });
|
|
432
|
+
|
|
433
|
+
// A change another process made marks the loop, so it takes one more pass
|
|
434
|
+
// before sleeping again. Writes this pass makes itself must not keep the
|
|
435
|
+
// loop busy, so they are ignored while a pass is running.
|
|
436
|
+
let inPass = false;
|
|
437
|
+
let woken = false;
|
|
438
|
+
const unsubscribe = options.log.subscribe?.(() => {
|
|
439
|
+
if (!inPass) woken = true;
|
|
440
|
+
});
|
|
441
|
+
|
|
442
|
+
try {
|
|
443
|
+
// A serve that died left the processes of its steps running: the runs that
|
|
444
|
+
// are no longer active have none to keep.
|
|
445
|
+
try {
|
|
446
|
+
const active = await options.log.runs({ active: true });
|
|
447
|
+
await reapStale({
|
|
448
|
+
home: options.home,
|
|
449
|
+
activeRunIds: active.map((run) => run.runId),
|
|
450
|
+
log: (message) => options.onLog?.(message),
|
|
451
|
+
});
|
|
452
|
+
} catch (error) {
|
|
453
|
+
options.onLog?.(`serve start: could not look for left-over processes: ${error instanceof Error ? error.message : String(error)}`);
|
|
454
|
+
}
|
|
455
|
+
while (!stopped) {
|
|
456
|
+
inPass = true;
|
|
457
|
+
const result = await serveOnce({
|
|
458
|
+
...options,
|
|
459
|
+
shouldStop: () => stopped,
|
|
460
|
+
isRecentlySpawned: (runId) => {
|
|
461
|
+
const at = spawnedAt.get(runId);
|
|
462
|
+
return at !== undefined && clock() - at < intervalMs * 2;
|
|
463
|
+
},
|
|
464
|
+
});
|
|
465
|
+
inPass = false;
|
|
466
|
+
options.onPass?.();
|
|
467
|
+
const now = clock();
|
|
468
|
+
for (const runId of result.spawned) spawnedAt.set(runId, now);
|
|
469
|
+
if (stopped) break;
|
|
470
|
+
if (woken) {
|
|
471
|
+
woken = false;
|
|
472
|
+
continue;
|
|
473
|
+
}
|
|
474
|
+
await sleep(intervalMs, options.signal);
|
|
475
|
+
}
|
|
476
|
+
} finally {
|
|
477
|
+
unsubscribe?.();
|
|
478
|
+
options.signal?.removeEventListener("abort", stop);
|
|
479
|
+
lock.release();
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
export { parseObjectKey };
|