Open History to see the last commit
1// The workflow service on Effect's workflow engine. Loaded only when workflows are enabled: the
2// engine's modules are not worth their load time on a server that registers none.
3import * as Cause from "effect/Cause";
4import {
5 ClusterWorkflowEngine,
6 EntityAddress,
7 EntityId,
8 EntityType,
9 MessageStorage,
10 Sharding,
11 SingleRunner,
12} from "effect/cluster";
13import * as Digest from "effect/crypto/Digest";
14import * as SecureRandom from "effect/crypto/SecureRandom";
15import * as DateTime from "effect/DateTime";
16import * as Duration from "effect/Duration";
17import * as Effect from "effect/Effect";
18import * as Fiber from "effect/Fiber";
19import * as Layer from "effect/Layer";
20import * as Option from "effect/Option";
21import * as PubSub from "effect/PubSub";
22import * as Result from "effect/Result";
23import * as Schedule from "effect/Schedule";
24import * as Schema from "effect/Schema";
25import * as Scope from "effect/Scope";
26import * as SqlClient from "effect/sql/SqlClient";
27import * as Stream from "effect/Stream";
28import { DurableDeferred, WorkflowEngine } from "effect/workflow";
29import {
30 DEFAULT_WORKFLOW_SKIPPED_RUNS_KEPT,
31 type WorkflowRunsUpdate,
32 workflowQuestionKey,
33} from "@t3tools/contracts";
34
35import { checkOutput, rejectionText } from "../orchestration-v2/runOutput.ts";
36import * as ServerSettings from "../serverSettings.ts";
37import { isMissedFixedTimeRun, nextScheduledRunAt } from "../scheduledTasks/Schedule.ts";
38import { constantTimeEquals } from "../scheduledTasks/webhookVerification.ts";
39import {
40 answerStamped,
41 END_STEP,
42 type EngineWorkflow,
43 engineTag,
44 engineWorkflow,
45 layerDefinition,
46 text,
47 wakeOf,
48 type Woke,
49 type WorkflowDefinition,
50} from "./workflow.ts";
51import { issueReference, noteFor, stepReferences } from "./runReferences.ts";
52import { forStep, KeyValues, layerKeyValues, EngineLink, layerEngineLink } from "./stepServices.ts";
53import { WorkflowAgents } from "./WorkflowAgents.ts";
54import { answerProblem, settleTurn, TurnEnd, TurnWatch } from "./workflowAgent.ts";
55import {
56 type Issue,
57 isSettled,
58 type PullRequest,
59 type PullRequestAddress,
60 type PullRequestWatch,
61 pullRequestReferenceOf,
62 standingOf,
63 unavailable,
64 WorkflowForge,
65} from "./WorkflowForge.ts";
66import {
67 hookId as hookIdOf,
68 WorkflowHookBusyError,
69 WorkflowInputError,
70 WorkflowNotRegisteredError,
71 WorkflowRunNotFoundError,
72 Workflows,
73} from "./Workflows.ts";
74import * as WorkflowStore from "./WorkflowStore.ts";
75
76const SWEEP_EVERY = Duration.seconds(15);
77const LOOK_EVERY = Duration.minutes(1);
78const LOOK_AT_MOST = 100;
79const DEFAULT_SIGNAL_TTL = Duration.days(7);
80const RESUME_LOOK_EVERY = Duration.millis(25);
81const RESUME_LOOKS = 80;
82const WATCH_SETTLE = Duration.millis(100);
83// What a watcher was last sent, as text to compare against, by run and by question.
84interface Sent {
85 readonly runs: Map<string, string>;
86 readonly questions: Map<string, { runId: string; name: string; text: string }>;
87}
88const END_TRIES = 5;
89// How long a cancelled run's cleanup rests after each failed try before the sweep tries again.
90const END_AFTER = ["5 minutes", "20 minutes", "80 minutes", "5 hours"] as const;
91// An ended run's engine journal only answers replays that will not come; the run's own rows stay.
92const PRUNE_AFTER = Duration.hours(1);
93const PRUNE_BATCH = 100;
94// Skipped runs deleted per sweep, small enough that the writer lock is never held for long.
95const SKIPPED_PRUNE_BATCH = 500;
96// Delivery ids that common senders put on a request and keep when they send it again.
97const DELIVERY_HEADERS = [
98 "x-github-delivery",
99 "x-gitea-delivery",
100 "x-gitlab-event-uuid",
101 "linear-delivery",
102 "webhook-id",
103 "idempotency-key",
104];
105// The relay's limit for one hook, kept here too: a hook's URL can be called without the relay.
106const HOOK_RUNS_PER_MINUTE = 60;
107const CANCEL_WAITS = Duration.seconds(30);
108const decodeTurnWatch = Schema.decodeUnknownEffect(Schema.toCodecJson(TurnWatch));
109const encodeTurnEnd = Schema.encodeEffect(Schema.toCodecJson(TurnEnd));
110// Times of day are the server's own, as they are for scheduled tasks.
111const localNow = DateTime.withCurrentZoneLocal(DateTime.nowInCurrentZone);
112
113const make = Effect.fn("WorkflowEngine.make")(function* (
114 registered: ReadonlyArray<readonly [WorkflowDefinition, EngineWorkflow]>,
115) {
116 const store = yield* WorkflowStore.WorkflowStore;
117 const keyValues = yield* KeyValues;
118 const link = yield* EngineLink;
119 const trackers = Option.getOrElse(yield* Effect.serviceOption(WorkflowForge), () => unavailable);
120 const messages = yield* Effect.serviceOption(MessageStorage.MessageStorage);
121 const sharding = yield* Effect.serviceOption(Sharding.Sharding);
122 const settings = yield* Effect.serviceOption(ServerSettings.ServerSettingsService);
123 // The engine reads its own tables as BigInts. The rest of the server's queries must not.
124 const plain =
125 <Args extends ReadonlyArray<unknown>, A, E>(call: (...args: Args) => Effect.Effect<A, E>) =>
126 (...args: Args) =>
127 call(...args).pipe(Effect.provideService(SqlClient.SafeIntegers, false));
128 const forge = WorkflowForge.of({
129 issues: {
130 list: plain(trackers.issues.list),
131 read: plain(trackers.issues.read),
132 comment: plain(trackers.issues.comment),
133 setState: plain(trackers.issues.setState),
134 create: plain(trackers.issues.create),
135 },
136 pullRequests: {
137 list: plain(trackers.pullRequests.list),
138 read: plain(trackers.pullRequests.read),
139 comment: plain(trackers.pullRequests.comment),
140 act: plain(trackers.pullRequests.act),
141 },
142 });
143 const scope = yield* Scope.Scope;
144 const agents = yield* WorkflowAgents;
145 const stopTurn = plain(agents.interrupt);
146 const random = yield* SecureRandom.SecureRandom;
147 const digest = yield* Digest.Digest;
148 const context = yield* Effect.context<WorkflowEngine.WorkflowEngine>();
149 // The engine keeps 64-bit ids, which this SQLite client only reads when asked for BigInts.
150 const withEngine = <A, E>(effect: Effect.Effect<A, E, WorkflowEngine.WorkflowEngine>) =>
151 effect.pipe(
152 Effect.provideContext(context),
153 Effect.provideService(SqlClient.SafeIntegers, true),
154 );
155 const byTag = new Map(registered.map(([, engine]) => [engine._tag, engine] as const));
156 const definitionByTag = new Map(
157 registered.map(([definition]) => [engineTag(definition), definition] as const),
158 );
159 const latest = (name: string) =>
160 registered
161 .filter(([definition]) => definition.name === name)
162 .toSorted(([left], [right]) => right.version - left.version)[0];
163
164 /** When the sweep resumes a paused run; undefined once it has used up its tries. */
165 const resumesAt = (row: WorkflowStore.RunSummaryRow) => {
166 if (row.status !== "paused" || Number(row.held) === 1) return undefined;
167 const rest = definitionByTag.get(row.engine_tag)?.resumeAfter[Number(row.pauses) - 1];
168 return rest === undefined
169 ? undefined
170 : DateTime.addDuration(DateTime.makeUnsafe(row.updated_at), Duration.fromInputUnsafe(rest));
171 };
172 const toRun = (row: WorkflowStore.RunSummaryRow): WorkflowStore.WorkflowRun => {
173 const resumes = resumesAt(row);
174 return toRunAt(row, resumes === undefined ? null : DateTime.formatIso(resumes));
175 };
176 const toRunAt = (
177 row: WorkflowStore.RunSummaryRow,
178 resumes: string | null,
179 ): WorkflowStore.WorkflowRun => ({
180 runId: row.run_id,
181 workflow: row.workflow,
182 version: Number(row.version),
183 title: row.title,
184 status: row.status,
185 detail: row.detail,
186 result: row.result_json === null ? null : WorkflowStore.jsonValue(row.result_json),
187 pauses: Number(row.pauses),
188 retired: row.ended_at === null && !byTag.has(row.engine_tag),
189 resumesAt: resumes,
190 parentRunId: row.parent_run_id,
191 parentStep: row.parent_wait,
192 // Left out of a run with none: most have none, and every run is in each whole list sent.
193 ...(row.tags_json === "[]"
194 ? {}
195 : { tags: WorkflowStore.jsonValue(row.tags_json) as ReadonlyArray<string> }),
196 startedAt: row.started_at,
197 updatedAt: row.updated_at,
198 endedAt: row.ended_at,
199 });
200 const requireRun = Effect.fn("WorkflowEngine.requireRun")(function* (runId: string) {
201 const row = yield* store.run(runId);
202 if (row === undefined) return yield* new WorkflowRunNotFoundError({ runId });
203 return row;
204 });
205 const send = (wait: WorkflowStore.WaitRow, value: typeof Woke.Type) =>
206 withEngine(
207 DurableDeferred.succeed(wakeOf(wait.name), {
208 token: wait.token as DurableDeferred.Token,
209 value,
210 }),
211 );
212 // Runs being resumed now: until the engine has them, the sweep must not take them for paused.
213 const resuming = new Set<string>();
214 // The engine would replay a paused run for the wake and run its failed step again unasked. The
215 // claim keeps the value, and the resume sends it.
216 const wake = Effect.fnUntraced(function* (wait: WorkflowStore.WaitRow, value: typeof Woke.Type) {
217 if (resuming.has(wait.run_id) || (yield* store.run(wait.run_id))?.status === "paused") return;
218 yield* send(wait, value);
219 });
220
221 // Agent turns being watched now, by run and wait. The fibers live in the engine's scope, so a
222 // reload stops them at once and the next engine picks the turns up from their open waits.
223 const watchingTurns = new Set<string>();
224 const seeTurn = Effect.fn("WorkflowEngine.seeTurn")(function* (wait: WorkflowStore.WaitRow) {
225 const id = `${wait.run_id}/${wait.name}`;
226 // Taken before the first yield: the wait's own step and the sweep can both ask at once.
227 if (watchingTurns.has(id)) return;
228 watchingTurns.add(id);
229 const watch = yield* decodeTurnWatch(WorkflowStore.jsonValue(wait.watch_json ?? "null")).pipe(
230 Effect.option,
231 );
232 if (Option.isNone(watch)) {
233 watchingTurns.delete(id);
234 return;
235 }
236 yield* settleTurn(watch.value).pipe(
237 Effect.flatMap(encodeTurnEnd),
238 Effect.catch((error) => encodeTurnEnd({ lost: text(error) })),
239 Effect.flatMap(
240 Effect.fnUntraced(function* (end) {
241 const woke = { expired: false, value: end as Schema.Json };
242 if (yield* store.waitSignalled(wait.run_id, wait.name, woke)) yield* wake(wait, woke);
243 }),
244 ),
245 Effect.provideService(WorkflowAgents, agents),
246 Effect.provideContext(stepReferences(store, wait.run_id, watch.value.agent.step)),
247 Effect.provideService(SqlClient.SafeIntegers, false),
248 Effect.catchCause((cause) =>
249 Cause.hasInterruptsOnly(cause)
250 ? Effect.void
251 : Effect.logWarning("A workflow could not see an agent's turn through", cause).pipe(
252 Effect.annotateLogs({ wait: id }),
253 ),
254 ),
255 Effect.ensuring(Effect.sync(() => watchingTurns.delete(id))),
256 Effect.forkIn(scope),
257 );
258 });
259 const watchTurn = Effect.fn("WorkflowEngine.watchTurn")(function* (runId: string, name: string) {
260 const wait = yield* store.waitAt({ runId, wait: name });
261 if (wait !== undefined) yield* seeTurn(wait);
262 });
263
264 const start: Workflows["Service"]["start"] = Effect.fn("Workflows.start")(
265 function* (name, input, options) {
266 // A parent written against one version of a child must not get another one's payload.
267 const found =
268 options.version === undefined
269 ? latest(name)
270 : registered.find(
271 ([candidate]) => candidate.name === name && candidate.version === options.version,
272 );
273 if (found === undefined) {
274 return yield* new WorkflowNotRegisteredError({
275 workflow: name,
276 ...(options.version === undefined ? {} : { version: options.version }),
277 });
278 }
279 const [definition, engine] = found;
280 // A key is one run of the workflow: the engine's own id also counts the version, so a
281 // start after a new version would otherwise begin the same work again.
282 const other = Effect.fnUntraced(function* (earlier: WorkflowStore.RunRow) {
283 if (
284 options.parent !== undefined &&
285 (earlier.parent_run_id !== options.parent.runId ||
286 earlier.parent_wait !== options.parent.wait)
287 ) {
288 return yield* new WorkflowInputError({
289 problem: `Run ${earlier.run_id} of ${name} was started by something else under this key, so it cannot be invoked. Give the invoke a key of its own.`,
290 });
291 }
292 // A start cut off between its row and the engine left a run nothing executes. Executing
293 // one the engine has is a no-op.
294 const its = byTag.get(earlier.engine_tag);
295 if (earlier.ended_at === null && its !== undefined && earlier.input_json !== null) {
296 yield* withEngine(
297 its.execute(
298 {
299 idempotencyKey: earlier.idempotency_key,
300 input: WorkflowStore.jsonValue(earlier.input_json),
301 },
302 { discard: true },
303 ),
304 );
305 }
306 return { runId: earlier.run_id };
307 });
308 const earlier = yield* store.runByKey(name, options.idempotencyKey);
309 // An ended run's journal may be pruned, so executing it again would start the work over.
310 if (
311 earlier !== undefined &&
312 (earlier.engine_tag !== engineTag(definition) || earlier.ended_at !== null)
313 ) {
314 return yield* other(earlier);
315 }
316 const payloadCodec = Schema.toCodecJson(definition.payload);
317 const encode = Schema.encodeUnknownEffect(payloadCodec);
318 const encoded = yield* encode(input).pipe(
319 Effect.mapError(
320 (error) =>
321 new WorkflowInputError({
322 problem: `The payload does not fit workflow ${name}: ${text(error)}`,
323 }),
324 ),
325 );
326 const payload = { idempotencyKey: options.idempotencyKey, input: encoded as Schema.Json };
327 // The row is written first, with who waits for it: the run's own first step writes the same
328 // row without that, and whichever write lands first is the one that stays.
329 const runId = yield* engine.executionId(payload);
330 yield* store.runStarted({
331 runId,
332 workflow: definition.name,
333 version: definition.version,
334 engineTag: engineTag(definition),
335 idempotencyKey: options.idempotencyKey,
336 input: payload.input,
337 parent: options.parent,
338 });
339 // The key is unique, so the row holding it is the run, even one another version started.
340 const holder = yield* store.runByKey(name, options.idempotencyKey);
341 if (holder !== undefined && holder.run_id !== runId) return yield* other(holder);
342 yield* withEngine(engine.execute(payload, { discard: true }));
343 if (options.parent !== undefined) {
344 // The key named a run that someone else started: it would never tell this parent.
345 const row = yield* store.run(runId);
346 if (
347 row?.parent_run_id !== options.parent.runId ||
348 row.parent_wait !== options.parent.wait
349 ) {
350 return yield* new WorkflowInputError({
351 problem: `Run ${runId} of ${name} was started by something else under this key, so it cannot be invoked. Give the invoke a key of its own.`,
352 });
353 }
354 }
355 return { runId };
356 },
357 );
358
359 const latestDefinitions = [...new Set(registered.map(([definition]) => definition.name))].map(
360 (name) => latest(name)![0],
361 );
362 // A schedule taken out and put back is new again: its first run is one interval away.
363 yield* store.triggersKeep(
364 latestDefinitions.flatMap((definition) =>
365 definition.triggers.flatMap((trigger) =>
366 trigger.kind === "webhook" ? [] : [`${definition.name}/${trigger.id}`],
367 ),
368 ),
369 );
370 /** Start what each schedule is due for, once, however long ago that was. */
371 const fireSchedules = Effect.gen(function* () {
372 const now = yield* localNow;
373 for (const definition of latestDefinitions) {
374 for (const trigger of definition.triggers) {
375 if (trigger.kind !== "schedule") continue;
376 const id = `${definition.name}/${trigger.id}`;
377 const due = yield* store.triggerNext(id);
378 if (due !== undefined) {
379 const dueAt = DateTime.makeUnsafe(due);
380 if (DateTime.isLessThan(now, dueAt)) continue;
381 if (!isMissedFixedTimeRun(trigger.schedule, dueAt, now)) {
382 // The key is the time it was due, so a crash before the next line starts no second run.
383 const started = yield* start(
384 definition.name,
385 { scheduledAt: due },
386 { idempotencyKey: `trigger:${id}:${due}` },
387 ).pipe(
388 Effect.as(true),
389 Effect.catch((error) =>
390 Effect.as(
391 Effect.logWarning("A scheduled workflow run did not start", {
392 trigger: id,
393 error,
394 }),
395 false,
396 ),
397 ),
398 );
399 // Not moved past a time it has not started: the next sweep tries that one again.
400 if (!started) continue;
401 }
402 }
403 const next = nextScheduledRunAt(trigger.schedule, now);
404 if (next !== null) {
405 yield* store.triggerSet(id, DateTime.formatIso(DateTime.toUtc(next)));
406 }
407 }
408 }
409 }).pipe(Effect.withSpan("Workflows.fireSchedules"));
410
411 // Trackers and hosts count requests, and nothing here is in that much of a hurry.
412 const lookedAt = new Map<string, number>();
413 // Said once per engine: the same item is in every look until newer ones push it out.
414 const turnedDown = new Set<string>();
415 const millisOf = (at: string) =>
416 Option.match(DateTime.make(at), { onNone: () => undefined, onSome: DateTime.toEpochMillis });
417 /**
418 * Start a run for each issue or pull request opened since the trigger last looked. The first
419 * look only notes the time, so a workflow never starts on everything that was already there.
420 */
421 const fireOpened = Effect.gen(function* () {
422 const now = yield* DateTime.now;
423 for (const definition of latestDefinitions) {
424 for (const trigger of definition.triggers) {
425 if (trigger.kind !== "issues" && trigger.kind !== "pullRequests") continue;
426 const id = `${definition.name}/${trigger.id}`;
427 const since = yield* store.triggerNext(id);
428 if (since === undefined) {
429 yield* store.triggerSet(id, DateTime.formatIso(now));
430 continue;
431 }
432 const last = lookedAt.get(id);
433 const at = DateTime.toEpochMillis(now);
434 if (last !== undefined && at - last < Duration.toMillis(LOOK_EVERY)) continue;
435 lookedAt.set(id, at);
436 const found =
437 trigger.kind === "issues"
438 ? forge.issues.list({
439 project: trigger.project,
440 // Closed ones too: an item can open and close between two looks.
441 state: "all",
442 sort: "created",
443 limit: LOOK_AT_MOST,
444 labels: trigger.labels,
445 query: trigger.query,
446 })
447 : forge.pullRequests.list({
448 project: trigger.project,
449 state: "all",
450 limit: LOOK_AT_MOST,
451 query: trigger.query,
452 });
453 const sinceMillis = millisOf(since) ?? at;
454 yield* found.pipe(
455 Effect.flatMap(
456 Effect.fnUntraced(function* (entries: ReadonlyArray<Issue | PullRequest>) {
457 // From the mark on, not after it: two items can share a moment. As times, since a
458 // host writes them in its own format and the mark is ours.
459 const fresh = entries
460 .flatMap((entry) => {
461 const created = millisOf(entry.createdAt);
462 return created === undefined || created < sinceMillis ? [] : [{ entry, created }];
463 })
464 .toSorted((a, b) => a.created - b.created);
465 if (entries.length >= LOOK_AT_MOST && fresh.length === entries.length) {
466 yield* Effect.logWarning(
467 "More new items than one look reads; older ones among them start no run",
468 { trigger: id, read: entries.length },
469 );
470 }
471 for (const { entry, created } of fresh) {
472 // The key is the address, so an issue seen twice is still one run. One the
473 // workflow turns down is passed over, so it does not hold back the ones after it.
474 const key = `trigger:${id}:${entry.url}`;
475 if (
476 !turnedDown.has(key) &&
477 (yield* store.runByKey(definition.name, key)) === undefined
478 ) {
479 yield* start(definition.name, entry, { idempotencyKey: key }).pipe(
480 // What started the run is the first thing it touched.
481 Effect.flatMap(({ runId }) =>
482 noteFor(
483 store,
484 runId,
485 null,
486 "tracker" in entry
487 ? issueReference(entry, entry)
488 : pullRequestReferenceOf(entry, entry),
489 ),
490 ),
491 Effect.catchTags({
492 WorkflowInputError: (error) =>
493 Effect.andThen(
494 Effect.sync(() => turnedDown.add(key)),
495 Effect.logWarning("A workflow turned down an item it was started on", {
496 trigger: id,
497 item: entry.url,
498 error,
499 }),
500 ),
501 }),
502 );
503 }
504 yield* store.triggerSet(id, DateTime.formatIso(DateTime.makeUnsafe(created)));
505 }
506 }),
507 ),
508 Effect.catch((error) =>
509 Effect.logWarning("A workflow could not look for new work", { trigger: id, error }),
510 ),
511 );
512 }
513 }
514 }).pipe(Effect.withSpan("Workflows.fireOpened"));
515
516 const noChecksSince = new Map<string, number>();
517 /** End each wait on a pull request that has got where the wait wanted it. */
518 const fireWatches = Effect.gen(function* () {
519 const now = DateTime.toEpochMillis(yield* DateTime.now);
520 for (const wait of yield* store.watches) {
521 const watched = WorkflowStore.jsonValue(wait.watch_json ?? "null");
522 // An agent's turn is watched by a fiber of its own, started again here after a reload.
523 if (typeof watched === "object" && watched !== null && "agent" in watched) {
524 yield* seeTurn(wait);
525 continue;
526 }
527 const id = `watch:${wait.run_id}/${wait.name}`;
528 const last = lookedAt.get(id);
529 if (last !== undefined && now - last < Duration.toMillis(LOOK_EVERY)) continue;
530 lookedAt.set(id, now);
531 const watch = watched as unknown as PullRequestWatch;
532 yield* forge.pullRequests.read(watch.pullRequest as PullRequestAddress).pipe(
533 // Each look keeps where the pull request stands on the wait's own step.
534 Effect.provideContext(stepReferences(store, wait.run_id, wait.name)),
535 Effect.flatMap(
536 Effect.fnUntraced(function* (detail) {
537 const standing = standingOf(detail);
538 // How long the host has listed no checks, not how long the wait is open: a push can
539 // clear the list for a moment in the middle of a long wait.
540 if (standing.checks !== "none") noChecksSince.delete(id);
541 else if (!noChecksSince.has(id)) noChecksSince.set(id, now);
542 const without = now - (noChecksSince.get(id) ?? now);
543 if (!isSettled(watch.until, standing, without)) return;
544 const woke = { expired: false, value: standing };
545 if (!(yield* store.waitSignalled(wait.run_id, wait.name, woke))) return;
546 lookedAt.delete(id);
547 noChecksSince.delete(id);
548 yield* wake(wait, woke);
549 }),
550 ),
551 // The wait's own timeout is what ends a wait on something that cannot be read.
552 Effect.catch((error) =>
553 Effect.logWarning("A workflow could not look at a pull request", { wait: id, error }),
554 ),
555 );
556 }
557 }).pipe(Effect.withSpan("Workflows.fireWatches"));
558
559 const hooks = yield* Effect.forEach(
560 latestDefinitions.flatMap((definition) =>
561 definition.triggers.flatMap((trigger) =>
562 trigger.kind === "webhook" ? [{ definition, trigger }] : [],
563 ),
564 ),
565 Effect.fnUntraced(function* ({ definition, trigger }) {
566 const hookId = hookIdOf(definition.name, trigger.name);
567 const token = yield* store.hookToken(hookId, yield* random.uuidV4());
568 return {
569 hookId,
570 token,
571 trigger,
572 workflow: definition.name,
573 name: trigger.name,
574 path: `/api/hooks/${encodeURIComponent(hookId)}/${token}`,
575 };
576 }),
577 );
578 const hookStarts = new Map<string, ReadonlyArray<number>>();
579 const deliver: Workflows["Service"]["deliver"] = Effect.fn("Workflows.deliver")(
580 function* (delivery) {
581 const hook = hooks.find((candidate) => candidate.hookId === delivery.hookId);
582 // A wrong token reads the same as an unknown hook, so the URL does not say which exist.
583 const known =
584 hook !== undefined &&
585 (yield* constantTimeEquals(delivery.token, hook.token).pipe(
586 Effect.provideService(Digest.Digest, digest),
587 Effect.orElseSucceed(() => false),
588 ));
589 if (!known) return Option.none();
590 const authored = yield* Effect.try({
591 try: () => hook.trigger.key?.(delivery.request),
592 catch: (error) =>
593 new WorkflowInputError({
594 problem: `The key of hook ${hook.name} could not be read from the request: ${text(error)}`,
595 }),
596 });
597 // A sender's own delivery id is kept on its retry, so the retry is the same run.
598 const sent = DELIVERY_HEADERS.find((header) => delivery.request.headers[header]);
599 const key =
600 authored ??
601 (sent === undefined ? undefined : `${sent}:${delivery.request.headers[sent]}`) ??
602 delivery.deliveryId ??
603 (yield* random.uuidV4());
604 const idempotencyKey = `hook:${hook.hookId}:${key}`;
605 // A retry of a run that exists starts nothing, so it takes none of the minute.
606 if ((yield* store.runByKey(hook.workflow, idempotencyKey)) === undefined) {
607 const now = DateTime.toEpochMillis(yield* DateTime.now);
608 const recent = (hookStarts.get(hook.hookId) ?? []).filter((at) => now - at < 60_000);
609 if (recent.length >= HOOK_RUNS_PER_MINUTE) {
610 return yield* new WorkflowHookBusyError({ hook: hook.name });
611 }
612 hookStarts.set(hook.hookId, [...recent, now]);
613 }
614 return Option.some(yield* start(hook.workflow, delivery.request, { idempotencyKey }));
615 },
616 );
617
618 /** With `pause`, the sweep's own resume, which only resumes that pause and not a later one. */
619 const resumeRun = Effect.fn("WorkflowEngine.resumeRun")(function* (
620 runId: string,
621 pause?: WorkflowStore.RunRow,
622 ) {
623 const row = yield* requireRun(runId);
624 const engine = byTag.get(row.engine_tag);
625 if (engine === undefined) {
626 return yield* new WorkflowNotRegisteredError({ workflow: row.engine_tag });
627 }
628 if (row.ended_at !== null) return;
629 resuming.add(runId);
630 const resumed = yield* Effect.gen(function* () {
631 // Marked first: once the engine is resumed, the step may fail again and pause the run, and
632 // that must be the last word. A crash in between leaves `running`, which the sweep corrects.
633 if (row.status === "paused") {
634 const unpaused = yield* store.runUnpaused(
635 runId,
636 pause === undefined
637 ? undefined
638 : { pauses: Number(pause.pauses), updatedAt: pause.updated_at },
639 );
640 if (!unpaused && pause !== undefined) return false;
641 }
642 // The step marks its run paused from inside the engine, a moment before the engine records
643 // the failure. Resuming in that moment would do nothing, so the record is waited for.
644 yield* withEngine(engine.poll(runId)).pipe(
645 Effect.repeat({
646 until: (result) => Option.isSome(result) && result.value._tag === "Suspended",
647 schedule: Schedule.spaced(RESUME_LOOK_EVERY),
648 times: RESUME_LOOKS,
649 }),
650 );
651 yield* withEngine(engine.resume(runId));
652 yield* store.runUnheld(runId);
653 return true;
654 }).pipe(Effect.ensuring(Effect.sync(() => resuming.delete(runId))));
655 // Read once `resuming` is clear, so a wake held back meanwhile is among them.
656 if (!resumed) return;
657 for (const wait of yield* store.waitsClaimed(runId)) {
658 yield* send(wait, WorkflowStore.jsonValue(wait.woke_json ?? "null") as typeof Woke.Type);
659 }
660 });
661 const resume: Workflows["Service"]["resume"] = (runId) => resumeRun(runId);
662
663 /** A run the engine holds as failed while its row says it goes on: paused, after all. */
664 const reconcile = Effect.fn("WorkflowEngine.reconcile")(function* (row: WorkflowStore.RunRow) {
665 if (resuming.has(row.run_id)) return;
666 const engine = byTag.get(row.engine_tag);
667 if (engine === undefined) return;
668 const result = yield* withEngine(engine.poll(row.run_id));
669 if (Option.isNone(result) || result.value._tag !== "Suspended") return;
670 if (result.value.failed !== true) return;
671 const cause = result.value.cause;
672 // Held as it was: a run that waited for a person still does.
673 yield* store.runPaused(
674 row.run_id,
675 cause === undefined ? "A step failed." : text(Cause.squash(cause)),
676 );
677 });
678
679 // A cancelled run's body is gone, so its `onEnd` runs here, outside the engine. The sweep asks
680 // again after a failure or a restart, and `ending` keeps the two from running it at once.
681 const ending = new Set<string>();
682 const endCancelled = Effect.fn("WorkflowEngine.endCancelled")(function* (
683 row: WorkflowStore.RunRow,
684 ) {
685 const definition = definitionByTag.get(row.engine_tag);
686 if (definition?.onEnd === undefined || ending.has(row.run_id)) return;
687 const onEnd = definition.onEnd;
688 ending.add(row.run_id);
689 // A step still running would race the cleanup: a machine deleted before it is made.
690 yield* link.inFlight.settled(row.run_id);
691 // The body may have run its own `onEnd` just as the run was cancelled: once is enough.
692 const steps = yield* store.steps(row.run_id);
693 if (steps.some((step) => step.name === END_STEP && step.status === "completed")) {
694 ending.delete(row.run_id);
695 return;
696 }
697 yield* store.stepStarted(row.run_id, END_STEP, "step");
698 const payloadCodec = Schema.toCodecJson(definition.payload);
699 const decode = Schema.decodeEffect(payloadCodec);
700 yield* decode(row.input_json === null ? null : WorkflowStore.jsonValue(row.input_json)).pipe(
701 Effect.flatMap((input) =>
702 onEnd(input as never, {
703 id: row.run_id,
704 outcome: "cancelled",
705 reason: row.detail ?? undefined,
706 }),
707 ),
708 Effect.provideContext(forStep(store, keyValues, link, forge, row.run_id, END_STEP)),
709 // The sweep that runs it reads the engine's BigInts; the cleanup's own code must not.
710 Effect.provideService(SqlClient.SafeIntegers, false),
711 Effect.matchCauseEffect({
712 onSuccess: () => store.stepEnded(row.run_id, END_STEP, "completed", null),
713 onFailure: (cause) =>
714 store.stepEnded(row.run_id, END_STEP, "failed", text(Cause.squash(cause))),
715 }),
716 Effect.ensuring(Effect.sync(() => ending.delete(row.run_id))),
717 );
718 });
719
720 const prune = Effect.fn("WorkflowEngine.prune")(function* (at: DateTime.Utc) {
721 if (Option.isNone(messages) || Option.isNone(sharding)) return;
722 const before = DateTime.formatIso(DateTime.subtractDuration(at, PRUNE_AFTER));
723 for (const row of yield* store.prunable(before, PRUNE_BATCH)) {
724 const entityId = EntityId.make(row.run_id);
725 const shardId = sharding.value.getShardId(entityId, "default");
726 // Its sleeps are entities of their own under the same id.
727 yield* Effect.forEach(
728 [`Workflow/${row.engine_tag}`, "Workflow/-/DurableClock"],
729 (type) =>
730 messages.value.clearAddress(
731 EntityAddress.make({ shardId, entityType: EntityType.make(type), entityId }),
732 ),
733 { discard: true },
734 ).pipe(
735 Effect.andThen(store.enginePruned(row.run_id)),
736 // Left unmarked, so the next sweep tries it again.
737 Effect.catchCause((cause) =>
738 Effect.logWarning("Could not prune a workflow run's engine journal", cause),
739 ),
740 );
741 }
742 const kept = yield* Option.match(settings, {
743 onNone: () => Effect.succeed(DEFAULT_WORKFLOW_SKIPPED_RUNS_KEPT),
744 onSome: (service) =>
745 service.getSettings.pipe(
746 Effect.map((current) => current.workflowSkippedRunsKept),
747 Effect.orElseSucceed(() => DEFAULT_WORKFLOW_SKIPPED_RUNS_KEPT),
748 ),
749 });
750 yield* store.pruneSkipped(kept, SKIPPED_PRUNE_BATCH);
751 });
752
753 const sweep: Workflows["Service"]["sweep"] = Effect.gen(function* () {
754 for (const wait of yield* store.waitsPastDeadline) {
755 const woke = { expired: true, value: null };
756 if (yield* store.waitSignalled(wait.run_id, wait.name, woke)) yield* wake(wait, woke);
757 }
758 // A claim whose wake a crash swallowed: the wake is made again. Waking twice is harmless.
759 for (const wait of yield* store.waitsToWake) {
760 if (wait.woke_json === null) continue;
761 yield* wake(wait, WorkflowStore.jsonValue(wait.woke_json) as typeof Woke.Type);
762 }
763 // A cancel that was cut short before it reached what the run had invoked.
764 for (const child of yield* store.orphans) {
765 yield* Effect.ignore(cancel(child.run_id, "the run that invoked it was cancelled"));
766 }
767 // A cancel cut short after the run was ended: what it had not stopped yet is stopped here.
768 for (const row of yield* store.cancelsCutShort(END_STEP)) {
769 if (cancelling.has(row.run_id) || ending.has(row.run_id)) continue;
770 const engine = byTag.get(row.engine_tag);
771 if (engine !== undefined) yield* withEngine(engine.interrupt(row.run_id));
772 yield* stopSteps(row.run_id, yield* store.runningThreads(row.run_id));
773 }
774 // A run that ended without its parent hearing of it. Telling twice is harmless.
775 for (const child of yield* store.untold) yield* ended(child.run_id);
776 yield* store.mailExpire;
777 yield* fireSchedules;
778 yield* fireOpened;
779 yield* fireWatches;
780 const at = yield* DateTime.now;
781 // A run with a step still going is ended by its cancel, which waits for that step.
782 for (const row of yield* store.runsToEnd(END_STEP, END_TRIES)) {
783 const rest = END_AFTER[Number(row.end_attempts ?? 0) - 1];
784 if (row.end_ended_at !== null && rest !== undefined) {
785 const due = DateTime.addDuration(
786 DateTime.makeUnsafe(row.end_ended_at),
787 Duration.fromInputUnsafe(rest),
788 );
789 if (DateTime.isLessThan(at, due)) continue;
790 }
791 if (!link.inFlight.busy(row.run_id)) yield* endCancelled(row);
792 }
793 for (const row of yield* store.everyRun("running")) yield* reconcile(row);
794 for (const row of yield* store.everyRun("waiting")) yield* reconcile(row);
795 for (const row of yield* store.everyRun("paused")) {
796 const due = resumesAt(row);
797 if (due === undefined || DateTime.isLessThan(at, due)) continue;
798 yield* Effect.ignore(resumeRun(row.run_id, row));
799 }
800 yield* prune(at);
801 }).pipe(Effect.withSpan("Workflows.sweep"));
802
803 // With nothing registered there is nothing to resume, end or start: only history to read.
804 if (registered.length > 0) {
805 yield* sweep.pipe(
806 Effect.catchCause((cause) => Effect.logWarning("Workflow sweep failed", cause)),
807 Effect.andThen(Effect.sleep(SWEEP_EVERY)),
808 Effect.forever,
809 Effect.forkScoped,
810 );
811 }
812
813 const questions = Effect.flatMap(store.requests, (waits) =>
814 Effect.forEach(
815 waits.filter((wait) => wait.request_json !== null),
816 (wait) =>
817 Effect.map(store.latestThread(wait.run_id), (thread) => {
818 const request = WorkflowStore.jsonValue(wait.request_json ?? "null");
819 const kind =
820 request !== null && typeof request === "object" && !Array.isArray(request)
821 ? (request as { readonly kind?: unknown }).kind
822 : undefined;
823 return {
824 runId: wait.run_id,
825 name: wait.name,
826 request,
827 ...(typeof kind === "string" ? { kind } : {}),
828 askedAt: wait.opened_at,
829 thread,
830 };
831 }),
832 ),
833 );
834 const WEEKDAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
835 const triggerText = (trigger: WorkflowDefinition["triggers"][number]) => {
836 if (trigger.kind === "webhook") return `webhook ${trigger.name}`;
837 if (trigger.kind !== "schedule") {
838 return `new ${trigger.kind === "issues" ? "issues" : "pull requests"} in ${trigger.project}`;
839 }
840 if (trigger.schedule.type === "interval") {
841 return `every ${Duration.format(Duration.millis(trigger.schedule.everyMs))}`;
842 }
843 const days = trigger.schedule.weekdays;
844 return `daily at ${trigger.schedule.timeOfDay}${
845 days === undefined ? "" : ` on ${days.map((day) => WEEKDAYS[day] ?? day).join(", ")}`
846 }`;
847 };
848 const summaries = [...new Set(registered.map(([definition]) => definition.name))].flatMap(
849 (name) => {
850 const found = latest(name);
851 return found === undefined
852 ? []
853 : [
854 {
855 name,
856 version: found[0].version,
857 triggers: found[0].triggers.map(triggerText),
858 ...(Object.keys(found[0].asks).length === 0
859 ? {}
860 : {
861 asks: Object.entries(found[0].asks).map(([kind, label]) => ({ kind, label })),
862 }),
863 },
864 ];
865 },
866 );
867 const snapshot = Effect.all({
868 workflows: Effect.succeed(summaries),
869 runs: Effect.map(store.runs(undefined), (rows) => rows.map(toRun)),
870 questions,
871 });
872 const watch: Workflows["Service"]["watch"] = Stream.unwrap(
873 Effect.gen(function* () {
874 // Subscribed before the first look, so a change in between is not missed.
875 const changes = yield* PubSub.subscribe(store.changes);
876 return Stream.concat(
877 Stream.fromEffect(snapshot),
878 // A run writes several rows per step; one list answers a burst of them.
879 Stream.fromSubscription(changes).pipe(
880 Stream.debounce(WATCH_SETTLE),
881 Stream.mapEffect(() => snapshot),
882 ),
883 ).pipe(
884 // Each list is told as what differs from the one before, which this watcher already has.
885 // A list with no difference is still sent: a client reads an open run's steps again on it.
886 Stream.mapAccum(
887 () => undefined as Sent | undefined,
888 (sent, next) => {
889 const now: Sent = {
890 runs: new Map(next.runs.map((run) => [run.runId, JSON.stringify(run)])),
891 questions: new Map(
892 next.questions.map((question) => [
893 workflowQuestionKey(question),
894 { runId: question.runId, name: question.name, text: JSON.stringify(question) },
895 ]),
896 ),
897 };
898 const update: WorkflowRunsUpdate =
899 sent === undefined
900 ? next
901 : {
902 _tag: "changed",
903 runs: next.runs.filter(
904 (run) => sent.runs.get(run.runId) !== now.runs.get(run.runId),
905 ),
906 removed: [...sent.runs.keys()].filter((runId) => !now.runs.has(runId)),
907 questions: next.questions.filter((question) => {
908 const key = workflowQuestionKey(question);
909 return sent.questions.get(key)?.text !== now.questions.get(key)?.text;
910 }),
911 closed: [...sent.questions]
912 .filter(([key]) => !now.questions.has(key))
913 .map(([, { runId, name }]) => ({ runId, name })),
914 };
915 return [now, [update]] as const;
916 },
917 ),
918 );
919 }),
920 );
921
922 const counts: Workflows["Service"]["counts"] = Stream.unwrap(
923 Effect.gen(function* () {
924 const changes = yield* PubSub.subscribe(store.changes);
925 return Stream.concat(
926 Stream.fromEffect(store.counts),
927 Stream.fromSubscription(changes).pipe(
928 Stream.debounce(WATCH_SETTLE),
929 Stream.mapEffect(() => store.counts),
930 ),
931 // Most changes move no count, and a badge has no use for hearing of those.
932 ).pipe(Stream.changesWith((left, right) => JSON.stringify(left) === JSON.stringify(right)));
933 }),
934 );
935
936 /**
937 * A signal to a question, as its wait receives it: with who sent it and when, which the sender
938 * does not get to say. Undefined for a wait that is not a question, or one asked before answers
939 * kept that, whose closed schema would refuse them.
940 */
941 const answerOf = Effect.fn("WorkflowEngine.answerOf")(function* (
942 wait: { readonly request_json: string | null; readonly schema_json: string },
943 value: Schema.Json,
944 sender: WorkflowStore.SignalSender,
945 ) {
946 if (wait.request_json === null || typeof value !== "object" || value === null) return undefined;
947 if (Array.isArray(value)) return undefined;
948 const problem = answerProblem(WorkflowStore.jsonValue(wait.request_json), value);
949 if (problem !== undefined) return yield* new WorkflowInputError({ problem });
950 return stamped(wait, value, sender);
951 });
952 /** `answerOf` without the words for an answer that lacks its reason, which the schema refuses too. */
953 const stamped = (
954 wait: { readonly request_json: string | null; readonly schema_json: string },
955 value: Schema.Json,
956 sender: WorkflowStore.SignalSender,
957 ) => {
958 const answer = answerStamped(
959 { request: wait.request_json !== null, schemaJson: wait.schema_json },
960 value,
961 sender,
962 );
963 return answer === undefined ? undefined : { expired: false, value: answer };
964 };
965 const signal: Workflows["Service"]["signal"] = Effect.fn("Workflows.signal")(
966 function* (address, value, options) {
967 // A sender's retry of a signal that already woke a wait is not a second signal.
968 if (yield* store.signalSeen(options.id)) return "delivered" as const;
969 const valueJson = WorkflowStore.jsonText(value);
970 const woke = { expired: false, value };
971 // Who sent it and when it came, said once here and by no one else, however it is delivered.
972 // A retry of a signal that is still kept is that signal: its first arrival says both.
973 const arrived: WorkflowStore.SignalSender = {
974 answeredBy: options.answeredBy,
975 answeredBySession: options.answeredBySession,
976 answeredAt: DateTime.formatIso(yield* DateTime.now),
977 };
978 let sender = (yield* store.mailSender(options.id)) ?? arrived;
979 // One signal per wait: a wait another signal took first sends this one to the next.
980 while (true) {
981 const wait = yield* store.waitAt(address);
982 if (wait === undefined) break;
983 const answered = yield* answerOf(wait, value, sender);
984 const schema = WorkflowStore.jsonValue(wait.schema_json) as Record<string, Schema.Json>;
985 const checked = yield* checkOutput(
986 schema,
987 answered === undefined ? valueJson : WorkflowStore.jsonText(answered.value),
988 );
989 if (Result.isFailure(checked)) {
990 return yield* new WorkflowInputError({
991 problem: `The value does not fit what ${wait.name} waits for. ${rejectionText(checked.failure)}`,
992 });
993 }
994 if (yield* store.waitSignalled(wait.run_id, wait.name, answered ?? woke, options.id)) {
995 yield* wake(wait, answered ?? woke);
996 return "delivered" as const;
997 }
998 // Refused for its id: the same signal, sent again at once, woke a wait.
999 if (yield* store.signalSeen(options.id)) return "delivered" as const;
1000 }
1001 const expiresAt = DateTime.formatIso(
1002 DateTime.addDuration(
1003 yield* DateTime.now,
1004 Duration.fromInputUnsafe(options.ttl ?? DEFAULT_SIGNAL_TTL),
1005 ),
1006 );
1007 if (yield* store.signalSeen(options.id)) return "delivered" as const;
1008 yield* store.mailPut({ signalId: options.id, address, valueJson, expiresAt, sender });
1009 // A copy the same signal kept first, while this one looked for a wait, is the one that stays.
1010 sender = (yield* store.mailSender(options.id)) ?? sender;
1011 // The wait may have opened and looked for mail between the look above and this write.
1012 while (true) {
1013 const late = yield* store.waitAt(address);
1014 if (late === undefined) return "buffered" as const;
1015 const schema = WorkflowStore.jsonValue(late.schema_json) as Record<string, Schema.Json>;
1016 // Kept for a wait it fits; this one, the oldest on the channel, is not it.
1017 const answered = stamped(late, value, sender) ?? woke;
1018 if (Result.isFailure(yield* checkOutput(schema, WorkflowStore.jsonText(answered.value)))) {
1019 return "buffered" as const;
1020 }
1021 const outcome = yield* store.mailDeliver(options.id, late.run_id, late.name, answered);
1022 if (outcome === "delivered") {
1023 yield* wake(late, answered);
1024 return "delivered" as const;
1025 }
1026 // The kept copy went to a wait that opened, or was dropped as already delivered.
1027 if (outcome === "gone") return "delivered" as const;
1028 }
1029 },
1030 );
1031 const answer: Workflows["Service"]["answer"] = Effect.fn("Workflows.answer")(
1032 function* (runId, name, value, answeredBy) {
1033 const wait = yield* store.waitAt({ runId, wait: name });
1034 // Answered already, or never asked: kept, it would answer whatever asks there next.
1035 if (wait === undefined || wait.request_json === null) return;
1036 // Named by this asking of the question, so every answer to it is one signal.
1037 yield* signal({ runId, wait: name }, value, {
1038 id: `answer:${wait.token}`,
1039 ...(answeredBy === undefined
1040 ? {}
1041 : { answeredBy: answeredBy.label, answeredBySession: answeredBy.sessionId }),
1042 });
1043 },
1044 );
1045 const signalAll = Effect.fn("WorkflowEngine.signalAll")(function* (
1046 address: { readonly channel: string; readonly workflow?: string | undefined },
1047 value: Schema.Json,
1048 ) {
1049 const valueJson = WorkflowStore.jsonText(value);
1050 let woken = 0;
1051 for (const wait of yield* store.waitsOn(address.channel, address.workflow)) {
1052 const schema = WorkflowStore.jsonValue(wait.schema_json) as Record<string, Schema.Json>;
1053 // A wait this value does not fit was not waiting for it; the others are still woken.
1054 if (Result.isFailure(yield* checkOutput(schema, valueJson))) continue;
1055 const woke = { expired: false, value };
1056 if (!(yield* store.waitSignalled(wait.run_id, wait.name, woke))) continue;
1057 yield* wake(wait, woke);
1058 woken++;
1059 }
1060 return woken;
1061 });
1062 /** Tell the run that invoked this one, if one did, how it ended. */
1063 const ended = Effect.fn("WorkflowEngine.ended")(function* (runId: string) {
1064 const row = yield* store.run(runId);
1065 if (row === undefined || row.parent_run_id === null || row.parent_wait === null) return;
1066 if (row.ended_at === null) return;
1067 yield* signal(
1068 { runId: row.parent_run_id, wait: row.parent_wait },
1069 {
1070 outcome: row.status,
1071 value: row.result_json === null ? null : WorkflowStore.jsonValue(row.result_json),
1072 ...(row.detail === null ? {} : { reason: row.detail }),
1073 },
1074 { id: `${runId}/ended` },
1075 ).pipe(Effect.ignore);
1076 });
1077
1078 /** A step in flight cannot be interrupted, so the agent it waits on is stopped instead. */
1079 const stopSteps = Effect.fn("WorkflowEngine.stopSteps")(function* (
1080 runId: string,
1081 threads: ReadonlyArray<Parameters<typeof stopTurn>[0]>,
1082 ) {
1083 yield* Effect.forEach(threads, (thread) => Effect.ignore(stopTurn(thread)), {
1084 discard: true,
1085 });
1086 yield* store.stepsCancelled(runId, END_STEP);
1087 });
1088
1089 // Cancels under way, whose slow part the sweep must not take for one cut short.
1090 const cancelling = new Set<string>();
1091 const cancel: Workflows["Service"]["cancel"] = Effect.fn("Workflows.cancel")(
1092 function* (runId, reason) {
1093 const row = yield* requireRun(runId);
1094 if (row.ended_at !== null) return;
1095 const threads = yield* store.runningThreads(runId);
1096 const engine = byTag.get(row.engine_tag);
1097 cancelling.add(runId);
1098 yield* Effect.gen(function* () {
1099 // Ended first, so nothing the run still does can be recorded as its outcome. A run that
1100 // finished in the meantime keeps its own ending, and its cleanup is its own. Not cut off
1101 // midway: the engine would go on with a cancelled run, or its parent wait forever.
1102 const cancelled = yield* Effect.uninterruptible(
1103 Effect.gen(function* () {
1104 if (!(yield* store.runEnded(runId, "cancelled", reason ?? null, null))) return false;
1105 if (engine !== undefined) yield* withEngine(engine.interrupt(runId));
1106 yield* ended(runId);
1107 return true;
1108 }),
1109 );
1110 if (!cancelled) return;
1111 yield* stopSteps(runId, threads);
1112 // What this run invoked was part of it.
1113 yield* Effect.forEach(
1114 yield* store.children(runId),
1115 (child) => Effect.ignore(cancel(child.run_id, reason)),
1116 { discard: true },
1117 );
1118 // Waited for briefly, so the caller usually hears of a run that is cleaned up. A cleanup
1119 // can take minutes; it goes on by itself, and the sweep finishes one that is cut short.
1120 const cleanup = yield* Effect.forkIn(
1121 endCancelled({ ...row, detail: reason ?? null }),
1122 scope,
1123 );
1124 yield* Fiber.join(cleanup).pipe(Effect.timeoutOption(CANCEL_WAITS));
1125 }).pipe(Effect.ensuring(Effect.sync(() => cancelling.delete(runId))));
1126 },
1127 );
1128
1129 // Steps were registered before this engine existed; now they can reach it.
1130 link.current = {
1131 signal,
1132 signalAll,
1133 start,
1134 ended,
1135 watchTurn,
1136 cancel: (runId, reason) => cancel(runId, reason),
1137 list: Effect.fn("WorkflowEngine.list")(function* (filter) {
1138 return (yield* store.runsWhere(filter)).map((row) => ({
1139 id: row.run_id,
1140 workflow: row.workflow,
1141 key: row.idempotency_key,
1142 title: row.title,
1143 status: row.status,
1144 detail: row.detail,
1145 tags: WorkflowStore.jsonValue(row.tags_json) as ReadonlyArray<string>,
1146 startedAt: row.started_at,
1147 endedAt: row.ended_at,
1148 }));
1149 }),
1150 };
1151
1152 return Workflows.of({
1153 start,
1154 hooks: Effect.succeed(hooks.map(({ workflow, name, path }) => ({ workflow, name, path }))),
1155 // A cancelled run whose cleanup has not worked yet still needs its version to run it.
1156 unfinished: Effect.map(
1157 Effect.all([store.unfinished, store.runsToEnd(END_STEP, END_TRIES)]),
1158 ([open, ending]) => [
1159 ...open,
1160 ...ending
1161 .filter((row) => definitionByTag.get(row.engine_tag)?.onEnd !== undefined)
1162 .map((row) => ({ workflow: row.workflow, version: Number(row.version) })),
1163 ],
1164 ),
1165 deliver,
1166 signal,
1167 answer,
1168 resume,
1169 cancel,
1170 get: Effect.fn("Workflows.get")(function* (runId) {
1171 const row = yield* requireRun(runId);
1172 const steps = yield* store.steps(runId);
1173 return {
1174 run: toRun(row),
1175 references: yield* store.references(runId),
1176 steps: steps.map((step) => ({
1177 name: step.name,
1178 kind: step.kind,
1179 status: step.status,
1180 attempts: Number(step.attempts),
1181 detail: step.detail,
1182 threadId: step.thread_id,
1183 environmentId: step.environment_id,
1184 result: step.result_json === null ? null : WorkflowStore.jsonValue(step.result_json),
1185 said: step.said,
1186 startedAt: step.started_at,
1187 endedAt: step.ended_at,
1188 })),
1189 };
1190 }),
1191 list: Effect.fn("Workflows.list")(function* (filter) {
1192 const rows =
1193 filter?.tag === undefined
1194 ? yield* store.runs(filter?.status)
1195 : yield* store.runsWhere({ status: filter.status, tag: filter.tag });
1196 return rows.map(toRun);
1197 }),
1198 waitFor: Effect.fn("Workflows.waitFor")(function* (runId, done) {
1199 // Subscribed before the first look, so a change in between is not missed.
1200 const changes = yield* PubSub.subscribe(store.changes);
1201 while (true) {
1202 const row = yield* store.run(runId);
1203 if (row !== undefined && done(toRun(row))) return toRun(row);
1204 yield* Effect.repeat(PubSub.take(changes), { until: (changed) => changed === runId });
1205 }
1206 }, Effect.scoped),
1207 questions,
1208 counts,
1209 stored: Effect.fn("Workflows.stored")(function* (prefix) {
1210 return (yield* keyValues.list(prefix)).map((row) => ({
1211 key: row.key,
1212 value: WorkflowStore.jsonValue(row.valueJson),
1213 }));
1214 }),
1215 storeSet: Effect.fn("Workflows.storeSet")(function* (key, value) {
1216 yield* keyValues.set(key, WorkflowStore.jsonText(value));
1217 }),
1218 storeDelete: Effect.fn("Workflows.storeDelete")(function* (key) {
1219 yield* keyValues.delete(key);
1220 }),
1221 watch,
1222 sweep,
1223 });
1224});
1225
1226/**
1227 * The workflow service with these definitions registered, on the SQLite database provided to it.
1228 * Only one process may run this layer against a database.
1229 */
1230export const layer = (
1231 definitions: ReadonlyArray<WorkflowDefinition>,
1232 store: typeof WorkflowStore.layer = WorkflowStore.layer,
1233) => {
1234 const registered = definitions.map(
1235 (definition) => [definition, engineWorkflow(definition)] as const,
1236 );
1237 const layerDefinitions = Layer.mergeAll(
1238 Layer.empty,
1239 ...registered.map(([definition, engine]) => layerDefinition(definition, engine)),
1240 );
1241 return Layer.effect(Workflows, make(registered)).pipe(
1242 Layer.provide(layerDefinitions),
1243 Layer.provide(store),
1244 Layer.provide(Layer.merge(layerKeyValues, layerEngineLink)),
1245 Layer.provide(
1246 registered.length === 0
1247 ? WorkflowEngine.layerMemory
1248 : ClusterWorkflowEngine.layer.pipe(
1249 // Merged so the sweep can prune ended runs' journals from the same storage.
1250 Layer.provideMerge(SingleRunner.layer({ runnerStorage: "sql" })),
1251 ),
1252 ),
1253 Layer.provide(Layer.succeed(SqlClient.SafeIntegers, true)),
1254 );
1255};