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