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