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
452/**
453 * A signal's value as a question's wait receives it: with who sent it and when, as the server saw
454 * them. What the value itself says of those is the sender's word and is dropped. Undefined for a
455 * wait that is not a question, a value that is no answer, and a question asked before answers
456 * kept who gave them, whose closed schema would refuse the stamp.
457 */
458export const answerStamped = (
459 wait: { readonly request: boolean; readonly schemaJson: string },
460 value: Schema.Json,
461 sender: WorkflowStore.SignalSender,
462): Schema.JsonObject | undefined => {
463 if (!wait.request || typeof value !== "object" || value === null || Array.isArray(value)) {
464 return undefined;
465 }
466 if (!wait.schemaJson.includes('"answeredAt"')) return undefined;
467 const {
468 answeredBy: _by,
469 answeredBySession: _session,
470 answeredAt: _at,
471 ...given
472 } = value as Schema.JsonObject;
473 return {
474 ...given,
475 ...(sender.answeredBy === undefined ? {} : { answeredBy: sender.answeredBy }),
476 // A question asked before answers kept the session has a closed schema without it.
477 ...(sender.answeredBySession === undefined || !wait.schemaJson.includes('"answeredBySession"')
478 ? {}
479 : { answeredBySession: sender.answeredBySession }),
480 answeredAt: sender.answeredAt,
481 };
482};
483
484const sameAddress = (left: WorkflowStore.SignalAddress, right: WorkflowStore.SignalAddress) =>
485 "runId" in left
486 ? "runId" in right && left.runId === right.runId && left.wait === right.wait
487 : "channel" in right && left.workflow === right.workflow && left.channel === right.channel;
488
489const waitClaimed = Effect.fnUntraced(function* <A, I>(
490 run: RunContext["Service"],
491 kind: "wait" | "ask",
492 name: string,
493 options: WaitOptions<A, I>,
494): Effect.fn.Return<Option.Option<A>, StepFailed, InRun> {
495 const here: WorkflowStore.SignalAddress = { runId: run.runId, wait: name };
496 const schema = jsonSchemaOf(options.returns);
497 const question = {
498 request: options.request !== undefined,
499 schemaJson: WorkflowStore.jsonText(schema),
500 };
501 const codec = Schema.toCodecJson(options.returns);
502 const decode = Schema.decodeEffect(codec);
503 const fits = (value: Schema.Json) => Effect.result(decode(value));
504 const addresses: ReadonlyArray<WorkflowStore.SignalAddress> =
505 options.channel === undefined
506 ? [here]
507 : [here, { workflow: run.workflow, channel: options.channel }];
508 // Whatever arrived early is delivered now, checked as this wait reads it. The mail goes only
509 // after the wake: waking twice is harmless, and losing the signal is not.
510 const deliverEarly = Effect.fnUntraced(function* (
511 wake: ReturnType<typeof wakeOf>,
512 token: DurableDeferred.Token,
513 ) {
514 const passed = new Set<string>();
515 while (true) {
516 const early = yield* run.store.mailNext(addresses, passed);
517 if (early === undefined) return;
518 const sent = WorkflowStore.jsonValue(early.valueJson);
519 // An answer is its sender's as the server recorded on receiving it. One kept before signals
520 // kept that has no name, and its time is this one.
521 const value =
522 answerStamped(
523 question,
524 sent,
525 early.sender ?? { answeredAt: DateTime.formatIso(yield* DateTime.now) },
526 ) ?? sent;
527 if (Result.isFailure(yield* fits(value))) {
528 // Kept when it went to a channel: another run, or another version, may read it.
529 if (sameAddress(early.address, here)) yield* run.store.mailDelete(early.signalId);
530 passed.add(early.signalId);
531 continue;
532 }
533 const woke = { expired: false, value };
534 const outcome = yield* run.store.mailDeliver(early.signalId, run.runId, name, woke);
535 // Another wait on the same key took that one; there may be a next.
536 if (outcome === "gone") continue;
537 // Another signal claimed this wait first: its wake, or the sweep, carries what it claimed.
538 if (outcome === "claimed") return;
539 yield* DurableDeferred.succeed(wake, { token, value: woke });
540 return;
541 }
542 });
543 const first = wakeOf(name);
544 const firstToken = yield* DurableDeferred.token(first);
545 yield* Activity.make({
546 name: `wait/${name}/open`,
547 execute: Effect.gen(function* () {
548 const deadline =
549 options.timeout === undefined
550 ? null
551 : DateTime.formatIso(
552 DateTime.addDuration(yield* DateTime.now, Duration.fromInputUnsafe(options.timeout)),
553 );
554 yield* run.store.stepStarted(run.runId, name, kind);
555 yield* run.store.waitOpened({
556 runId: run.runId,
557 name,
558 workflow: run.workflow,
559 key: options.channel,
560 token: firstToken,
561 schemaJson: question.schemaJson,
562 requestJson: options.request === undefined ? null : WorkflowStore.jsonText(options.request),
563 watchJson: options.watch === undefined ? null : WorkflowStore.jsonText(options.watch),
564 deadline,
565 });
566 yield* run.store.runStatus(run.runId, "waiting", name);
567 yield* deliverEarly(first, firstToken);
568 }),
569 });
570 // A value that fit the wait's JSON Schema can still fail its codec. It was not for this wait,
571 // so the wait opens again under a fresh wake instead of breaking the run on every replay.
572 let wake = first;
573 for (let again = 1; ; again++) {
574 const woke = yield* DurableDeferred.await(wake);
575 const value = woke.expired ? undefined : yield* fits(woke.value);
576 if (value !== undefined && Result.isFailure(value)) {
577 const problem = `It was signalled with a value it cannot read, and waits again: ${text(value.failure)}`;
578 wake = wakeOf(`${name}/again/${again}`);
579 const token = yield* DurableDeferred.token(wake);
580 const next = wake;
581 yield* Activity.make({
582 name: `wait/${name}/again/${again}`,
583 execute: Effect.gen(function* () {
584 yield* run.store.waitReopened(run.runId, name, token);
585 yield* run.store.stepDetail(run.runId, name, WorkflowStore.detailCut(problem));
586 yield* deliverEarly(next, token);
587 }),
588 });
589 continue;
590 }
591 yield* Activity.make({
592 name: `wait/${name}/close`,
593 execute: Effect.gen(function* () {
594 yield* run.store.waitClosed(run.runId, name);
595 yield* run.store.stepEnded(run.runId, name, "completed", woke.expired ? "timed out" : null);
596 if (!woke.expired) yield* run.store.stepResult(run.runId, name, woke.value);
597 yield* run.store.runResumed(run.runId);
598 }),
599 });
600 return value === undefined ? Option.none() : Option.some(value.success);
601 }
602});
603
604/**
605 * Sleep until something outside signals this wait; `None` when the timeout passes first.
606 * Addressed by run and wait name, or by `channel` (scoped to the workflow's name) when the sender
607 * cannot know the run. A signal sent before the wait opened is delivered when it opens.
608 */
609export const wait = <A, I>(
610 name: string,
611 options: {
612 readonly returns: Schema.Codec<A, I>;
613 readonly timeout?: Duration.Input;
614 readonly channel?: string;
615 },
616): Effect.Effect<Option.Option<A>, never, InRun> => {
617 checkOptions(`wait("${name}")`, options, ["returns", "timeout", "channel"]);
618 return Effect.orDie(waitAs("wait", name, options));
619};
620
621/** End the run by the workflow's own decision. It ends as `stopped`, which is not a failure. */
622export const stop = (reason: string): Effect.Effect<never, WorkflowStop> =>
623 Effect.fail(new WorkflowStop({ reason }));
624
625/**
626 * End the run because it was not this workflow's to do: a webhook delivery it ignores, a pull
627 * request it opened itself. It ends as `skipped`, which lists leave out unless asked. Use `stop`
628 * for a run that did something and then decided to end.
629 */
630export const skip = (reason: string): Effect.Effect<never, WorkflowStop> =>
631 Effect.fail(new WorkflowStop({ reason, skipped: true }));
632
633/** Name the run in lists. Defaults to the workflow's name and the run's key. */
634export const title = (
635 value: string,
636 ...rest: ReadonlyArray<never>
637): Effect.Effect<void, never, InRun> => {
638 // Files are not type-checked, so `title("name", text)` would title the run "name".
639 if (typeof value !== "string" || rest.length > 0) {
640 throw new Error("title takes only the text, as in title(`Release ${name}`), and no step name.");
641 }
642 return Effect.flatMap(RunContext, (current) => {
643 // Numbered by how many came before in the body, which a replay walks the same way.
644 let n = 0;
645 while (current.names.has(`title/${n}`)) n++;
646 const name = `title/${n}`;
647 return Effect.flatMap(claim(name), (run) =>
648 Activity.make({ name, execute: run.store.runTitle(run.runId, value) }),
649 );
650 }).pipe(Effect.orDie);
651};
652
653/**
654 * Tag the run, for finding it among the others: `t3 workflow list --tag` and `runs({ tag })`.
655 * Calling it again replaces the tags.
656 */
657export const tags = (
658 values: ReadonlyArray<string>,
659 ...rest: ReadonlyArray<never>
660): Effect.Effect<void, never, InRun> => {
661 // Files are not type-checked, so `tags("pr", "backlog")` would tag the run with one of them.
662 if (
663 !Array.isArray(values) ||
664 rest.length > 0 ||
665 // Array.from fills a gap, as in `tags([, "pr"])`, which `some` would step over.
666 Array.from(values).some((value) => typeof value !== "string" || value.trim() === "")
667 ) {
668 throw new Error('tags takes one list of words, as in tags(["pr", "backlog"]).');
669 }
670 const kept = [...new Set(values as ReadonlyArray<string>)];
671 return Effect.flatMap(RunContext, (current) => {
672 // Numbered by how many came before in the body, which a replay walks the same way.
673 let n = 0;
674 while (current.names.has(`tags/${n}`)) n++;
675 const name = `tags/${n}`;
676 return Effect.flatMap(claim(name), (run) =>
677 Activity.make({ name, execute: run.store.runTags(run.runId, kept) }),
678 );
679 }).pipe(Effect.orDie);
680};
681
682/** What `workflow(…)`'s `asks` declares: each kind of question with the label a list shows. */
683export type AskKinds = Readonly<Record<string, string>>;
684
685/** The `asks` a workflow was given, refused when it is not kinds with a label each. */
686const checkAskKinds = (workflow: string, asks: unknown): AskKinds => {
687 if (asks === undefined) return {};
688 const example = 'as in asks: { feature: "Feature wanted?" }';
689 if (typeof asks !== "object" || asks === null || Array.isArray(asks)) {
690 throw new Error(`workflow("${workflow}")'s asks is each kind with its label, ${example}.`);
691 }
692 for (const [kind, label] of Object.entries(asks)) {
693 if (kind.trim() === "" || typeof label !== "string" || label.trim() === "") {
694 throw new Error(
695 `workflow("${workflow}")'s asks gives the kind "${kind}" no label. Each kind takes one, ${example}.`,
696 );
697 }
698 }
699 return { ...(asks as AskKinds) };
700};
701
702// The defaults are every workflow: a registry holds workflows of every payload and result type.
703export interface WorkflowDefinition<P = never, A = unknown> {
704 /** Types only: what a run is started with and what it returns, for `start` and `invoke`. */
705 readonly "~types"?: { readonly payload: (payload: P) => void; readonly returns: A };
706 readonly name: string;
707 readonly version: number;
708 readonly payload: Schema.Codec<unknown, unknown>;
709 readonly returns: Schema.Codec<unknown, unknown>;
710 /** How long a paused run rests before it is resumed by itself, per pause in a row. */
711 readonly resumeAfter: ReadonlyArray<Duration.Input>;
712 readonly triggers: ReadonlyArray<ScheduleTrigger | WebhookTrigger | OpenedTrigger>;
713 /** The kinds of question it asks, each with the label a list shows, in the order to show them. */
714 readonly asks: AskKinds;
715 /** Fails with the reason as text: by here nothing reads the error but a person. */
716 readonly onEnd:
717 | ((payload: never, end: RunEnd) => Effect.Effect<void, string, InStep>)
718 | undefined;
719 // The registry holds workflows of every payload type; `workflow` is where the types are checked.
720 readonly body: (
721 payload: never,
722 run: { readonly id: string },
723 ) => Effect.Effect<unknown, StepFailed | WorkflowStop, InRun>;
724}
725
726/** How a run ended, as its `onEnd` is told. A paused run has not ended. */
727export interface RunEnd {
728 readonly id: string;
729 readonly outcome: "completed" | "stopped" | "skipped" | "cancelled";
730 readonly reason: string | undefined;
731}
732
733/**
734 * Run another workflow as part of this one and wait for how it ends. The other run is a run of
735 * its own, listed and resumable by itself; cancelling this run cancels it. A run that paused has
736 * not ended, so this waits on while someone resumes it.
737 */
738export const invoke = <P, A>(
739 name: string,
740 workflow: WorkflowDefinition<P, A>,
741 payload: P,
742 options?: { readonly key?: string },
743): Effect.Effect<
744 | { readonly outcome: "completed"; readonly value: A }
745 | { readonly outcome: "stopped" | "skipped" | "cancelled"; readonly reason: string },
746 never,
747 InRun
748> => {
749 // Files are not type-checked, and a name would start nothing until its first step failed.
750 if (typeof workflow !== "object" || workflow === null || typeof workflow.name !== "string") {
751 return Effect.die(
752 new Error(
753 `invoke takes the workflow definition, not its name: invoke("${name}", …) was given ${JSON.stringify(workflow)}. Pass what workflow(…) returned.`,
754 ),
755 );
756 }
757 checkOptions(`invoke("${name}")`, options, ["key"]);
758 return Effect.orDie(invokeAs(name, workflow, payload, options));
759};
760
761const invokeAs = Effect.fn("workflow.invoke")(function* <P, A>(
762 name: string,
763 workflow: WorkflowDefinition<P, A>,
764 payload: P,
765 options?: { readonly key?: string },
766): Effect.fn.Return<
767 | { readonly outcome: "completed"; readonly value: A }
768 | { readonly outcome: "stopped" | "skipped" | "cancelled"; readonly reason: string },
769 StepFailed,
770 InRun
771> {
772 // Taken before the child starts: a name already used would refuse the wait after the start.
773 const run = yield* claim(name);
774 yield* step(
775 `${name}/start`,
776 { returns: Schema.String },
777 Effect.flatMap(Runs, (runs) =>
778 runs.start(workflow.name, payload, {
779 version: workflow.version,
780 idempotencyKey: options?.key ?? `${run.runId}/${name}`,
781 parent: { runId: run.runId, wait: name },
782 }),
783 ).pipe(Effect.map((started) => started.runId)),
784 );
785 const ended = yield* waitClaimed(run, "wait", name, { returns: ChildEnd });
786 if (Option.isNone(ended)) {
787 return yield* new StepFailed({ step: name, reason: "the wait ended without an outcome" });
788 }
789 if (ended.value.outcome !== "completed") {
790 return { outcome: ended.value.outcome, reason: ended.value.reason ?? "" };
791 }
792 const returnsCodec = Schema.toCodecJson(workflow.returns);
793 const decode = Schema.decodeEffect(returnsCodec);
794 const value = yield* decode(ended.value.value).pipe(
795 Effect.mapError((error) => new StepFailed({ step: name, reason: text(error) })),
796 );
797 return { outcome: "completed", value: value as A };
798});
799
800/** The step `onEnd` runs as. */
801export const END_STEP = "onEnd";
802const END_RETRY: StepRetry = { times: 3, schedule: Schedule.exponential("2 seconds") };
803
804const DEFAULT_RESUME_AFTER: ReadonlyArray<Duration.Input> = [
805 "5 minutes",
806 "20 minutes",
807 "80 minutes",
808];
809
810/**
811 * A workflow: a name, a version, and a body.
812 *
813 * A run keeps the version it started with. To change the order of steps or the shape of a stored
814 * result, register the new body under a higher version and keep the old one registered until its
815 * runs have ended.
816 */
817export const workflow = <P, PI, A = void, AI = void, EndError = never>(
818 name: string,
819 options: {
820 readonly version: number;
821 readonly payload: Schema.Codec<P, PI>;
822 readonly returns?: Schema.Codec<A, AI>;
823 readonly resumeAfter?: ReadonlyArray<Duration.Input>;
824 /** What starts a run by itself. Each must give what `payload` takes. */
825 readonly triggers?: ReadonlyArray<Trigger<P>>;
826 /**
827 * The kinds of question this workflow asks, each with the label a list shows, in the order
828 * to show them: an `ask` names one as its `kind`. A question of a kind that is not here is
829 * listed as Other.
830 */
831 readonly asks?: AskKinds;
832 /**
833 * Runs once when the run ends, however it ends, to give back what the run took: a machine, a
834 * lock. It gets the payload and the run's id, not the body's values, so name what the run
835 * takes after its id. It must be safe to run for a run that took nothing.
836 */
837 readonly onEnd?: (payload: P, end: RunEnd) => Effect.Effect<unknown, EndError, InStep>;
838 },
839 body: (
840 payload: P,
841 run: { readonly id: string },
842 ) => Effect.Effect<A, StepFailed | WorkflowStop, InRun>,
843): WorkflowDefinition<P, A> => {
844 checkOptions(`workflow("${name}")`, options, [
845 "version",
846 "payload",
847 "returns",
848 "resumeAfter",
849 "triggers",
850 "asks",
851 "onEnd",
852 ]);
853 // Read once now, so a duration that does not parse fails the file and not a paused run later.
854 for (const rest of options.resumeAfter ?? [])
855 durationOf(`workflow("${name}")'s resumeAfter`, rest);
856 checkTriggers(name, options.triggers ?? []);
857 checkAskKinds(name, options.asks);
858 return definitionOf(name, options, body);
859};
860
861const definitionOf = <P, PI, A, AI, EndError>(
862 name: string,
863 options: Parameters<typeof workflow<P, PI, A, AI, EndError>>[1],
864 body: Parameters<typeof workflow<P, PI, A, AI, EndError>>[2],
865): WorkflowDefinition<P, A> => ({
866 name,
867 version: options.version,
868 // Erased here, once: the registry holds workflows of every payload and result type.
869 payload: options.payload as Schema.Codec<unknown, unknown>,
870 // Without a schema the result is whatever JSON the body returned: dropping it would be a
871 // surprise, and a value that is not JSON pauses the run with the reason.
872 returns: (options.returns ?? ANY_JSON) as Schema.Codec<unknown, unknown>,
873 resumeAfter: options.resumeAfter ?? DEFAULT_RESUME_AFTER,
874 triggers: options.triggers ?? [],
875 asks: checkAskKinds(name, options.asks),
876 onEnd:
877 options.onEnd === undefined
878 ? undefined
879 : (payload, end) => options.onEnd!(payload, end).pipe(Effect.asVoid, Effect.mapError(text)),
880 body,
881});
882
883export const engineTag = (definition: Pick<WorkflowDefinition, "name" | "version">) =>
884 `${definition.name}@${definition.version}`;
885
886const Outcome = Schema.Struct({
887 outcome: Schema.Literals(["completed", "stopped", "skipped"]),
888 value: Schema.Json,
889 reason: Schema.optional(Schema.String),
890});
891
892export const engineWorkflow = (definition: WorkflowDefinition) =>
893 Workflow.make(engineTag(definition), {
894 payload: { idempotencyKey: Schema.String, input: Schema.Json },
895 idempotencyKey: (payload) => payload.idempotencyKey,
896 success: Outcome,
897 error: Schema.Union([StepFailed, WorkflowStop]),
898 // A failure parks the run instead of ending it; only an explicit resume wakes it.
899 }).annotate(Workflow.SuspendOnFailure, true);
900export type EngineWorkflow = ReturnType<typeof engineWorkflow>;
901
902export const layerDefinition = (definition: WorkflowDefinition, engine: EngineWorkflow) => {
903 const payloadCodec = Schema.toCodecJson(definition.payload);
904 const decodePayload = Schema.decodeEffect(payloadCodec);
905 const returnsCodec = Schema.toCodecJson(definition.returns);
906 const encodeResult = Schema.encodeUnknownEffect(returnsCodec);
907 return engine.toLayer((payload, runId) =>
908 Effect.gen(function* () {
909 const store = yield* WorkflowStore.WorkflowStore;
910 const keyValues = yield* KeyValues;
911 const link = yield* EngineLink;
912 const forge = Option.getOrElse(yield* Effect.serviceOption(WorkflowForge), () => unavailable);
913 yield* Activity.make({
914 name: "run/begin",
915 execute: store.runStarted({
916 runId,
917 workflow: definition.name,
918 version: definition.version,
919 engineTag: engineTag(definition),
920 idempotencyKey: payload.idempotencyKey,
921 input: payload.input,
922 }),
923 });
924 const input = (yield* Effect.orDie(decodePayload(payload.input))) as never;
925 const outcome = yield* definition.body(input, { id: runId }).pipe(
926 Effect.flatMap((value) =>
927 definition.returns === ANY_JSON
928 ? untypedResult(value)
929 : encodeResult(value).pipe(
930 Effect.mapError(
931 (error) =>
932 new Error(
933 `The run's result does not fit its returns: ${encodeFailure("the run's result", error, value)}`,
934 ),
935 ),
936 Effect.orDie,
937 ),
938 ),
939 Effect.map((value): typeof Outcome.Type => ({
940 outcome: "completed",
941 value: (value ?? null) as Schema.Json,
942 })),
943 Effect.catchTags({
944 WorkflowStop: (stopped) =>
945 Effect.succeed<typeof Outcome.Type>({
946 outcome: stopped.skipped === true ? "skipped" : "stopped",
947 value: null,
948 reason: stopped.reason,
949 }),
950 }),
951 // A step like any other: a cleanup that fails pauses the run, and resuming tries it again.
952 Effect.tap((ended) =>
953 definition.onEnd === undefined
954 ? Effect.void
955 : stepAs(
956 claim(END_STEP, true),
957 END_STEP,
958 // A cleanup is safe to run again, and has nobody else to try it.
959 { returns: Schema.Void, retry: END_RETRY },
960 definition.onEnd(input, {
961 id: runId,
962 outcome: ended.outcome,
963 reason: ended.reason,
964 }),
965 ),
966 ),
967 Effect.provideService(
968 RunContext,
969 RunContext.of({
970 runId,
971 workflow: definition.name,
972 store,
973 names: new Set(),
974 forStep: (name) => forStep(store, keyValues, link, forge, runId, name),
975 inFlight: link.inFlight,
976 watchTurn: Effect.fn("RunContext.watchTurn")(function* (wait: string) {
977 if (link.current !== undefined) yield* link.current.watchTurn(runId, wait);
978 }),
979 }),
980 ),
981 );
982 yield* Activity.make({
983 name: "run/end",
984 execute: Effect.asVoid(
985 store.runEnded(runId, outcome.outcome, outcome.reason ?? null, outcome.value),
986 ),
987 });
988 yield* Activity.make({
989 name: "run/told",
990 execute: Effect.suspend(() => link.current?.ended(runId) ?? Effect.void),
991 });
992 return outcome;
993 }).pipe(
994 // A failing step marked the run paused itself. What reaches here otherwise is the body
995 // breaking outside a step: a duplicate name, a payload that no longer decodes.
996 Effect.tapCause((cause) =>
997 Cause.hasInterruptsOnly(cause)
998 ? Effect.void
999 : Effect.flatMap(WorkflowStore.WorkflowStore, (store) =>
1000 store.runPaused(runId, text(Cause.squash(cause))),
1001 ),
1002 ),
1003 ),
1004 );
1005};