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