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