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

WorkflowEngine.ts

1,131 lines48.3 KB

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