@mark1russell7/workflow-runner 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/build/index.js ADDED
@@ -0,0 +1,984 @@
1
+ import { transitionOn } from "@mark1russell7/algebra";
2
+ import { readRecord } from "@mark1russell7/optional/read";
3
+ import { Failure, context, isEnvelope, isRecord, run } from "@mark1russell7/coeval";
4
+ import { canonicalHash } from "@mark1russell7/rigor-generators";
5
+ import { backoffDelay } from "@mark1russell7/service/backoff";
6
+ import { checkWorkflow, workflowMachine } from "@mark1russell7/workflow";
7
+ // src/machines.ts
8
+ const SOURCES = [{
9
+ ref: "docs/WORKFLOW.md#the-runner-w4",
10
+ rung: "implemented",
11
+ note: "D225"
12
+ }];
13
+ /**
14
+ * The state machine of a run. A run is queued, then it runs. It ends with one status. The runner records each
15
+ * transition, and a test checks the record against this machine.
16
+ */
17
+ const RUN_MACHINE = {
18
+ format: "mark1russell7.machine/1",
19
+ id: "workflow.run",
20
+ title: "The run of a workflow",
21
+ layer: "self",
22
+ version: "1.0.0",
23
+ sources: SOURCES,
24
+ states: {
25
+ queued: { initial: true },
26
+ running: {},
27
+ succeeded: { final: true },
28
+ failed: { final: true },
29
+ refused: {
30
+ final: true,
31
+ note: "A grant, an owner or a check refused the run. No later effect happened."
32
+ },
33
+ invalid: {
34
+ final: true,
35
+ note: "The document has an error. No effect happened."
36
+ },
37
+ "in-doubt": {
38
+ final: true,
39
+ note: "An effect started and has no outcome, and its procedure does not remove a second call."
40
+ },
41
+ cancelled: { final: true }
42
+ },
43
+ events: {
44
+ start: { kind: "app" },
45
+ succeed: { kind: "local" },
46
+ fail: { kind: "local" },
47
+ refuse: { kind: "local" },
48
+ reject: { kind: "local" },
49
+ doubt: { kind: "local" },
50
+ cancel: { kind: "app" }
51
+ },
52
+ knobs: {},
53
+ timers: {},
54
+ transitions: [
55
+ {
56
+ id: "start",
57
+ from: "queued",
58
+ to: "running",
59
+ on: "start"
60
+ },
61
+ {
62
+ id: "reject",
63
+ from: "queued",
64
+ to: "invalid",
65
+ on: "reject"
66
+ },
67
+ {
68
+ id: "refuse-early",
69
+ from: "queued",
70
+ to: "refused",
71
+ on: "refuse"
72
+ },
73
+ {
74
+ id: "succeed",
75
+ from: "running",
76
+ to: "succeeded",
77
+ on: "succeed"
78
+ },
79
+ {
80
+ id: "fail",
81
+ from: "running",
82
+ to: "failed",
83
+ on: "fail"
84
+ },
85
+ {
86
+ id: "refuse",
87
+ from: "running",
88
+ to: "refused",
89
+ on: "refuse"
90
+ },
91
+ {
92
+ id: "doubt",
93
+ from: "running",
94
+ to: "in-doubt",
95
+ on: "doubt"
96
+ },
97
+ {
98
+ id: "cancel",
99
+ from: ["queued", "running"],
100
+ to: "cancelled",
101
+ on: "cancel"
102
+ }
103
+ ]
104
+ };
105
+ /**
106
+ * The state machine of one step of one job instance. A failed try waits for its retry. A refusal and a doubt end the
107
+ * step at once: no retry and no `continue` changes them.
108
+ */
109
+ const STEP_MACHINE = {
110
+ format: "mark1russell7.machine/1",
111
+ id: "workflow.step",
112
+ title: "The step of a job",
113
+ layer: "self",
114
+ version: "1.0.0",
115
+ sources: SOURCES,
116
+ states: {
117
+ pending: { initial: true },
118
+ running: {},
119
+ waiting: { note: "A try failed. The next try starts at the due time of the record." },
120
+ succeeded: { final: true },
121
+ skipped: { final: true },
122
+ failed: { final: true },
123
+ "timed-out": { final: true },
124
+ refused: { final: true },
125
+ "in-doubt": { final: true },
126
+ cancelled: { final: true }
127
+ },
128
+ events: {
129
+ run: { kind: "local" },
130
+ skip: { kind: "local" },
131
+ succeed: { kind: "local" },
132
+ fail: { kind: "local" },
133
+ retry: { kind: "local" },
134
+ due: { kind: "timer" },
135
+ expire: { kind: "timer" },
136
+ refuse: { kind: "local" },
137
+ doubt: { kind: "local" },
138
+ cancel: { kind: "app" }
139
+ },
140
+ knobs: {},
141
+ timers: {},
142
+ transitions: [
143
+ {
144
+ id: "run",
145
+ from: "pending",
146
+ to: "running",
147
+ on: "run"
148
+ },
149
+ {
150
+ id: "skip",
151
+ from: "pending",
152
+ to: "skipped",
153
+ on: "skip"
154
+ },
155
+ {
156
+ id: "succeed",
157
+ from: "running",
158
+ to: "succeeded",
159
+ on: "succeed"
160
+ },
161
+ {
162
+ id: "fail",
163
+ from: "running",
164
+ to: "failed",
165
+ on: "fail"
166
+ },
167
+ {
168
+ id: "retry",
169
+ from: "running",
170
+ to: "waiting",
171
+ on: "retry"
172
+ },
173
+ {
174
+ id: "due",
175
+ from: "waiting",
176
+ to: "running",
177
+ on: "due"
178
+ },
179
+ {
180
+ id: "expire",
181
+ from: "running",
182
+ to: "timed-out",
183
+ on: "expire"
184
+ },
185
+ {
186
+ id: "refuse",
187
+ from: ["pending", "running"],
188
+ to: "refused",
189
+ on: "refuse"
190
+ },
191
+ {
192
+ id: "doubt",
193
+ from: ["pending", "running"],
194
+ to: "in-doubt",
195
+ on: "doubt"
196
+ },
197
+ {
198
+ id: "cancel",
199
+ from: [
200
+ "pending",
201
+ "running",
202
+ "waiting"
203
+ ],
204
+ to: "cancelled",
205
+ on: "cancel"
206
+ }
207
+ ]
208
+ };
209
+ // src/engine.ts
210
+ const fieldsOrEmpty = (value) => readRecord(value) ?? {};
211
+ const listOf = (value) => Array.isArray(value) ? value : [];
212
+ const valueOf = (doc) => isEnvelope(doc) ? fieldsOrEmpty(doc.value) : {};
213
+ /** The error of a step that ends it at once: a refusal or a doubt. No retry and no `continue` changes it. */
214
+ var Halt = class extends Error {
215
+ status;
216
+ constructor(status, why) {
217
+ super(why);
218
+ this.status = status;
219
+ }
220
+ };
221
+ /** The error of a document part that the runner cannot evaluate. */
222
+ var PartError = class extends Error {};
223
+ function priorOf(entries) {
224
+ const ends = /* @__PURE__ */ new Map();
225
+ const starts = /* @__PURE__ */ new Map();
226
+ const steps = /* @__PURE__ */ new Map();
227
+ const jobs = /* @__PURE__ */ new Map();
228
+ const rows = /* @__PURE__ */ new Map();
229
+ const states = /* @__PURE__ */ new Map();
230
+ let end;
231
+ for (const entry of entries) if (entry.type === "effect-start") starts.set(entry.at, entry);
232
+ else if (entry.type === "effect-end") ends.set(entry.at, entry.outcome);
233
+ else if (entry.type === "step-end") steps.set(entry.instance, entry);
234
+ else if (entry.type === "job-end") jobs.set(entry.instance, entry);
235
+ else if (entry.type === "rows") rows.set(entry.job, entry.rows);
236
+ else if (entry.type === "transition" && entry.machine === "workflow.step") {
237
+ const was = states.get(entry.instance) ?? {
238
+ state: "pending",
239
+ runs: 0
240
+ };
241
+ states.set(entry.instance, {
242
+ state: entry.to,
243
+ runs: was.runs + (entry.to === "running" ? 1 : 0),
244
+ ...entry.due === void 0 ? {} : { due: entry.due }
245
+ });
246
+ } else if (entry.type === "end") end = entry;
247
+ return {
248
+ ends,
249
+ starts,
250
+ steps,
251
+ jobs,
252
+ rows,
253
+ states,
254
+ ...end === void 0 ? {} : { end }
255
+ };
256
+ }
257
+ /** The short hash of a matrix row. The address of a row does not change when the order of the rows changes. */
258
+ function rowKey(row) {
259
+ return canonicalHash(row).slice(0, 12);
260
+ }
261
+ /** The order of the jobs: each job after its needs. A cycle or a missing need gives `undefined`. */
262
+ function jobOrder(jobs) {
263
+ const order = [];
264
+ const state = /* @__PURE__ */ new Map();
265
+ const visit = (id) => {
266
+ if (state.get(id) === "done") return true;
267
+ if (state.get(id) === "open" || !(id in jobs)) return false;
268
+ state.set(id, "open");
269
+ for (const need of listOf(valueOf(jobs[id])["needs"])) if (typeof need !== "string" || !visit(need)) return false;
270
+ state.set(id, "done");
271
+ order.push(id);
272
+ return true;
273
+ };
274
+ for (const id of Object.keys(jobs)) if (!visit(id)) return void 0;
275
+ return order;
276
+ }
277
+ /** The problems that make a document `invalid` for the runner, besides the errors of `checkWorkflow`. */
278
+ function runnerProblems(doc, limits) {
279
+ const problems = [];
280
+ const jobs = fieldsOrEmpty(valueOf(doc)["jobs"]);
281
+ if (jobOrder(jobs) === void 0) problems.push("The needs of the jobs have a cycle or name no job.");
282
+ for (const [id, job] of Object.entries(jobs)) listOf(valueOf(job)["steps"]).forEach((step, index) => {
283
+ const s = valueOf(step);
284
+ 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.`);
285
+ const retry = s["retry"];
286
+ if (retry !== void 0) {
287
+ const r = fieldsOrEmpty(retry);
288
+ const tries = r["tries"];
289
+ 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)}.`);
290
+ for (const key of [
291
+ "delay",
292
+ "factor",
293
+ "cap"
294
+ ]) if (r[key] !== void 0 && (typeof r[key] !== "number" || r[key] < 0)) problems.push(`The retry ${key} of the step ${String(s["id"])} of the job ${id} must be a number of 0 or more.`);
295
+ }
296
+ });
297
+ return problems;
298
+ }
299
+ /** The default value of each input of a document that has one. */
300
+ function defaultsOf(doc) {
301
+ const out = {};
302
+ for (const [name, input] of Object.entries(fieldsOrEmpty(valueOf(doc)["inputs"]))) if (isRecord(input) && "default" in input) out[name] = input["default"];
303
+ return out;
304
+ }
305
+ const DEFAULT_LIMITS = {
306
+ matrix: 256,
307
+ tries: 10,
308
+ outcomeBytes: 1e6,
309
+ jobs: 8
310
+ };
311
+ /**
312
+ * This function makes a runner of workflows. The runner records each run in the store, and each record is the log of
313
+ * a resume. It refuses an effect that the grant check does not permit, and it records each answer.
314
+ *
315
+ * @param options - The ports and the limits.
316
+ * @returns The runner.
317
+ */
318
+ function workflowRunner(options) {
319
+ const machine = options.machine ?? workflowMachine();
320
+ const limits = {
321
+ ...DEFAULT_LIMITS,
322
+ ...options.limits
323
+ };
324
+ const wall = options.wall ?? Date.now;
325
+ const namespaces = ["procedure", ...options.callNamespaces ?? []];
326
+ const callCaps = namespaces.map((namespace) => [namespace]);
327
+ const runIdOf = (request) => canonicalHash({
328
+ doc: canonicalHash(request.doc),
329
+ owner: request.owner,
330
+ trigger: {
331
+ kind: request.trigger.kind,
332
+ id: request.trigger.id
333
+ }
334
+ });
335
+ async function start(request) {
336
+ const id = runIdOf(request);
337
+ if ((await options.store.read(id)).length > 0) return resume(id);
338
+ const start = {
339
+ type: "start",
340
+ run: id,
341
+ docHash: canonicalHash(request.doc),
342
+ doc: request.doc,
343
+ owner: request.owner,
344
+ workspace: valueOf(request.doc)["workspace"],
345
+ trigger: options.redact(request.trigger),
346
+ inputs: options.redact({
347
+ ...defaultsOf(request.doc),
348
+ ...request.inputs
349
+ }),
350
+ time: wall()
351
+ };
352
+ await options.store.append(id, 0, start);
353
+ return resume(id);
354
+ }
355
+ async function resume(id) {
356
+ const entries = [...await options.store.read(id)];
357
+ const first = entries[0];
358
+ if (first?.type !== "start") throw new Error(`The run ${id} has no record.`);
359
+ const prior = priorOf(entries);
360
+ if (prior.end !== void 0) return {
361
+ run: id,
362
+ status: prior.end.status,
363
+ why: prior.end.why,
364
+ entries
365
+ };
366
+ return new Run(id, first, entries, prior).go();
367
+ }
368
+ /** One run: its writer, its state and its jobs. */
369
+ class Run {
370
+ tail = Promise.resolve();
371
+ runState;
372
+ halt;
373
+ failed = false;
374
+ event;
375
+ doc;
376
+ id;
377
+ first;
378
+ entries;
379
+ prior;
380
+ constructor(id, first, entries, prior) {
381
+ this.id = id;
382
+ this.first = first;
383
+ this.entries = entries;
384
+ this.prior = prior;
385
+ this.doc = first.doc;
386
+ let state = "queued";
387
+ for (const entry of entries) if (entry.type === "transition" && entry.machine === "workflow.run") state = entry.to;
388
+ this.runState = state;
389
+ this.event = {
390
+ name: first.trigger.kind,
391
+ id: first.trigger.id,
392
+ data: first.trigger.data ?? null
393
+ };
394
+ }
395
+ /** This function appends one entry. The appends of one run go in one order, and a conflict stops the run. */
396
+ write(entry) {
397
+ const next = this.tail.then(async () => {
398
+ await options.store.append(this.id, this.entries.length, entry);
399
+ this.entries.push(entry);
400
+ });
401
+ this.tail = next.catch(() => void 0);
402
+ return next;
403
+ }
404
+ async move(event) {
405
+ const t = transitionOn(RUN_MACHINE, this.runState, event);
406
+ if (t === void 0) throw new Error(`The run machine has no transition on ${event} from ${this.runState}.`);
407
+ await this.write({
408
+ type: "transition",
409
+ machine: "workflow.run",
410
+ instance: this.id,
411
+ from: this.runState,
412
+ on: event,
413
+ to: t.to,
414
+ time: wall()
415
+ });
416
+ this.runState = t.to;
417
+ }
418
+ async finish(event, status, why) {
419
+ await this.move(event);
420
+ await this.write({
421
+ type: "end",
422
+ status,
423
+ why,
424
+ time: wall()
425
+ });
426
+ return {
427
+ run: this.id,
428
+ status,
429
+ why,
430
+ entries: this.entries
431
+ };
432
+ }
433
+ async ask(at, access, target, from = this.first.owner) {
434
+ let answer;
435
+ if (typeof target !== "string" || target === "") answer = {
436
+ ok: false,
437
+ why: "The target workspace is not a text."
438
+ };
439
+ else try {
440
+ const given = await options.access({
441
+ from,
442
+ access,
443
+ target
444
+ });
445
+ answer = isRecord(given) && given["ok"] === true ? {
446
+ ok: true,
447
+ why: String(given["why"] ?? "")
448
+ } : {
449
+ ok: false,
450
+ why: String(fieldsOrEmpty(given)["why"] ?? "The grant check gave no grant.")
451
+ };
452
+ } catch (error) {
453
+ answer = {
454
+ ok: false,
455
+ why: `The grant check failed: ${error instanceof Error ? error.message : String(error)}`
456
+ };
457
+ }
458
+ await this.write({
459
+ type: "grant",
460
+ at,
461
+ from,
462
+ access,
463
+ target: typeof target === "string" ? target : JSON.stringify(target ?? null),
464
+ ok: answer.ok,
465
+ why: answer.why,
466
+ time: wall()
467
+ });
468
+ return answer;
469
+ }
470
+ async go() {
471
+ if (this.runState !== "queued" && this.runState !== "running") {
472
+ const status = this.runState;
473
+ await this.write({
474
+ type: "end",
475
+ status,
476
+ why: "The record ended after the last transition of the run.",
477
+ time: wall()
478
+ });
479
+ return {
480
+ run: this.id,
481
+ status,
482
+ why: "The record ended after the last transition of the run.",
483
+ entries: this.entries
484
+ };
485
+ }
486
+ if (this.runState === "queued") {
487
+ const reject = await this.precheck();
488
+ if (reject !== void 0) return reject;
489
+ await this.move("start");
490
+ }
491
+ const jobs = fieldsOrEmpty(valueOf(this.doc)["jobs"]);
492
+ const order = jobOrder(jobs) ?? [];
493
+ const done = /* @__PURE__ */ new Map();
494
+ const running = /* @__PURE__ */ new Map();
495
+ const waiting = [...order];
496
+ while (waiting.length > 0 || running.size > 0) {
497
+ for (const id of [...waiting]) {
498
+ if (running.size >= limits.jobs) break;
499
+ const needs = listOf(valueOf(jobs[id])["needs"]);
500
+ if (!needs.every((need) => done.has(need))) continue;
501
+ waiting.splice(waiting.indexOf(id), 1);
502
+ const task = this.job(id, jobs[id], needs, done).then((end) => {
503
+ done.set(id, end);
504
+ running.delete(id);
505
+ });
506
+ running.set(id, task);
507
+ }
508
+ if (running.size > 0) await Promise.race(running.values());
509
+ }
510
+ if (this.halt !== void 0) return this.finish(this.halt.status === "refused" ? "refuse" : "doubt", this.halt.status, this.halt.why);
511
+ if (this.failed) return this.finish("fail", "failed", "A job failed.");
512
+ return this.finish("succeed", "succeeded", "Each job succeeded or was skipped.");
513
+ }
514
+ /** The checks before the first effect: the document, the owner and the trigger. */
515
+ async precheck() {
516
+ const problems = [...checkWorkflow(this.doc, {
517
+ machine,
518
+ procedures: options.procedures,
519
+ callNamespaces: options.callNamespaces ?? []
520
+ }).filter((issue) => issue.level === "error").map((issue) => `${issue.code}: ${issue.message}`), ...runnerProblems(this.doc, limits)];
521
+ if (problems.length > 0) return this.finish("reject", "invalid", problems.join(" "));
522
+ if (this.first.workspace !== this.first.owner) return this.finish("refuse", "refused", `The document names the workspace ${JSON.stringify(this.first.workspace)}, and the workspace ${this.first.owner} holds it.`);
523
+ const trigger = this.first.trigger;
524
+ if (trigger.kind === "feed") {
525
+ const answer = await this.ask("trigger", "read", trigger.from);
526
+ if (!answer.ok) return this.finish("refuse", "refused", `The feed cannot read ${String(trigger.from)}: ${answer.why}`);
527
+ }
528
+ if (trigger.kind === "call") {
529
+ const answer = await this.ask("trigger", "write", this.first.owner, typeof trigger.caller === "string" ? trigger.caller : "");
530
+ if (!answer.ok) return this.finish("refuse", "refused", `The caller ${String(trigger.caller)} cannot start a workflow of ${this.first.owner}: ${answer.why}`);
531
+ }
532
+ }
533
+ /** This function evaluates one part with no capability: a call in it gives `#CAP!`. */
534
+ async part(doc, names) {
535
+ if (!isEnvelope(doc)) return doc;
536
+ const ran = await run(machine, doc, context({
537
+ names,
538
+ event: this.event
539
+ }), { perform: () => {
540
+ throw new Failure({
541
+ code: "#CAP!",
542
+ reason: "Only the field do of a step can call a procedure."
543
+ });
544
+ } });
545
+ if (!ran.result.ok) throw new PartError(`${ran.result.error.code} ${ran.result.error.reason}`);
546
+ return ran.result.value;
547
+ }
548
+ async terms(record, names) {
549
+ const out = {};
550
+ for (const [key, doc] of Object.entries(fieldsOrEmpty(isEnvelope(record) && record.type === "record" ? record.value : record))) out[key] = await this.part(doc, names);
551
+ return out;
552
+ }
553
+ async job(id, job, needs, done) {
554
+ const recorded = this.prior.jobs.get(id);
555
+ if (recorded !== void 0) return {
556
+ status: recorded.status,
557
+ outputs: recorded.outputs ?? {}
558
+ };
559
+ const end = async (status, outputs = {}) => {
560
+ await this.write({
561
+ type: "job-end",
562
+ instance: id,
563
+ status,
564
+ ...outputs === void 0 ? {} : { outputs },
565
+ time: wall()
566
+ });
567
+ return {
568
+ status,
569
+ outputs
570
+ };
571
+ };
572
+ const j = valueOf(job);
573
+ if (this.halt !== void 0) return end("cancelled");
574
+ const needNames = {};
575
+ for (const need of needs) needNames[need] = {
576
+ result: done.get(need)?.status,
577
+ outputs: done.get(need)?.outputs ?? {}
578
+ };
579
+ if (needs.some((need) => done.get(need)?.status !== "succeeded")) return end("skipped");
580
+ const inputs = this.first.inputs;
581
+ try {
582
+ const workflowEnv = await this.terms(valueOf(this.doc)["env"], { inputs });
583
+ const base = {
584
+ inputs,
585
+ needs: needNames
586
+ };
587
+ if (j["if"] !== void 0 && await this.part(j["if"], {
588
+ ...base,
589
+ env: workflowEnv
590
+ }) !== true) return end("skipped");
591
+ let rows = this.prior.rows.get(id);
592
+ if (rows === void 0 && j["matrix"] !== void 0) {
593
+ const value = await this.part(j["matrix"], base);
594
+ if (!Array.isArray(value)) throw new PartError("The matrix gives no list of rows.");
595
+ if (value.length > limits.matrix) {
596
+ this.failed = true;
597
+ throw new PartError(`The matrix has ${String(value.length)} rows. The limit is ${String(limits.matrix)}.`);
598
+ }
599
+ rows = value;
600
+ await this.write({
601
+ type: "rows",
602
+ job: id,
603
+ rows: value,
604
+ time: wall()
605
+ });
606
+ }
607
+ const seen = /* @__PURE__ */ new Map();
608
+ const instances = rows === void 0 ? [{
609
+ key: id,
610
+ row: void 0
611
+ }] : rows.map((row) => {
612
+ const hash = rowKey(row);
613
+ const count = (seen.get(hash) ?? 0) + 1;
614
+ seen.set(hash, count);
615
+ return {
616
+ key: `${id}[${hash}${count > 1 ? `~${String(count)}` : ""}]`,
617
+ row
618
+ };
619
+ });
620
+ let status = "succeeded";
621
+ let outputs = {};
622
+ const deadline = typeof j["timeout"] === "number" ? options.clock.now() + j["timeout"] * 1e3 : void 0;
623
+ for (const instance of instances) {
624
+ const ended = await this.instance(instance.key, j, {
625
+ ...base,
626
+ ...instance.row === void 0 ? {} : { matrix: instance.row }
627
+ }, workflowEnv, deadline);
628
+ if (ended.status !== "succeeded") status = ended.status;
629
+ outputs = ended.outputs;
630
+ }
631
+ if (status !== "succeeded") this.failed = true;
632
+ return end(status, outputs);
633
+ } catch (error) {
634
+ if (!(error instanceof PartError)) throw error;
635
+ this.failed = true;
636
+ return end("failed", { error: error.message });
637
+ }
638
+ }
639
+ /** One job instance: its steps in order. */
640
+ async instance(key, j, base, workflowEnv, deadline) {
641
+ const jobEnv = {
642
+ ...workflowEnv,
643
+ ...await this.terms(j["env"], {
644
+ ...base,
645
+ env: workflowEnv
646
+ })
647
+ };
648
+ const steps = {};
649
+ let failedBefore = false;
650
+ for (const step of listOf(j["steps"])) {
651
+ const s = valueOf(step);
652
+ const instance = `${key}/${String(s["id"])}`;
653
+ const status = await this.step(instance, s, {
654
+ ...base,
655
+ env: jobEnv,
656
+ job: { status: failedBefore ? "failure" : "success" },
657
+ steps
658
+ }, failedBefore, (value) => {
659
+ steps[String(s["id"])] = value;
660
+ }, deadline);
661
+ if (status === "failed" && s["continue"] !== true) failedBefore = true;
662
+ if (status === "timed-out" || status === "cancelled") failedBefore = true;
663
+ if (status === "refused" || status === "in-doubt") return {
664
+ status,
665
+ outputs: {}
666
+ };
667
+ }
668
+ if (failedBefore) return {
669
+ status: "failed",
670
+ outputs: {}
671
+ };
672
+ const outputs = await this.terms(j["outputs"], {
673
+ ...base,
674
+ env: jobEnv,
675
+ steps
676
+ });
677
+ return {
678
+ status: "succeeded",
679
+ outputs: options.redact(outputs)
680
+ };
681
+ }
682
+ async stepMove(instance, state, event, due) {
683
+ const t = transitionOn(STEP_MACHINE, state.value, event);
684
+ if (t === void 0) throw new Error(`The step machine has no transition on ${event} from ${state.value}.`);
685
+ await this.write({
686
+ type: "transition",
687
+ machine: "workflow.step",
688
+ instance,
689
+ from: state.value,
690
+ on: event,
691
+ to: t.to,
692
+ time: wall(),
693
+ ...due === void 0 ? {} : { due }
694
+ });
695
+ state.value = t.to;
696
+ }
697
+ async stepEnd(instance, status, value) {
698
+ await this.write({
699
+ type: "step-end",
700
+ instance,
701
+ status,
702
+ ...value === void 0 ? {} : { value },
703
+ time: wall()
704
+ });
705
+ return status;
706
+ }
707
+ /** One step: its condition, its tries, its time limit, and the grant check at each effect. */
708
+ async step(instance, s, names, failedBefore, keep, deadline) {
709
+ const recorded = this.prior.steps.get(instance);
710
+ if (recorded !== void 0) {
711
+ if (recorded.status === "succeeded") keep(recorded.value);
712
+ return recorded.status;
713
+ }
714
+ const was = this.prior.states.get(instance);
715
+ const state = { value: was?.state ?? "pending" };
716
+ const env = {
717
+ ...fieldsOrEmpty(names["env"]),
718
+ ...await this.terms(s["env"], names)
719
+ };
720
+ const scope = {
721
+ ...names,
722
+ env
723
+ };
724
+ if (this.halt !== void 0 || state.value === "pending" && deadline !== void 0 && options.clock.now() >= deadline) {
725
+ await this.stepMove(instance, state, "cancel");
726
+ return this.stepEnd(instance, "cancelled");
727
+ }
728
+ if (state.value !== "pending" && state.value !== "running" && state.value !== "waiting") {
729
+ if (state.value !== "succeeded") return this.stepEnd(instance, state.value, { why: "The record ended after the last transition of the step." });
730
+ const outcome = await this.attempt(instance, s, scope, Math.max(was?.runs ?? 1, 1));
731
+ if (outcome.kind !== "ok") throw new Error(`The step ${instance} succeeded in its record, and its replay gives no value.`);
732
+ const value = options.redact(outcome.value);
733
+ keep(value);
734
+ return this.stepEnd(instance, "succeeded", value);
735
+ }
736
+ if (state.value === "pending") {
737
+ if (!(s["if"] === void 0 ? !failedBefore : await this.part(s["if"], scope) === true)) {
738
+ await this.stepMove(instance, state, "skip");
739
+ return this.stepEnd(instance, "skipped");
740
+ }
741
+ }
742
+ const retry = fieldsOrEmpty(s["retry"]);
743
+ const tries = typeof retry["tries"] === "number" ? retry["tries"] : 1;
744
+ let attempt = was?.runs ?? 0;
745
+ if (state.value === "waiting") {
746
+ await this.wait((was?.due ?? wall()) - wall());
747
+ await this.stepMove(instance, state, "due");
748
+ } else if (state.value === "pending") {
749
+ await this.stepMove(instance, state, "run");
750
+ attempt += 1;
751
+ }
752
+ if (attempt === 0) attempt = 1;
753
+ for (;;) {
754
+ const outcome = await this.attempt(instance, s, scope, attempt, deadline);
755
+ if (outcome.kind === "ok") {
756
+ await this.stepMove(instance, state, "succeed");
757
+ const value = options.redact(outcome.value);
758
+ keep(value);
759
+ return this.stepEnd(instance, "succeeded", value);
760
+ }
761
+ if (outcome.kind === "halt") {
762
+ this.halt ??= {
763
+ status: outcome.status,
764
+ why: outcome.why
765
+ };
766
+ await this.stepMove(instance, state, outcome.status === "refused" ? "refuse" : "doubt");
767
+ return this.stepEnd(instance, outcome.status, { why: outcome.why });
768
+ }
769
+ if (attempt >= tries || this.halt !== void 0) {
770
+ await this.stepMove(instance, state, outcome.kind === "expired" ? "expire" : "fail");
771
+ return this.stepEnd(instance, outcome.kind === "expired" ? "timed-out" : "failed", { why: outcome.why });
772
+ }
773
+ const delay = backoffDelay({
774
+ base: 1e3 * Number(retry["delay"] ?? 1),
775
+ factor: Number(retry["factor"] ?? 2),
776
+ ...retry["cap"] === void 0 ? {} : { cap: 1e3 * Number(retry["cap"]) }
777
+ }, attempt);
778
+ await this.stepMove(instance, state, "retry", wall() + delay);
779
+ await this.wait(delay);
780
+ await this.stepMove(instance, state, "due");
781
+ attempt += 1;
782
+ }
783
+ }
784
+ wait(ms) {
785
+ if (ms <= 0) return Promise.resolve();
786
+ return new Promise((resolve) => options.clock.after(ms, resolve));
787
+ }
788
+ /** One try of a step. */
789
+ async attempt(instance, s, scope, attempt, deadline) {
790
+ const controller = new AbortController();
791
+ const own = typeof s["timeout"] === "number" ? s["timeout"] * 1e3 : 1e400;
792
+ const left = deadline === void 0 ? 1e400 : Math.max(0, deadline - options.clock.now());
793
+ const timeout = Math.min(own, left) === 1e400 ? void 0 : Math.min(own, left);
794
+ let expired = false;
795
+ const cancel = timeout === void 0 ? void 0 : options.clock.after(timeout, () => {
796
+ expired = true;
797
+ controller.abort(/* @__PURE__ */ new Error("The time limit of the step ended."));
798
+ });
799
+ const open = /* @__PURE__ */ new Set();
800
+ let halt;
801
+ const perform = async (effect) => {
802
+ try {
803
+ return await this.effect(instance, attempt, effect, controller.signal, open);
804
+ } catch (error) {
805
+ if (error instanceof Halt) halt ??= error;
806
+ throw error;
807
+ }
808
+ };
809
+ try {
810
+ const ran = await run(machine, s["do"], context({
811
+ names: scope,
812
+ event: this.event,
813
+ caps: callCaps
814
+ }), {
815
+ perform,
816
+ signal: controller.signal
817
+ });
818
+ if (halt !== void 0) return {
819
+ kind: "halt",
820
+ status: halt.status,
821
+ why: halt.message
822
+ };
823
+ if (expired) {
824
+ const doubt = [...open].find((at) => !this.idempotent(at));
825
+ if (doubt !== void 0) return {
826
+ kind: "halt",
827
+ status: "in-doubt",
828
+ why: `The time limit ended while the effect ${doubt} ran. Its procedure does not remove a second call.`
829
+ };
830
+ return {
831
+ kind: "expired",
832
+ why: "The time limit of the step ended."
833
+ };
834
+ }
835
+ if (!ran.result.ok) return {
836
+ kind: "fail",
837
+ why: `${ran.result.error.code} ${String(options.redact(ran.result.error.reason))}`
838
+ };
839
+ return {
840
+ kind: "ok",
841
+ value: ran.result.value
842
+ };
843
+ } finally {
844
+ cancel?.();
845
+ }
846
+ }
847
+ procedureAt = /* @__PURE__ */ new Map();
848
+ idempotent(at) {
849
+ const name = this.procedureAt.get(at);
850
+ return name !== void 0 && options.procedures[name]?.idempotent === true;
851
+ }
852
+ /** One effect: the replay of its record, or the grant check and the live call. */
853
+ async effect(instance, attempt, effect, signal, open) {
854
+ const address = effect.address ?? `#${String(effect.index)}`;
855
+ const at = `${instance}@${String(attempt)}/${address}`;
856
+ const key = `${this.id}/${instance}/${address}`;
857
+ const ended = this.prior.ends.get(at);
858
+ if (ended !== void 0) {
859
+ if (ended.ok) return ended.value;
860
+ throw new Failure({
861
+ code: ended.code,
862
+ reason: ended.why
863
+ });
864
+ }
865
+ const refuse = async (why) => {
866
+ await this.write({
867
+ type: "effect-end",
868
+ at,
869
+ outcome: {
870
+ ok: false,
871
+ code: "#GRANT!",
872
+ why
873
+ },
874
+ time: wall()
875
+ });
876
+ throw new Halt("refused", why);
877
+ };
878
+ const namespace = String(effect.path[0]);
879
+ if (!namespaces.includes(namespace)) return refuse(`The effect ${effect.kind} is not a call.`);
880
+ const name = (namespace === "procedure" ? effect.path.slice(1) : effect.path).map(String).join(".");
881
+ this.procedureAt.set(at, name);
882
+ const info = options.procedures[name];
883
+ if (info === void 0) return refuse(`No procedure ${name} is known, thus no grant covers it.`);
884
+ if (!isRecord(effect.payload)) return refuse(`The inputs of ${name} are not a record.`);
885
+ const payload = effect.payload;
886
+ for (const access of ["read", "write"]) for (const input of info.workspaces?.[access] ?? []) {
887
+ const answer = await this.ask(at, access, payload[input]);
888
+ if (!answer.ok) return refuse(`The workspace ${this.first.owner} cannot ${access} ${JSON.stringify(payload[input] ?? null)} (the input ${input} of ${name}): ${answer.why}`);
889
+ }
890
+ if (this.prior.starts.has(at) && info.idempotent !== true) throw new Halt("in-doubt", `The effect ${at} started before and has no outcome. The procedure ${name} does not remove a second call.`);
891
+ if (!this.prior.starts.has(at)) await this.write({
892
+ type: "effect-start",
893
+ at,
894
+ key,
895
+ try: attempt,
896
+ procedure: name,
897
+ payload: options.redact(payload),
898
+ time: wall()
899
+ });
900
+ open.add(at);
901
+ let outcome;
902
+ try {
903
+ const value = options.redact(await options.call({
904
+ procedure: name.split("."),
905
+ inputs: payload,
906
+ key,
907
+ try: attempt,
908
+ workspace: this.first.owner,
909
+ signal
910
+ }));
911
+ const bytes = JSON.stringify(value ?? null).length;
912
+ outcome = bytes > limits.outcomeBytes ? {
913
+ ok: false,
914
+ code: "#SIZE!",
915
+ why: `The outcome has ${String(bytes)} bytes. The limit is ${String(limits.outcomeBytes)}.`
916
+ } : {
917
+ ok: true,
918
+ value: value ?? null
919
+ };
920
+ } catch (error) {
921
+ if (signal.aborted) throw error;
922
+ const code = error instanceof Failure ? error.error.code : "#CALL!";
923
+ const why = error instanceof Failure ? error.error.reason : error instanceof Error ? error.message : String(error);
924
+ outcome = {
925
+ ok: false,
926
+ code,
927
+ why: String(options.redact(why))
928
+ };
929
+ }
930
+ await this.write({
931
+ type: "effect-end",
932
+ at,
933
+ outcome,
934
+ time: wall()
935
+ });
936
+ open.delete(at);
937
+ if (outcome.ok) return outcome.value;
938
+ throw new Failure({
939
+ code: outcome.code,
940
+ reason: outcome.why
941
+ });
942
+ }
943
+ }
944
+ return {
945
+ runIdOf,
946
+ start,
947
+ resume
948
+ };
949
+ }
950
+ // src/record.ts
951
+ /** The answer of a store to an append that another writer took first. */
952
+ var RecordConflict = class extends Error {
953
+ /** The count of the entries that the store holds. */
954
+ length;
955
+ /**
956
+ * This constructor makes the error.
957
+ *
958
+ * @param run - The run id.
959
+ * @param seq - The place that the writer asked for.
960
+ * @param length - The count of the entries that the store holds.
961
+ */
962
+ constructor(run, seq, length) {
963
+ super(`The record of the run ${run} has ${String(length)} entries, not ${String(seq)}. Another runner writes it.`);
964
+ this.name = "RecordConflict";
965
+ this.length = length;
966
+ }
967
+ };
968
+ /** A store in memory, for tests and for a host with no durable store. Each entry is a copy as JSON. */
969
+ function memoryStore() {
970
+ const records = /* @__PURE__ */ new Map();
971
+ return {
972
+ append(run, seq, entry) {
973
+ const list = records.get(run) ?? [];
974
+ if (seq !== list.length) throw new RecordConflict(run, seq, list.length);
975
+ list.push(JSON.parse(JSON.stringify(entry)));
976
+ records.set(run, list);
977
+ },
978
+ read: (run) => [...records.get(run) ?? []],
979
+ runs: () => [...records.keys()]
980
+ };
981
+ }
982
+ export { RUN_MACHINE, RecordConflict, STEP_MACHINE, memoryStore, workflowRunner };
983
+
984
+ //# sourceMappingURL=index.js.map