Open History to see the last commit
1// The author-facing primitives. A workflow body is replayed after a restart, so anything that
2// touches the world goes through `step`; these are all a body may use.
3import * as Cause from "effect/Cause";
4import * as Context from "effect/Context";
5import * as DateTime from "effect/DateTime";
6import * as Duration from "effect/Duration";
7import * as Effect from "effect/Effect";
8import * as Option from "effect/Option";
9import * as Result from "effect/Result";
10import * as Schedule from "effect/Schedule";
11import * as Schema from "effect/Schema";
12import * as SchemaAST from "effect/SchemaAST";
13import * as SqlClient from "effect/sql/SqlClient";
14import { Activity, DurableClock, DurableDeferred, Workflow, WorkflowEngine } from "effect/workflow";
15
16import { checkOptions, durationOf } from "./options.ts";
17import {
18 EngineLink,
19 forStep,
20 type InFlight,
21 type InStep,
22 KeyValues,
23 Runs,
24} from "./stepServices.ts";
25import {
26 checkTriggers,
27 type OpenedTrigger,
28 type ScheduleTrigger,
29 type Trigger,
30 type WebhookTrigger,
31} from "./triggers.ts";
32import type { WorkflowAgents } from "./WorkflowAgents.ts";
33import { unavailable, WorkflowForge } from "./WorkflowForge.ts";
34import * as WorkflowStore from "./WorkflowStore.ts";
35
36/** A step that could not be completed. Its run is paused until someone resumes it. */
37export class StepFailed extends Schema.TaggedError<StepFailed>()("StepFailed", {
38 step: Schema.String,
39 reason: Schema.String,
40}) {
41 override get message(): string {
42 return `${this.step}: ${this.reason}`;
43 }
44}
45
46/** The workflow's own decision to end without a result. */
47export class WorkflowStop extends Schema.TaggedError<WorkflowStop>()("WorkflowStop", {
48 reason: Schema.String,
49 /** The run was never for this workflow to do, which lists leave out. */
50 skipped: Schema.optional(Schema.Boolean),
51}) {
52 override get message(): string {
53 return this.reason;
54 }
55}
56
57/** What the primitives need from the run they are called in. */
58export class RunContext extends Context.Service<
59 RunContext,
60 {
61 readonly runId: string;
62 readonly workflow: string;
63 readonly store: WorkflowStore.WorkflowStore["Service"];
64 /** Names used so far in this pass over the body: two steps with one name would share a result. */
65 readonly names: Set<string>;
66 /** What the code of the step `name` may use. */
67 readonly forStep: (name: string) => Context.Context<InStep>;
68 /** The steps running now, which a cancelled run's cleanup waits for. */
69 readonly inFlight: InFlight;
70 /** Have the engine see the agent turn behind the open wait `wait` through, and wake it. */
71 readonly watchTurn: (wait: string) => Effect.Effect<void>;
72 }
73>()("t3/workflows/workflow/RunContext") {}
74
75/** What a workflow body may require: the run it is in, the engine, and somewhere to run agents. */
76export type InRun =
77 | RunContext
78 | WorkflowAgents
79 | WorkflowEngine.WorkflowEngine
80 | WorkflowEngine.WorkflowInstance;
81
82/** Takes `name` for one step of the run. Step results and the step list are both kept by name. */
83export const claim = (name: string, cleanup = false) =>
84 Effect.flatMap(RunContext, (run) => {
85 // The cleanup step's name is its own, or a body step would take it and cleanup never run.
86 if (name === END_STEP && !cleanup) {
87 return Effect.die(
88 new Error(
89 `"${END_STEP}" is the name of workflow ${run.workflow}'s cleanup step. Name this step something else.`,
90 ),
91 );
92 }
93 if (run.names.has(name)) {
94 return Effect.die(
95 new Error(
96 `Two steps in workflow ${run.workflow} are named "${name}". Names are unique in a run.`,
97 ),
98 );
99 }
100 run.names.add(name);
101 return Effect.succeed(run);
102 });
103
104/** An error as one line for a person, with what caused it when the error only wraps something. */
105export const text = (error: unknown): string => {
106 if (typeof error === "string") return WorkflowStore.detailCut(error);
107 if (typeof error !== "object" || error === null) return String(error);
108 // Also an error that came back from the journal, which is its fields and no longer an Error.
109 const fields = error as {
110 readonly message?: unknown;
111 readonly reason?: unknown;
112 cause?: unknown;
113 };
114 const message =
115 typeof fields.message === "string" && fields.message !== ""
116 ? fields.message
117 : typeof fields.reason === "string"
118 ? fields.reason
119 : "Unknown error";
120 return WorkflowStore.detailCut(
121 fields.cause === undefined ? message : `${message}: ${text(fields.cause)}`,
122 );
123};
124
125// What a workflow without `returns` returns: any JSON value, or nothing.
126const ANY_JSON = Schema.UndefinedOr(Schema.Json);
127
128/** Where in `value` JSON cannot hold what it finds, with `undefined` counted only when `strict`. */
129const notJson = (value: unknown, at: string, strict: boolean): string | undefined => {
130 if (value === null || typeof value === "string" || typeof value === "boolean") return undefined;
131 if (typeof value === "number") return Number.isFinite(value) ? undefined : `${at} is ${value}`;
132 if (value === undefined) return strict ? `${at} is undefined` : undefined;
133 if (Array.isArray(value)) {
134 for (const [index, item] of value.entries()) {
135 const found = notJson(item, `${at}[${index}]`, strict);
136 if (found !== undefined) return found;
137 }
138 return undefined;
139 }
140 const proto = typeof value === "object" ? Object.getPrototypeOf(value) : undefined;
141 if (proto !== Object.prototype && proto !== null) {
142 return `${at} is ${typeof value === "object" ? (proto?.constructor?.name ?? "an object") : `a ${typeof value}`}`;
143 }
144 for (const [key, field] of Object.entries(value as object)) {
145 const found = notJson(field, `${at}.${key}`, strict);
146 if (found !== undefined) return found;
147 }
148 return undefined;
149};
150
151/** A value that did not encode, said with where JSON could not hold it, which `Schema.Json` omits. */
152const encodeFailure = (what: string, error: unknown, value: unknown) => {
153 const where = notJson(value, what, true);
154 return where === undefined ? text(error) : `${text(error)}: ${where}`;
155};
156
157/** A step result the journal cannot store, which fails the step it came from. */
158const unstorable = (error: unknown, value: unknown) =>
159 Effect.die(new Error(encodeFailure("the result", error, value)));
160
161/** What a run without `returns` returns, read as `JSON.stringify` reads it. */
162const untypedResult = (value: unknown): Effect.Effect<Schema.Json> => {
163 const where = notJson(value, "the run's result", false);
164 if (where !== undefined) return Effect.die(new Error(`The run's result is not JSON: ${where}.`));
165 return Effect.succeed(
166 value === undefined ? null : (JSON.parse(JSON.stringify(value)) as Schema.Json),
167 );
168};
169
170/**
171 * One journaled action of the step `name`: it happens once, and a replay returns what it stored.
172 * A failure marks the step failed and pauses the run here; resuming the run executes it again.
173 */
174export const journaled = <A, I, E>(
175 run: RunContext["Service"],
176 name: string,
177 action: string,
178 returns: Schema.Codec<A, I>,
179 execute: Effect.Effect<A, E>,
180 // The run waits for a person after this fails, not for `resumeAfter`.
181 held = false,
182) => {
183 const codec = Schema.toCodecJson(returns);
184 const encodable = Schema.encodeEffect(codec);
185 return Activity.make({
186 name: action,
187 success: returns,
188 error: StepFailed,
189 execute: run.inFlight.track(run.runId, execute).pipe(
190 // A result the journal cannot store is this step's failure, found before it is journaled.
191 Effect.tap((value) => Effect.catch(encodable(value), (error) => unstorable(error, value))),
192 // The engine reads its own 64-bit ids as BigInt. What a step calls must not inherit that.
193 Effect.provideService(SqlClient.SafeIntegers, false),
194 // Also a step that dies: left as a defect the engine would park the run without a word.
195 Effect.catchCause((cause) =>
196 Cause.hasInterruptsOnly(cause)
197 ? Effect.failCause(cause as Cause.Cause<never>)
198 : Effect.fail(new StepFailed({ step: name, reason: text(Cause.squash(cause)) })),
199 ),
200 Effect.tapError((error) =>
201 Effect.andThen(
202 run.store.stepEnded(run.runId, name, "failed", error.reason),
203 run.store.runPaused(run.runId, error.message, held),
204 ),
205 ),
206 ),
207 });
208};
209
210/** How an invoked run ended, as its parent's wait receives it. */
211export const ChildEnd = Schema.Struct({
212 outcome: Schema.Literals(["completed", "stopped", "skipped", "cancelled"]),
213 value: Schema.Json,
214 reason: Schema.optional(Schema.String),
215});
216
217export interface StepRetry {
218 /** How many more times to try before the run is paused. */
219 readonly times: number;
220 readonly schedule?: Schedule.Schedule<unknown, unknown>;
221}
222// Once, unless asked: a step that posts or merges must not do it again after a lost reply.
223const DEFAULT_RETRY: StepRetry = { times: 0 };
224
225const checkStepOptions = (what: string, options: { readonly retry?: StepRetry | undefined }) => {
226 checkOptions(what, options, ["returns", "retry"]);
227 checkOptions(`${what}'s retry`, options?.retry, ["times", "schedule"]);
228};
229
230/** How `step.try` ended: its value, or why it failed once its retries were used up. */
231export type StepAttempt<A> =
232 | { readonly outcome: "done"; readonly value: A }
233 | { readonly outcome: "failed"; readonly reason: string };
234
235const attemptOf = <A, I>(returns: Schema.Codec<A, I>) =>
236 Schema.Union([
237 Schema.Struct({ outcome: Schema.Literal("done"), value: returns }),
238 Schema.Struct({ outcome: Schema.Literal("failed"), reason: Schema.String }),
239 ]);
240
241/**
242 * Do something once per run. The result is stored, and a replay returns the stored result.
243 *
244 * A failure is retried by `retry`, then pauses the run at this step: resuming the run runs the step
245 * again. Nothing in the body can catch that. For a failure the workflow decides about, use
246 * `step.try`.
247 */
248export const step = Object.assign(
249 <A, I, E>(
250 name: string,
251 options: { readonly returns: Schema.Codec<A, I>; readonly retry?: StepRetry },
252 code: Effect.Effect<A, E, InStep>,
253 ): Effect.Effect<A, never, InRun> => {
254 checkStepOptions(`step("${name}")`, options);
255 return Effect.orDie(stepAs(claim(name), name, options, code));
256 },
257 {
258 /** As `step`, but a failure left after the retries comes back as `failed` with the reason. */
259 try: <A, I, E>(
260 name: string,
261 options: { readonly returns: Schema.Codec<A, I>; readonly retry?: StepRetry },
262 code: Effect.Effect<A, E, InStep>,
263 ): Effect.Effect<StepAttempt<A>, never, InRun> => {
264 checkStepOptions(`step.try("${name}")`, options);
265 return Effect.orDie(
266 stepAs(
267 claim(name),
268 name,
269 { returns: attemptOf(options.returns), retry: options.retry },
270 code,
271 (tried) =>
272 tried.pipe(
273 Effect.map((value): StepAttempt<A> => ({ outcome: "done", value })),
274 Effect.catchCause((cause) =>
275 Cause.hasInterruptsOnly(cause)
276 ? Effect.failCause(cause as Cause.Cause<never>)
277 : Effect.succeed<StepAttempt<A>>({
278 outcome: "failed",
279 reason: text(Cause.squash(cause)),
280 }),
281 ),
282 ),
283 ),
284 );
285 },
286 },
287);
288
289const stepAs = <A, I, X, E>(
290 claimed: Effect.Effect<RunContext["Service"], never, InRun>,
291 name: string,
292 options: { readonly returns: Schema.Codec<A, I>; readonly retry?: StepRetry | undefined },
293 code: Effect.Effect<X, E, InStep>,
294 // What the step makes of its tries: by default their value, or their failure.
295 settle: (tried: Effect.Effect<X, E>) => Effect.Effect<A, E> = (tried) =>
296 tried as unknown as Effect.Effect<A, E>,
297): Effect.Effect<A, StepFailed, InRun> =>
298 Effect.flatMap(claimed, (run) => {
299 const retry = options.retry ?? DEFAULT_RETRY;
300 const resultCodec = Schema.toCodecJson(options.returns);
301 const encodeResult = Schema.encodeEffect(resultCodec);
302 // Made per try, so a retry numbers its signals from the start again and counts as an attempt.
303 const execute = Effect.andThen(
304 run.store.stepStarted(run.runId, name, "step"),
305 Effect.suspend(() => Effect.provideContext(code, run.forStep(name))),
306 );
307 return journaled(
308 run,
309 name,
310 `step/${name}`,
311 options.returns,
312 settle(
313 retry.times === 0
314 ? execute
315 : Effect.retry(execute, {
316 times: retry.times,
317 ...(retry.schedule === undefined ? {} : { schedule: retry.schedule }),
318 }),
319 ).pipe(
320 // A value that does not encode fails the step, so it is never marked done first.
321 Effect.tap((value) =>
322 Effect.flatMap(
323 Effect.catch(encodeResult(value), (error) => unstorable(error, value)),
324 (json) =>
325 Effect.andThen(
326 run.store.stepEnded(run.runId, name, "completed", null),
327 // For a person reading the run.
328 Effect.ignore(run.store.stepResult(run.runId, name, json as Schema.Json)),
329 ),
330 ),
331 ),
332 ),
333 );
334 });
335
336/** A sleep that survives a restart. */
337export const sleep = Effect.fn("workflow.sleep")(function* (
338 name: string,
339 duration: Duration.Input,
340): Effect.fn.Return<void, never, InRun> {
341 const length = durationOf(`sleep("${name}")`, duration);
342 const run = yield* claim(name);
343 // Listed like any step, with when it wakes, so a run that sleeps for days says so.
344 yield* Activity.make({
345 name: `sleep/${name}/open`,
346 execute: Effect.gen(function* () {
347 const wakes = DateTime.addDuration(yield* DateTime.now, length);
348 yield* run.store.stepStarted(run.runId, name, "sleep");
349 yield* run.store.stepDetail(run.runId, name, DateTime.formatIso(wakes));
350 yield* run.store.runStatus(run.runId, "waiting", `sleep ${name}`);
351 }),
352 });
353 // Effect keeps a short sleep in memory, where a restart would start it over.
354 yield* DurableClock.sleep({
355 name: `sleep/${name}`,
356 duration: length,
357 inMemoryThreshold: Duration.zero,
358 });
359 yield* Activity.make({
360 name: `sleep/${name}/close`,
361 execute: Effect.andThen(
362 run.store.stepEnded(run.runId, name, "completed", null),
363 run.store.runResumed(run.runId),
364 ),
365 });
366});
367
368export const Woke = Schema.Struct({ expired: Schema.Boolean, value: Schema.Json });
369export const wakeOf = (name: string) => DurableDeferred.make(`wait/${name}`, { success: Woke });
370const finite = [Schema.isFinite()] as const;
371// JSON carries a bare `Schema.Number` as a number or the text "Infinity", "-Infinity" or "NaN",
372// and that form drops the number's own checks. Whoever writes the value is told a finite number
373// with its checks instead. Transformations and recursion keep their own form.
374const finiteNumbers = (ast: SchemaAST.AST): SchemaAST.AST => {
375 if (ast.encoding !== undefined) return ast;
376 if (SchemaAST.isNumber(ast)) {
377 return new SchemaAST.Number(
378 ast.annotations,
379 ast.checks === undefined ? finite : [...ast.checks, ...finite],
380 undefined,
381 ast.context,
382 );
383 }
384 if (SchemaAST.isObjects(ast)) {
385 return new SchemaAST.Objects(
386 ast.propertySignatures.map(
387 (field) => new SchemaAST.PropertySignature(field.name, finiteNumbers(field.type)),
388 ),
389 ast.indexSignatures.map(
390 (index) => new SchemaAST.IndexSignature(index.parameter, finiteNumbers(index.type)),
391 ),
392 ast.annotations,
393 ast.checks,
394 undefined,
395 ast.context,
396 ast.encodingChecks,
397 );
398 }
399 if (SchemaAST.isArrays(ast)) {
400 return new SchemaAST.Arrays(
401 ast.isMutable,
402 ast.elements.map(finiteNumbers),
403 ast.rest.map(finiteNumbers),
404 ast.annotations,
405 ast.checks,
406 undefined,
407 ast.context,
408 ast.encodingChecks,
409 );
410 }
411 if (SchemaAST.isUnion(ast)) {
412 return new SchemaAST.Union(
413 ast.types.map(finiteNumbers),
414 ast.options,
415 ast.annotations,
416 ast.checks,
417 undefined,
418 ast.context,
419 ast.encodingChecks,
420 );
421 }
422 return ast;
423};
424
425/** What a value must look like, as JSON Schema; `closed` objects turn down keys they do not name. */
426export const jsonSchemaOf = (schema: Schema.Top, closed = false): Record<string, Schema.Json> => {
427 const document = Schema.toJsonSchemaDocument(
428 Schema.make(finiteNumbers(schema.ast)),
429 closed ? { onExcessProperty: "error" } : undefined,
430 );
431 return { ...document.schema, $defs: document.definitions } as Record<string, Schema.Json>;
432};
433
434/** `wait`, also as the question a person answers: `request` is what an inbox shows them. */
435export const waitAs = Effect.fn("workflow.wait")(function* <A, I>(
436 kind: "wait" | "ask",
437 name: string,
438 options: WaitOptions<A, I>,
439): Effect.fn.Return<Option.Option<A>, StepFailed, InRun> {
440 return yield* waitClaimed(yield* claim(name), kind, name, options);
441});
442
443interface WaitOptions<A, I> {
444 readonly returns: Schema.Codec<A, I>;
445 readonly timeout?: Duration.Input | undefined;
446 readonly channel?: string | undefined;
447 readonly request?: Schema.Json | undefined;
448 /** What the engine looks at to end the wait by itself. */
449 readonly watch?: Schema.Json | undefined;
450}
451
452const sameAddress = (left: WorkflowStore.SignalAddress, right: WorkflowStore.SignalAddress) =>
453 "runId" in left
454 ? "runId" in right && left.runId === right.runId && left.wait === right.wait
455 : "channel" in right && left.workflow === right.workflow && left.channel === right.channel;
456
457const waitClaimed = Effect.fnUntraced(function* <A, I>(
458 run: RunContext["Service"],
459 kind: "wait" | "ask",
460 name: string,
461 options: WaitOptions<A, I>,
462): Effect.fn.Return<Option.Option<A>, StepFailed, InRun> {
463 const here: WorkflowStore.SignalAddress = { runId: run.runId, wait: name };
464 const schema = jsonSchemaOf(options.returns);
465 const codec = Schema.toCodecJson(options.returns);
466 const decode = Schema.decodeEffect(codec);
467 const fits = (value: Schema.Json) => Effect.result(decode(value));
468 const addresses: ReadonlyArray<WorkflowStore.SignalAddress> =
469 options.channel === undefined
470 ? [here]
471 : [here, { workflow: run.workflow, channel: options.channel }];
472 // Whatever arrived early is delivered now, checked as this wait reads it. The mail goes only
473 // after the wake: waking twice is harmless, and losing the signal is not.
474 const deliverEarly = Effect.fnUntraced(function* (
475 wake: ReturnType<typeof wakeOf>,
476 token: DurableDeferred.Token,
477 ) {
478 const passed = new Set<string>();
479 while (true) {
480 const early = yield* run.store.mailNext(addresses, passed);
481 if (early === undefined) return;
482 const value = WorkflowStore.jsonValue(early.valueJson);
483 if (Result.isFailure(yield* fits(value))) {
484 // Kept when it went to a channel: another run, or another version, may read it.
485 if (sameAddress(early.address, here)) yield* run.store.mailDelete(early.signalId);
486 passed.add(early.signalId);
487 continue;
488 }
489 const woke = { expired: false, value };
490 const outcome = yield* run.store.mailDeliver(early.signalId, run.runId, name, woke);
491 // Another wait on the same key took that one; there may be a next.
492 if (outcome === "gone") continue;
493 // Another signal claimed this wait first: its wake, or the sweep, carries what it claimed.
494 if (outcome === "claimed") return;
495 yield* DurableDeferred.succeed(wake, { token, value: woke });
496 return;
497 }
498 });
499 const first = wakeOf(name);
500 const firstToken = yield* DurableDeferred.token(first);
501 yield* Activity.make({
502 name: `wait/${name}/open`,
503 execute: Effect.gen(function* () {
504 const deadline =
505 options.timeout === undefined
506 ? null
507 : DateTime.formatIso(
508 DateTime.addDuration(yield* DateTime.now, Duration.fromInputUnsafe(options.timeout)),
509 );
510 yield* run.store.stepStarted(run.runId, name, kind);
511 yield* run.store.waitOpened({
512 runId: run.runId,
513 name,
514 workflow: run.workflow,
515 key: options.channel,
516 token: firstToken,
517 schemaJson: WorkflowStore.jsonText(schema),
518 requestJson: options.request === undefined ? null : WorkflowStore.jsonText(options.request),
519 watchJson: options.watch === undefined ? null : WorkflowStore.jsonText(options.watch),
520 deadline,
521 });
522 yield* run.store.runStatus(run.runId, "waiting", name);
523 yield* deliverEarly(first, firstToken);
524 }),
525 });
526 // A value that fit the wait's JSON Schema can still fail its codec. It was not for this wait,
527 // so the wait opens again under a fresh wake instead of breaking the run on every replay.
528 let wake = first;
529 for (let again = 1; ; again++) {
530 const woke = yield* DurableDeferred.await(wake);
531 const value = woke.expired ? undefined : yield* fits(woke.value);
532 if (value !== undefined && Result.isFailure(value)) {
533 const problem = `It was signalled with a value it cannot read, and waits again: ${text(value.failure)}`;
534 wake = wakeOf(`${name}/again/${again}`);
535 const token = yield* DurableDeferred.token(wake);
536 const next = wake;
537 yield* Activity.make({
538 name: `wait/${name}/again/${again}`,
539 execute: Effect.gen(function* () {
540 yield* run.store.waitReopened(run.runId, name, token);
541 yield* run.store.stepDetail(run.runId, name, WorkflowStore.detailCut(problem));
542 yield* deliverEarly(next, token);
543 }),
544 });
545 continue;
546 }
547 yield* Activity.make({
548 name: `wait/${name}/close`,
549 execute: Effect.gen(function* () {
550 yield* run.store.waitClosed(run.runId, name);
551 yield* run.store.stepEnded(run.runId, name, "completed", woke.expired ? "timed out" : null);
552 if (!woke.expired) yield* run.store.stepResult(run.runId, name, woke.value);
553 yield* run.store.runResumed(run.runId);
554 }),
555 });
556 return value === undefined ? Option.none() : Option.some(value.success);
557 }
558});
559
560/**
561 * Sleep until something outside signals this wait; `None` when the timeout passes first.
562 * Addressed by run and wait name, or by `channel` (scoped to the workflow's name) when the sender
563 * cannot know the run. A signal sent before the wait opened is delivered when it opens.
564 */
565export const wait = <A, I>(
566 name: string,
567 options: {
568 readonly returns: Schema.Codec<A, I>;
569 readonly timeout?: Duration.Input;
570 readonly channel?: string;
571 },
572): Effect.Effect<Option.Option<A>, never, InRun> => {
573 checkOptions(`wait("${name}")`, options, ["returns", "timeout", "channel"]);
574 return Effect.orDie(waitAs("wait", name, options));
575};
576
577/** End the run by the workflow's own decision. It ends as `stopped`, which is not a failure. */
578export const stop = (reason: string): Effect.Effect<never, WorkflowStop> =>
579 Effect.fail(new WorkflowStop({ reason }));
580
581/**
582 * End the run because it was not this workflow's to do: a webhook delivery it ignores, a pull
583 * request it opened itself. It ends as `skipped`, which lists leave out unless asked. Use `stop`
584 * for a run that did something and then decided to end.
585 */
586export const skip = (reason: string): Effect.Effect<never, WorkflowStop> =>
587 Effect.fail(new WorkflowStop({ reason, skipped: true }));
588
589/** Name the run in lists. Defaults to the workflow's name and the run's key. */
590export const title = (
591 value: string,
592 ...rest: ReadonlyArray<never>
593): Effect.Effect<void, never, InRun> => {
594 // Files are not type-checked, so `title("name", text)` would title the run "name".
595 if (typeof value !== "string" || rest.length > 0) {
596 throw new Error("title takes only the text, as in title(`Release ${name}`), and no step name.");
597 }
598 return Effect.flatMap(RunContext, (current) => {
599 // Numbered by how many came before in the body, which a replay walks the same way.
600 let n = 0;
601 while (current.names.has(`title/${n}`)) n++;
602 const name = `title/${n}`;
603 return Effect.flatMap(claim(name), (run) =>
604 Activity.make({ name, execute: run.store.runTitle(run.runId, value) }),
605 );
606 }).pipe(Effect.orDie);
607};
608
609// The defaults are every workflow: a registry holds workflows of every payload and result type.
610export interface WorkflowDefinition<P = never, A = unknown> {
611 /** Types only: what a run is started with and what it returns, for `start` and `invoke`. */
612 readonly "~types"?: { readonly payload: (payload: P) => void; readonly returns: A };
613 readonly name: string;
614 readonly version: number;
615 readonly payload: Schema.Codec<unknown, unknown>;
616 readonly returns: Schema.Codec<unknown, unknown>;
617 /** How long a paused run rests before it is resumed by itself, per pause in a row. */
618 readonly resumeAfter: ReadonlyArray<Duration.Input>;
619 readonly triggers: ReadonlyArray<ScheduleTrigger | WebhookTrigger | OpenedTrigger>;
620 /** Fails with the reason as text: by here nothing reads the error but a person. */
621 readonly onEnd:
622 | ((payload: never, end: RunEnd) => Effect.Effect<void, string, InStep>)
623 | undefined;
624 // The registry holds workflows of every payload type; `workflow` is where the types are checked.
625 readonly body: (
626 payload: never,
627 run: { readonly id: string },
628 ) => Effect.Effect<unknown, StepFailed | WorkflowStop, InRun>;
629}
630
631/** How a run ended, as its `onEnd` is told. A paused run has not ended. */
632export interface RunEnd {
633 readonly id: string;
634 readonly outcome: "completed" | "stopped" | "skipped" | "cancelled";
635 readonly reason: string | undefined;
636}
637
638/**
639 * Run another workflow as part of this one and wait for how it ends. The other run is a run of
640 * its own, listed and resumable by itself; cancelling this run cancels it. A run that paused has
641 * not ended, so this waits on while someone resumes it.
642 */
643export const invoke = <P, A>(
644 name: string,
645 workflow: WorkflowDefinition<P, A>,
646 payload: P,
647 options?: { readonly key?: string },
648): Effect.Effect<
649 | { readonly outcome: "completed"; readonly value: A }
650 | { readonly outcome: "stopped" | "skipped" | "cancelled"; readonly reason: string },
651 never,
652 InRun
653> => {
654 // Files are not type-checked, and a name would start nothing until its first step failed.
655 if (typeof workflow !== "object" || workflow === null || typeof workflow.name !== "string") {
656 return Effect.die(
657 new Error(
658 `invoke takes the workflow definition, not its name: invoke("${name}", …) was given ${JSON.stringify(workflow)}. Pass what workflow(…) returned.`,
659 ),
660 );
661 }
662 checkOptions(`invoke("${name}")`, options, ["key"]);
663 return Effect.orDie(invokeAs(name, workflow, payload, options));
664};
665
666const invokeAs = Effect.fn("workflow.invoke")(function* <P, A>(
667 name: string,
668 workflow: WorkflowDefinition<P, A>,
669 payload: P,
670 options?: { readonly key?: string },
671): Effect.fn.Return<
672 | { readonly outcome: "completed"; readonly value: A }
673 | { readonly outcome: "stopped" | "skipped" | "cancelled"; readonly reason: string },
674 StepFailed,
675 InRun
676> {
677 // Taken before the child starts: a name already used would refuse the wait after the start.
678 const run = yield* claim(name);
679 yield* step(
680 `${name}/start`,
681 { returns: Schema.String },
682 Effect.flatMap(Runs, (runs) =>
683 runs.start(workflow.name, payload, {
684 version: workflow.version,
685 idempotencyKey: options?.key ?? `${run.runId}/${name}`,
686 parent: { runId: run.runId, wait: name },
687 }),
688 ).pipe(Effect.map((started) => started.runId)),
689 );
690 const ended = yield* waitClaimed(run, "wait", name, { returns: ChildEnd });
691 if (Option.isNone(ended)) {
692 return yield* new StepFailed({ step: name, reason: "the wait ended without an outcome" });
693 }
694 if (ended.value.outcome !== "completed") {
695 return { outcome: ended.value.outcome, reason: ended.value.reason ?? "" };
696 }
697 const returnsCodec = Schema.toCodecJson(workflow.returns);
698 const decode = Schema.decodeEffect(returnsCodec);
699 const value = yield* decode(ended.value.value).pipe(
700 Effect.mapError((error) => new StepFailed({ step: name, reason: text(error) })),
701 );
702 return { outcome: "completed", value: value as A };
703});
704
705/** The step `onEnd` runs as. */
706export const END_STEP = "onEnd";
707const END_RETRY: StepRetry = { times: 3, schedule: Schedule.exponential("2 seconds") };
708
709const DEFAULT_RESUME_AFTER: ReadonlyArray<Duration.Input> = [
710 "5 minutes",
711 "20 minutes",
712 "80 minutes",
713];
714
715/**
716 * A workflow: a name, a version, and a body.
717 *
718 * A run keeps the version it started with. To change the order of steps or the shape of a stored
719 * result, register the new body under a higher version and keep the old one registered until its
720 * runs have ended.
721 */
722export const workflow = <P, PI, A = void, AI = void, EndError = never>(
723 name: string,
724 options: {
725 readonly version: number;
726 readonly payload: Schema.Codec<P, PI>;
727 readonly returns?: Schema.Codec<A, AI>;
728 readonly resumeAfter?: ReadonlyArray<Duration.Input>;
729 /** What starts a run by itself. Each must give what `payload` takes. */
730 readonly triggers?: ReadonlyArray<Trigger<P>>;
731 /**
732 * Runs once when the run ends, however it ends, to give back what the run took: a machine, a
733 * lock. It gets the payload and the run's id, not the body's values, so name what the run
734 * takes after its id. It must be safe to run for a run that took nothing.
735 */
736 readonly onEnd?: (payload: P, end: RunEnd) => Effect.Effect<unknown, EndError, InStep>;
737 },
738 body: (
739 payload: P,
740 run: { readonly id: string },
741 ) => Effect.Effect<A, StepFailed | WorkflowStop, InRun>,
742): WorkflowDefinition<P, A> => {
743 checkOptions(`workflow("${name}")`, options, [
744 "version",
745 "payload",
746 "returns",
747 "resumeAfter",
748 "triggers",
749 "onEnd",
750 ]);
751 // Read once now, so a duration that does not parse fails the file and not a paused run later.
752 for (const rest of options.resumeAfter ?? [])
753 durationOf(`workflow("${name}")'s resumeAfter`, rest);
754 checkTriggers(name, options.triggers ?? []);
755 return definitionOf(name, options, body);
756};
757
758const definitionOf = <P, PI, A, AI, EndError>(
759 name: string,
760 options: Parameters<typeof workflow<P, PI, A, AI, EndError>>[1],
761 body: Parameters<typeof workflow<P, PI, A, AI, EndError>>[2],
762): WorkflowDefinition<P, A> => ({
763 name,
764 version: options.version,
765 // Erased here, once: the registry holds workflows of every payload and result type.
766 payload: options.payload as Schema.Codec<unknown, unknown>,
767 // Without a schema the result is whatever JSON the body returned: dropping it would be a
768 // surprise, and a value that is not JSON pauses the run with the reason.
769 returns: (options.returns ?? ANY_JSON) as Schema.Codec<unknown, unknown>,
770 resumeAfter: options.resumeAfter ?? DEFAULT_RESUME_AFTER,
771 triggers: options.triggers ?? [],
772 onEnd:
773 options.onEnd === undefined
774 ? undefined
775 : (payload, end) => options.onEnd!(payload, end).pipe(Effect.asVoid, Effect.mapError(text)),
776 body,
777});
778
779export const engineTag = (definition: Pick<WorkflowDefinition, "name" | "version">) =>
780 `${definition.name}@${definition.version}`;
781
782const Outcome = Schema.Struct({
783 outcome: Schema.Literals(["completed", "stopped", "skipped"]),
784 value: Schema.Json,
785 reason: Schema.optional(Schema.String),
786});
787
788export const engineWorkflow = (definition: WorkflowDefinition) =>
789 Workflow.make(engineTag(definition), {
790 payload: { idempotencyKey: Schema.String, input: Schema.Json },
791 idempotencyKey: (payload) => payload.idempotencyKey,
792 success: Outcome,
793 error: Schema.Union([StepFailed, WorkflowStop]),
794 // A failure parks the run instead of ending it; only an explicit resume wakes it.
795 }).annotate(Workflow.SuspendOnFailure, true);
796export type EngineWorkflow = ReturnType<typeof engineWorkflow>;
797
798export const layerDefinition = (definition: WorkflowDefinition, engine: EngineWorkflow) => {
799 const payloadCodec = Schema.toCodecJson(definition.payload);
800 const decodePayload = Schema.decodeEffect(payloadCodec);
801 const returnsCodec = Schema.toCodecJson(definition.returns);
802 const encodeResult = Schema.encodeUnknownEffect(returnsCodec);
803 return engine.toLayer((payload, runId) =>
804 Effect.gen(function* () {
805 const store = yield* WorkflowStore.WorkflowStore;
806 const keyValues = yield* KeyValues;
807 const link = yield* EngineLink;
808 const forge = Option.getOrElse(yield* Effect.serviceOption(WorkflowForge), () => unavailable);
809 yield* Activity.make({
810 name: "run/begin",
811 execute: store.runStarted({
812 runId,
813 workflow: definition.name,
814 version: definition.version,
815 engineTag: engineTag(definition),
816 idempotencyKey: payload.idempotencyKey,
817 input: payload.input,
818 }),
819 });
820 const input = (yield* Effect.orDie(decodePayload(payload.input))) as never;
821 const outcome = yield* definition.body(input, { id: runId }).pipe(
822 Effect.flatMap((value) =>
823 definition.returns === ANY_JSON
824 ? untypedResult(value)
825 : encodeResult(value).pipe(
826 Effect.mapError(
827 (error) =>
828 new Error(
829 `The run's result does not fit its returns: ${encodeFailure("the run's result", error, value)}`,
830 ),
831 ),
832 Effect.orDie,
833 ),
834 ),
835 Effect.map((value): typeof Outcome.Type => ({
836 outcome: "completed",
837 value: (value ?? null) as Schema.Json,
838 })),
839 Effect.catchTags({
840 WorkflowStop: (stopped) =>
841 Effect.succeed<typeof Outcome.Type>({
842 outcome: stopped.skipped === true ? "skipped" : "stopped",
843 value: null,
844 reason: stopped.reason,
845 }),
846 }),
847 // A step like any other: a cleanup that fails pauses the run, and resuming tries it again.
848 Effect.tap((ended) =>
849 definition.onEnd === undefined
850 ? Effect.void
851 : stepAs(
852 claim(END_STEP, true),
853 END_STEP,
854 // A cleanup is safe to run again, and has nobody else to try it.
855 { returns: Schema.Void, retry: END_RETRY },
856 definition.onEnd(input, {
857 id: runId,
858 outcome: ended.outcome,
859 reason: ended.reason,
860 }),
861 ),
862 ),
863 Effect.provideService(
864 RunContext,
865 RunContext.of({
866 runId,
867 workflow: definition.name,
868 store,
869 names: new Set(),
870 forStep: (name) => forStep(store, keyValues, link, forge, runId, name),
871 inFlight: link.inFlight,
872 watchTurn: Effect.fn("RunContext.watchTurn")(function* (wait: string) {
873 if (link.current !== undefined) yield* link.current.watchTurn(runId, wait);
874 }),
875 }),
876 ),
877 );
878 yield* Activity.make({
879 name: "run/end",
880 execute: Effect.asVoid(
881 store.runEnded(runId, outcome.outcome, outcome.reason ?? null, outcome.value),
882 ),
883 });
884 yield* Activity.make({
885 name: "run/told",
886 execute: Effect.suspend(() => link.current?.ended(runId) ?? Effect.void),
887 });
888 return outcome;
889 }).pipe(
890 // A failing step marked the run paused itself. What reaches here otherwise is the body
891 // breaking outside a step: a duplicate name, a payload that no longer decodes.
892 Effect.tapCause((cause) =>
893 Cause.hasInterruptsOnly(cause)
894 ? Effect.void
895 : Effect.flatMap(WorkflowStore.WorkflowStore, (store) =>
896 store.runPaused(runId, text(Cause.squash(cause))),
897 ),
898 ),
899 ),
900 );
901};