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

workflow.ts

1,212 lines48.1 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 Predicate from "effect/Predicate";
10import * as Result from "effect/Result";
11import * as Schedule from "effect/Schedule";
12import * as Schema from "effect/Schema";
13import * as SchemaAST from "effect/SchemaAST";
14import * as SqlClient from "effect/sql/SqlClient";
15import { Activity, DurableClock, DurableDeferred, Workflow, WorkflowEngine } from "effect/workflow";
16​
17import { checkOptions, durationOf } from "./options.ts";
18import {
19 EngineLink,
20 forStep,
21 type InFlight,
22 type InStep,
23 KeyValues,
24 Runs,
25} from "./stepServices.ts";
26import {
27 checkTriggers,
28 type OpenedTrigger,
29 type ScheduleTrigger,
30 type Trigger,
31 type WebhookTrigger,
32} from "./triggers.ts";
33import type { WorkflowAgents } from "./WorkflowAgents.ts";
34import {
35 type SubjectInput,
36 subjectReference,
37 unavailable,
38 WorkflowForge,
39} from "./WorkflowForge.ts";
40import { subjectSet } from "./runReferences.ts";
41import * as WorkflowStore from "./WorkflowStore.ts";
42import { withoutRoutineSpans } from "@t3tools/shared/observability";
43​
44/** A step that could not be completed. Its run is paused until someone resumes it. */
45export class StepFailed extends Schema.TaggedError<StepFailed>()("StepFailed", {
46 step: Schema.String,
47 reason: Schema.String,
48}) {
49 override get message(): string {
50 return `${this.step}: ${this.reason}`;
51 }
53​
54/** The workflow's own decision to end without a result. */
55export class WorkflowStop extends Schema.TaggedError<WorkflowStop>()("WorkflowStop", {
56 reason: Schema.String,
57 /** The run was never for this workflow to do, which lists leave out. */
58 skipped: Schema.optional(Schema.Boolean),
59}) {
60 override get message(): string {
61 return this.reason;
62 }
64​
65/** What the primitives need from the run they are called in. */
66export class RunContext extends Context.Service<
67 RunContext,
68 {
69 readonly runId: string;
70 readonly workflow: string;
71 readonly store: WorkflowStore.WorkflowStore["Service"];
72 /** Names used so far in this pass over the body: two steps with one name would share a result. */
73 readonly names: Set<string>;
74 /** What the code of the step `name` may use. */
75 readonly forStep: (name: string) => Context.Context<InStep>;
76 /** The steps running now, which a cancelled run's cleanup waits for. */
77 readonly inFlight: InFlight;
78 /** Have the engine see the agent turn behind the open wait `wait` through, and wake it. */
79 readonly watchTurn: (wait: string) => Effect.Effect<void>;
80 /** Queue the wait `name` for a place in `pool`, which wakes it once it has one. */
81 readonly placeAsked: (name: string, pool: string, size: number) => Effect.Effect<void>;
82 readonly placeLeft: (name: string) => Effect.Effect<void>;
83 /** Hands out the places a pause gave back. */
84 readonly placesFreed: Effect.Effect<void>;
85 }
86>()("t3/workflows/workflow/RunContext") {}
87​
88/** What a workflow body may require: the run it is in, the engine, and somewhere to run agents. */
89export type InRun =
90 | RunContext
91 | WorkflowAgents
92 | WorkflowEngine.WorkflowEngine
93 | WorkflowEngine.WorkflowInstance;
94​
95/** Takes `name` for one step of the run. Step results and the step list are both kept by name. */
96export const claim = (name: string, internal = false) =>
97 Effect.flatMap(RunContext, (run) => {
98 // The cleanup step's name is its own, or a body step would take it and cleanup never run.
99 if (name === END_STEP && !internal) {
100 return Effect.die(
101 new Error(
102 `"${END_STEP}" is the name of workflow ${run.workflow}'s cleanup step. Name this step something else.`,
103 ),
104 );
105 }
106 // Nor can a body step take the name a pool queues at, whatever the pool is called.
107 if (name.startsWith(PLACE_PREFIX) && !internal) {
108 return Effect.die(
109 new Error(
110 `Names starting with "${PLACE_PREFIX}" are kept for the steps that queue for a place in a pool. Name "${name}" in workflow ${run.workflow} something else.`,
111 ),
112 );
113 }
114 if (run.names.has(name)) {
115 return Effect.die(
116 new Error(
117 `Two steps in workflow ${run.workflow} are named "${name}". Names are unique in a run.`,
118 ),
119 );
120 }
121 run.names.add(name);
122 return Effect.succeed(run);
123 });
124​
125/** An error as one line for a person, with what caused it when the error only wraps something. */
126export const text = (error: unknown): string => {
127 if (typeof error === "string") return WorkflowStore.detailCut(error);
128 if (typeof error !== "object" || error === null) return String(error);
129 // Also an error that came back from the journal, which is its fields and no longer an Error.
130 const fields = error as {
131 readonly message?: unknown;
132 readonly reason?: unknown;
133 cause?: unknown;
134 };
135 const message =
136 typeof fields.message === "string" && fields.message !== ""
137 ? fields.message
138 : typeof fields.reason === "string"
139 ? fields.reason
140 : "Unknown error";
141 return WorkflowStore.detailCut(
142 fields.cause === undefined ? message : `${message}: ${text(fields.cause)}`,
143 );
144};
145​
146// What a workflow without `returns` returns: any JSON value, or nothing.
147const ANY_JSON = Schema.UndefinedOr(Schema.Json);
148​
149/** Where in `value` JSON cannot hold what it finds, with `undefined` counted only when `strict`. */
150const notJson = (value: unknown, at: string, strict: boolean): string | undefined => {
151 if (value === null || typeof value === "string" || typeof value === "boolean") return undefined;
152 if (typeof value === "number") return Number.isFinite(value) ? undefined : `${at} is ${value}`;
153 if (value === undefined) return strict ? `${at} is undefined` : undefined;
154 if (Array.isArray(value)) {
155 for (const [index, item] of value.entries()) {
156 const found = notJson(item, `${at}[${index}]`, strict);
157 if (found !== undefined) return found;
158 }
159 return undefined;
160 }
161 const proto = typeof value === "object" ? Object.getPrototypeOf(value) : undefined;
162 if (proto !== Object.prototype && proto !== null) {
163 return `${at} is ${typeof value === "object" ? (proto?.constructor?.name ?? "an object") : `a ${typeof value}`}`;
164 }
165 for (const [key, field] of Object.entries(value as object)) {
166 const found = notJson(field, `${at}.${key}`, strict);
167 if (found !== undefined) return found;
168 }
169 return undefined;
170};
171​
172/** A value that did not encode, said with where JSON could not hold it, which `Schema.Json` omits. */
173const encodeFailure = (what: string, error: unknown, value: unknown) => {
174 const where = notJson(value, what, true);
175 return where === undefined ? text(error) : `${text(error)}: ${where}`;
176};
177​
178/** A step result the journal cannot store, which fails the step it came from. */
179const unstorable = (error: unknown, value: unknown) =>
180 Effect.die(new Error(encodeFailure("the result", error, value)));
181​
182/** What a run without `returns` returns, read as `JSON.stringify` reads it. */
183const untypedResult = (value: unknown): Effect.Effect<Schema.Json> => {
184 const where = notJson(value, "the run's result", false);
185 if (where !== undefined) return Effect.die(new Error(`The run's result is not JSON: ${where}.`));
186 return Effect.succeed(
187 value === undefined ? null : (JSON.parse(JSON.stringify(value)) as Schema.Json),
188 );
189};
190​
191/**
192 * One journaled action of the step `name`: it happens once, and a replay returns what it stored.
193 * A failure marks the step failed and pauses the run here; resuming the run executes it again.
194 */
195export const journaled = <A, I, E>(
196 run: RunContext["Service"],
197 name: string,
198 action: string,
199 returns: Schema.Codec<A, I>,
200 execute: Effect.Effect<A, E>,
201 // The run waits for a person after this fails, not for `resumeAfter`.
202 held = false,
203) => {
204 const codec = Schema.toCodecJson(returns);
205 const encodable = Schema.encodeEffect(codec);
206 // A wake can preempt the run while a failed step is still finishing, and the engine then
207 // replays the paused run and runs the step again. Only a resume, which unpauses first, may.
208 const unlessPaused = Effect.flatMap(run.store.run(run.runId), (row) =>
209 row?.status === "paused"
210 ? Effect.fail(new StepFailed({ step: name, reason: "The run is paused." }))
211 : Effect.void,
212 );
213 return Activity.make({
214 name: action,
215 success: returns,
216 error: StepFailed,
217 execute: run.inFlight.track(run.runId, execute).pipe(
218 // A result the journal cannot store is this step's failure, found before it is journaled.
219 Effect.tap((value) => Effect.catch(encodable(value), (error) => unstorable(error, value))),
220 // The engine reads its own 64-bit ids as BigInt. What a step calls must not inherit that.
221 Effect.provideService(SqlClient.SafeIntegers, false),
222 // Also a step that dies: left as a defect the engine would park the run without a word.
223 Effect.catchCause((cause) =>
224 Cause.hasInterruptsOnly(cause)
225 ? Effect.failCause(cause as Cause.Cause<never>)
226 : Effect.fail(new StepFailed({ step: name, reason: text(Cause.squash(cause)) })),
227 ),
228 Effect.tapError((error) =>
229 Effect.andThen(
230 run.store.stepEnded(run.runId, name, "failed", error.reason),
231 Effect.andThen(run.store.runPaused(run.runId, error.message, held), run.placesFreed),
232 ),
233 ),
234 (attempt) => Effect.andThen(unlessPaused, attempt),
235 ),
236 });
237};
238​
239/** How an invoked run ended, as its parent's wait receives it. */
240export const ChildEnd = Schema.Struct({
241 outcome: Schema.Literals(["completed", "stopped", "skipped", "cancelled"]),
242 value: Schema.Json,
243 reason: Schema.optional(Schema.String),
244});
245​
246export interface StepRetry {
247 /** How many more times to try before the run is paused. */
248 readonly times: number;
249 readonly schedule?: Schedule.Schedule<unknown, unknown>;
251// Once, unless asked: a step that posts or merges must not do it again after a lost reply.
252const DEFAULT_RETRY: StepRetry = { times: 0 };
253​
254const checkStepOptions = (what: string, options: { readonly retry?: StepRetry | undefined }) => {
255 checkOptions(what, options, ["returns", "retry"]);
256 checkOptions(`${what}'s retry`, options?.retry, ["times", "schedule"]);
257};
258​
259/** How `step.try` ended: its value, or why it failed once its retries were used up. */
260export type StepAttempt<A> =
261 | { readonly outcome: "done"; readonly value: A }
262 | { readonly outcome: "failed"; readonly reason: string };
263​
264const attemptOf = <A, I>(returns: Schema.Codec<A, I>) =>
265 Schema.Union([
266 Schema.Struct({ outcome: Schema.Literal("done"), value: returns }),
267 Schema.Struct({ outcome: Schema.Literal("failed"), reason: Schema.String }),
268 ]);
269​
270/**
271 * Do something once per run. The result is stored, and a replay returns the stored result.
272 *
273 * A failure is retried by `retry`, then pauses the run at this step: resuming the run runs the step
274 * again. Nothing in the body can catch that. For a failure the workflow decides about, use
275 * `step.try`.
276 */
277export const step = Object.assign(
278 <A, I, E>(
279 name: string,
280 options: { readonly returns: Schema.Codec<A, I>; readonly retry?: StepRetry },
281 code: Effect.Effect<A, E, InStep>,
282 ): Effect.Effect<A, never, InRun> => {
283 checkStepOptions(`step("${name}")`, options);
284 return Effect.orDie(stepAs(claim(name), name, options, code));
285 },
286 {
287 /** As `step`, but a failure left after the retries comes back as `failed` with the reason. */
288 try: <A, I, E>(
289 name: string,
290 options: { readonly returns: Schema.Codec<A, I>; readonly retry?: StepRetry },
291 code: Effect.Effect<A, E, InStep>,
292 ): Effect.Effect<StepAttempt<A>, never, InRun> => {
293 checkStepOptions(`step.try("${name}")`, options);
294 return Effect.orDie(
295 stepAs(
296 claim(name),
297 name,
298 { returns: attemptOf(options.returns), retry: options.retry },
299 code,
300 (tried) =>
301 tried.pipe(
302 Effect.map((value): StepAttempt<A> => ({ outcome: "done", value })),
303 Effect.catchCause((cause) =>
304 Cause.hasInterruptsOnly(cause)
305 ? Effect.failCause(cause as Cause.Cause<never>)
306 : Effect.succeed<StepAttempt<A>>({
307 outcome: "failed",
308 reason: text(Cause.squash(cause)),
309 }),
310 ),
311 ),
312 ),
313 );
314 },
315 },
316);
317​
318const stepAs = <A, I, X, E>(
319 claimed: Effect.Effect<RunContext["Service"], never, InRun>,
320 name: string,
321 options: { readonly returns: Schema.Codec<A, I>; readonly retry?: StepRetry | undefined },
322 code: Effect.Effect<X, E, InStep>,
323 // What the step makes of its tries: by default their value, or their failure.
324 settle: (tried: Effect.Effect<X, E>) => Effect.Effect<A, E> = (tried) =>
325 tried as unknown as Effect.Effect<A, E>,
326): Effect.Effect<A, StepFailed, InRun> =>
327 Effect.flatMap(claimed, (run) => {
328 const retry = options.retry ?? DEFAULT_RETRY;
329 const resultCodec = Schema.toCodecJson(options.returns);
330 const encodeResult = Schema.encodeEffect(resultCodec);
331 // Made per try, so a retry numbers its signals from the start again and counts as an attempt.
332 const execute = Effect.andThen(
333 run.store.stepStarted(run.runId, name, "step"),
334 Effect.suspend(() => Effect.provideContext(code, run.forStep(name))),
335 );
336 return journaled(
337 run,
338 name,
339 `step/${name}`,
340 options.returns,
341 settle(
342 // A step and its retry schedule are the workflow author's own work, never sampled.
343 withoutRoutineSpans(
344 retry.times === 0
345 ? execute
346 : Effect.retry(execute, {
347 times: retry.times,
348 ...(retry.schedule === undefined ? {} : { schedule: retry.schedule }),
349 }),
350 ),
351 ).pipe(
352 // A value that does not encode fails the step, so it is never marked done first.
353 Effect.tap((value) =>
354 Effect.flatMap(
355 Effect.catch(encodeResult(value), (error) => unstorable(error, value)),
356 (json) =>
357 Effect.andThen(
358 run.store.stepEnded(run.runId, name, "completed", null),
359 // For a person reading the run.
360 Effect.ignore(run.store.stepResult(run.runId, name, json as Schema.Json)),
361 ),
362 ),
363 ),
364 ),
365 );
366 });
367​
368/** A sleep that survives a restart. */
369export const sleep = Effect.fn("workflow.sleep")(function* (
370 name: string,
371 duration: Duration.Input,
372): Effect.fn.Return<void, never, InRun> {
373 const length = durationOf(`sleep("${name}")`, duration);
374 const run = yield* claim(name);
375 // Listed like any step, with when it wakes, so a run that sleeps for days says so.
376 yield* Activity.make({
377 name: `sleep/${name}/open`,
378 execute: Effect.gen(function* () {
379 const wakes = DateTime.addDuration(yield* DateTime.now, length);
380 yield* run.store.stepStarted(run.runId, name, "sleep");
381 yield* run.store.stepDetail(run.runId, name, DateTime.formatIso(wakes));
382 yield* run.store.runStatus(run.runId, "waiting", `sleep ${name}`);
383 }),
384 });
385 // Effect keeps a short sleep in memory, where a restart would start it over.
386 yield* DurableClock.sleep({
387 name: `sleep/${name}`,
388 duration: length,
389 inMemoryThreshold: Duration.zero,
390 });
391 yield* Activity.make({
392 name: `sleep/${name}/close`,
393 execute: Effect.andThen(
394 run.store.stepEnded(run.runId, name, "completed", null),
395 run.store.runResumed(run.runId),
396 ),
397 });
398});
399​
400export const Woke = Schema.Struct({
401 expired: Schema.Boolean,
402 value: Schema.Json,
403 /** Ended unanswered from outside the run, which reads it as a timeout. */
404 withdrawn: Schema.optional(
405 Schema.Struct({ by: Schema.String, reason: Schema.NullOr(Schema.String) }),
406 ),
407});
408const closedDetail = (woke: typeof Woke.Type) => {
409 if (woke.withdrawn !== undefined) {
410 const { by, reason } = woke.withdrawn;
411 return `withdrawn by ${by}${reason === null ? "" : `: ${reason}`}`;
412 }
413 return woke.expired ? "timed out" : null;
414};
415export const wakeOf = (name: string) => DurableDeferred.make(`wait/${name}`, { success: Woke });
416const finite = [Schema.isFinite()] as const;
417// JSON carries a bare `Schema.Number` as a number or the text "Infinity", "-Infinity" or "NaN",
418// and that form drops the number's own checks. Whoever writes the value is told a finite number
419// with its checks instead. Transformations and recursion keep their own form.
420const finiteNumbers = (ast: SchemaAST.AST): SchemaAST.AST => {
421 if (ast.encoding !== undefined) return ast;
422 if (SchemaAST.isNumber(ast)) {
423 return new SchemaAST.Number(
424 ast.annotations,
425 ast.checks === undefined ? finite : [...ast.checks, ...finite],
426 undefined,
427 ast.context,
428 );
429 }
430 if (SchemaAST.isObjects(ast)) {
431 return new SchemaAST.Objects(
432 ast.propertySignatures.map(
433 (field) => new SchemaAST.PropertySignature(field.name, finiteNumbers(field.type)),
434 ),
435 ast.indexSignatures.map(
436 (index) => new SchemaAST.IndexSignature(index.parameter, finiteNumbers(index.type)),
437 ),
438 ast.annotations,
439 ast.checks,
440 undefined,
441 ast.context,
442 ast.encodingChecks,
443 );
444 }
445 if (SchemaAST.isArrays(ast)) {
446 return new SchemaAST.Arrays(
447 ast.isMutable,
448 ast.elements.map(finiteNumbers),
449 ast.rest.map(finiteNumbers),
450 ast.annotations,
451 ast.checks,
452 undefined,
453 ast.context,
454 ast.encodingChecks,
455 );
456 }
457 if (SchemaAST.isUnion(ast)) {
458 return new SchemaAST.Union(
459 ast.types.map(finiteNumbers),
460 ast.options,
461 ast.annotations,
462 ast.checks,
463 undefined,
464 ast.context,
465 ast.encodingChecks,
466 );
467 }
468 return ast;
469};
470​
471/** What a value must look like, as JSON Schema; `closed` objects turn down keys they do not name. */
472export const jsonSchemaOf = (schema: Schema.Top, closed = false): Record<string, Schema.Json> => {
473 const document = Schema.toJsonSchemaDocument(
474 Schema.make(finiteNumbers(schema.ast)),
475 closed ? { onExcessProperty: "error" } : undefined,
476 );
477 return { ...document.schema, $defs: document.definitions } as Record<string, Schema.Json>;
478};
479​
480/** `wait`, also as the question a person answers: `request` is what an inbox shows them. */
481export const waitAs = Effect.fn("workflow.wait")(function* <A, I>(
482 kind: "wait" | "ask" | "queue",
483 name: string,
484 options: WaitOptions<A, I>,
485): Effect.fn.Return<Option.Option<A>, StepFailed, InRun> {
486 return yield* waitClaimed(yield* claim(name), kind, name, options);
487});
488​
489interface WaitOptions<A, I> {
490 readonly returns: Schema.Codec<A, I>;
491 readonly timeout?: Duration.Input | undefined;
492 readonly channel?: string | undefined;
493 readonly request?: Schema.Json | undefined;
494 /** What the engine looks at to end the wait by itself. */
495 readonly watch?: Schema.Json | undefined;
496 /** The pool a `queue` waits for a place in. */
497 readonly pool?: { readonly name: string; readonly size: number } | undefined;
499​
500/**
501 * A signal's value as a question's wait receives it: with who sent it and when, as the server saw
502 * them. What the value itself says of those is the sender's word and is dropped. Undefined for a
503 * wait that is not a question, a value that is no answer, and a question asked before answers
504 * kept who gave them, whose closed schema would refuse the stamp.
505 */
506export const answerStamped = (
507 wait: { readonly request: boolean; readonly schemaJson: string },
508 value: Schema.Json,
509 sender: WorkflowStore.SignalSender,
510): Schema.JsonObject | undefined => {
511 if (!wait.request || typeof value !== "object" || value === null || Array.isArray(value)) {
512 return undefined;
513 }
514 if (!wait.schemaJson.includes('"answeredAt"')) return undefined;
515 const {
516 answeredBy: _by,
517 answeredBySession: _session,
518 answeredAt: _at,
519 ...given
520 } = value as Schema.JsonObject;
521 return {
522 ...given,
523 ...(sender.answeredBy === undefined ? {} : { answeredBy: sender.answeredBy }),
524 // A question asked before answers kept the session has a closed schema without it.
525 ...(sender.answeredBySession === undefined || !wait.schemaJson.includes('"answeredBySession"')
526 ? {}
527 : { answeredBySession: sender.answeredBySession }),
528 answeredAt: sender.answeredAt,
529 };
530};
531​
532const sameAddress = (left: WorkflowStore.SignalAddress, right: WorkflowStore.SignalAddress) =>
533 "runId" in left
534 ? "runId" in right && left.runId === right.runId && left.wait === right.wait
535 : "channel" in right && left.workflow === right.workflow && left.channel === right.channel;
536​
537const waitClaimed = Effect.fnUntraced(function* <A, I>(
538 run: RunContext["Service"],
539 kind: "wait" | "ask" | "queue",
540 name: string,
541 options: WaitOptions<A, I>,
542): Effect.fn.Return<Option.Option<A>, StepFailed, InRun> {
543 const here: WorkflowStore.SignalAddress = { runId: run.runId, wait: name };
544 const schema = jsonSchemaOf(options.returns);
545 const question = {
546 request: options.request !== undefined,
547 schemaJson: WorkflowStore.jsonText(schema),
548 };
549 const codec = Schema.toCodecJson(options.returns);
550 const decode = Schema.decodeEffect(codec);
551 const fits = (value: Schema.Json) => Effect.result(decode(value));
552 const addresses: ReadonlyArray<WorkflowStore.SignalAddress> =
553 options.channel === undefined
554 ? [here]
555 : [here, { workflow: run.workflow, channel: options.channel }];
556 // Whatever arrived early is delivered now, checked as this wait reads it. The mail goes only
557 // after the wake: waking twice is harmless, and losing the signal is not.
558 const deliverEarly = Effect.fnUntraced(function* (
559 wake: ReturnType<typeof wakeOf>,
560 token: DurableDeferred.Token,
561 ) {
562 const passed = new Set<string>();
563 while (true) {
564 const early = yield* run.store.mailNext(addresses, passed);
565 if (early === undefined) return;
566 const sent = WorkflowStore.jsonValue(early.valueJson);
567 // An answer is its sender's as the server recorded on receiving it. One kept before signals
568 // kept that has no name, and its time is this one.
569 const value =
570 answerStamped(
571 question,
572 sent,
573 early.sender ?? { answeredAt: DateTime.formatIso(yield* DateTime.now) },
574 ) ?? sent;
575 if (Result.isFailure(yield* fits(value))) {
576 // Kept when it went to a channel: another run, or another version, may read it.
577 if (sameAddress(early.address, here)) yield* run.store.mailDelete(early.signalId);
578 passed.add(early.signalId);
579 continue;
580 }
581 const woke = { expired: false, value };
582 const outcome = yield* run.store.mailDeliver(early.signalId, run.runId, name, woke);
583 // Another wait on the same key took that one; there may be a next.
584 if (outcome === "gone") continue;
585 // Another signal claimed this wait first: its wake, or the sweep, carries what it claimed.
586 if (outcome === "claimed") return;
587 yield* DurableDeferred.succeed(wake, { token, value: woke });
588 return;
589 }
590 });
591 const first = wakeOf(name);
592 const firstToken = yield* DurableDeferred.token(first);
593 yield* Activity.make({
594 name: `wait/${name}/open`,
595 execute: Effect.gen(function* () {
596 const deadline =
597 options.timeout === undefined
598 ? null
599 : DateTime.formatIso(
600 DateTime.addDuration(yield* DateTime.now, Duration.fromInputUnsafe(options.timeout)),
601 );
602 yield* run.store.stepStarted(run.runId, name, kind);
603 yield* run.store.waitOpened({
604 runId: run.runId,
605 name,
606 workflow: run.workflow,
607 key: options.channel,
608 token: firstToken,
609 schemaJson: question.schemaJson,
610 requestJson: options.request === undefined ? null : WorkflowStore.jsonText(options.request),
611 watchJson: options.watch === undefined ? null : WorkflowStore.jsonText(options.watch),
612 deadline,
613 });
614 if (options.pool !== undefined) {
615 yield* run.store.stepDetail(run.runId, name, options.pool.name);
616 yield* run.placeAsked(name, options.pool.name, options.pool.size);
617 }
618 yield* run.store.runStatus(
619 run.runId,
620 "waiting",
621 options.pool === undefined ? name : `queue ${options.pool.name}`,
622 );
623 // Only the pool lets a queued step in, so no signal kept for its name is delivered.
624 if (options.pool === undefined) yield* deliverEarly(first, firstToken);
625 }),
626 });
627 // A value that fit the wait's JSON Schema can still fail its codec. It was not for this wait,
628 // so the wait opens again under a fresh wake instead of breaking the run on every replay.
629 let wake = first;
630 for (let again = 1; ; again++) {
631 const woke = yield* DurableDeferred.await(wake);
632 const value = woke.expired ? undefined : yield* fits(woke.value);
633 if (value !== undefined && Result.isFailure(value)) {
634 const problem = `It was signalled with a value it cannot read, and waits again: ${text(value.failure)}`;
635 wake = wakeOf(`${name}/again/${again}`);
636 const token = yield* DurableDeferred.token(wake);
637 const next = wake;
638 yield* Activity.make({
639 name: `wait/${name}/again/${again}`,
640 execute: Effect.gen(function* () {
641 yield* run.store.waitReopened(run.runId, name, token);
642 yield* run.store.stepDetail(run.runId, name, WorkflowStore.detailCut(problem));
643 yield* deliverEarly(next, token);
644 }),
645 });
646 continue;
647 }
648 yield* Activity.make({
649 name: `wait/${name}/close`,
650 execute: Effect.gen(function* () {
651 yield* run.store.waitClosed(run.runId, name);
652 yield* run.store.stepEnded(run.runId, name, "completed", closedDetail(woke));
653 if (!woke.expired) yield* run.store.stepResult(run.runId, name, woke.value);
654 // Kept as data, so the history can say who withdrew the question and why.
655 else if (woke.withdrawn !== undefined) {
656 yield* run.store.stepResult(run.runId, name, { withdrawn: woke.withdrawn });
657 }
658 yield* run.store.runResumed(run.runId);
659 }),
660 });
661 return value === undefined ? Option.none() : Option.some(value.success);
662 }
663});
664​
665/**
666 * Sleep until something outside signals this wait; `None` when the timeout passes first.
667 * Addressed by run and wait name, or by `channel` (scoped to the workflow's name) when the sender
668 * cannot know the run. A signal sent before the wait opened is delivered when it opens.
669 */
670export const wait = <A, I>(
671 name: string,
672 options: {
673 readonly returns: Schema.Codec<A, I>;
674 readonly timeout?: Duration.Input;
675 readonly channel?: string;
676 },
677): Effect.Effect<Option.Option<A>, never, InRun> => {
678 checkOptions(`wait("${name}")`, options, ["returns", "timeout", "channel"]);
679 return Effect.orDie(waitAs("wait", name, options));
680};
681​
682/** The pools the code running here holds a place in, and what took each. */
683const PoolsHeld = Context.Reference<ReadonlyMap<string, "within" | "concurrency">>(
684 "t3/workflows/workflow/PoolsHeld",
685 { defaultValue: () => new Map() },
686);
687​
688const checkLimit = (what: string, limit: unknown) => {
689 if (typeof limit !== "number" || !Number.isInteger(limit) || limit < 1) {
690 throw new Error(`${what} takes a whole number of places of 1 or more, as in { limit: 4 }.`);
691 }
692};
693​
694/**
695 * Holds a place in `pool` while `body` runs, waiting first in line for one when it is full. With
696 * `untilRunEnds` the place is kept past `body`, through `onEnd`, until the run ends or pauses.
697 */
698const holding = Effect.fn("workflow.within")(function* <A, E, R>(
699 name: string,
700 pool: string,
701 limit: number,
702 body: Effect.Effect<A, E, R>,
703 untilRunEnds = false,
704): Effect.fn.Return<A, E, R | InRun> {
705 // Waiting for a place in a pool while holding one in it is a run that can wait for itself.
706 const around = yield* PoolsHeld;
707 if (around.has(pool)) {
708 const outer = around.get(pool) === "concurrency";
709 const workflowName = (yield* RunContext).workflow;
710 return yield* Effect.die(
711 new Error(
712 `within("${pool}") in workflow ${workflowName} is called inside ${
713 outer ? `its concurrency, which is the pool "${pool}"` : `within("${pool}")`
714 }. A run cannot wait for a place in a pool it already holds one in: it could wait for itself. Take the inner one out, or name it another pool.`,
715 ),
716 );
717 }
718 const run = yield* claim(name, true);
719 yield* Effect.orDie(
720 waitClaimed(run, "queue", name, {
721 returns: Schema.Null,
722 pool: { name: pool, size: limit },
723 }),
724 );
725 const inside = Effect.provideService(
726 body,
727 PoolsHeld,
728 new Map(around).set(pool, untilRunEnds ? "concurrency" : "within"),
729 );
730 if (untilRunEnds) return yield* inside;
731 // A run that pauses or ends inside gives its place back there; this is the body finishing,
732 // or failing in a way its caller may catch and carry on from.
733 const leave = Activity.make({ name: `${name}/leave`, execute: run.placeLeft(name) });
734 const value = yield* inside.pipe(
735 Effect.tapError((error) => (Predicate.isTagged(error, "StepFailed") ? Effect.void : leave)),
736 );
737 yield* leave;
738 return value;
739});
740​
741/**
742 * Run `body` holding one of `limit` places in the pool `pool`, shared by every run on the server,
743 * queueing first come first served when all are taken. The place is given back when `body` ends,
744 * or its run pauses or ends; a resumed run takes back all it held at once, ahead of the queue.
745 * `limit: 1` is a lock. Called for a pool from inside that pool, it pauses the run with an error.
746 */
747export const within = <A, E, R>(
748 pool: string,
749 options: { readonly limit: number },
750 body: Effect.Effect<A, E, R>,
751): Effect.Effect<A, E, R | InRun> => {
752 if (typeof pool !== "string" || pool.trim() === "") {
753 throw new Error(
754 'within takes the pool\'s name first, as in within("builders", { limit: 4 }, …).',
755 );
756 }
757 checkOptions(`within("${pool}")`, options, ["limit"]);
758 checkLimit(`within("${pool}")`, options?.limit);
759 return Effect.flatMap(RunContext, (current) => {
760 // Numbered by how many came before in the body, which a replay walks the same way.
761 let n = 1;
762 const named = (index: number) => `${PLACE_PREFIX}${pool}${index === 1 ? "" : `#${index}`}`;
763 while (current.names.has(named(n))) n++;
764 return holding(named(n), pool, options.limit, body);
765 });
766};
767​
768/** End the run by the workflow's own decision. It ends as `stopped`, which is not a failure. */
769export const stop = (reason: string): Effect.Effect<never, WorkflowStop> =>
770 Effect.fail(new WorkflowStop({ reason }));
771​
772/**
773 * End the run because it was not this workflow's to do: a webhook delivery it ignores, a pull
774 * request it opened itself. It ends as `skipped`, which lists leave out unless asked. Use `stop`
775 * for a run that did something and then decided to end.
776 */
777export const skip = (reason: string): Effect.Effect<never, WorkflowStop> =>
778 Effect.fail(new WorkflowStop({ reason, skipped: true }));
779​
780/** Name the run in lists. Defaults to the workflow's name and the run's key. */
781export const title = (
782 value: string,
783 ...rest: ReadonlyArray<never>
784): Effect.Effect<void, never, InRun> => {
785 // Files are not type-checked, so `title("name", text)` would title the run "name".
786 if (typeof value !== "string" || rest.length > 0) {
787 throw new Error("title takes only the text, as in title(`Release ${name}`), and no step name.");
788 }
789 return Effect.flatMap(RunContext, (current) => {
790 // Numbered by how many came before in the body, which a replay walks the same way.
791 let n = 0;
792 while (current.names.has(`title/${n}`)) n++;
793 const name = `title/${n}`;
794 return Effect.flatMap(claim(name), (run) =>
795 Activity.make({ name, execute: run.store.runTitle(run.runId, value) }),
796 );
797 }).pipe(Effect.orDie);
798};
799​
800/**
801 * Tag the run, for finding it among the others: `t3 workflow list --tag` and `runs({ tag })`.
802 * Calling it again replaces the tags.
803 */
804export const tags = (
805 values: ReadonlyArray<string>,
806 ...rest: ReadonlyArray<never>
807): Effect.Effect<void, never, InRun> => {
808 // Files are not type-checked, so `tags("pr", "backlog")` would tag the run with one of them.
809 if (
810 !Array.isArray(values) ||
811 rest.length > 0 ||
812 // Array.from fills a gap, as in `tags([, "pr"])`, which `some` would step over.
813 Array.from(values).some((value) => typeof value !== "string" || value.trim() === "")
814 ) {
815 throw new Error('tags takes one list of words, as in tags(["pr", "backlog"]).');
816 }
817 const kept = [...new Set(values as ReadonlyArray<string>)];
818 return Effect.flatMap(RunContext, (current) => {
819 // Numbered by how many came before in the body, which a replay walks the same way.
820 let n = 0;
821 while (current.names.has(`tags/${n}`)) n++;
822 const name = `tags/${n}`;
823 return Effect.flatMap(claim(name), (run) =>
824 Activity.make({ name, execute: run.store.runTags(run.runId, kept) }),
825 );
826 }).pipe(Effect.orDie);
827};
828​
829/**
830 * Say what the run is about: an issue or pull request a trigger or listing gave, `{ threadId }`,
831 * or a web address. Lists show it and link to it, and `runs({ subject })` and
832 * `t3 workflow list --subject` find the run by it. Calling it again replaces the subject.
833 */
834export const subject = (
835 value: SubjectInput,
836 ...rest: ReadonlyArray<never>
837): Effect.Effect<void, never, InRun> => {
838 if (rest.length > 0) {
839 throw new Error("subject takes only what the run is about, and no step name.");
840 }
841 const reference = subjectReference("subject", value);
842 return Effect.flatMap(RunContext, (current) => {
843 // Numbered by how many came before in the body, which a replay walks the same way.
844 let n = 0;
845 while (current.names.has(`subject/${n}`)) n++;
846 const name = `subject/${n}`;
847 return Effect.flatMap(claim(name), (run) =>
848 Activity.make({ name, execute: subjectSet(run.store, run.runId, reference) }),
849 );
850 }).pipe(Effect.orDie);
851};
852​
853/** What `workflow(…)`'s `asks` declares: each kind of question with the label a list shows. */
854export type AskKinds = Readonly<Record<string, string>>;
855​
856/** The `asks` a workflow was given, refused when it is not kinds with a label each. */
857const checkAskKinds = (workflow: string, asks: unknown): AskKinds => {
858 if (asks === undefined) return {};
859 const example = 'as in asks: { feature: "Feature wanted?" }';
860 if (typeof asks !== "object" || asks === null || Array.isArray(asks)) {
861 throw new Error(`workflow("${workflow}")'s asks is each kind with its label, ${example}.`);
862 }
863 for (const [kind, label] of Object.entries(asks)) {
864 if (kind.trim() === "" || typeof label !== "string" || label.trim() === "") {
865 throw new Error(
866 `workflow("${workflow}")'s asks gives the kind "${kind}" no label. Each kind takes one, ${example}.`,
867 );
868 }
869 }
870 return { ...(asks as AskKinds) };
871};
872​
873// The defaults are every workflow: a registry holds workflows of every payload and result type.
874export interface WorkflowDefinition<P = never, A = unknown> {
875 /** Types only: what a run is started with and what it returns, for `start` and `invoke`. */
876 readonly "~types"?: { readonly payload: (payload: P) => void; readonly returns: A };
877 readonly name: string;
878 readonly version: number;
879 readonly payload: Schema.Codec<unknown, unknown>;
880 readonly returns: Schema.Codec<unknown, unknown>;
881 /** How long a paused run rests before it is resumed by itself, per pause in a row. */
882 readonly resumeAfter: ReadonlyArray<Duration.Input>;
883 readonly triggers: ReadonlyArray<ScheduleTrigger | WebhookTrigger | OpenedTrigger>;
884 /** The kinds of question it asks, each with the label a list shows, in the order to show them. */
885 readonly asks: AskKinds;
886 /** How many of its runs may go on at once; undefined for no limit. */
887 readonly concurrency: number | undefined;
888 /** Fails with the reason as text: by here nothing reads the error but a person. */
889 readonly onEnd:
890 | ((payload: never, end: RunEnd) => Effect.Effect<void, string, InStep>)
891 | undefined;
892 // The registry holds workflows of every payload type; `workflow` is where the types are checked.
893 readonly body: (
894 payload: never,
895 run: { readonly id: string },
896 ) => Effect.Effect<unknown, StepFailed | WorkflowStop, InRun>;
898​
899/** How a run ended, as its `onEnd` is told. A paused run has not ended. */
900export interface RunEnd {
901 readonly id: string;
902 readonly outcome: "completed" | "stopped" | "skipped" | "cancelled";
903 readonly reason: string | undefined;
905​
906/**
907 * Run another workflow as part of this one and wait for how it ends. The other run is a run of
908 * its own, listed and resumable by itself; cancelling this run cancels it. A run that paused has
909 * not ended, so this waits on while someone resumes it.
910 */
911export const invoke = <P, A>(
912 name: string,
913 workflow: WorkflowDefinition<P, A>,
914 payload: P,
915 options?: { readonly key?: string },
916): Effect.Effect<
917 | { readonly outcome: "completed"; readonly value: A }
918 | { readonly outcome: "stopped" | "skipped" | "cancelled"; readonly reason: string },
919 never,
920 InRun
921> => {
922 // Files are not type-checked, and a name would start nothing until its first step failed.
923 if (typeof workflow !== "object" || workflow === null || typeof workflow.name !== "string") {
924 return Effect.die(
925 new Error(
926 `invoke takes the workflow definition, not its name: invoke("${name}", …) was given ${JSON.stringify(workflow)}. Pass what workflow(…) returned.`,
927 ),
928 );
929 }
930 checkOptions(`invoke("${name}")`, options, ["key"]);
931 return Effect.orDie(invokeAs(name, workflow, payload, options));
932};
933​
934const invokeAs = Effect.fn("workflow.invoke")(function* <P, A>(
935 name: string,
936 workflow: WorkflowDefinition<P, A>,
937 payload: P,
938 options?: { readonly key?: string },
939): Effect.fn.Return<
940 | { readonly outcome: "completed"; readonly value: A }
941 | { readonly outcome: "stopped" | "skipped" | "cancelled"; readonly reason: string },
942 StepFailed,
943 InRun
944> {
945 // Taken before the child starts: a name already used would refuse the wait after the start.
946 const run = yield* claim(name);
947 yield* step(
948 `${name}/start`,
949 { returns: Schema.String },
950 Effect.flatMap(Runs, (runs) =>
951 runs.start(workflow.name, payload, {
952 version: workflow.version,
953 idempotencyKey: options?.key ?? `${run.runId}/${name}`,
954 parent: { runId: run.runId, wait: name },
955 }),
956 ).pipe(Effect.map((started) => started.runId)),
957 );
958 const ended = yield* waitClaimed(run, "wait", name, { returns: ChildEnd });
959 if (Option.isNone(ended)) {
960 return yield* new StepFailed({ step: name, reason: "the wait ended without an outcome" });
961 }
962 if (ended.value.outcome !== "completed") {
963 return { outcome: ended.value.outcome, reason: ended.value.reason ?? "" };
964 }
965 const returnsCodec = Schema.toCodecJson(workflow.returns);
966 const decode = Schema.decodeEffect(returnsCodec);
967 const value = yield* decode(ended.value.value).pipe(
968 Effect.mapError((error) => new StepFailed({ step: name, reason: text(error) })),
969 );
970 return { outcome: "completed", value: value as A };
971});
972​
973/** Starts the name of every step that waits for a place in a pool, and of no step of a body. */
974const PLACE_PREFIX = "@pool:";
975/** The step `onEnd` runs as. */
976export const END_STEP = "onEnd";
977const END_RETRY: StepRetry = { times: 3, schedule: Schedule.exponential("2 seconds") };
978​
979const DEFAULT_RESUME_AFTER: ReadonlyArray<Duration.Input> = [
980 "5 minutes",
981 "20 minutes",
982 "80 minutes",
983];
984​
985/**
986 * A workflow: a name, a version, and a body.
987 *
988 * A run keeps the version it started with. To change the order of steps or the shape of a stored
989 * result, register the new body under a higher version and keep the old one registered until its
990 * runs have ended.
991 */
992export const workflow = <P, PI, A = void, AI = void, EndError = never>(
993 name: string,
994 options: {
995 readonly version: number;
996 readonly payload: Schema.Codec<P, PI>;
997 readonly returns?: Schema.Codec<A, AI>;
998 readonly resumeAfter?: ReadonlyArray<Duration.Input>;
999 /** What starts a run by itself. Each must give what `payload` takes. */
1000 readonly triggers?: ReadonlyArray<Trigger<P>>;
1001 /**
1002 * The kinds of question this workflow asks, each with the label a list shows, in the order
1003 * to show them: an `ask` names one as its `kind`. A question of a kind that is not here is
1004 * listed as Other.
1005 */
1006 readonly asks?: AskKinds;
1007 /** How many runs of this workflow go on at once, across its versions. Later ones queue. */
1008 readonly concurrency?: number;
1009 /**
1010 * Runs once when the run ends, however it ends, to give back what the run took: a machine, a
1011 * lock. It gets the payload and the run's id, not the body's values, so name what the run
1012 * takes after its id. It must be safe to run for a run that took nothing.
1013 */
1014 readonly onEnd?: (payload: P, end: RunEnd) => Effect.Effect<unknown, EndError, InStep>;
1015 },
1016 body: (
1017 payload: P,
1018 run: { readonly id: string },
1019 ) => Effect.Effect<A, StepFailed | WorkflowStop, InRun>,
1020): WorkflowDefinition<P, A> => {
1021 checkOptions(`workflow("${name}")`, options, [
1022 "version",
1023 "payload",
1024 "returns",
1025 "resumeAfter",
1026 "triggers",
1027 "asks",
1028 "concurrency",
1029 "onEnd",
1030 ]);
1031 if (options.concurrency !== undefined) {
1032 checkLimit(`workflow("${name}")'s concurrency`, options.concurrency);
1034 // Read once now, so a duration that does not parse fails the file and not a paused run later.
1035 for (const rest of options.resumeAfter ?? [])
1036 durationOf(`workflow("${name}")'s resumeAfter`, rest);
1037 checkTriggers(name, options.triggers ?? []);
1038 checkAskKinds(name, options.asks);
1039 return definitionOf(name, options, body);
1041​
1042const definitionOf = <P, PI, A, AI, EndError>(
1043 name: string,
1044 options: Parameters<typeof workflow<P, PI, A, AI, EndError>>[1],
1045 body: Parameters<typeof workflow<P, PI, A, AI, EndError>>[2],
1046): WorkflowDefinition<P, A> => ({
1047 name,
1048 version: options.version,
1049 // Erased here, once: the registry holds workflows of every payload and result type.
1050 payload: options.payload as Schema.Codec<unknown, unknown>,
1051 // Without a schema the result is whatever JSON the body returned: dropping it would be a
1052 // surprise, and a value that is not JSON pauses the run with the reason.
1053 returns: (options.returns ?? ANY_JSON) as Schema.Codec<unknown, unknown>,
1054 resumeAfter: options.resumeAfter ?? DEFAULT_RESUME_AFTER,
1055 triggers: options.triggers ?? [],
1056 asks: checkAskKinds(name, options.asks),
1057 concurrency: options.concurrency,
1058 onEnd:
1059 options.onEnd === undefined
1060 ? undefined
1061 : (payload, end) => options.onEnd!(payload, end).pipe(Effect.asVoid, Effect.mapError(text)),
1062 body,
1063});
1064​
1065export const engineTag = (definition: Pick<WorkflowDefinition, "name" | "version">) =>
1066 `${definition.name}@${definition.version}`;
1067​
1068const Outcome = Schema.Struct({
1069 outcome: Schema.Literals(["completed", "stopped", "skipped"]),
1070 value: Schema.Json,
1071 reason: Schema.optional(Schema.String),
1072});
1073​
1074export const engineWorkflow = (definition: WorkflowDefinition) =>
1075 Workflow.make(engineTag(definition), {
1076 payload: { idempotencyKey: Schema.String, input: Schema.Json },
1077 idempotencyKey: (payload) => payload.idempotencyKey,
1078 success: Outcome,
1079 error: Schema.Union([StepFailed, WorkflowStop]),
1080 // A failure parks the run instead of ending it; only an explicit resume wakes it.
1081 }).annotate(Workflow.SuspendOnFailure, true);
1082export type EngineWorkflow = ReturnType<typeof engineWorkflow>;
1083​
1084export const layerDefinition = (definition: WorkflowDefinition, engine: EngineWorkflow) => {
1085 const payloadCodec = Schema.toCodecJson(definition.payload);
1086 const decodePayload = Schema.decodeEffect(payloadCodec);
1087 const returnsCodec = Schema.toCodecJson(definition.returns);
1088 const encodeResult = Schema.encodeUnknownEffect(returnsCodec);
1089 return engine.toLayer((payload, runId) =>
1090 Effect.gen(function* () {
1091 const store = yield* WorkflowStore.WorkflowStore;
1092 const keyValues = yield* KeyValues;
1093 const link = yield* EngineLink;
1094 const forge = Option.getOrElse(yield* Effect.serviceOption(WorkflowForge), () => unavailable);
1095 yield* Activity.make({
1096 name: "run/begin",
1097 execute: store.runStarted({
1098 runId,
1099 workflow: definition.name,
1100 version: definition.version,
1101 engineTag: engineTag(definition),
1102 idempotencyKey: payload.idempotencyKey,
1103 input: payload.input,
1104 }),
1105 });
1106 const input = (yield* Effect.orDie(decodePayload(payload.input))) as never;
1107 const body = definition.body(input, { id: runId });
1108 const outcome = yield* (
1109 definition.concurrency === undefined
1110 ? body
1111 : holding(
1112 `${PLACE_PREFIX}${definition.name}`,
1113 definition.name,
1114 definition.concurrency,
1115 body,
1116 true,
1118 ).pipe(
1119 Effect.flatMap((value) =>
1120 definition.returns === ANY_JSON
1121 ? untypedResult(value)
1122 : encodeResult(value).pipe(
1123 Effect.mapError(
1124 (error) =>
1125 new Error(
1126 `The run's result does not fit its returns: ${encodeFailure("the run's result", error, value)}`,
1127 ),
1128 ),
1129 Effect.orDie,
1130 ),
1131 ),
1132 Effect.map((value): typeof Outcome.Type => ({
1133 outcome: "completed",
1134 value: (value ?? null) as Schema.Json,
1135 })),
1136 Effect.catchTags({
1137 WorkflowStop: (stopped) =>
1138 Effect.succeed<typeof Outcome.Type>({
1139 outcome: stopped.skipped === true ? "skipped" : "stopped",
1140 value: null,
1141 reason: stopped.reason,
1142 }),
1143 }),
1144 // A step like any other: a cleanup that fails pauses the run, and resuming tries it again.
1145 Effect.tap((ended) =>
1146 definition.onEnd === undefined
1147 ? Effect.void
1148 : stepAs(
1149 claim(END_STEP, true),
1150 END_STEP,
1151 // A cleanup is safe to run again, and has nobody else to try it.
1152 { returns: Schema.Void, retry: END_RETRY },
1153 definition.onEnd(input, {
1154 id: runId,
1155 outcome: ended.outcome,
1156 reason: ended.reason,
1157 }),
1158 ),
1159 ),
1160 Effect.provideService(
1161 RunContext,
1162 RunContext.of({
1163 runId,
1164 workflow: definition.name,
1165 store,
1166 names: new Set(),
1167 forStep: (name) => forStep(store, keyValues, link, forge, runId, name),
1168 inFlight: link.inFlight,
1169 watchTurn: Effect.fn("RunContext.watchTurn")(function* (wait: string) {
1170 if (link.current !== undefined) yield* link.current.watchTurn(runId, wait);
1171 }),
1172 placeAsked: Effect.fn("RunContext.placeAsked")(function* (name, pool, size) {
1173 if (link.current !== undefined) {
1174 yield* link.current.placeAsked({ runId, name, pool, size });
1176 }),
1177 placeLeft: Effect.fn("RunContext.placeLeft")(function* (name) {
1178 if (link.current !== undefined) yield* link.current.placeLeft(runId, name);
1179 }),
1180 placesFreed: Effect.suspend(() => link.current?.placesFreed ?? Effect.void),
1181 }),
1182 ),
1183 );
1184 yield* Activity.make({
1185 name: "run/end",
1186 execute: Effect.andThen(
1187 store.runEnded(runId, outcome.outcome, outcome.reason ?? null, outcome.value),
1188 // What it still held, as a run that stops inside `within` does, goes to the next.
1189 Effect.suspend(() => link.current?.placesFreed ?? Effect.void),
1190 ),
1191 });
1192 yield* Activity.make({
1193 name: "run/told",
1194 execute: Effect.suspend(() => link.current?.ended(runId) ?? Effect.void),
1195 });
1196 return outcome;
1197 }).pipe(
1198 // A failing step marked the run paused itself. What reaches here otherwise is the body
1199 // breaking outside a step: a duplicate name, a payload that no longer decodes.
1200 Effect.tapCause((cause) =>
1201 Cause.hasInterruptsOnly(cause)
1202 ? Effect.void
1203 : Effect.gen(function* () {
1204 const store = yield* WorkflowStore.WorkflowStore;
1205 const link = yield* EngineLink;
1206 yield* store.runPaused(runId, text(Cause.squash(cause)));
1207 if (link.current !== undefined) yield* link.current.placesFreed;
1208 }),
1209 ),
1210 ),
1211 );