@mark1russell7/workflow-runner 0.0.0-bootstrap.0 → 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 +36 -1
- package/build/engine-B_0OOo1N.d.ts +229 -0
- package/build/engine-B_0OOo1N.d.ts.map +1 -0
- package/build/index.d.ts +14 -0
- package/build/index.d.ts.map +1 -0
- package/build/index.js +984 -0
- package/build/index.js.map +1 -0
- package/build/service.d.ts +31 -0
- package/build/service.d.ts.map +1 -0
- package/build/service.js +56 -0
- package/build/service.js.map +1 -0
- package/package.json +51 -8
- package/src/engine.ts +662 -0
- package/src/index.ts +14 -0
- package/src/machines.ts +98 -0
- package/src/record.ts +89 -0
- package/src/service.ts +54 -0
package/src/engine.ts
ADDED
|
@@ -0,0 +1,662 @@
|
|
|
1
|
+
import { transitionOn } from "@mark1russell7/algebra";
|
|
2
|
+
import type { Clock } from "@mark1russell7/algebra/clock";
|
|
3
|
+
import { readRecord } from "@mark1russell7/optional/read";
|
|
4
|
+
import { type Cap, type Effect, type Machine, Failure, context, isEnvelope, isRecord, run } from "@mark1russell7/coeval";
|
|
5
|
+
import { canonicalHash } from "@mark1russell7/rigor-generators";
|
|
6
|
+
import { backoffDelay } from "@mark1russell7/service/backoff";
|
|
7
|
+
import { type ProcedureInfo, checkWorkflow, workflowMachine } from "@mark1russell7/workflow";
|
|
8
|
+
import { RUN_MACHINE, STEP_MACHINE } from "./machines.ts";
|
|
9
|
+
import type { Outcome, RunEntry, RunStatus, RunStore, StepStatus, TriggerEvent } from "./record.ts";
|
|
10
|
+
|
|
11
|
+
/** The facts of one procedure for the runner: the facts of the check, and the removal of a second call. */
|
|
12
|
+
export interface RunnerProcedure extends ProcedureInfo {
|
|
13
|
+
/**
|
|
14
|
+
* `true` when the procedure removes a second call with the same key. Then the runner calls again after a crash or a
|
|
15
|
+
* time limit. Without it, an effect with no outcome ends the step as `in-doubt`.
|
|
16
|
+
*/
|
|
17
|
+
readonly idempotent?: boolean;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** One call of a procedure, for the host. */
|
|
21
|
+
export interface ProcedureCall {
|
|
22
|
+
/** The path of the procedure, for example `["git", "clone"]`. */
|
|
23
|
+
readonly procedure: readonly string[];
|
|
24
|
+
/** The inputs. A secret stays a reference: the host reads its value. */
|
|
25
|
+
readonly inputs: Readonly<Record<string, unknown>>;
|
|
26
|
+
/** The idempotency key: the same for each try and each resume of one effect. */
|
|
27
|
+
readonly key: string;
|
|
28
|
+
/** The number of the try, from 1. */
|
|
29
|
+
readonly try: number;
|
|
30
|
+
/** The workspace that runs the workflow. */
|
|
31
|
+
readonly workspace: string;
|
|
32
|
+
/** The signal of the time limit of the step. */
|
|
33
|
+
readonly signal: AbortSignal;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** One question to the grant check. */
|
|
37
|
+
export interface AccessRequest {
|
|
38
|
+
readonly from: string;
|
|
39
|
+
readonly access: "read" | "write";
|
|
40
|
+
readonly target: string;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** The answer of the grant check. */
|
|
44
|
+
export interface AccessAnswer {
|
|
45
|
+
readonly ok: boolean;
|
|
46
|
+
readonly why: string;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** The limits of the runner. A document over a limit is `invalid`, and an outcome over its limit fails its step. */
|
|
50
|
+
export interface RunnerLimits {
|
|
51
|
+
/** The most rows of one matrix. The default is 256. */
|
|
52
|
+
readonly matrix?: number;
|
|
53
|
+
/** The most tries of one step. The default is 10. */
|
|
54
|
+
readonly tries?: number;
|
|
55
|
+
/** The most bytes of one outcome as JSON. The default is 1000000. */
|
|
56
|
+
readonly outcomeBytes?: number;
|
|
57
|
+
/** The most job instances that run at the same time. The default is 8. */
|
|
58
|
+
readonly jobs?: number;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** The ports of the runner. The runner names no host: the host gives each port. */
|
|
62
|
+
export interface RunnerOptions {
|
|
63
|
+
/** The facts of each procedure, by its path with dots. A call of a procedure that is not here is refused. */
|
|
64
|
+
readonly procedures: Readonly<Record<string, RunnerProcedure>>;
|
|
65
|
+
/** The host does one call. A throw is the failure of the call. */
|
|
66
|
+
readonly call: (call: ProcedureCall) => Promise<unknown>;
|
|
67
|
+
/** The grant check. A throw is a refusal. */
|
|
68
|
+
readonly access: (request: AccessRequest) => AccessAnswer | Promise<AccessAnswer>;
|
|
69
|
+
/**
|
|
70
|
+
* The redaction of the host: it removes the value of each secret from a value. The runner gives it each outcome, each
|
|
71
|
+
* error text, each payload and the trigger event, before the record and before a later step reads them.
|
|
72
|
+
*/
|
|
73
|
+
readonly redact: (value: unknown) => unknown;
|
|
74
|
+
/** The store of the records. */
|
|
75
|
+
readonly store: RunStore;
|
|
76
|
+
/** The clock of the time limits and the retry waits. */
|
|
77
|
+
readonly clock: Clock;
|
|
78
|
+
/** The wall time of the record, in milliseconds. The default is `Date.now`. A due time of a retry uses it. */
|
|
79
|
+
readonly wall?: () => number;
|
|
80
|
+
/** The machine of the documents. The default is `workflowMachine()`. */
|
|
81
|
+
readonly machine?: Machine;
|
|
82
|
+
/** The namespaces of calls, besides `procedure`. */
|
|
83
|
+
readonly callNamespaces?: readonly string[];
|
|
84
|
+
/** The limits. */
|
|
85
|
+
readonly limits?: RunnerLimits;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** A request to start a run. */
|
|
89
|
+
export interface StartRequest {
|
|
90
|
+
/** The workflow document. */
|
|
91
|
+
readonly doc: unknown;
|
|
92
|
+
/** The workspace that holds the document, from the store of the host. The field `workspace` of the document must be the same. */
|
|
93
|
+
readonly owner: string;
|
|
94
|
+
/** The event that starts the run. */
|
|
95
|
+
readonly trigger: TriggerEvent;
|
|
96
|
+
/** The inputs of the run. */
|
|
97
|
+
readonly inputs?: Readonly<Record<string, unknown>>;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** The end of a run. */
|
|
101
|
+
export interface RunResult {
|
|
102
|
+
readonly run: string;
|
|
103
|
+
readonly status: RunStatus;
|
|
104
|
+
readonly why: string;
|
|
105
|
+
readonly entries: readonly RunEntry[];
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** The runner of a workflow. */
|
|
109
|
+
export interface WorkflowRunner {
|
|
110
|
+
/** This function gives the run id of a request: the same document, owner and event give the same id. */
|
|
111
|
+
readonly runIdOf: (request: StartRequest) => string;
|
|
112
|
+
/** This function starts a run. A request with a run id that has a record resumes that run. */
|
|
113
|
+
readonly start: (request: StartRequest) => Promise<RunResult>;
|
|
114
|
+
/** This function resumes a run from its record. The record holds the document, thus a changed document makes no change. */
|
|
115
|
+
readonly resume: (run: string) => Promise<RunResult>;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
type Rec = Readonly<Record<string, unknown>>;
|
|
119
|
+
|
|
120
|
+
const fieldsOrEmpty = (value: unknown): Rec => readRecord(value) ?? {};
|
|
121
|
+
const listOf = (value: unknown): readonly unknown[] => (Array.isArray(value) ? value : []);
|
|
122
|
+
const valueOf = (doc: unknown): Rec => (isEnvelope(doc) ? fieldsOrEmpty(doc.value) : {});
|
|
123
|
+
|
|
124
|
+
/** The error of a step that ends it at once: a refusal or a doubt. No retry and no `continue` changes it. */
|
|
125
|
+
class Halt extends Error {
|
|
126
|
+
readonly status: "refused" | "in-doubt";
|
|
127
|
+
|
|
128
|
+
constructor(status: "refused" | "in-doubt", why: string) {
|
|
129
|
+
super(why);
|
|
130
|
+
this.status = status;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** The error of a document part that the runner cannot evaluate. */
|
|
135
|
+
class PartError extends Error {}
|
|
136
|
+
|
|
137
|
+
/** The prior record of a run, as maps for a resume. */
|
|
138
|
+
interface Prior {
|
|
139
|
+
readonly ends: ReadonlyMap<string, Outcome>;
|
|
140
|
+
readonly starts: ReadonlyMap<string, RunEntry & { readonly type: "effect-start" }>;
|
|
141
|
+
readonly steps: ReadonlyMap<string, RunEntry & { readonly type: "step-end" }>;
|
|
142
|
+
readonly jobs: ReadonlyMap<string, RunEntry & { readonly type: "job-end" }>;
|
|
143
|
+
readonly rows: ReadonlyMap<string, readonly unknown[]>;
|
|
144
|
+
readonly states: ReadonlyMap<string, { readonly state: string; readonly runs: number; readonly due?: number }>;
|
|
145
|
+
readonly end?: RunEntry & { readonly type: "end" };
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function priorOf(entries: readonly RunEntry[]): Prior {
|
|
149
|
+
const ends = new Map<string, Outcome>();
|
|
150
|
+
const starts = new Map<string, RunEntry & { readonly type: "effect-start" }>();
|
|
151
|
+
const steps = new Map<string, RunEntry & { readonly type: "step-end" }>();
|
|
152
|
+
const jobs = new Map<string, RunEntry & { readonly type: "job-end" }>();
|
|
153
|
+
const rows = new Map<string, readonly unknown[]>();
|
|
154
|
+
const states = new Map<string, { state: string; runs: number; due?: number }>();
|
|
155
|
+
let end: (RunEntry & { readonly type: "end" }) | undefined;
|
|
156
|
+
for (const entry of entries) {
|
|
157
|
+
if (entry.type === "effect-start") starts.set(entry.at, entry);
|
|
158
|
+
else if (entry.type === "effect-end") ends.set(entry.at, entry.outcome);
|
|
159
|
+
else if (entry.type === "step-end") steps.set(entry.instance, entry);
|
|
160
|
+
else if (entry.type === "job-end") jobs.set(entry.instance, entry);
|
|
161
|
+
else if (entry.type === "rows") rows.set(entry.job, entry.rows);
|
|
162
|
+
else if (entry.type === "transition" && entry.machine === "workflow.step") {
|
|
163
|
+
const was = states.get(entry.instance) ?? { state: "pending", runs: 0 };
|
|
164
|
+
states.set(entry.instance, { state: entry.to, runs: was.runs + (entry.to === "running" ? 1 : 0), ...(entry.due === undefined ? {} : { due: entry.due }) });
|
|
165
|
+
} else if (entry.type === "end") end = entry;
|
|
166
|
+
}
|
|
167
|
+
return { ends, starts, steps, jobs, rows, states, ...(end === undefined ? {} : { end }) };
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** The short hash of a matrix row. The address of a row does not change when the order of the rows changes. */
|
|
171
|
+
function rowKey(row: unknown): string {
|
|
172
|
+
return canonicalHash(row).slice(0, 12);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** The order of the jobs: each job after its needs. A cycle or a missing need gives `undefined`. */
|
|
176
|
+
function jobOrder(jobs: Rec): readonly string[] | undefined {
|
|
177
|
+
const order: string[] = [];
|
|
178
|
+
const state = new Map<string, "open" | "done">();
|
|
179
|
+
const visit = (id: string): boolean => {
|
|
180
|
+
if (state.get(id) === "done") return true;
|
|
181
|
+
if (state.get(id) === "open" || !(id in jobs)) return false;
|
|
182
|
+
state.set(id, "open");
|
|
183
|
+
for (const need of listOf(valueOf(jobs[id])["needs"])) if (typeof need !== "string" || !visit(need)) return false;
|
|
184
|
+
state.set(id, "done");
|
|
185
|
+
order.push(id);
|
|
186
|
+
return true;
|
|
187
|
+
};
|
|
188
|
+
for (const id of Object.keys(jobs)) if (!visit(id)) return undefined;
|
|
189
|
+
return order;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** The problems that make a document `invalid` for the runner, besides the errors of `checkWorkflow`. */
|
|
193
|
+
function runnerProblems(doc: unknown, limits: Required<RunnerLimits>): readonly string[] {
|
|
194
|
+
const problems: string[] = [];
|
|
195
|
+
const jobs = fieldsOrEmpty(valueOf(doc)["jobs"]);
|
|
196
|
+
if (jobOrder(jobs) === undefined) problems.push("The needs of the jobs have a cycle or name no job.");
|
|
197
|
+
for (const [id, job] of Object.entries(jobs)) {
|
|
198
|
+
listOf(valueOf(job)["steps"]).forEach((step, index) => {
|
|
199
|
+
const s = valueOf(step);
|
|
200
|
+
if (typeof s["id"] !== "string") problems.push(`The step ${String(index + 1)} of the job ${id} has no id. The runner addresses each effect by the step id.`);
|
|
201
|
+
const retry = s["retry"];
|
|
202
|
+
if (retry !== undefined) {
|
|
203
|
+
const r = fieldsOrEmpty(retry);
|
|
204
|
+
const tries = r["tries"];
|
|
205
|
+
if (typeof tries !== "number" || !Number.isInteger(tries) || tries < 1 || tries > limits.tries) problems.push(`The retry of the step ${String(s["id"])} of the job ${id} needs tries: a whole number from 1 to ${String(limits.tries)}.`);
|
|
206
|
+
for (const key of ["delay", "factor", "cap"]) if (r[key] !== undefined && (typeof r[key] !== "number" || (r[key] as number) < 0)) problems.push(`The retry ${key} of the step ${String(s["id"])} of the job ${id} must be a number of 0 or more.`);
|
|
207
|
+
}
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
return problems;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** The default value of each input of a document that has one. */
|
|
214
|
+
function defaultsOf(doc: unknown): Record<string, unknown> {
|
|
215
|
+
const out: Record<string, unknown> = {};
|
|
216
|
+
for (const [name, input] of Object.entries(fieldsOrEmpty(valueOf(doc)["inputs"]))) if (isRecord(input) && "default" in input) out[name] = input["default"];
|
|
217
|
+
return out;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
const DEFAULT_LIMITS: Required<RunnerLimits> = { matrix: 256, tries: 10, outcomeBytes: 1_000_000, jobs: 8 };
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* This function makes a runner of workflows. The runner records each run in the store, and each record is the log of
|
|
224
|
+
* a resume. It refuses an effect that the grant check does not permit, and it records each answer.
|
|
225
|
+
*
|
|
226
|
+
* @param options - The ports and the limits.
|
|
227
|
+
* @returns The runner.
|
|
228
|
+
*/
|
|
229
|
+
export function workflowRunner(options: RunnerOptions): WorkflowRunner {
|
|
230
|
+
const machine = options.machine ?? workflowMachine();
|
|
231
|
+
const limits: Required<RunnerLimits> = { ...DEFAULT_LIMITS, ...options.limits };
|
|
232
|
+
const wall = options.wall ?? Date.now;
|
|
233
|
+
const namespaces = ["procedure", ...(options.callNamespaces ?? [])];
|
|
234
|
+
const callCaps: readonly Cap[] = namespaces.map((namespace) => [namespace]);
|
|
235
|
+
|
|
236
|
+
const runIdOf = (request: StartRequest): string =>
|
|
237
|
+
canonicalHash({ doc: canonicalHash(request.doc), owner: request.owner, trigger: { kind: request.trigger.kind, id: request.trigger.id } });
|
|
238
|
+
|
|
239
|
+
async function start(request: StartRequest): Promise<RunResult> {
|
|
240
|
+
const id = runIdOf(request);
|
|
241
|
+
const entries = await options.store.read(id);
|
|
242
|
+
if (entries.length > 0) return resume(id);
|
|
243
|
+
const start: RunEntry = {
|
|
244
|
+
type: "start",
|
|
245
|
+
run: id,
|
|
246
|
+
docHash: canonicalHash(request.doc),
|
|
247
|
+
doc: request.doc,
|
|
248
|
+
owner: request.owner,
|
|
249
|
+
workspace: valueOf(request.doc)["workspace"],
|
|
250
|
+
trigger: options.redact(request.trigger) as TriggerEvent,
|
|
251
|
+
inputs: options.redact({ ...defaultsOf(request.doc), ...request.inputs }),
|
|
252
|
+
time: wall(),
|
|
253
|
+
};
|
|
254
|
+
await options.store.append(id, 0, start);
|
|
255
|
+
return resume(id);
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
async function resume(id: string): Promise<RunResult> {
|
|
259
|
+
const entries = [...(await options.store.read(id))];
|
|
260
|
+
const first = entries[0];
|
|
261
|
+
if (first?.type !== "start") throw new Error(`The run ${id} has no record.`);
|
|
262
|
+
const prior = priorOf(entries);
|
|
263
|
+
if (prior.end !== undefined) return { run: id, status: prior.end.status, why: prior.end.why, entries };
|
|
264
|
+
return new Run(id, first, entries, prior).go();
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/** One run: its writer, its state and its jobs. */
|
|
268
|
+
class Run {
|
|
269
|
+
private tail: Promise<void> = Promise.resolve();
|
|
270
|
+
private runState: string;
|
|
271
|
+
private halt: { readonly status: "refused" | "in-doubt"; readonly why: string } | undefined;
|
|
272
|
+
private failed = false;
|
|
273
|
+
private readonly event: unknown;
|
|
274
|
+
private readonly doc: unknown;
|
|
275
|
+
|
|
276
|
+
private readonly id: string;
|
|
277
|
+
private readonly first: RunEntry & { readonly type: "start" };
|
|
278
|
+
private readonly entries: RunEntry[];
|
|
279
|
+
private readonly prior: Prior;
|
|
280
|
+
|
|
281
|
+
constructor(id: string, first: RunEntry & { readonly type: "start" }, entries: RunEntry[], prior: Prior) {
|
|
282
|
+
this.id = id;
|
|
283
|
+
this.first = first;
|
|
284
|
+
this.entries = entries;
|
|
285
|
+
this.prior = prior;
|
|
286
|
+
this.doc = first.doc;
|
|
287
|
+
let state = "queued";
|
|
288
|
+
for (const entry of entries) if (entry.type === "transition" && entry.machine === "workflow.run") state = entry.to;
|
|
289
|
+
this.runState = state;
|
|
290
|
+
this.event = { name: first.trigger.kind, id: first.trigger.id, data: first.trigger.data ?? null };
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/** This function appends one entry. The appends of one run go in one order, and a conflict stops the run. */
|
|
294
|
+
private write(entry: RunEntry): Promise<void> {
|
|
295
|
+
const next = this.tail.then(async () => {
|
|
296
|
+
await options.store.append(this.id, this.entries.length, entry);
|
|
297
|
+
this.entries.push(entry);
|
|
298
|
+
});
|
|
299
|
+
this.tail = next.catch(() => undefined);
|
|
300
|
+
return next;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
private async move(event: string): Promise<void> {
|
|
304
|
+
const t = transitionOn(RUN_MACHINE, this.runState, event);
|
|
305
|
+
if (t === undefined) throw new Error(`The run machine has no transition on ${event} from ${this.runState}.`);
|
|
306
|
+
await this.write({ type: "transition", machine: "workflow.run", instance: this.id, from: this.runState, on: event, to: t.to, time: wall() });
|
|
307
|
+
this.runState = t.to;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
private async finish(event: string, status: RunStatus, why: string): Promise<RunResult> {
|
|
311
|
+
await this.move(event);
|
|
312
|
+
await this.write({ type: "end", status, why, time: wall() });
|
|
313
|
+
return { run: this.id, status, why, entries: this.entries };
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
private async ask(at: string, access: "read" | "write", target: unknown, from = this.first.owner): Promise<AccessAnswer> {
|
|
317
|
+
let answer: AccessAnswer;
|
|
318
|
+
if (typeof target !== "string" || target === "") answer = { ok: false, why: "The target workspace is not a text." };
|
|
319
|
+
else {
|
|
320
|
+
try {
|
|
321
|
+
const given = await options.access({ from, access, target });
|
|
322
|
+
answer = isRecord(given) && given["ok"] === true ? { ok: true, why: String(given["why"] ?? "") } : { ok: false, why: String(fieldsOrEmpty(given)["why"] ?? "The grant check gave no grant.") };
|
|
323
|
+
} catch (error) {
|
|
324
|
+
answer = { ok: false, why: `The grant check failed: ${error instanceof Error ? error.message : String(error)}` };
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
await this.write({ type: "grant", at, from, access, target: typeof target === "string" ? target : JSON.stringify(target ?? null), ok: answer.ok, why: answer.why, time: wall() });
|
|
328
|
+
return answer;
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
async go(): Promise<RunResult> {
|
|
332
|
+
if (this.runState !== "queued" && this.runState !== "running") {
|
|
333
|
+
// A crash after the last transition of the run and before its end: the end follows the transition.
|
|
334
|
+
const status = this.runState as RunStatus;
|
|
335
|
+
await this.write({ type: "end", status, why: "The record ended after the last transition of the run.", time: wall() });
|
|
336
|
+
return { run: this.id, status, why: "The record ended after the last transition of the run.", entries: this.entries };
|
|
337
|
+
}
|
|
338
|
+
if (this.runState === "queued") {
|
|
339
|
+
const reject = await this.precheck();
|
|
340
|
+
if (reject !== undefined) return reject;
|
|
341
|
+
await this.move("start");
|
|
342
|
+
}
|
|
343
|
+
const jobs = fieldsOrEmpty(valueOf(this.doc)["jobs"]);
|
|
344
|
+
const order = jobOrder(jobs) ?? [];
|
|
345
|
+
const done = new Map<string, { status: StepStatus; outputs: unknown }>();
|
|
346
|
+
const running = new Map<string, Promise<void>>();
|
|
347
|
+
const waiting = [...order];
|
|
348
|
+
while (waiting.length > 0 || running.size > 0) {
|
|
349
|
+
for (const id of [...waiting]) {
|
|
350
|
+
if (running.size >= limits.jobs) break;
|
|
351
|
+
const needs = listOf(valueOf(jobs[id])["needs"]) as readonly string[];
|
|
352
|
+
if (!needs.every((need) => done.has(need))) continue;
|
|
353
|
+
waiting.splice(waiting.indexOf(id), 1);
|
|
354
|
+
const task = this.job(id, jobs[id], needs, done).then((end) => {
|
|
355
|
+
done.set(id, end);
|
|
356
|
+
running.delete(id);
|
|
357
|
+
});
|
|
358
|
+
running.set(id, task);
|
|
359
|
+
}
|
|
360
|
+
if (running.size > 0) await Promise.race(running.values());
|
|
361
|
+
}
|
|
362
|
+
if (this.halt !== undefined) return this.finish(this.halt.status === "refused" ? "refuse" : "doubt", this.halt.status, this.halt.why);
|
|
363
|
+
if (this.failed) return this.finish("fail", "failed", "A job failed.");
|
|
364
|
+
return this.finish("succeed", "succeeded", "Each job succeeded or was skipped.");
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/** The checks before the first effect: the document, the owner and the trigger. */
|
|
368
|
+
private async precheck(): Promise<RunResult | undefined> {
|
|
369
|
+
const problems = [
|
|
370
|
+
...checkWorkflow(this.doc, { machine, procedures: options.procedures, callNamespaces: options.callNamespaces ?? [] })
|
|
371
|
+
.filter((issue) => issue.level === "error")
|
|
372
|
+
.map((issue) => `${issue.code}: ${issue.message}`),
|
|
373
|
+
...runnerProblems(this.doc, limits),
|
|
374
|
+
];
|
|
375
|
+
if (problems.length > 0) return this.finish("reject", "invalid", problems.join(" "));
|
|
376
|
+
if (this.first.workspace !== this.first.owner) {
|
|
377
|
+
return this.finish("refuse", "refused", `The document names the workspace ${JSON.stringify(this.first.workspace)}, and the workspace ${this.first.owner} holds it.`);
|
|
378
|
+
}
|
|
379
|
+
const trigger = this.first.trigger;
|
|
380
|
+
if (trigger.kind === "feed") {
|
|
381
|
+
const answer = await this.ask("trigger", "read", trigger.from);
|
|
382
|
+
if (!answer.ok) return this.finish("refuse", "refused", `The feed cannot read ${String(trigger.from)}: ${answer.why}`);
|
|
383
|
+
}
|
|
384
|
+
if (trigger.kind === "call") {
|
|
385
|
+
const answer = await this.ask("trigger", "write", this.first.owner, typeof trigger.caller === "string" ? trigger.caller : "");
|
|
386
|
+
if (!answer.ok) return this.finish("refuse", "refused", `The caller ${String(trigger.caller)} cannot start a workflow of ${this.first.owner}: ${answer.why}`);
|
|
387
|
+
}
|
|
388
|
+
return undefined;
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/** This function evaluates one part with no capability: a call in it gives `#CAP!`. */
|
|
392
|
+
private async part(doc: unknown, names: Rec): Promise<unknown> {
|
|
393
|
+
if (!isEnvelope(doc)) return doc;
|
|
394
|
+
const ran = await run(machine, doc, context({ names, event: this.event }), { perform: () => {
|
|
395
|
+
throw new Failure({ code: "#CAP!", reason: "Only the field do of a step can call a procedure." });
|
|
396
|
+
} });
|
|
397
|
+
if (!ran.result.ok) throw new PartError(`${ran.result.error.code} ${ran.result.error.reason}`);
|
|
398
|
+
return ran.result.value;
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
private async terms(record: unknown, names: Rec): Promise<Record<string, unknown>> {
|
|
402
|
+
const out: Record<string, unknown> = {};
|
|
403
|
+
for (const [key, doc] of Object.entries(fieldsOrEmpty(isEnvelope(record) && record.type === "record" ? record.value : record))) out[key] = await this.part(doc, names);
|
|
404
|
+
return out;
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
private async job(id: string, job: unknown, needs: readonly string[], done: ReadonlyMap<string, { status: StepStatus; outputs: unknown }>): Promise<{ status: StepStatus; outputs: unknown }> {
|
|
408
|
+
const recorded = this.prior.jobs.get(id);
|
|
409
|
+
if (recorded !== undefined) return { status: recorded.status, outputs: recorded.outputs ?? {} };
|
|
410
|
+
const end = async (status: StepStatus, outputs: unknown = {}): Promise<{ status: StepStatus; outputs: unknown }> => {
|
|
411
|
+
await this.write({ type: "job-end", instance: id, status, ...(outputs === undefined ? {} : { outputs }), time: wall() });
|
|
412
|
+
return { status, outputs };
|
|
413
|
+
};
|
|
414
|
+
const j = valueOf(job);
|
|
415
|
+
if (this.halt !== undefined) return end("cancelled");
|
|
416
|
+
const needNames: Record<string, unknown> = {};
|
|
417
|
+
for (const need of needs) needNames[need] = { result: done.get(need)?.status, outputs: done.get(need)?.outputs ?? {} };
|
|
418
|
+
if (needs.some((need) => done.get(need)?.status !== "succeeded")) return end("skipped");
|
|
419
|
+
const inputs = this.first.inputs;
|
|
420
|
+
try {
|
|
421
|
+
const workflowEnv = await this.terms(valueOf(this.doc)["env"], { inputs });
|
|
422
|
+
const base = { inputs, needs: needNames };
|
|
423
|
+
if (j["if"] !== undefined && (await this.part(j["if"], { ...base, env: workflowEnv })) !== true) return end("skipped");
|
|
424
|
+
let rows = this.prior.rows.get(id);
|
|
425
|
+
if (rows === undefined && j["matrix"] !== undefined) {
|
|
426
|
+
const value = await this.part(j["matrix"], base);
|
|
427
|
+
if (!Array.isArray(value)) throw new PartError("The matrix gives no list of rows.");
|
|
428
|
+
if (value.length > limits.matrix) {
|
|
429
|
+
this.failed = true;
|
|
430
|
+
throw new PartError(`The matrix has ${String(value.length)} rows. The limit is ${String(limits.matrix)}.`);
|
|
431
|
+
}
|
|
432
|
+
rows = value;
|
|
433
|
+
await this.write({ type: "rows", job: id, rows: value, time: wall() });
|
|
434
|
+
}
|
|
435
|
+
const seen = new Map<string, number>();
|
|
436
|
+
const instances = rows === undefined ? [{ key: id, row: undefined }] : rows.map((row) => {
|
|
437
|
+
const hash = rowKey(row);
|
|
438
|
+
const count = (seen.get(hash) ?? 0) + 1;
|
|
439
|
+
seen.set(hash, count);
|
|
440
|
+
return { key: `${id}[${hash}${count > 1 ? `~${String(count)}` : ""}]`, row };
|
|
441
|
+
});
|
|
442
|
+
let status: StepStatus = "succeeded";
|
|
443
|
+
let outputs: unknown = {};
|
|
444
|
+
// The time limit of the job counts from its start in this process. Each step of the job ends by it.
|
|
445
|
+
const deadline = typeof j["timeout"] === "number" ? options.clock.now() + j["timeout"] * 1000 : undefined;
|
|
446
|
+
for (const instance of instances) {
|
|
447
|
+
const ended = await this.instance(instance.key, j, { ...base, ...(instance.row === undefined ? {} : { matrix: instance.row }) }, workflowEnv, deadline);
|
|
448
|
+
if (ended.status !== "succeeded") status = ended.status;
|
|
449
|
+
outputs = ended.outputs;
|
|
450
|
+
}
|
|
451
|
+
if (status !== "succeeded") this.failed = true;
|
|
452
|
+
return end(status, outputs);
|
|
453
|
+
} catch (error) {
|
|
454
|
+
if (!(error instanceof PartError)) throw error;
|
|
455
|
+
this.failed = true;
|
|
456
|
+
return end("failed", { error: error.message });
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
/** One job instance: its steps in order. */
|
|
461
|
+
private async instance(key: string, j: Rec, base: Rec, workflowEnv: Rec, deadline: number | undefined): Promise<{ status: StepStatus; outputs: unknown }> {
|
|
462
|
+
const jobEnv = { ...workflowEnv, ...(await this.terms(j["env"], { ...base, env: workflowEnv })) };
|
|
463
|
+
const steps: Record<string, unknown> = {};
|
|
464
|
+
let failedBefore = false;
|
|
465
|
+
for (const step of listOf(j["steps"])) {
|
|
466
|
+
const s = valueOf(step);
|
|
467
|
+
const instance = `${key}/${String(s["id"])}`;
|
|
468
|
+
const status = await this.step(instance, s, { ...base, env: jobEnv, job: { status: failedBefore ? "failure" : "success" }, steps }, failedBefore, (value) => {
|
|
469
|
+
steps[String(s["id"])] = value;
|
|
470
|
+
}, deadline);
|
|
471
|
+
if (status === "failed" && s["continue"] !== true) failedBefore = true;
|
|
472
|
+
if (status === "timed-out" || status === "cancelled") failedBefore = true;
|
|
473
|
+
if (status === "refused" || status === "in-doubt") return { status, outputs: {} };
|
|
474
|
+
}
|
|
475
|
+
if (failedBefore) return { status: "failed", outputs: {} };
|
|
476
|
+
const outputs = await this.terms(j["outputs"], { ...base, env: jobEnv, steps });
|
|
477
|
+
return { status: "succeeded", outputs: options.redact(outputs) };
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
private async stepMove(instance: string, state: { value: string }, event: string, due?: number): Promise<void> {
|
|
481
|
+
const t = transitionOn(STEP_MACHINE, state.value, event);
|
|
482
|
+
if (t === undefined) throw new Error(`The step machine has no transition on ${event} from ${state.value}.`);
|
|
483
|
+
await this.write({ type: "transition", machine: "workflow.step", instance, from: state.value, on: event, to: t.to, time: wall(), ...(due === undefined ? {} : { due }) });
|
|
484
|
+
state.value = t.to;
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
private async stepEnd(instance: string, status: StepStatus, value?: unknown): Promise<StepStatus> {
|
|
488
|
+
await this.write({ type: "step-end", instance, status, ...(value === undefined ? {} : { value }), time: wall() });
|
|
489
|
+
return status;
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
/** One step: its condition, its tries, its time limit, and the grant check at each effect. */
|
|
493
|
+
private async step(instance: string, s: Rec, names: Rec, failedBefore: boolean, keep: (value: unknown) => void, deadline?: number): Promise<StepStatus> {
|
|
494
|
+
const recorded = this.prior.steps.get(instance);
|
|
495
|
+
if (recorded !== undefined) {
|
|
496
|
+
if (recorded.status === "succeeded") keep(recorded.value);
|
|
497
|
+
return recorded.status;
|
|
498
|
+
}
|
|
499
|
+
const was = this.prior.states.get(instance);
|
|
500
|
+
const state = { value: was?.state ?? "pending" };
|
|
501
|
+
const env = { ...fieldsOrEmpty(names["env"]), ...(await this.terms(s["env"], names)) };
|
|
502
|
+
const scope = { ...names, env };
|
|
503
|
+
if (this.halt !== undefined || (state.value === "pending" && deadline !== undefined && options.clock.now() >= deadline)) {
|
|
504
|
+
await this.stepMove(instance, state, "cancel");
|
|
505
|
+
return this.stepEnd(instance, "cancelled");
|
|
506
|
+
}
|
|
507
|
+
if (state.value !== "pending" && state.value !== "running" && state.value !== "waiting") {
|
|
508
|
+
// A crash after the last transition of the step and before its end: the end follows the transition.
|
|
509
|
+
if (state.value !== "succeeded") return this.stepEnd(instance, state.value as StepStatus, { why: "The record ended after the last transition of the step." });
|
|
510
|
+
const outcome = await this.attempt(instance, s, scope, Math.max(was?.runs ?? 1, 1));
|
|
511
|
+
if (outcome.kind !== "ok") throw new Error(`The step ${instance} succeeded in its record, and its replay gives no value.`);
|
|
512
|
+
const value = options.redact(outcome.value);
|
|
513
|
+
keep(value);
|
|
514
|
+
return this.stepEnd(instance, "succeeded", value);
|
|
515
|
+
}
|
|
516
|
+
if (state.value === "pending") {
|
|
517
|
+
const go = s["if"] === undefined ? !failedBefore : (await this.part(s["if"], scope)) === true;
|
|
518
|
+
if (!go) {
|
|
519
|
+
await this.stepMove(instance, state, "skip");
|
|
520
|
+
return this.stepEnd(instance, "skipped");
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
const retry = fieldsOrEmpty(s["retry"]);
|
|
524
|
+
const tries = typeof retry["tries"] === "number" ? retry["tries"] : 1;
|
|
525
|
+
let attempt = was?.runs ?? 0;
|
|
526
|
+
if (state.value === "waiting") {
|
|
527
|
+
await this.wait((was?.due ?? wall()) - wall());
|
|
528
|
+
await this.stepMove(instance, state, "due");
|
|
529
|
+
} else if (state.value === "pending") {
|
|
530
|
+
await this.stepMove(instance, state, "run");
|
|
531
|
+
attempt += 1;
|
|
532
|
+
}
|
|
533
|
+
// A resume in the state running continues the same try: its effects replay, and an open effect is in doubt.
|
|
534
|
+
if (attempt === 0) attempt = 1;
|
|
535
|
+
for (;;) {
|
|
536
|
+
const outcome = await this.attempt(instance, s, scope, attempt, deadline);
|
|
537
|
+
if (outcome.kind === "ok") {
|
|
538
|
+
await this.stepMove(instance, state, "succeed");
|
|
539
|
+
const value = options.redact(outcome.value);
|
|
540
|
+
keep(value);
|
|
541
|
+
return this.stepEnd(instance, "succeeded", value);
|
|
542
|
+
}
|
|
543
|
+
if (outcome.kind === "halt") {
|
|
544
|
+
this.halt ??= { status: outcome.status, why: outcome.why };
|
|
545
|
+
await this.stepMove(instance, state, outcome.status === "refused" ? "refuse" : "doubt");
|
|
546
|
+
return this.stepEnd(instance, outcome.status, { why: outcome.why });
|
|
547
|
+
}
|
|
548
|
+
if (attempt >= tries || this.halt !== undefined) {
|
|
549
|
+
await this.stepMove(instance, state, outcome.kind === "expired" ? "expire" : "fail");
|
|
550
|
+
return this.stepEnd(instance, outcome.kind === "expired" ? "timed-out" : "failed", { why: outcome.why });
|
|
551
|
+
}
|
|
552
|
+
const delay = backoffDelay({ base: 1000 * Number(retry["delay"] ?? 1), factor: Number(retry["factor"] ?? 2), ...(retry["cap"] === undefined ? {} : { cap: 1000 * Number(retry["cap"]) }) }, attempt);
|
|
553
|
+
await this.stepMove(instance, state, "retry", wall() + delay);
|
|
554
|
+
await this.wait(delay);
|
|
555
|
+
await this.stepMove(instance, state, "due");
|
|
556
|
+
attempt += 1;
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
private wait(ms: number): Promise<void> {
|
|
561
|
+
if (ms <= 0) return Promise.resolve();
|
|
562
|
+
return new Promise((resolve) => options.clock.after(ms, resolve));
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
/** One try of a step. */
|
|
566
|
+
private async attempt(instance: string, s: Rec, scope: Rec, attempt: number, deadline?: number): Promise<{ kind: "ok"; value: unknown } | { kind: "fail" | "expired"; why: string } | { kind: "halt"; status: "refused" | "in-doubt"; why: string }> {
|
|
567
|
+
const controller = new AbortController();
|
|
568
|
+
const own = typeof s["timeout"] === "number" ? s["timeout"] * 1000 : Infinity;
|
|
569
|
+
const left = deadline === undefined ? Infinity : Math.max(0, deadline - options.clock.now());
|
|
570
|
+
const timeout = Math.min(own, left) === Infinity ? undefined : Math.min(own, left);
|
|
571
|
+
let expired = false;
|
|
572
|
+
const cancel = timeout === undefined ? undefined : options.clock.after(timeout, () => {
|
|
573
|
+
expired = true;
|
|
574
|
+
controller.abort(new Error("The time limit of the step ended."));
|
|
575
|
+
});
|
|
576
|
+
const open = new Set<string>();
|
|
577
|
+
let halt: Halt | undefined;
|
|
578
|
+
const perform = async (effect: Effect): Promise<unknown> => {
|
|
579
|
+
try {
|
|
580
|
+
return await this.effect(instance, attempt, effect, controller.signal, open);
|
|
581
|
+
} catch (error) {
|
|
582
|
+
if (error instanceof Halt) halt ??= error;
|
|
583
|
+
throw error;
|
|
584
|
+
}
|
|
585
|
+
};
|
|
586
|
+
try {
|
|
587
|
+
const ran = await run(machine, s["do"], context({ names: scope, event: this.event, caps: callCaps }), { perform, signal: controller.signal });
|
|
588
|
+
if (halt !== undefined) return { kind: "halt", status: halt.status, why: halt.message };
|
|
589
|
+
if (expired) {
|
|
590
|
+
const doubt = [...open].find((at) => !this.idempotent(at));
|
|
591
|
+
if (doubt !== undefined) return { kind: "halt", status: "in-doubt", why: `The time limit ended while the effect ${doubt} ran. Its procedure does not remove a second call.` };
|
|
592
|
+
return { kind: "expired", why: "The time limit of the step ended." };
|
|
593
|
+
}
|
|
594
|
+
if (!ran.result.ok) return { kind: "fail", why: `${ran.result.error.code} ${String(options.redact(ran.result.error.reason))}` };
|
|
595
|
+
return { kind: "ok", value: ran.result.value };
|
|
596
|
+
} finally {
|
|
597
|
+
cancel?.();
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
private readonly procedureAt = new Map<string, string>();
|
|
602
|
+
|
|
603
|
+
private idempotent(at: string): boolean {
|
|
604
|
+
const name = this.procedureAt.get(at);
|
|
605
|
+
return name !== undefined && options.procedures[name]?.idempotent === true;
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
/** One effect: the replay of its record, or the grant check and the live call. */
|
|
609
|
+
private async effect(instance: string, attempt: number, effect: Effect, signal: AbortSignal, open: Set<string>): Promise<unknown> {
|
|
610
|
+
const address = effect.address ?? `#${String(effect.index)}`;
|
|
611
|
+
const at = `${instance}@${String(attempt)}/${address}`;
|
|
612
|
+
const key = `${this.id}/${instance}/${address}`;
|
|
613
|
+
const ended = this.prior.ends.get(at);
|
|
614
|
+
if (ended !== undefined) {
|
|
615
|
+
if (ended.ok) return ended.value;
|
|
616
|
+
throw new Failure({ code: ended.code as `#${string}`, reason: ended.why });
|
|
617
|
+
}
|
|
618
|
+
const refuse = async (why: string): Promise<never> => {
|
|
619
|
+
await this.write({ type: "effect-end", at, outcome: { ok: false, code: "#GRANT!", why }, time: wall() });
|
|
620
|
+
throw new Halt("refused", why);
|
|
621
|
+
};
|
|
622
|
+
const namespace = String(effect.path[0]);
|
|
623
|
+
if (!namespaces.includes(namespace)) return refuse(`The effect ${effect.kind} is not a call.`);
|
|
624
|
+
const name = (namespace === "procedure" ? effect.path.slice(1) : effect.path).map(String).join(".");
|
|
625
|
+
this.procedureAt.set(at, name);
|
|
626
|
+
const info = options.procedures[name];
|
|
627
|
+
if (info === undefined) return refuse(`No procedure ${name} is known, thus no grant covers it.`);
|
|
628
|
+
if (!isRecord(effect.payload)) return refuse(`The inputs of ${name} are not a record.`);
|
|
629
|
+
const payload = effect.payload;
|
|
630
|
+
for (const access of ["read", "write"] as const) {
|
|
631
|
+
for (const input of info.workspaces?.[access] ?? []) {
|
|
632
|
+
const answer = await this.ask(at, access, payload[input]);
|
|
633
|
+
if (!answer.ok) return refuse(`The workspace ${this.first.owner} cannot ${access} ${JSON.stringify(payload[input] ?? null)} (the input ${input} of ${name}): ${answer.why}`);
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
if (this.prior.starts.has(at) && info.idempotent !== true) {
|
|
637
|
+
throw new Halt("in-doubt", `The effect ${at} started before and has no outcome. The procedure ${name} does not remove a second call.`);
|
|
638
|
+
}
|
|
639
|
+
if (!this.prior.starts.has(at)) {
|
|
640
|
+
await this.write({ type: "effect-start", at, key, try: attempt, procedure: name, payload: options.redact(payload), time: wall() });
|
|
641
|
+
}
|
|
642
|
+
open.add(at);
|
|
643
|
+
let outcome: Outcome;
|
|
644
|
+
try {
|
|
645
|
+
const value = options.redact(await options.call({ procedure: name.split("."), inputs: payload, key, try: attempt, workspace: this.first.owner, signal }));
|
|
646
|
+
const bytes = JSON.stringify(value ?? null).length;
|
|
647
|
+
outcome = bytes > limits.outcomeBytes ? { ok: false, code: "#SIZE!", why: `The outcome has ${String(bytes)} bytes. The limit is ${String(limits.outcomeBytes)}.` } : { ok: true, value: value ?? null };
|
|
648
|
+
} catch (error) {
|
|
649
|
+
if (signal.aborted) throw error;
|
|
650
|
+
const code = error instanceof Failure ? error.error.code : "#CALL!";
|
|
651
|
+
const why = error instanceof Failure ? error.error.reason : error instanceof Error ? error.message : String(error);
|
|
652
|
+
outcome = { ok: false, code, why: String(options.redact(why)) };
|
|
653
|
+
}
|
|
654
|
+
await this.write({ type: "effect-end", at, outcome, time: wall() });
|
|
655
|
+
open.delete(at);
|
|
656
|
+
if (outcome.ok) return outcome.value;
|
|
657
|
+
throw new Failure({ code: outcome.code as `#${string}`, reason: outcome.why });
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
return { runIdOf, start, resume };
|
|
662
|
+
}
|