@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/build/index.js ADDED
@@ -0,0 +1,1125 @@
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/record.ts
210
+ /** The answer of a store to an append that another writer took first. */
211
+ var RecordConflict = class extends Error {
212
+ /** The count of the entries that the store holds. */
213
+ length;
214
+ /**
215
+ * This constructor makes the error.
216
+ *
217
+ * @param run - The run id.
218
+ * @param seq - The place that the writer asked for.
219
+ * @param length - The count of the entries that the store holds.
220
+ */
221
+ constructor(run, seq, length) {
222
+ super(`The record of the run ${run} has ${String(length)} entries, not ${String(seq)}. Another runner writes it.`);
223
+ this.name = "RecordConflict";
224
+ this.length = length;
225
+ }
226
+ };
227
+ /** The answer of a resume of a run that another runner holds: its lease is live. */
228
+ var RunHeld = class extends Error {
229
+ /** The holder of the lease. */
230
+ holder;
231
+ /** The wall time at the end of the lease, in milliseconds. */
232
+ until;
233
+ /**
234
+ * This constructor makes the error.
235
+ *
236
+ * @param run - The run id.
237
+ * @param holder - The holder of the lease.
238
+ * @param until - The wall time at the end of the lease.
239
+ */
240
+ constructor(run, holder, until) {
241
+ super(`The runner ${holder} holds the run ${run} until ${new Date(until).toISOString()}.`);
242
+ this.name = "RunHeld";
243
+ this.holder = holder;
244
+ this.until = until;
245
+ }
246
+ };
247
+ /** A store in memory, for tests and for a host with no durable store. Each entry is a copy as JSON. */
248
+ function memoryStore() {
249
+ const records = /* @__PURE__ */ new Map();
250
+ return {
251
+ append(run, seq, entry) {
252
+ const list = records.get(run) ?? [];
253
+ if (seq !== list.length) throw new RecordConflict(run, seq, list.length);
254
+ list.push(JSON.parse(JSON.stringify(entry)));
255
+ records.set(run, list);
256
+ },
257
+ read: (run) => [...records.get(run) ?? []],
258
+ open: () => [...records].filter(([, list]) => !list.some((entry) => entry.type === "end")).map(([run]) => run),
259
+ runs: () => [...records.keys()]
260
+ };
261
+ }
262
+ // src/engine.ts
263
+ const fieldsOrEmpty = (value) => readRecord(value) ?? {};
264
+ const listOf = (value) => Array.isArray(value) ? value : [];
265
+ const valueOf = (doc) => isEnvelope(doc) ? fieldsOrEmpty(doc.value) : {};
266
+ /** The error of a step that ends it at once: a refusal or a doubt. No retry and no `continue` changes it. */
267
+ var Halt = class extends Error {
268
+ status;
269
+ constructor(status, why) {
270
+ super(why);
271
+ this.status = status;
272
+ }
273
+ };
274
+ /** The error of a document part that the runner cannot evaluate. */
275
+ var PartError = class extends Error {};
276
+ function priorOf(entries) {
277
+ const ends = /* @__PURE__ */ new Map();
278
+ const starts = /* @__PURE__ */ new Map();
279
+ const steps = /* @__PURE__ */ new Map();
280
+ const jobs = /* @__PURE__ */ new Map();
281
+ const rows = /* @__PURE__ */ new Map();
282
+ const states = /* @__PURE__ */ new Map();
283
+ let end;
284
+ for (const entry of entries) if (entry.type === "effect-start") starts.set(entry.at, entry);
285
+ else if (entry.type === "effect-end") ends.set(entry.at, entry.outcome);
286
+ else if (entry.type === "step-end") steps.set(entry.instance, entry);
287
+ else if (entry.type === "job-end") jobs.set(entry.instance, entry);
288
+ else if (entry.type === "rows") rows.set(entry.job, entry.rows);
289
+ else if (entry.type === "transition" && entry.machine === "workflow.step") {
290
+ const was = states.get(entry.instance) ?? {
291
+ state: "pending",
292
+ runs: 0
293
+ };
294
+ states.set(entry.instance, {
295
+ state: entry.to,
296
+ runs: was.runs + (entry.to === "running" ? 1 : 0),
297
+ ...entry.due === void 0 ? {} : { due: entry.due }
298
+ });
299
+ } else if (entry.type === "end") end = entry;
300
+ return {
301
+ ends,
302
+ starts,
303
+ steps,
304
+ jobs,
305
+ rows,
306
+ states,
307
+ ...end === void 0 ? {} : { end }
308
+ };
309
+ }
310
+ /** The short hash of a matrix row. The address of a row does not change when the order of the rows changes. */
311
+ function rowKey(row) {
312
+ return canonicalHash(row).slice(0, 12);
313
+ }
314
+ /** The order of the jobs: each job after its needs. A cycle or a missing need gives `undefined`. */
315
+ function jobOrder(jobs) {
316
+ const order = [];
317
+ const state = /* @__PURE__ */ new Map();
318
+ const visit = (id) => {
319
+ if (state.get(id) === "done") return true;
320
+ if (state.get(id) === "open" || !(id in jobs)) return false;
321
+ state.set(id, "open");
322
+ for (const need of listOf(valueOf(jobs[id])["needs"])) if (typeof need !== "string" || !visit(need)) return false;
323
+ state.set(id, "done");
324
+ order.push(id);
325
+ return true;
326
+ };
327
+ for (const id of Object.keys(jobs)) if (!visit(id)) return void 0;
328
+ return order;
329
+ }
330
+ /**
331
+ * The problems that make a document `invalid` for the runner, besides the errors of `checkWorkflow`. The check holds the
332
+ * retry rule, with the limit of tries of the runner.
333
+ */
334
+ function runnerProblems(doc) {
335
+ const problems = [];
336
+ const jobs = fieldsOrEmpty(valueOf(doc)["jobs"]);
337
+ if (jobOrder(jobs) === void 0) problems.push("The needs of the jobs have a cycle or name no job.");
338
+ for (const [id, job] of Object.entries(jobs)) listOf(valueOf(job)["steps"]).forEach((step, index) => {
339
+ if (typeof valueOf(step)["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.`);
340
+ });
341
+ return problems;
342
+ }
343
+ /** This function gives the fields of a trigger that are present among `keys`, for a record with no undefined value. */
344
+ function present(trigger, keys) {
345
+ const out = {};
346
+ for (const key of keys) {
347
+ const value = trigger[key];
348
+ if (value !== void 0) out[key] = value;
349
+ }
350
+ return out;
351
+ }
352
+ /**
353
+ * 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
354
+ * 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
355
+ * these fields keeps the run id of before.
356
+ */
357
+ function sourceOf(trigger) {
358
+ return {
359
+ kind: trigger.kind,
360
+ id: trigger.id,
361
+ ...present(trigger, trigger.collection === void 0 ? ["event"] : [
362
+ "event",
363
+ "from",
364
+ "collection"
365
+ ])
366
+ };
367
+ }
368
+ /** This function gives the value that an expression reads as `event`: the kind as `name`, the id, the data and the source. */
369
+ function eventValueOf(trigger) {
370
+ return {
371
+ name: trigger.kind,
372
+ id: trigger.id,
373
+ data: trigger.data ?? null,
374
+ ...present(trigger, [
375
+ "event",
376
+ "type",
377
+ "from",
378
+ "collection"
379
+ ])
380
+ };
381
+ }
382
+ /** The default value of each input of a document that has one. */
383
+ function defaultsOf(doc) {
384
+ const out = {};
385
+ for (const [name, input] of Object.entries(fieldsOrEmpty(valueOf(doc)["inputs"]))) if (isRecord(input) && "default" in input) out[name] = input["default"];
386
+ return out;
387
+ }
388
+ const DEFAULT_LIMITS = {
389
+ matrix: 256,
390
+ tries: 10,
391
+ outcomeBytes: 1e6,
392
+ jobs: 8,
393
+ lease: 6e4,
394
+ callDepth: 8
395
+ };
396
+ /**
397
+ * This function makes a runner of workflows. The runner records each run in the store, and each record is the log of
398
+ * a resume. It refuses an effect that the grant check does not permit, and it records each answer.
399
+ *
400
+ * @param options - The ports and the limits.
401
+ * @returns The runner.
402
+ */
403
+ function workflowRunner(options) {
404
+ const machine = options.machine ?? workflowMachine();
405
+ const limits = {
406
+ ...DEFAULT_LIMITS,
407
+ ...options.limits
408
+ };
409
+ const wall = options.wall ?? Date.now;
410
+ const namespaces = ["procedure", ...options.callNamespaces ?? []];
411
+ const callCaps = namespaces.map((namespace) => [namespace]);
412
+ const holder = options.holder ?? `runner-${globalThis.crypto.randomUUID()}`;
413
+ const runIdOf = (request) => canonicalHash({
414
+ doc: canonicalHash(request.doc),
415
+ owner: request.owner,
416
+ trigger: sourceOf(request.trigger)
417
+ });
418
+ async function start(request) {
419
+ const id = runIdOf(request);
420
+ if ((await options.store.read(id)).length > 0) return resume(id);
421
+ const start = {
422
+ type: "start",
423
+ run: id,
424
+ docHash: canonicalHash(request.doc),
425
+ doc: request.doc,
426
+ owner: request.owner,
427
+ workspace: valueOf(request.doc)["workspace"],
428
+ trigger: options.redact(request.trigger),
429
+ inputs: options.redact({
430
+ ...defaultsOf(request.doc),
431
+ ...request.inputs
432
+ }),
433
+ time: wall()
434
+ };
435
+ await options.store.append(id, 0, start);
436
+ return resume(id);
437
+ }
438
+ async function resume(id) {
439
+ const entries = [...await options.store.read(id)];
440
+ const first = entries[0];
441
+ if (first?.type !== "start") throw new Error(`The run ${id} has no record.`);
442
+ const prior = priorOf(entries);
443
+ if (prior.end !== void 0) return {
444
+ run: id,
445
+ status: prior.end.status,
446
+ why: prior.end.why,
447
+ entries
448
+ };
449
+ const lease = entries.findLast((entry) => entry.type === "lease");
450
+ if (lease !== void 0 && lease.holder !== holder && lease.until > wall()) throw new RunHeld(id, lease.holder, lease.until);
451
+ return new Run(id, first, entries, prior).go();
452
+ }
453
+ async function recover(recoverOptions = {}) {
454
+ if (options.store.open === void 0) throw new Error("The store gives no list of open runs: it has no function open.");
455
+ const waiting = [...await options.store.open()];
456
+ const resumed = [];
457
+ const held = [];
458
+ const failed = [];
459
+ const worker = async () => {
460
+ for (let id = waiting.shift(); id !== void 0; id = waiting.shift()) try {
461
+ const result = await resume(id);
462
+ resumed.push({
463
+ run: id,
464
+ status: result.status,
465
+ why: result.why
466
+ });
467
+ } catch (error) {
468
+ if (error instanceof RunHeld) held.push({
469
+ run: id,
470
+ holder: error.holder,
471
+ until: error.until
472
+ });
473
+ else if (error instanceof RecordConflict) held.push({
474
+ run: id,
475
+ holder: "another runner",
476
+ until: wall()
477
+ });
478
+ else failed.push({
479
+ run: id,
480
+ why: error instanceof Error ? error.message : String(error)
481
+ });
482
+ }
483
+ };
484
+ const width = Math.max(1, Math.floor(recoverOptions.concurrency ?? 4));
485
+ await Promise.all(Array.from({ length: width }, worker));
486
+ return {
487
+ resumed,
488
+ held,
489
+ failed
490
+ };
491
+ }
492
+ /** One run: its writer, its state and its jobs. */
493
+ class Run {
494
+ tail = Promise.resolve();
495
+ runState;
496
+ halt;
497
+ failed = false;
498
+ ended = false;
499
+ renewal;
500
+ /** The end of the last lease that this runner wrote. */
501
+ leaseUntil = 0;
502
+ /** This signal aborts when the runner loses the lease: each call in flight then stops. */
503
+ lost = new AbortController();
504
+ event;
505
+ doc;
506
+ id;
507
+ first;
508
+ entries;
509
+ prior;
510
+ constructor(id, first, entries, prior) {
511
+ this.id = id;
512
+ this.first = first;
513
+ this.entries = entries;
514
+ this.prior = prior;
515
+ this.doc = first.doc;
516
+ let state = "queued";
517
+ for (const entry of entries) if (entry.type === "transition" && entry.machine === "workflow.run") state = entry.to;
518
+ this.runState = state;
519
+ this.event = eventValueOf(first.trigger);
520
+ }
521
+ /** This function appends one entry. The appends of one run go in one order, and a conflict stops the run. */
522
+ write(entry) {
523
+ const next = this.tail.then(async () => {
524
+ if (this.ended) throw new Error(`The record of the run ${this.id} has its end.`);
525
+ await options.store.append(this.id, this.entries.length, entry);
526
+ this.entries.push(entry);
527
+ if (entry.type === "end") this.ended = true;
528
+ });
529
+ this.tail = next.catch(() => void 0);
530
+ return next;
531
+ }
532
+ async move(event) {
533
+ const t = transitionOn(RUN_MACHINE, this.runState, event);
534
+ if (t === void 0) throw new Error(`The run machine has no transition on ${event} from ${this.runState}.`);
535
+ await this.write({
536
+ type: "transition",
537
+ machine: "workflow.run",
538
+ instance: this.id,
539
+ from: this.runState,
540
+ on: event,
541
+ to: t.to,
542
+ time: wall()
543
+ });
544
+ this.runState = t.to;
545
+ }
546
+ async finish(event, status, why) {
547
+ await this.move(event);
548
+ await this.write({
549
+ type: "end",
550
+ status,
551
+ why,
552
+ time: wall()
553
+ });
554
+ return {
555
+ run: this.id,
556
+ status,
557
+ why,
558
+ entries: this.entries
559
+ };
560
+ }
561
+ async ask(at, access, target, from = this.first.owner) {
562
+ let answer;
563
+ if (typeof target !== "string" || target === "") answer = {
564
+ ok: false,
565
+ why: "The target workspace is not a text."
566
+ };
567
+ else try {
568
+ const given = await options.access({
569
+ from,
570
+ access,
571
+ target
572
+ });
573
+ answer = isRecord(given) && given["ok"] === true ? {
574
+ ok: true,
575
+ why: String(given["why"] ?? "")
576
+ } : {
577
+ ok: false,
578
+ why: String(fieldsOrEmpty(given)["why"] ?? "The grant check gave no grant.")
579
+ };
580
+ } catch (error) {
581
+ answer = {
582
+ ok: false,
583
+ why: `The grant check failed: ${error instanceof Error ? error.message : String(error)}`
584
+ };
585
+ }
586
+ await this.write({
587
+ type: "grant",
588
+ at,
589
+ from,
590
+ access,
591
+ target: typeof target === "string" ? target : JSON.stringify(target ?? null),
592
+ ok: answer.ok,
593
+ why: answer.why,
594
+ time: wall()
595
+ });
596
+ return answer;
597
+ }
598
+ /** This function takes the lease of the run, and renews it after each third of its time until the end. */
599
+ async lease() {
600
+ const take = async () => {
601
+ const until = wall() + limits.lease;
602
+ await this.write({
603
+ type: "lease",
604
+ holder,
605
+ until,
606
+ time: wall()
607
+ });
608
+ this.leaseUntil = until;
609
+ };
610
+ await take();
611
+ const lose = (why) => {
612
+ this.renewal = void 0;
613
+ this.lost.abort(new Error(why));
614
+ };
615
+ const renew = () => {
616
+ if (this.ended || this.lost.signal.aborted) return;
617
+ this.renewal = options.clock.after(Math.max(1, Math.floor(limits.lease / 3)), renew);
618
+ take().catch((error) => {
619
+ if (this.ended) return;
620
+ if (error instanceof RecordConflict) lose(`Another runner took the run ${this.id}.`);
621
+ else if (wall() >= this.leaseUntil) lose(`The lease of the run ${this.id} ended, because the store refused each renewal.`);
622
+ });
623
+ };
624
+ this.renewal = options.clock.after(Math.max(1, Math.floor(limits.lease / 3)), renew);
625
+ }
626
+ async go() {
627
+ await this.lease();
628
+ try {
629
+ return await this.body();
630
+ } finally {
631
+ this.renewal?.();
632
+ }
633
+ }
634
+ async body() {
635
+ if (this.runState !== "queued" && this.runState !== "running") {
636
+ const status = this.runState;
637
+ await this.write({
638
+ type: "end",
639
+ status,
640
+ why: "The record ended after the last transition of the run.",
641
+ time: wall()
642
+ });
643
+ return {
644
+ run: this.id,
645
+ status,
646
+ why: "The record ended after the last transition of the run.",
647
+ entries: this.entries
648
+ };
649
+ }
650
+ if (this.runState === "queued") {
651
+ const reject = await this.precheck();
652
+ if (reject !== void 0) return reject;
653
+ await this.move("start");
654
+ }
655
+ const jobs = fieldsOrEmpty(valueOf(this.doc)["jobs"]);
656
+ const order = jobOrder(jobs) ?? [];
657
+ const done = /* @__PURE__ */ new Map();
658
+ const running = /* @__PURE__ */ new Map();
659
+ const waiting = [...order];
660
+ while (waiting.length > 0 || running.size > 0) {
661
+ for (const id of [...waiting]) {
662
+ if (running.size >= limits.jobs) break;
663
+ const needs = listOf(valueOf(jobs[id])["needs"]);
664
+ if (!needs.every((need) => done.has(need))) continue;
665
+ waiting.splice(waiting.indexOf(id), 1);
666
+ const task = this.job(id, jobs[id], needs, done).then((end) => {
667
+ done.set(id, end);
668
+ running.delete(id);
669
+ });
670
+ running.set(id, task);
671
+ }
672
+ if (running.size > 0) await Promise.race(running.values());
673
+ }
674
+ if (this.halt !== void 0) return this.finish(this.halt.status === "refused" ? "refuse" : "doubt", this.halt.status, this.halt.why);
675
+ if (this.failed) return this.finish("fail", "failed", "A job failed.");
676
+ return this.finish("succeed", "succeeded", "Each job succeeded or was skipped.");
677
+ }
678
+ /** The checks before the first effect: the document, the owner and the trigger. */
679
+ async precheck() {
680
+ const problems = [...checkWorkflow(this.doc, {
681
+ machine,
682
+ procedures: options.procedures,
683
+ callNamespaces: options.callNamespaces ?? [],
684
+ maxTries: limits.tries
685
+ }).filter((issue) => issue.level === "error").map((issue) => `${issue.code}: ${issue.message}`), ...runnerProblems(this.doc)];
686
+ if (problems.length > 0) return this.finish("reject", "invalid", problems.join(" "));
687
+ 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.`);
688
+ const trigger = this.first.trigger;
689
+ const depth = trigger.depth ?? 0;
690
+ if (!Number.isInteger(depth) || depth < 0 || depth > limits.callDepth) 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)}.`);
691
+ if (trigger.kind === "feed") {
692
+ const answer = await this.ask("trigger", "read", trigger.from);
693
+ if (!answer.ok) return this.finish("refuse", "refused", `The feed cannot read ${String(trigger.from)}: ${answer.why}`);
694
+ }
695
+ if (trigger.kind === "call") {
696
+ const answer = await this.ask("trigger", "write", this.first.owner, typeof trigger.caller === "string" ? trigger.caller : "");
697
+ if (!answer.ok) return this.finish("refuse", "refused", `The caller ${String(trigger.caller)} cannot start a workflow of ${this.first.owner}: ${answer.why}`);
698
+ }
699
+ }
700
+ /** This function evaluates one part with no capability: a call in it gives `#CAP!`. */
701
+ async part(doc, names) {
702
+ if (!isEnvelope(doc)) return doc;
703
+ const ran = await run(machine, doc, context({
704
+ names,
705
+ event: this.event
706
+ }), { perform: () => {
707
+ throw new Failure({
708
+ code: "#CAP!",
709
+ reason: "Only the field do of a step can call a procedure."
710
+ });
711
+ } });
712
+ if (!ran.result.ok) throw new PartError(`${ran.result.error.code} ${ran.result.error.reason}`);
713
+ return ran.result.value;
714
+ }
715
+ async terms(record, names) {
716
+ const out = {};
717
+ for (const [key, doc] of Object.entries(fieldsOrEmpty(isEnvelope(record) && record.type === "record" ? record.value : record))) out[key] = await this.part(doc, names);
718
+ return out;
719
+ }
720
+ async job(id, job, needs, done) {
721
+ const recorded = this.prior.jobs.get(id);
722
+ if (recorded !== void 0) return {
723
+ status: recorded.status,
724
+ outputs: recorded.outputs ?? {}
725
+ };
726
+ const end = async (status, outputs = {}) => {
727
+ await this.write({
728
+ type: "job-end",
729
+ instance: id,
730
+ status,
731
+ ...outputs === void 0 ? {} : { outputs },
732
+ time: wall()
733
+ });
734
+ return {
735
+ status,
736
+ outputs
737
+ };
738
+ };
739
+ const j = valueOf(job);
740
+ if (this.halt !== void 0) return end("cancelled");
741
+ const needNames = {};
742
+ for (const need of needs) needNames[need] = {
743
+ result: done.get(need)?.status,
744
+ outputs: done.get(need)?.outputs ?? {}
745
+ };
746
+ if (needs.some((need) => done.get(need)?.status !== "succeeded")) return end("skipped");
747
+ const inputs = this.first.inputs;
748
+ try {
749
+ const workflowEnv = await this.terms(valueOf(this.doc)["env"], { inputs });
750
+ const base = {
751
+ inputs,
752
+ needs: needNames
753
+ };
754
+ if (j["if"] !== void 0 && await this.part(j["if"], {
755
+ ...base,
756
+ env: workflowEnv
757
+ }) !== true) return end("skipped");
758
+ let rows = this.prior.rows.get(id);
759
+ if (rows === void 0 && j["matrix"] !== void 0) {
760
+ const value = await this.part(j["matrix"], base);
761
+ if (!Array.isArray(value)) throw new PartError("The matrix gives no list of rows.");
762
+ if (value.length > limits.matrix) {
763
+ this.failed = true;
764
+ throw new PartError(`The matrix has ${String(value.length)} rows. The limit is ${String(limits.matrix)}.`);
765
+ }
766
+ rows = value;
767
+ await this.write({
768
+ type: "rows",
769
+ job: id,
770
+ rows: value,
771
+ time: wall()
772
+ });
773
+ }
774
+ const seen = /* @__PURE__ */ new Map();
775
+ const instances = rows === void 0 ? [{
776
+ key: id,
777
+ row: void 0
778
+ }] : rows.map((row) => {
779
+ const hash = rowKey(row);
780
+ const count = (seen.get(hash) ?? 0) + 1;
781
+ seen.set(hash, count);
782
+ return {
783
+ key: `${id}[${hash}${count > 1 ? `~${String(count)}` : ""}]`,
784
+ row
785
+ };
786
+ });
787
+ let status = "succeeded";
788
+ let outputs = {};
789
+ const deadline = typeof j["timeout"] === "number" ? options.clock.now() + j["timeout"] * 1e3 : void 0;
790
+ for (const instance of instances) {
791
+ const ended = await this.instance(instance.key, j, {
792
+ ...base,
793
+ ...instance.row === void 0 ? {} : { matrix: instance.row }
794
+ }, workflowEnv, deadline);
795
+ if (ended.status !== "succeeded") status = ended.status;
796
+ outputs = ended.outputs;
797
+ }
798
+ if (status !== "succeeded") this.failed = true;
799
+ return end(status, outputs);
800
+ } catch (error) {
801
+ if (!(error instanceof PartError)) throw error;
802
+ this.failed = true;
803
+ return end("failed", { error: error.message });
804
+ }
805
+ }
806
+ /** One job instance: its steps in order. */
807
+ async instance(key, j, base, workflowEnv, deadline) {
808
+ const jobEnv = {
809
+ ...workflowEnv,
810
+ ...await this.terms(j["env"], {
811
+ ...base,
812
+ env: workflowEnv
813
+ })
814
+ };
815
+ const steps = {};
816
+ let failedBefore = false;
817
+ for (const step of listOf(j["steps"])) {
818
+ const s = valueOf(step);
819
+ const instance = `${key}/${String(s["id"])}`;
820
+ const status = await this.step(instance, s, {
821
+ ...base,
822
+ env: jobEnv,
823
+ job: { status: failedBefore ? "failure" : "success" },
824
+ steps
825
+ }, failedBefore, (value) => {
826
+ steps[String(s["id"])] = value;
827
+ }, deadline);
828
+ if (status === "failed" && s["continue"] !== true) failedBefore = true;
829
+ if (status === "timed-out" || status === "cancelled") failedBefore = true;
830
+ if (status === "refused" || status === "in-doubt") return {
831
+ status,
832
+ outputs: {}
833
+ };
834
+ }
835
+ if (failedBefore) return {
836
+ status: "failed",
837
+ outputs: {}
838
+ };
839
+ const outputs = await this.terms(j["outputs"], {
840
+ ...base,
841
+ env: jobEnv,
842
+ steps
843
+ });
844
+ return {
845
+ status: "succeeded",
846
+ outputs: options.redact(outputs)
847
+ };
848
+ }
849
+ async stepMove(instance, state, event, due) {
850
+ const t = transitionOn(STEP_MACHINE, state.value, event);
851
+ if (t === void 0) throw new Error(`The step machine has no transition on ${event} from ${state.value}.`);
852
+ await this.write({
853
+ type: "transition",
854
+ machine: "workflow.step",
855
+ instance,
856
+ from: state.value,
857
+ on: event,
858
+ to: t.to,
859
+ time: wall(),
860
+ ...due === void 0 ? {} : { due }
861
+ });
862
+ state.value = t.to;
863
+ }
864
+ async stepEnd(instance, status, value) {
865
+ await this.write({
866
+ type: "step-end",
867
+ instance,
868
+ status,
869
+ ...value === void 0 ? {} : { value },
870
+ time: wall()
871
+ });
872
+ return status;
873
+ }
874
+ /** One step: its condition, its tries, its time limit, and the grant check at each effect. */
875
+ async step(instance, s, names, failedBefore, keep, deadline) {
876
+ const recorded = this.prior.steps.get(instance);
877
+ if (recorded !== void 0) {
878
+ if (recorded.status === "succeeded") keep(recorded.value);
879
+ return recorded.status;
880
+ }
881
+ const was = this.prior.states.get(instance);
882
+ const state = { value: was?.state ?? "pending" };
883
+ const env = {
884
+ ...fieldsOrEmpty(names["env"]),
885
+ ...await this.terms(s["env"], names)
886
+ };
887
+ const scope = {
888
+ ...names,
889
+ env
890
+ };
891
+ if (this.halt !== void 0 || state.value === "pending" && deadline !== void 0 && options.clock.now() >= deadline) {
892
+ await this.stepMove(instance, state, "cancel");
893
+ return this.stepEnd(instance, "cancelled");
894
+ }
895
+ if (state.value !== "pending" && state.value !== "running" && state.value !== "waiting") {
896
+ if (state.value !== "succeeded") return this.stepEnd(instance, state.value, { why: "The record ended after the last transition of the step." });
897
+ const outcome = await this.attempt(instance, s, scope, Math.max(was?.runs ?? 1, 1));
898
+ if (outcome.kind !== "ok") throw new Error(`The step ${instance} succeeded in its record, and its replay gives no value.`);
899
+ const value = options.redact(outcome.value);
900
+ keep(value);
901
+ return this.stepEnd(instance, "succeeded", value);
902
+ }
903
+ if (state.value === "pending") {
904
+ if (!(s["if"] === void 0 ? !failedBefore : await this.part(s["if"], scope) === true)) {
905
+ await this.stepMove(instance, state, "skip");
906
+ return this.stepEnd(instance, "skipped");
907
+ }
908
+ }
909
+ const retry = fieldsOrEmpty(s["retry"]);
910
+ const tries = typeof retry["tries"] === "number" ? retry["tries"] : 1;
911
+ let attempt = was?.runs ?? 0;
912
+ if (state.value === "waiting") {
913
+ await this.wait((was?.due ?? wall()) - wall());
914
+ await this.stepMove(instance, state, "due");
915
+ } else if (state.value === "pending") {
916
+ await this.stepMove(instance, state, "run");
917
+ attempt += 1;
918
+ }
919
+ if (attempt === 0) attempt = 1;
920
+ for (;;) {
921
+ const outcome = await this.attempt(instance, s, scope, attempt, deadline);
922
+ if (outcome.kind === "ok") {
923
+ await this.stepMove(instance, state, "succeed");
924
+ const value = options.redact(outcome.value);
925
+ keep(value);
926
+ return this.stepEnd(instance, "succeeded", value);
927
+ }
928
+ if (outcome.kind === "halt") {
929
+ this.halt ??= {
930
+ status: outcome.status,
931
+ why: outcome.why
932
+ };
933
+ await this.stepMove(instance, state, outcome.status === "refused" ? "refuse" : "doubt");
934
+ return this.stepEnd(instance, outcome.status, { why: outcome.why });
935
+ }
936
+ if (attempt >= tries || this.halt !== void 0) {
937
+ await this.stepMove(instance, state, outcome.kind === "expired" ? "expire" : "fail");
938
+ return this.stepEnd(instance, outcome.kind === "expired" ? "timed-out" : "failed", { why: outcome.why });
939
+ }
940
+ const delay = backoffDelay({
941
+ base: 1e3 * Number(retry["delay"] ?? 1),
942
+ factor: Number(retry["factor"] ?? 2),
943
+ ...retry["cap"] === void 0 ? {} : { cap: 1e3 * Number(retry["cap"]) }
944
+ }, attempt);
945
+ await this.stepMove(instance, state, "retry", wall() + delay);
946
+ await this.wait(delay);
947
+ await this.stepMove(instance, state, "due");
948
+ attempt += 1;
949
+ }
950
+ }
951
+ wait(ms) {
952
+ if (ms <= 0) return Promise.resolve();
953
+ return new Promise((resolve) => options.clock.after(ms, resolve));
954
+ }
955
+ /** One try of a step. */
956
+ async attempt(instance, s, scope, attempt, deadline) {
957
+ const controller = new AbortController();
958
+ const stop = () => controller.abort(this.lost.signal.reason);
959
+ if (this.lost.signal.aborted) stop();
960
+ else this.lost.signal.addEventListener("abort", stop, { once: true });
961
+ const own = typeof s["timeout"] === "number" ? s["timeout"] * 1e3 : 1e400;
962
+ const left = deadline === void 0 ? 1e400 : Math.max(0, deadline - options.clock.now());
963
+ const timeout = Math.min(own, left) === 1e400 ? void 0 : Math.min(own, left);
964
+ let expired = false;
965
+ const cancel = timeout === void 0 ? void 0 : options.clock.after(timeout, () => {
966
+ expired = true;
967
+ controller.abort(/* @__PURE__ */ new Error("The time limit of the step ended."));
968
+ });
969
+ const open = /* @__PURE__ */ new Set();
970
+ let halt;
971
+ const perform = async (effect) => {
972
+ try {
973
+ return await this.effect(instance, attempt, effect, controller.signal, open);
974
+ } catch (error) {
975
+ if (error instanceof Halt) halt ??= error;
976
+ throw error;
977
+ }
978
+ };
979
+ try {
980
+ const ran = await run(machine, s["do"], context({
981
+ names: scope,
982
+ event: this.event,
983
+ caps: callCaps
984
+ }), {
985
+ perform,
986
+ signal: controller.signal
987
+ });
988
+ if (halt !== void 0) return {
989
+ kind: "halt",
990
+ status: halt.status,
991
+ why: halt.message
992
+ };
993
+ if (expired) {
994
+ const doubt = [...open].find((at) => !this.idempotent(at));
995
+ if (doubt !== void 0) return {
996
+ kind: "halt",
997
+ status: "in-doubt",
998
+ why: `The time limit ended while the effect ${doubt} ran. Its procedure does not remove a second call.`
999
+ };
1000
+ return {
1001
+ kind: "expired",
1002
+ why: "The time limit of the step ended."
1003
+ };
1004
+ }
1005
+ if (!ran.result.ok) return {
1006
+ kind: "fail",
1007
+ why: `${ran.result.error.code} ${String(options.redact(ran.result.error.reason))}`
1008
+ };
1009
+ return {
1010
+ kind: "ok",
1011
+ value: ran.result.value
1012
+ };
1013
+ } finally {
1014
+ cancel?.();
1015
+ this.lost.signal.removeEventListener("abort", stop);
1016
+ }
1017
+ }
1018
+ procedureAt = /* @__PURE__ */ new Map();
1019
+ idempotent(at) {
1020
+ const name = this.procedureAt.get(at);
1021
+ return name !== void 0 && Object.hasOwn(options.procedures, name) && options.procedures[name]?.idempotent === true;
1022
+ }
1023
+ /** One effect: the replay of its record, or the grant check and the live call. */
1024
+ async effect(instance, attempt, effect, signal, open) {
1025
+ const address = effect.address ?? `#${String(effect.index)}`;
1026
+ const at = `${instance}@${String(attempt)}/${address}`;
1027
+ const key = `${this.id}/${instance}/${address}`;
1028
+ const ended = this.prior.ends.get(at);
1029
+ if (ended !== void 0) {
1030
+ if (ended.ok) return ended.value;
1031
+ throw new Failure({
1032
+ code: ended.code,
1033
+ reason: ended.why
1034
+ });
1035
+ }
1036
+ const refuse = async (why) => {
1037
+ await this.write({
1038
+ type: "effect-end",
1039
+ at,
1040
+ outcome: {
1041
+ ok: false,
1042
+ code: "#GRANT!",
1043
+ why
1044
+ },
1045
+ time: wall()
1046
+ });
1047
+ throw new Halt("refused", why);
1048
+ };
1049
+ const namespace = String(effect.path[0]);
1050
+ if (!namespaces.includes(namespace)) return refuse(`The effect ${effect.kind} is not a call.`);
1051
+ const name = (namespace === "procedure" ? effect.path.slice(1) : effect.path).map(String).join(".");
1052
+ this.procedureAt.set(at, name);
1053
+ const info = Object.hasOwn(options.procedures, name) ? options.procedures[name] : void 0;
1054
+ if (info === void 0) return refuse(`No procedure ${name} is known, thus no grant covers it.`);
1055
+ if (!isRecord(effect.payload)) return refuse(`The inputs of ${name} are not a record.`);
1056
+ const payload = effect.payload;
1057
+ for (const access of ["read", "write"]) for (const input of info.workspaces?.[access] ?? []) {
1058
+ const answer = await this.ask(at, access, payload[input]);
1059
+ if (!answer.ok) return refuse(`The workspace ${this.first.owner} cannot ${access} ${JSON.stringify(payload[input] ?? null)} (the input ${input} of ${name}): ${answer.why}`);
1060
+ }
1061
+ 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.`);
1062
+ if (!this.prior.starts.has(at)) await this.write({
1063
+ type: "effect-start",
1064
+ at,
1065
+ key,
1066
+ try: attempt,
1067
+ procedure: name,
1068
+ payload: options.redact(payload),
1069
+ time: wall()
1070
+ });
1071
+ open.add(at);
1072
+ let outcome;
1073
+ try {
1074
+ const value = options.redact(await options.call({
1075
+ procedure: name.split("."),
1076
+ inputs: payload,
1077
+ key,
1078
+ try: attempt,
1079
+ workspace: this.first.owner,
1080
+ depth: this.first.trigger.depth ?? 0,
1081
+ signal
1082
+ }));
1083
+ const bytes = JSON.stringify(value ?? null).length;
1084
+ outcome = bytes > limits.outcomeBytes ? {
1085
+ ok: false,
1086
+ code: "#SIZE!",
1087
+ why: `The outcome has ${String(bytes)} bytes. The limit is ${String(limits.outcomeBytes)}.`
1088
+ } : {
1089
+ ok: true,
1090
+ value: value ?? null
1091
+ };
1092
+ } catch (error) {
1093
+ if (signal.aborted) throw error;
1094
+ const code = error instanceof Failure ? error.error.code : "#CALL!";
1095
+ const why = error instanceof Failure ? error.error.reason : error instanceof Error ? error.message : String(error);
1096
+ outcome = {
1097
+ ok: false,
1098
+ code,
1099
+ why: String(options.redact(why))
1100
+ };
1101
+ }
1102
+ await this.write({
1103
+ type: "effect-end",
1104
+ at,
1105
+ outcome,
1106
+ time: wall()
1107
+ });
1108
+ open.delete(at);
1109
+ if (outcome.ok) return outcome.value;
1110
+ throw new Failure({
1111
+ code: outcome.code,
1112
+ reason: outcome.why
1113
+ });
1114
+ }
1115
+ }
1116
+ return {
1117
+ runIdOf,
1118
+ start,
1119
+ resume,
1120
+ recover
1121
+ };
1122
+ }
1123
+ export { RUN_MACHINE, RecordConflict, RunHeld, STEP_MACHINE, memoryStore, workflowRunner };
1124
+
1125
+ //# sourceMappingURL=index.js.map