Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

workflow.ts

897 lines34.7 KB

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