@mark1russell7/workflow-runner 0.1.0 → 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.
@@ -11,12 +11,23 @@ interface TriggerEvent {
11
11
  readonly kind: string;
12
12
  /** The id of the event, for example the id of a delivery or the time of a schedule boundary. */
13
13
  readonly id: string;
14
- /** The data of the event. A reference reads it as `event`. */
14
+ /** The data of the event. A reference reads it as `event.data`. */
15
15
  readonly data?: unknown;
16
+ /** For an event: the name of the event, for example `push`. A reference reads it as `event.event`. */
17
+ readonly event?: string;
18
+ /** For an event: its type, for example `opened`. A reference reads it as `event.type`. */
19
+ readonly type?: string;
16
20
  /** For a feed: the workspace that the feed reads. */
17
21
  readonly from?: string;
22
+ /** For a feed: the collection that the feed reads. */
23
+ readonly collection?: string;
18
24
  /** For a call: the workspace of the caller. */
19
25
  readonly caller?: string;
26
+ /**
27
+ * For a call: the count of the runs above this run in the chain of calls. A start by a person, a schedule or a source has
28
+ * the depth 0. The host gives the depth of the calling run plus 1.
29
+ */
30
+ readonly depth?: number;
20
31
  }
21
32
  /** The outcome of one effect, after the redaction of the host. */
22
33
  type Outcome = {
@@ -91,6 +102,11 @@ type RunEntry = {
91
102
  readonly status: RunStatus;
92
103
  readonly why: string;
93
104
  readonly time: number;
105
+ } | {
106
+ readonly type: "lease";
107
+ readonly holder: string;
108
+ readonly until: number;
109
+ readonly time: number;
94
110
  };
95
111
  /** The answer of a store to an append that another writer took first. */
96
112
  declare class RecordConflict extends Error {
@@ -114,6 +130,23 @@ interface RunStore {
114
130
  readonly append: (run: string, seq: number, entry: RunEntry) => Promise<void> | void;
115
131
  /** This function gives the entries of a run in their order. A run with no record gives an empty list. */
116
132
  readonly read: (run: string) => Promise<readonly RunEntry[]> | readonly RunEntry[];
133
+ /** This function gives the ids of the runs with no `end` entry. The recovery of a runner reads it. */
134
+ readonly open?: () => Promise<readonly string[]> | readonly string[];
135
+ }
136
+ /** The answer of a resume of a run that another runner holds: its lease is live. */
137
+ declare class RunHeld extends Error {
138
+ /** The holder of the lease. */
139
+ readonly holder: string;
140
+ /** The wall time at the end of the lease, in milliseconds. */
141
+ readonly until: number;
142
+ /**
143
+ * This constructor makes the error.
144
+ *
145
+ * @param run - The run id.
146
+ * @param holder - The holder of the lease.
147
+ * @param until - The wall time at the end of the lease.
148
+ */
149
+ constructor(run: string, holder: string, until: number);
117
150
  }
118
151
  /** A store in memory, for tests and for a host with no durable store. Each entry is a copy as JSON. */
119
152
  declare function memoryStore(): RunStore & {
@@ -139,6 +172,11 @@ interface ProcedureCall {
139
172
  readonly try: number;
140
173
  /** The workspace that runs the workflow. */
141
174
  readonly workspace: string;
175
+ /**
176
+ * 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.
177
+ * The host takes the depth from this field, not from the inputs of the call.
178
+ */
179
+ readonly depth: number;
142
180
  /** The signal of the time limit of the step. */
143
181
  readonly signal: AbortSignal;
144
182
  }
@@ -163,6 +201,10 @@ interface RunnerLimits {
163
201
  readonly outcomeBytes?: number;
164
202
  /** The most job instances that run at the same time. The default is 8. */
165
203
  readonly jobs?: number;
204
+ /** The time of a lease on a run, in milliseconds. The runner renews it after each third of this time. The default is 60000. */
205
+ readonly lease?: number;
206
+ /** The most depth of a call trigger. A deeper chain of calls is refused. The default is 8. */
207
+ readonly callDepth?: number;
166
208
  }
167
209
  /** The ports of the runner. The runner names no host: the host gives each port. */
168
210
  interface RunnerOptions {
@@ -189,6 +231,11 @@ interface RunnerOptions {
189
231
  readonly callNamespaces?: readonly string[];
190
232
  /** The limits. */
191
233
  readonly limits?: RunnerLimits;
234
+ /**
235
+ * 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.
236
+ * Another runner waits for the end of the lease. The default is a new random id.
237
+ */
238
+ readonly holder?: string;
192
239
  }
193
240
  /** A request to start a run. */
194
241
  interface StartRequest {
@@ -214,8 +261,35 @@ interface WorkflowRunner {
214
261
  readonly runIdOf: (request: StartRequest) => string;
215
262
  /** This function starts a run. A request with a run id that has a record resumes that run. */
216
263
  readonly start: (request: StartRequest) => Promise<RunResult>;
217
- /** This function resumes a run from its record. The record holds the document, thus a changed document makes no change. */
264
+ /**
265
+ * This function resumes a run from its record. The record holds the document, thus a changed document makes no change.
266
+ * A live lease of another runner gives the error `RunHeld`.
267
+ */
218
268
  readonly resume: (run: string) => Promise<RunResult>;
269
+ /** This function resumes each open run of the store with no live lease of another runner. The store must give `open`. */
270
+ readonly recover: (options?: RecoverOptions) => Promise<RecoverReport>;
271
+ }
272
+ /** The options of a recovery. */
273
+ interface RecoverOptions {
274
+ /** The most runs that resume at the same time. The default is 4. */
275
+ readonly concurrency?: number;
276
+ }
277
+ /** The report of a recovery: the runs that ended, the runs that another runner holds, and the runs that failed to resume. */
278
+ interface RecoverReport {
279
+ readonly resumed: readonly {
280
+ readonly run: string;
281
+ readonly status: RunStatus;
282
+ readonly why: string;
283
+ }[];
284
+ readonly held: readonly {
285
+ readonly run: string;
286
+ readonly holder: string;
287
+ readonly until: number;
288
+ }[];
289
+ readonly failed: readonly {
290
+ readonly run: string;
291
+ readonly why: string;
292
+ }[];
219
293
  }
220
294
  /**
221
295
  * This function makes a runner of workflows. The runner records each run in the store, and each record is the log of
@@ -225,5 +299,5 @@ interface WorkflowRunner {
225
299
  * @returns The runner.
226
300
  */
227
301
  declare function workflowRunner(options: RunnerOptions): WorkflowRunner;
228
- export { TriggerEvent as _, RunnerLimits as a, StartRequest as c, Outcome as d, RecordConflict as f, StepStatus as g, RunStore as h, RunResult as i, WorkflowRunner as l, RunStatus as m, AccessRequest as n, RunnerOptions as o, RunEntry as p, ProcedureCall as r, RunnerProcedure as s, AccessAnswer as t, workflowRunner as u, memoryStore as v };
229
- //# sourceMappingURL=engine-B_0OOo1N.d.ts.map
302
+ export { RunStatus as _, RecoverReport as a, TriggerEvent as b, RunnerOptions as c, WorkflowRunner as d, workflowRunner as f, RunHeld as g, RunEntry as h, RecoverOptions as i, RunnerProcedure as l, RecordConflict as m, AccessRequest as n, RunResult as o, Outcome as p, ProcedureCall as r, RunnerLimits as s, AccessAnswer as t, StartRequest as u, RunStore as v, memoryStore as x, StepStatus as y };
303
+ //# sourceMappingURL=engine-bAZZ3ZT9.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"engine-bAZZ3ZT9.d.ts","names":[],"sources":["../src/record.ts","../src/engine.ts"],"mappings":";;;;KACY;;KAGA;;UAGK;;WAEN;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;;;;;WAKA;;;KAIC;WAAqB;WAAmB;;WAA8B;WAAoB;WAAuB;;;KAGjH;WAEG;WACA;WACA;WACA;WACA;WACA;WACA,SAAS;WACT;WACA;;WAEA;WAAwB;WAAqB;WAAuB;WAAmC;WAAyB;WAAsB;WAAsB;;WAC5K;WAA6B;WAAoD;WAA2B;WAAuB;WAAqB;WAAqB;WAAuB;;WACpM;WAAuB;WAAsB;WAAmC;;WAChF;WAA+B;WAAqB;WAAsB;WAAsB;WAA4B;WAA2B;;WACvJ;WAA6B;WAAqB,SAAS;WAAkB;;WAC7E;WAA2B;WAA2B,QAAQ;WAAqB;WAA0B;;WAC7G;WAA0B;WAA2B,QAAQ;WAAqB;WAA4B;;WAC9G;WAAsB,QAAQ;WAAoB;WAAsB;;WACxE;WAAwB;WAAyB;WAAwB;;;cAG3E,uBAAuB;;WAEzB;;;;;;;;EAST,YAAY,aAAa,aAAa;;;;;;UAWvB;;WAEN,SAAS,aAAa,aAAa,OAAO,aAAa;;WAEvD,OAAO,gBAAgB,iBAAiB,uBAAuB;;WAE/D,aAAa;;;cAIX,gBAAgB;;WAElB;;WAEA;;;;;;;;EAST,YAAY,aAAa,gBAAgB;;;iBAS3B,eAAe;WAAsB;;;UCrGpC,wBAAwB;;;;;WAK9B;;;UAIM;;WAEN;;WAEA,QAAQ,SAAS;;WAEjB;;WAEA;;WAEA;;;;;WAKA;;WAEA,QAAQ;;;UAIF;WACN;WACA;WACA;;;UAIM;WACN;WACA;;;UAIM;;WAEN;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;;;UAIM;;WAEN,YAAY,SAAS,eAAe;;WAEpC,OAAO,MAAM,kBAAkB;;WAE/B,SAAS,SAAS,kBAAkB,eAAe,QAAQ;;;;;WAK3D,SAAS;;WAET,OAAO;;WAEP,OAAO;;WAEP;;WAEA,UAAU;;WAEV;;WAEA,SAAS;;;;;WAKT;;;UAIM;;WAEN;;WAEA;;WAEA,SAAS;;WAET,SAAS,SAAS;;;UAIZ;WACN;WACA,QAAQ;WACR;WACA,kBAAkB;;;UAIZ;;WAEN,UAAU,SAAS;;WAEnB,QAAQ,SAAS,iBAAiB,QAAQ;;;;;WAK1C,SAAS,gBAAgB,QAAQ;;WAEjC,UAAU,UAAU,mBAAmB,QAAQ;;;UAIzC;;WAEN;;;UAIM;WACN;aAA6B;aAAsB,QAAQ;aAAoB;;WAC/E;aAA0B;aAAsB;aAAyB;;WACzE;aAA4B;aAAsB;;;;;;;;;;iBAsI7C,eAAe,SAAS,gBAAgB"}
package/build/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { _ as TriggerEvent, a as RunnerLimits, c as StartRequest, d as Outcome, f as RecordConflict, g as StepStatus, h as RunStore, i as RunResult, l as WorkflowRunner, m as RunStatus, n as AccessRequest, o as RunnerOptions, p as RunEntry, r as ProcedureCall, s as RunnerProcedure, t as AccessAnswer, u as workflowRunner, v as memoryStore } from "./engine-B_0OOo1N.js";
1
+ import { _ as RunStatus, a as RecoverReport, b as TriggerEvent, c as RunnerOptions, d as WorkflowRunner, f as workflowRunner, g as RunHeld, h as RunEntry, i as RecoverOptions, l as RunnerProcedure, m as RecordConflict, n as AccessRequest, o as RunResult, p as Outcome, r as ProcedureCall, s as RunnerLimits, t as AccessAnswer, u as StartRequest, v as RunStore, x as memoryStore, y as StepStatus } from "./engine-bAZZ3ZT9.js";
2
2
  import { Machine } from "@mark1russell7/algebra";
3
3
  /**
4
4
  * The state machine of a run. A run is queued, then it runs. It ends with one status. The runner records each
@@ -10,5 +10,5 @@ export declare const RUN_MACHINE: Machine;
10
10
  * step at once: no retry and no `continue` changes them.
11
11
  */
12
12
  export declare const STEP_MACHINE: Machine;
13
- export { type AccessAnswer, type AccessRequest, type Outcome, type ProcedureCall, RecordConflict, type RunEntry, type RunResult, type RunStatus, type RunStore, type RunnerLimits, type RunnerOptions, type RunnerProcedure, type StartRequest, type StepStatus, type TriggerEvent, type WorkflowRunner, memoryStore, workflowRunner };
13
+ export { type AccessAnswer, type AccessRequest, type Outcome, type ProcedureCall, RecordConflict, type RecoverOptions, type RecoverReport, type RunEntry, RunHeld, type RunResult, type RunStatus, type RunStore, type RunnerLimits, type RunnerOptions, type RunnerProcedure, type StartRequest, type StepStatus, type TriggerEvent, type WorkflowRunner, memoryStore, workflowRunner };
14
14
  //# sourceMappingURL=index.d.ts.map
package/build/index.js CHANGED
@@ -206,6 +206,59 @@ const STEP_MACHINE = {
206
206
  }
207
207
  ]
208
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
+ }
209
262
  // src/engine.ts
210
263
  const fieldsOrEmpty = (value) => readRecord(value) ?? {};
211
264
  const listOf = (value) => Array.isArray(value) ? value : [];
@@ -274,28 +327,58 @@ function jobOrder(jobs) {
274
327
  for (const id of Object.keys(jobs)) if (!visit(id)) return void 0;
275
328
  return order;
276
329
  }
277
- /** The problems that make a document `invalid` for the runner, besides the errors of `checkWorkflow`. */
278
- function runnerProblems(doc, limits) {
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) {
279
335
  const problems = [];
280
336
  const jobs = fieldsOrEmpty(valueOf(doc)["jobs"]);
281
337
  if (jobOrder(jobs) === void 0) problems.push("The needs of the jobs have a cycle or name no job.");
282
338
  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
- }
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.`);
296
340
  });
297
341
  return problems;
298
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
+ }
299
382
  /** The default value of each input of a document that has one. */
300
383
  function defaultsOf(doc) {
301
384
  const out = {};
@@ -306,7 +389,9 @@ const DEFAULT_LIMITS = {
306
389
  matrix: 256,
307
390
  tries: 10,
308
391
  outcomeBytes: 1e6,
309
- jobs: 8
392
+ jobs: 8,
393
+ lease: 6e4,
394
+ callDepth: 8
310
395
  };
311
396
  /**
312
397
  * This function makes a runner of workflows. The runner records each run in the store, and each record is the log of
@@ -324,13 +409,11 @@ function workflowRunner(options) {
324
409
  const wall = options.wall ?? Date.now;
325
410
  const namespaces = ["procedure", ...options.callNamespaces ?? []];
326
411
  const callCaps = namespaces.map((namespace) => [namespace]);
412
+ const holder = options.holder ?? `runner-${globalThis.crypto.randomUUID()}`;
327
413
  const runIdOf = (request) => canonicalHash({
328
414
  doc: canonicalHash(request.doc),
329
415
  owner: request.owner,
330
- trigger: {
331
- kind: request.trigger.kind,
332
- id: request.trigger.id
333
- }
416
+ trigger: sourceOf(request.trigger)
334
417
  });
335
418
  async function start(request) {
336
419
  const id = runIdOf(request);
@@ -363,14 +446,61 @@ function workflowRunner(options) {
363
446
  why: prior.end.why,
364
447
  entries
365
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);
366
451
  return new Run(id, first, entries, prior).go();
367
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
+ }
368
492
  /** One run: its writer, its state and its jobs. */
369
493
  class Run {
370
494
  tail = Promise.resolve();
371
495
  runState;
372
496
  halt;
373
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();
374
504
  event;
375
505
  doc;
376
506
  id;
@@ -386,17 +516,15 @@ function workflowRunner(options) {
386
516
  let state = "queued";
387
517
  for (const entry of entries) if (entry.type === "transition" && entry.machine === "workflow.run") state = entry.to;
388
518
  this.runState = state;
389
- this.event = {
390
- name: first.trigger.kind,
391
- id: first.trigger.id,
392
- data: first.trigger.data ?? null
393
- };
519
+ this.event = eventValueOf(first.trigger);
394
520
  }
395
521
  /** This function appends one entry. The appends of one run go in one order, and a conflict stops the run. */
396
522
  write(entry) {
397
523
  const next = this.tail.then(async () => {
524
+ if (this.ended) throw new Error(`The record of the run ${this.id} has its end.`);
398
525
  await options.store.append(this.id, this.entries.length, entry);
399
526
  this.entries.push(entry);
527
+ if (entry.type === "end") this.ended = true;
400
528
  });
401
529
  this.tail = next.catch(() => void 0);
402
530
  return next;
@@ -467,7 +595,43 @@ function workflowRunner(options) {
467
595
  });
468
596
  return answer;
469
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
+ }
470
626
  async go() {
627
+ await this.lease();
628
+ try {
629
+ return await this.body();
630
+ } finally {
631
+ this.renewal?.();
632
+ }
633
+ }
634
+ async body() {
471
635
  if (this.runState !== "queued" && this.runState !== "running") {
472
636
  const status = this.runState;
473
637
  await this.write({
@@ -516,11 +680,14 @@ function workflowRunner(options) {
516
680
  const problems = [...checkWorkflow(this.doc, {
517
681
  machine,
518
682
  procedures: options.procedures,
519
- callNamespaces: options.callNamespaces ?? []
520
- }).filter((issue) => issue.level === "error").map((issue) => `${issue.code}: ${issue.message}`), ...runnerProblems(this.doc, limits)];
683
+ callNamespaces: options.callNamespaces ?? [],
684
+ maxTries: limits.tries
685
+ }).filter((issue) => issue.level === "error").map((issue) => `${issue.code}: ${issue.message}`), ...runnerProblems(this.doc)];
521
686
  if (problems.length > 0) return this.finish("reject", "invalid", problems.join(" "));
522
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.`);
523
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)}.`);
524
691
  if (trigger.kind === "feed") {
525
692
  const answer = await this.ask("trigger", "read", trigger.from);
526
693
  if (!answer.ok) return this.finish("refuse", "refused", `The feed cannot read ${String(trigger.from)}: ${answer.why}`);
@@ -788,6 +955,9 @@ function workflowRunner(options) {
788
955
  /** One try of a step. */
789
956
  async attempt(instance, s, scope, attempt, deadline) {
790
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 });
791
961
  const own = typeof s["timeout"] === "number" ? s["timeout"] * 1e3 : 1e400;
792
962
  const left = deadline === void 0 ? 1e400 : Math.max(0, deadline - options.clock.now());
793
963
  const timeout = Math.min(own, left) === 1e400 ? void 0 : Math.min(own, left);
@@ -842,12 +1012,13 @@ function workflowRunner(options) {
842
1012
  };
843
1013
  } finally {
844
1014
  cancel?.();
1015
+ this.lost.signal.removeEventListener("abort", stop);
845
1016
  }
846
1017
  }
847
1018
  procedureAt = /* @__PURE__ */ new Map();
848
1019
  idempotent(at) {
849
1020
  const name = this.procedureAt.get(at);
850
- return name !== void 0 && options.procedures[name]?.idempotent === true;
1021
+ return name !== void 0 && Object.hasOwn(options.procedures, name) && options.procedures[name]?.idempotent === true;
851
1022
  }
852
1023
  /** One effect: the replay of its record, or the grant check and the live call. */
853
1024
  async effect(instance, attempt, effect, signal, open) {
@@ -879,7 +1050,7 @@ function workflowRunner(options) {
879
1050
  if (!namespaces.includes(namespace)) return refuse(`The effect ${effect.kind} is not a call.`);
880
1051
  const name = (namespace === "procedure" ? effect.path.slice(1) : effect.path).map(String).join(".");
881
1052
  this.procedureAt.set(at, name);
882
- const info = options.procedures[name];
1053
+ const info = Object.hasOwn(options.procedures, name) ? options.procedures[name] : void 0;
883
1054
  if (info === void 0) return refuse(`No procedure ${name} is known, thus no grant covers it.`);
884
1055
  if (!isRecord(effect.payload)) return refuse(`The inputs of ${name} are not a record.`);
885
1056
  const payload = effect.payload;
@@ -906,6 +1077,7 @@ function workflowRunner(options) {
906
1077
  key,
907
1078
  try: attempt,
908
1079
  workspace: this.first.owner,
1080
+ depth: this.first.trigger.depth ?? 0,
909
1081
  signal
910
1082
  }));
911
1083
  const bytes = JSON.stringify(value ?? null).length;
@@ -944,41 +1116,10 @@ function workflowRunner(options) {
944
1116
  return {
945
1117
  runIdOf,
946
1118
  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()]
1119
+ resume,
1120
+ recover
980
1121
  };
981
1122
  }
982
- export { RUN_MACHINE, RecordConflict, STEP_MACHINE, memoryStore, workflowRunner };
1123
+ export { RUN_MACHINE, RecordConflict, RunHeld, STEP_MACHINE, memoryStore, workflowRunner };
983
1124
 
984
1125
  //# sourceMappingURL=index.js.map