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 if (rest === undefined) return undefined;
176 const due = DateTime.addDuration(DateTime.makeUnsafe(row.updated_at), rest);
177 return Number.isNaN(DateTime.toDateUtc(due).getTime()) ? undefined : due;
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 const unrepresentableSchedules = new Set<string>();
402 /** Start what each schedule is due for, once, however long ago that was. */
403 const fireSchedules = Effect.gen(function* () {
404 const now = yield* localNow;
405 for (const definition of latestDefinitions) {
406 for (const trigger of definition.triggers) {
407 if (trigger.kind !== "schedule") continue;
408 const id = stateId(definition, trigger);
409 const due = yield* store.triggerNext(id);
410 if (due !== undefined) {
411 const dueAt = DateTime.makeUnsafe(due);
412 if (DateTime.isLessThan(now, dueAt)) continue;
413 if (!isMissedFixedTimeRun(trigger.schedule, dueAt, now)) {
414 // The key is the time it was due, so a crash before the next line starts no second run.
415 const started = yield* start(
416 definition.name,
417 { scheduledAt: due },
418 { idempotencyKey: `trigger:${id}:${due}` },
419 ).pipe(
420 Effect.as(true),
421 Effect.catch((error) =>
422 Effect.as(
423 Effect.logWarning("A scheduled workflow run did not start", {
424 trigger: id,
425 error,
426 }),
427 false,
428 ),
429 ),
430 );
431 // Not moved past a time it has not started: the next sweep tries that one again.
432 if (!started) continue;
433 }
434 }
435 const next = nextScheduledRunAt(trigger.schedule, now);
436 if (next === null) continue;
437 const nextAt = DateTime.toDateUtc(next);
438 if (Number.isNaN(nextAt.getTime())) {
439 if (!unrepresentableSchedules.has(id)) {
440 unrepresentableSchedules.add(id);
441 yield* Effect.logWarning("A scheduled workflow's next run time is out of range", {
442 trigger: id,
443 });
444 }
445 continue;
446 }
447 yield* store.triggerSet(id, nextAt.toISOString());
448 }
449 }
450 }).pipe(Effect.withSpan("Workflows.fireSchedules"));
451
452 // Trackers and hosts count requests, and nothing here is in that much of a hurry.
453 const lookedAt = new Map<string, number>();
454 // Said once per engine: the same item is in every look until newer ones push it out.
455 const turnedDown = new Set<string>();
456 const millisOf = (at: string) =>
457 Option.match(DateTime.make(at), { onNone: () => undefined, onSome: DateTime.toEpochMillis });
458 /**
459 * Start a run for each issue or pull request opened since the trigger last looked. The first
460 * look only notes the time, so a workflow never starts on everything that was already there.
461 */
462 const fireOpened = Effect.gen(function* () {
463 const now = yield* DateTime.now;
464 for (const definition of latestDefinitions) {
465 for (const trigger of definition.triggers) {
466 if (trigger.kind !== "issues" && trigger.kind !== "pullRequests") continue;
467 const id = stateId(definition, trigger);
468 const since = yield* store.triggerNext(id);
469 if (since === undefined) {
470 yield* store.triggerSet(id, DateTime.formatIso(now));
471 continue;
472 }
473 const last = lookedAt.get(id);
474 const at = DateTime.toEpochMillis(now);
475 if (last !== undefined && at - last < Duration.toMillis(LOOK_EVERY)) continue;
476 lookedAt.set(id, at);
477 const found =
478 trigger.kind === "issues"
479 ? forge.issues.list({
480 project: trigger.project,
481 // Closed ones too: an item can open and close between two looks.
482 state: "all",
483 sort: "created",
484 limit: LOOK_AT_MOST,
485 labels: trigger.labels,
486 query: trigger.query,
487 })
488 : forge.pullRequests.list({
489 project: trigger.project,
490 state: "all",
491 limit: LOOK_AT_MOST,
492 query: trigger.query,
493 });
494 const sinceMillis = millisOf(since) ?? at;
495 yield* found.pipe(
496 Effect.flatMap(
497 Effect.fnUntraced(function* (entries: ReadonlyArray<Issue | PullRequest>) {
498 // From the mark on, not after it: two items can share a moment. As times, since a
499 // host writes them in its own format and the mark is ours.
500 const fresh = entries
501 .flatMap((entry) => {
502 const created = millisOf(entry.createdAt);
503 return created === undefined || created < sinceMillis ? [] : [{ entry, created }];
504 })
505 .toSorted((a, b) => a.created - b.created);
506 if (entries.length >= LOOK_AT_MOST && fresh.length === entries.length) {
507 yield* Effect.logWarning(
508 "More new items than one look reads; older ones among them start no run",
509 { trigger: id, read: entries.length },
510 );
511 }
512 for (const { entry, created } of fresh) {
513 // The key is the address, so an issue seen twice is still one run. One the
514 // workflow turns down is passed over, so it does not hold back the ones after it.
515 const key = `trigger:${id}:${entry.url}`;
516 if (
517 !turnedDown.has(key) &&
518 (yield* store.runByKey(definition.name, key)) === undefined
519 ) {
520 yield* start(definition.name, entry, { idempotencyKey: key }).pipe(
521 // What started the run is the first thing it touched.
522 Effect.flatMap(({ runId }) =>
523 noteFor(
524 store,
525 runId,
526 null,
527 "tracker" in entry
528 ? issueReference(entry, entry)
529 : pullRequestReferenceOf(entry, entry),
530 ),
531 ),
532 Effect.catchTags({
533 WorkflowInputError: (error) =>
534 Effect.andThen(
535 Effect.sync(() => turnedDown.add(key)),
536 Effect.logWarning("A workflow turned down an item it was started on", {
537 trigger: id,
538 item: entry.url,
539 error,
540 }),
541 ),
542 }),
543 );
544 }
545 yield* store.triggerSet(id, DateTime.formatIso(DateTime.makeUnsafe(created)));
546 }
547 }),
548 ),
549 Effect.catch((error) =>
550 Effect.logWarning("A workflow could not look for new work", { trigger: id, error }),
551 ),
552 );
553 }
554 }
555 }).pipe(Effect.withSpan("Workflows.fireOpened"));
556
557 const noChecksSince = new Map<string, number>();
558 /** End each wait on a pull request that has got where the wait wanted it. */
559 const fireWatches = Effect.gen(function* () {
560 const now = DateTime.toEpochMillis(yield* DateTime.now);
561 for (const wait of yield* store.watches) {
562 const watched = WorkflowStore.jsonValue(wait.watch_json ?? "null");
563 // An agent's turn is watched by a fiber of its own, started again here after a reload.
564 if (typeof watched === "object" && watched !== null && "agent" in watched) {
565 yield* seeTurn(wait);
566 continue;
567 }
568 const id = `watch:${wait.run_id}/${wait.name}`;
569 const last = lookedAt.get(id);
570 if (last !== undefined && now - last < Duration.toMillis(LOOK_EVERY)) continue;
571 lookedAt.set(id, now);
572 const watch = watched as unknown as PullRequestWatch;
573 yield* forge.pullRequests.read(watch.pullRequest as PullRequestAddress).pipe(
574 // Each look keeps where the pull request stands on the wait's own step.
575 Effect.provideContext(stepReferences(store, wait.run_id, wait.name)),
576 Effect.flatMap(
577 Effect.fnUntraced(function* (detail) {
578 const standing = standingOf(detail);
579 // How long the host has listed no checks, not how long the wait is open: a push can
580 // clear the list for a moment in the middle of a long wait.
581 if (standing.checks !== "none") noChecksSince.delete(id);
582 else if (!noChecksSince.has(id)) noChecksSince.set(id, now);
583 const without = now - (noChecksSince.get(id) ?? now);
584 if (!isSettled(watch.until, standing, without)) return;
585 const woke = { expired: false, value: standing };
586 if (!(yield* store.waitSignalled(wait.run_id, wait.name, woke))) return;
587 lookedAt.delete(id);
588 noChecksSince.delete(id);
589 yield* wake(wait, woke);
590 }),
591 ),
592 // The wait's own timeout is what ends a wait on something that cannot be read.
593 Effect.catch((error) =>
594 Effect.logWarning("A workflow could not look at a pull request", { wait: id, error }),
595 ),
596 );
597 }
598 }).pipe(Effect.withSpan("Workflows.fireWatches"));
599
600 const hooks = yield* Effect.forEach(
601 latestDefinitions.flatMap((definition) =>
602 definition.triggers.flatMap((trigger) =>
603 trigger.kind === "webhook" ? [{ definition, trigger }] : [],
604 ),
605 ),
606 Effect.fnUntraced(function* ({ definition, trigger }) {
607 const hookId = hookIdOf(definition.name, trigger.name);
608 const token = yield* store.hookToken(hookId, yield* random.uuidV4());
609 return {
610 hookId,
611 token,
612 trigger,
613 workflow: definition.name,
614 name: trigger.name,
615 path: `/api/hooks/${encodeURIComponent(hookId)}/${token}`,
616 };
617 }),
618 );
619 const hookStarts = new Map<string, ReadonlyArray<number>>();
620 const deliver: Workflows["Service"]["deliver"] = Effect.fn("Workflows.deliver")(
621 function* (delivery) {
622 const hook = hooks.find((candidate) => candidate.hookId === delivery.hookId);
623 // A wrong token reads the same as an unknown hook, so the URL does not say which exist.
624 const known =
625 hook !== undefined &&
626 (yield* constantTimeEquals(delivery.token, hook.token).pipe(
627 Effect.provideService(Digest.Digest, digest),
628 Effect.orElseSucceed(() => false),
629 ));
630 if (!known) return Option.none();
631 const authored = yield* Effect.try({
632 try: () => hook.trigger.key?.(delivery.request),
633 catch: (error) =>
634 new WorkflowInputError({
635 problem: `The key of hook ${hook.name} could not be read from the request: ${text(error)}`,
636 }),
637 });
638 // A sender's own delivery id is kept on its retry, so the retry is the same run.
639 const sent = DELIVERY_HEADERS.find((header) => delivery.request.headers[header]);
640 const key =
641 authored ??
642 (sent === undefined ? undefined : `${sent}:${delivery.request.headers[sent]}`) ??
643 delivery.deliveryId ??
644 (yield* random.uuidV4());
645 const idempotencyKey = `hook:${hook.hookId}:${key}`;
646 // A retry of a run that exists starts nothing, so it takes none of the minute.
647 if ((yield* store.runByKey(hook.workflow, idempotencyKey)) === undefined) {
648 const now = DateTime.toEpochMillis(yield* DateTime.now);
649 const recent = (hookStarts.get(hook.hookId) ?? []).filter((at) => now - at < 60_000);
650 if (recent.length >= HOOK_RUNS_PER_MINUTE) {
651 return yield* new WorkflowHookBusyError({ hook: hook.name });
652 }
653 hookStarts.set(hook.hookId, [...recent, now]);
654 }
655 return Option.some(yield* start(hook.workflow, delivery.request, { idempotencyKey }));
656 },
657 );
658
659 // A place given to a queued step wakes its wait. A place given back to a resumed run, once it
660 // has all it gave up, resumes it, apart from whatever handed the place out.
661 const placeWake = (runId: string, name: string) =>
662 Effect.ignore(signalWait({ runId, wait: name }, null, { id: `place:${runId}/${name}` }, true));
663 // Typed, as it and the resume it starts refer to each other.
664 const placesTaken: (given: ReadonlyArray<WorkflowStore.PlaceRow>) => Effect.Effect<void> =
665 Effect.fnUntraced(function* (given) {
666 // Several of one run's places can come back at once; the run is resumed once.
667 const resumed = new Set<string>();
668 for (const place of given) {
669 if (place.state === "queued") {
670 yield* placeWake(place.run_id, place.name);
671 continue;
672 }
673 if (resumed.has(place.run_id)) continue;
674 if (yield* store.placesReturning(place.run_id)) continue;
675 resumed.add(place.run_id);
676 yield* store.runResumed(place.run_id);
677 yield* Effect.forkIn(Effect.ignore(resumeRun(place.run_id)), scope);
678 }
679 });
680 const placesFreed: Effect.Effect<void> = Effect.flatMap(store.placesGiven, (given) =>
681 placesTaken(given),
682 );
683
684 /** With `pause`, the sweep's own resume, which only resumes that pause and not a later one. */
685 const resumeRun = Effect.fn("WorkflowEngine.resumeRun")(function* (
686 runId: string,
687 pause?: WorkflowStore.RunRow,
688 ) {
689 const row = yield* requireRun(runId);
690 const engine = byTag.get(row.engine_tag);
691 if (engine === undefined) {
692 return yield* new WorkflowNotRegisteredError({ workflow: row.engine_tag });
693 }
694 if (row.ended_at !== null) return;
695 resuming.add(runId);
696 const resumed = yield* Effect.gen(function* () {
697 // Marked first: once the engine is resumed, the step may fail again and pause the run, and
698 // that must be the last word. A crash in between leaves `running`, which the sweep corrects.
699 if (row.status === "paused") {
700 const unpaused = yield* store.runUnpaused(
701 runId,
702 pause === undefined
703 ? undefined
704 : { pauses: Number(pause.pauses), updatedAt: pause.updated_at },
705 );
706 if (!unpaused && pause !== undefined) return false;
707 }
708 // The places its pause gave up come back first, in its old turn.
709 if (yield* store.placesBack(runId)) return "queued" as const;
710 if (yield* store.placesReturning(runId)) return "queued" as const;
711 // The step marks its run paused from inside the engine, a moment before the engine records
712 // the failure. Resuming in that moment would do nothing, so the record is waited for.
713 yield* withEngine(engine.poll(runId)).pipe(
714 Effect.repeat({
715 until: (result) => Option.isSome(result) && result.value._tag === "Suspended",
716 schedule: Schedule.spaced(RESUME_LOOK_EVERY),
717 times: RESUME_LOOKS,
718 }),
719 );
720 yield* withEngine(engine.resume(runId));
721 yield* store.runUnheld(runId);
722 return true;
723 }).pipe(Effect.ensuring(Effect.sync(() => resuming.delete(runId))));
724 if (resumed === "queued") return yield* placesFreed;
725 // Read once `resuming` is clear, so a wake held back meanwhile is among them.
726 if (!resumed) return;
727 for (const wait of yield* store.waitsClaimed(runId)) {
728 yield* send(wait, WorkflowStore.jsonValue(wait.woke_json ?? "null") as typeof Woke.Type);
729 }
730 });
731 const resume: Workflows["Service"]["resume"] = (runId) => resumeRun(runId);
732
733 /** A run the engine holds as failed while its row says it goes on: paused, after all. */
734 const reconcile = Effect.fn("WorkflowEngine.reconcile")(function* (row: WorkflowStore.RunRow) {
735 if (resuming.has(row.run_id)) return;
736 const engine = byTag.get(row.engine_tag);
737 if (engine === undefined) return;
738 // Resumed already, and held back until it has its places again.
739 if (yield* store.placesReturning(row.run_id)) return;
740 const result = yield* withEngine(engine.poll(row.run_id));
741 if (Option.isNone(result) || result.value._tag !== "Suspended") return;
742 if (result.value.failed !== true) return;
743 const cause = result.value.cause;
744 // Held as it was: a run that waited for a person still does.
745 yield* store.runPaused(
746 row.run_id,
747 cause === undefined ? "A step failed." : text(Cause.squash(cause)),
748 );
749 yield* placesFreed;
750 });
751
752 // A cancelled run's body is gone, so its `onEnd` runs here, outside the engine. The sweep asks
753 // again after a failure or a restart, and `ending` keeps the two from running it at once.
754 const ending = new Set<string>();
755 const endCancelled = Effect.fn("WorkflowEngine.endCancelled")(function* (
756 row: WorkflowStore.RunRow,
757 ) {
758 const definition = definitionByTag.get(row.engine_tag);
759 if (definition?.onEnd === undefined || ending.has(row.run_id)) return;
760 const onEnd = definition.onEnd;
761 ending.add(row.run_id);
762 // A step still running would race the cleanup: a machine deleted before it is made.
763 yield* link.inFlight.settled(row.run_id);
764 // The body may have run its own `onEnd` just as the run was cancelled: once is enough.
765 const steps = yield* store.steps(row.run_id);
766 if (steps.some((step) => step.name === END_STEP && step.status === "completed")) {
767 ending.delete(row.run_id);
768 return;
769 }
770 yield* store.stepStarted(row.run_id, END_STEP, "step");
771 const payloadCodec = Schema.toCodecJson(definition.payload);
772 const decode = Schema.decodeEffect(payloadCodec);
773 yield* decode(row.input_json === null ? null : WorkflowStore.jsonValue(row.input_json)).pipe(
774 Effect.flatMap((input) =>
775 withoutRoutineSpans(
776 onEnd(input as never, {
777 id: row.run_id,
778 outcome: "cancelled",
779 reason: row.detail ?? undefined,
780 }),
781 ),
782 ),
783 Effect.provideContext(forStep(store, keyValues, link, forge, row.run_id, END_STEP)),
784 // The sweep that runs it reads the engine's BigInts; the cleanup's own code must not.
785 Effect.provideService(SqlClient.SafeIntegers, false),
786 Effect.matchCauseEffect({
787 onSuccess: () => store.stepEnded(row.run_id, END_STEP, "completed", null),
788 onFailure: (cause) =>
789 store.stepEnded(row.run_id, END_STEP, "failed", text(Cause.squash(cause))),
790 }),
791 Effect.ensuring(Effect.sync(() => ending.delete(row.run_id))),
792 );
793 });
794
795 const prune = Effect.fn("WorkflowEngine.prune")(function* (at: DateTime.Utc) {
796 if (Option.isNone(messages) || Option.isNone(sharding)) return;
797 const before = DateTime.formatIso(DateTime.subtractDuration(at, PRUNE_AFTER));
798 for (const row of yield* store.prunable(before, PRUNE_BATCH)) {
799 const entityId = EntityId.make(row.run_id);
800 const shardId = sharding.value.getShardId(entityId, "default");
801 // Its sleeps are entities of their own under the same id.
802 yield* Effect.forEach(
803 [`Workflow/${row.engine_tag}`, "Workflow/-/DurableClock"],
804 (type) =>
805 messages.value.clearAddress(
806 EntityAddress.make({ shardId, entityType: EntityType.make(type), entityId }),
807 ),
808 { discard: true },
809 ).pipe(
810 Effect.andThen(store.enginePruned(row.run_id)),
811 // Left unmarked, so the next sweep tries it again.
812 Effect.catchCause((cause) =>
813 Effect.logWarning("Could not prune a workflow run's engine journal", cause),
814 ),
815 );
816 }
817 const kept = yield* Option.match(settings, {
818 onNone: () => Effect.succeed(DEFAULT_WORKFLOW_SKIPPED_RUNS_KEPT),
819 onSome: (service) =>
820 service.getSettings.pipe(
821 Effect.map((current) => current.workflowSkippedRunsKept),
822 Effect.orElseSucceed(() => DEFAULT_WORKFLOW_SKIPPED_RUNS_KEPT),
823 ),
824 });
825 yield* store.pruneSkipped(kept, SKIPPED_PRUNE_BATCH);
826 });
827
828 const sweep: Workflows["Service"]["sweep"] = Effect.gen(function* () {
829 for (const wait of yield* store.waitsPastDeadline) {
830 const woke = { expired: true, value: null };
831 if (yield* store.waitSignalled(wait.run_id, wait.name, woke)) yield* wake(wait, woke);
832 }
833 // A claim whose wake a crash swallowed: the wake is made again. Waking twice is harmless.
834 for (const wait of yield* store.waitsToWake) {
835 if (wait.woke_json === null) continue;
836 yield* wake(wait, WorkflowStore.jsonValue(wait.woke_json) as typeof Woke.Type);
837 }
838 // Places a pause or an end gave back, and places whose wake a crash swallowed.
839 yield* placesFreed;
840 yield* placesTaken(yield* store.placesUnwoken);
841 // A cancel that was cut short before it reached what the run had invoked.
842 for (const child of yield* store.orphans) {
843 yield* Effect.ignore(cancel(child.run_id, "the run that invoked it was cancelled"));
844 }
845 // A cancel cut short after the run was ended: what it had not stopped yet is stopped here.
846 for (const row of yield* store.cancelsCutShort(END_STEP)) {
847 if (cancelling.has(row.run_id) || ending.has(row.run_id)) continue;
848 const engine = byTag.get(row.engine_tag);
849 if (engine !== undefined) yield* withEngine(engine.interrupt(row.run_id));
850 yield* stopSteps(row.run_id, yield* store.runningThreads(row.run_id));
851 }
852 // A run that ended without its parent hearing of it. Telling twice is harmless.
853 for (const child of yield* store.untold) yield* ended(child.run_id);
854 yield* store.mailExpire;
855 yield* fireSchedules;
856 yield* fireOpened;
857 yield* fireWatches;
858 const at = yield* DateTime.now;
859 // A run with a step still going is ended by its cancel, which waits for that step.
860 for (const row of yield* store.runsToEnd(END_STEP, END_TRIES)) {
861 const rest = END_AFTER[Number(row.end_attempts ?? 0) - 1];
862 if (row.end_ended_at !== null && rest !== undefined) {
863 const due = DateTime.addDuration(
864 DateTime.makeUnsafe(row.end_ended_at),
865 Duration.fromInputUnsafe(rest),
866 );
867 if (DateTime.isLessThan(at, due)) continue;
868 }
869 if (!link.inFlight.busy(row.run_id)) yield* endCancelled(row);
870 }
871 for (const row of yield* store.everyRun("running")) yield* reconcile(row);
872 for (const row of yield* store.everyRun("waiting")) yield* reconcile(row);
873 for (const row of yield* store.everyRun("paused")) {
874 const due = resumesAt(row);
875 if (due === undefined || DateTime.isLessThan(at, due)) continue;
876 yield* Effect.ignore(resumeRun(row.run_id, row));
877 }
878 yield* prune(at);
879 }).pipe(Effect.withSpan("Workflows.sweep"));
880
881 // With nothing registered there is nothing to resume, end or start: only history to read.
882 if (registered.length > 0) {
883 yield* sweep.pipe(
884 Effect.catchCause((cause) => Effect.logWarning("Workflow sweep failed", cause)),
885 Effect.andThen(Effect.sleep(SWEEP_EVERY)),
886 Effect.forever,
887 Effect.forkScoped,
888 );
889 }
890
891 const questions = Effect.flatMap(store.requests, (waits) =>
892 Effect.forEach(
893 waits.filter((wait) => wait.request_json !== null),
894 (wait) =>
895 Effect.map(store.latestThread(wait.run_id), (thread) => {
896 const request = WorkflowStore.jsonValue(wait.request_json ?? "null");
897 const kind =
898 request !== null && typeof request === "object" && !Array.isArray(request)
899 ? (request as { readonly kind?: unknown }).kind
900 : undefined;
901 return {
902 runId: wait.run_id,
903 name: wait.name,
904 request,
905 ...(typeof kind === "string" ? { kind } : {}),
906 askedAt: wait.opened_at,
907 thread,
908 };
909 }),
910 ),
911 );
912 const WEEKDAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
913 const triggerText = (trigger: WorkflowDefinition["triggers"][number]) => {
914 if (trigger.kind === "webhook") return `webhook ${trigger.name}`;
915 if (trigger.kind !== "schedule") {
916 return `new ${trigger.kind === "issues" ? "issues" : "pull requests"} in ${trigger.project}`;
917 }
918 if (trigger.schedule.type === "interval") {
919 return `every ${Duration.format(Duration.millis(trigger.schedule.everyMs))}`;
920 }
921 // Read as the schedule does: repeats once, in order, and all seven are every day.
922 const days = [...new Set(trigger.schedule.weekdays)].toSorted();
923 return `daily at ${trigger.schedule.timeOfDay}${
924 days.length > 0 && days.length < 7
925 ? ` on ${days.map((day) => WEEKDAYS[day] ?? day).join(", ")}`
926 : ""
927 }`;
928 };
929 const summaries = [...new Set(registered.map(([definition]) => definition.name))].flatMap(
930 (name) => {
931 const found = latest(name);
932 return found === undefined
933 ? []
934 : [
935 {
936 name,
937 version: found[0].version,
938 triggers: found[0].triggers.map(triggerText),
939 ...(Object.keys(found[0].asks).length === 0
940 ? {}
941 : {
942 asks: Object.entries(found[0].asks).map(([kind, label]) => ({ kind, label })),
943 }),
944 },
945 ];
946 },
947 );
948 const snapshot = Effect.all({
949 workflows: Effect.succeed(summaries),
950 runs: Effect.map(store.runs(undefined), (rows) => rows.map(toRun)),
951 questions,
952 });
953 const watch: Workflows["Service"]["watch"] = Stream.unwrap(
954 Effect.gen(function* () {
955 // Subscribed before the first look, so a change in between is not missed.
956 const changes = yield* PubSub.subscribe(store.changes);
957 return Stream.concat(
958 Stream.fromEffect(snapshot),
959 // A run writes several rows per step; one list answers a burst of them.
960 Stream.fromSubscription(changes).pipe(
961 Stream.debounce(WATCH_SETTLE),
962 Stream.mapEffect(() => snapshot),
963 ),
964 ).pipe(
965 // Each list is told as what differs from the one before, which this watcher already has.
966 // A list with no difference is still sent: a client reads an open run's steps again on it.
967 Stream.mapAccum(
968 () => undefined as Sent | undefined,
969 (sent, next) => {
970 const now: Sent = {
971 runs: new Map(next.runs.map((run) => [run.runId, JSON.stringify(run)])),
972 questions: new Map(
973 next.questions.map((question) => [
974 workflowQuestionKey(question),
975 { runId: question.runId, name: question.name, text: JSON.stringify(question) },
976 ]),
977 ),
978 };
979 const update: WorkflowRunsUpdate =
980 sent === undefined
981 ? next
982 : {
983 _tag: "changed",
984 runs: next.runs.filter(
985 (run) => sent.runs.get(run.runId) !== now.runs.get(run.runId),
986 ),
987 removed: [...sent.runs.keys()].filter((runId) => !now.runs.has(runId)),
988 questions: next.questions.filter((question) => {
989 const key = workflowQuestionKey(question);
990 return sent.questions.get(key)?.text !== now.questions.get(key)?.text;
991 }),
992 closed: [...sent.questions]
993 .filter(([key]) => !now.questions.has(key))
994 .map(([, { runId, name }]) => ({ runId, name })),
995 };
996 return [now, [update]] as const;
997 },
998 ),
999 );
1000 }),
1001 );
1002
1003 const counts: Workflows["Service"]["counts"] = Stream.unwrap(
1004 Effect.gen(function* () {
1005 const changes = yield* PubSub.subscribe(store.changes);
1006 return Stream.concat(
1007 Stream.fromEffect(store.counts),
1008 Stream.fromSubscription(changes).pipe(
1009 Stream.debounce(WATCH_SETTLE),
1010 Stream.mapEffect(() => store.counts),
1011 ),
1012 // Most changes move no count, and a badge has no use for hearing of those.
1013 ).pipe(Stream.changesWith((left, right) => JSON.stringify(left) === JSON.stringify(right)));
1014 }),
1015 );
1016
1017 /**
1018 * A signal to a question, as its wait receives it: with who sent it and when, which the sender
1019 * does not get to say. Undefined for a wait that is not a question, or one asked before answers
1020 * kept that, whose closed schema would refuse them.
1021 */
1022 const answerOf = Effect.fn("WorkflowEngine.answerOf")(function* (
1023 wait: { readonly request_json: string | null; readonly schema_json: string },
1024 value: Schema.Json,
1025 sender: WorkflowStore.SignalSender,
1026 ) {
1027 if (wait.request_json === null || typeof value !== "object" || value === null) return undefined;
1028 if (Array.isArray(value)) return undefined;
1029 const problem = answerProblem(WorkflowStore.jsonValue(wait.request_json), value);
1030 if (problem !== undefined) return yield* new WorkflowInputError({ problem });
1031 return stamped(wait, value, sender);
1032 });
1033 /** `answerOf` without the words for an answer that lacks its reason, which the schema refuses too. */
1034 const stamped = (
1035 wait: { readonly request_json: string | null; readonly schema_json: string },
1036 value: Schema.Json,
1037 sender: WorkflowStore.SignalSender,
1038 ) => {
1039 const answer = answerStamped(
1040 { request: wait.request_json !== null, schemaJson: wait.schema_json },
1041 value,
1042 sender,
1043 );
1044 return answer === undefined ? undefined : { expired: false, value: answer };
1045 };
1046 const notForQueue = (name: string) =>
1047 new WorkflowInputError({
1048 problem: `${name} waits for a place in a pool, and only the pool lets it in.`,
1049 });
1050 /** With `grant`, the pool letting a queued step in; nothing else wakes one. */
1051 const signalWait = Effect.fn("WorkflowEngine.signalWait")(function* (
1052 address: Parameters<Workflows["Service"]["signal"]>[0],
1053 value: Parameters<Workflows["Service"]["signal"]>[1],
1054 options: Parameters<Workflows["Service"]["signal"]>[2],
1055 grant = false,
1056 ): Effect.fn.Return<"delivered" | "buffered", WorkflowInputError> {
1057 // A sender's retry of a signal that already woke a wait is not a second signal.
1058 if (yield* store.signalSeen(options.id)) return "delivered" as const;
1059 const valueJson = WorkflowStore.jsonText(value);
1060 const woke = { expired: false, value };
1061 // Who sent it and when it came, said once here and by no one else, however it is delivered.
1062 // A retry of a signal that is still kept is that signal: its first arrival says both.
1063 const arrived: WorkflowStore.SignalSender = {
1064 answeredBy: options.answeredBy,
1065 answeredBySession: options.answeredBySession,
1066 answeredAt: DateTime.formatIso(yield* DateTime.now),
1067 };
1068 let sender = (yield* store.mailSender(options.id)) ?? arrived;
1069 // One signal per wait: a wait another signal took first sends this one to the next.
1070 while (true) {
1071 const wait = yield* store.waitAt(address);
1072 if (wait === undefined) break;
1073 // Looked at on the wait itself: a queue step is written before its wait opens, so one
1074 // that opened since the sender was checked is still seen here.
1075 if (!grant && (yield* store.queuesForPlace(wait.run_id, wait.name))) {
1076 return yield* notForQueue(wait.name);
1077 }
1078 const answered = yield* answerOf(wait, value, sender);
1079 const schema = WorkflowStore.jsonValue(wait.schema_json) as Record<string, Schema.Json>;
1080 const checked = yield* checkOutput(
1081 schema,
1082 answered === undefined ? valueJson : WorkflowStore.jsonText(answered.value),
1083 );
1084 if (Result.isFailure(checked)) {
1085 return yield* new WorkflowInputError({
1086 problem: `The value does not fit what ${wait.name} waits for. ${rejectionText(checked.failure)}`,
1087 });
1088 }
1089 if (yield* store.waitSignalled(wait.run_id, wait.name, answered ?? woke, options.id)) {
1090 yield* wake(wait, answered ?? woke);
1091 return "delivered" as const;
1092 }
1093 // Refused for its id: the same signal, sent again at once, woke a wait.
1094 if (yield* store.signalSeen(options.id)) return "delivered" as const;
1095 }
1096 const expiresAt = DateTime.formatIso(
1097 DateTime.addDuration(
1098 yield* DateTime.now,
1099 Duration.fromInputUnsafe(options.ttl ?? DEFAULT_SIGNAL_TTL),
1100 ),
1101 );
1102 if (yield* store.signalSeen(options.id)) return "delivered" as const;
1103 yield* store.mailPut({ signalId: options.id, address, valueJson, expiresAt, sender });
1104 // A copy the same signal kept first, while this one looked for a wait, is the one that stays.
1105 sender = (yield* store.mailSender(options.id)) ?? sender;
1106 // The wait may have opened and looked for mail between the look above and this write.
1107 while (true) {
1108 const late = yield* store.waitAt(address);
1109 if (late === undefined) return "buffered" as const;
1110 // A queue that opened while this was being kept: the signal is dropped, not left for it.
1111 if (yield* store.queuesForPlace(late.run_id, late.name)) {
1112 yield* store.mailDelete(options.id);
1113 return yield* notForQueue(late.name);
1114 }
1115 const schema = WorkflowStore.jsonValue(late.schema_json) as Record<string, Schema.Json>;
1116 // Kept for a wait it fits; this one, the oldest on the channel, is not it.
1117 const answered = stamped(late, value, sender) ?? woke;
1118 if (Result.isFailure(yield* checkOutput(schema, WorkflowStore.jsonText(answered.value)))) {
1119 return "buffered" as const;
1120 }
1121 const outcome = yield* store.mailDeliver(options.id, late.run_id, late.name, answered);
1122 if (outcome === "delivered") {
1123 yield* wake(late, answered);
1124 return "delivered" as const;
1125 }
1126 if (outcome === "claimed") continue;
1127 if (yield* store.signalSeen(options.id)) return "delivered" as const;
1128 return yield* new WorkflowInputError({ problem: "Buffered signal expired or was removed." });
1129 }
1130 });
1131 const signal: Workflows["Service"]["signal"] = Effect.fn("Workflows.signal")(
1132 function* (address, value, options) {
1133 // A step queued for a place goes in when the pool gives it one, never on a signal. Refused
1134 // here too, so a signal to a queue step that is done is not kept for nothing.
1135 if ("wait" in address && (yield* store.queuesForPlace(address.runId, address.wait))) {
1136 return yield* notForQueue(address.wait);
1137 }
1138 return yield* signalWait(address, value, options);
1139 },
1140 );
1141 const answer: Workflows["Service"]["answer"] = Effect.fn("Workflows.answer")(
1142 function* (runId, name, value, answeredBy) {
1143 const wait = yield* store.waitAt({ runId, wait: name });
1144 // Answered already, or never asked: kept, it would answer whatever asks there next.
1145 if (wait === undefined || wait.request_json === null) return;
1146 // Named by this asking of the question, so every answer to it is one signal.
1147 yield* signal({ runId, wait: name }, value, {
1148 id: `answer:${wait.token}`,
1149 ...(answeredBy === undefined
1150 ? {}
1151 : { answeredBy: answeredBy.label, answeredBySession: answeredBy.sessionId }),
1152 });
1153 },
1154 );
1155 const withdraw: Workflows["Service"]["withdraw"] = Effect.fn("Workflows.withdraw")(
1156 function* (runId, name, options) {
1157 yield* requireRun(runId);
1158 const wait = yield* store.waitAt({ runId, wait: name });
1159 // Only a question: a plain wait is something a run sleeps on, not something it asked.
1160 if (wait === undefined || wait.request_json === null) return "not_open" as const;
1161 const woke = {
1162 expired: true,
1163 value: null,
1164 withdrawn: { by: options.by, reason: options.reason ?? null },
1165 };
1166 if (!(yield* store.waitSignalled(runId, name, woke))) return "not_open" as const;
1167 yield* wake(wait, woke);
1168 return "withdrawn" as const;
1169 },
1170 );
1171 const signalAll = Effect.fn("WorkflowEngine.signalAll")(function* (
1172 address: { readonly channel: string; readonly workflow?: string | undefined },
1173 value: Schema.Json,
1174 ) {
1175 const valueJson = WorkflowStore.jsonText(value);
1176 let woken = 0;
1177 for (const wait of yield* store.waitsOn(address.channel, address.workflow)) {
1178 const schema = WorkflowStore.jsonValue(wait.schema_json) as Record<string, Schema.Json>;
1179 // A wait this value does not fit was not waiting for it; the others are still woken.
1180 if (Result.isFailure(yield* checkOutput(schema, valueJson))) continue;
1181 const woke = { expired: false, value };
1182 if (!(yield* store.waitSignalled(wait.run_id, wait.name, woke))) continue;
1183 yield* wake(wait, woke);
1184 woken++;
1185 }
1186 return woken;
1187 });
1188 /** Tell the run that invoked this one, if one did, how it ended. */
1189 const ended = Effect.fn("WorkflowEngine.ended")(function* (runId: string) {
1190 const row = yield* store.run(runId);
1191 if (row === undefined || row.parent_run_id === null || row.parent_wait === null) return;
1192 if (row.ended_at === null) return;
1193 yield* signal(
1194 { runId: row.parent_run_id, wait: row.parent_wait },
1195 {
1196 outcome: row.status,
1197 value: row.result_json === null ? null : WorkflowStore.jsonValue(row.result_json),
1198 ...(row.detail === null ? {} : { reason: row.detail }),
1199 },
1200 { id: `${runId}/ended` },
1201 ).pipe(Effect.ignore);
1202 });
1203
1204 /** A step in flight cannot be interrupted, so the agent it waits on is stopped instead. */
1205 const stopSteps = Effect.fn("WorkflowEngine.stopSteps")(function* (
1206 runId: string,
1207 threads: ReadonlyArray<Parameters<typeof stopTurn>[0]>,
1208 ) {
1209 yield* Effect.forEach(threads, (thread) => Effect.ignore(stopTurn(thread)), {
1210 discard: true,
1211 });
1212 yield* store.stepsCancelled(runId, END_STEP);
1213 });
1214
1215 // Cancels under way, whose slow part the sweep must not take for one cut short.
1216 const cancelling = new Set<string>();
1217 const cancel: Workflows["Service"]["cancel"] = Effect.fn("Workflows.cancel")(
1218 function* (runId, reason) {
1219 const row = yield* requireRun(runId);
1220 if (row.ended_at !== null) return;
1221 const threads = yield* store.runningThreads(runId);
1222 const engine = byTag.get(row.engine_tag);
1223 cancelling.add(runId);
1224 yield* Effect.gen(function* () {
1225 // Ended first, so nothing the run still does can be recorded as its outcome. A run that
1226 // finished in the meantime keeps its own ending, and its cleanup is its own. Not cut off
1227 // midway: the engine would go on with a cancelled run, or its parent wait forever.
1228 const cancelled = yield* Effect.uninterruptible(
1229 Effect.gen(function* () {
1230 if (!(yield* store.runEnded(runId, "cancelled", reason ?? null, null))) return false;
1231 if (engine !== undefined) yield* withEngine(engine.interrupt(runId));
1232 yield* ended(runId);
1233 yield* placesFreed;
1234 return true;
1235 }),
1236 );
1237 if (!cancelled) return;
1238 yield* stopSteps(runId, threads);
1239 // What this run invoked was part of it.
1240 yield* Effect.forEach(
1241 yield* store.children(runId),
1242 (child) => Effect.ignore(cancel(child.run_id, reason)),
1243 { discard: true },
1244 );
1245 // Waited for briefly, so the caller usually hears of a run that is cleaned up. A cleanup
1246 // can take minutes; it goes on by itself, and the sweep finishes one that is cut short.
1247 const cleanup = yield* Effect.forkIn(
1248 endCancelled({ ...row, detail: reason ?? null }),
1249 scope,
1250 );
1251 yield* Fiber.join(cleanup).pipe(Effect.timeoutOption(CANCEL_WAITS));
1252 }).pipe(Effect.ensuring(Effect.sync(() => cancelling.delete(runId))));
1253 },
1254 );
1255
1256 // Steps were registered before this engine existed; now they can reach it.
1257 link.current = {
1258 signal,
1259 signalAll,
1260 start,
1261 ended,
1262 watchTurn,
1263 placeAsked: Effect.fn("WorkflowEngine.placeAsked")(function* (place) {
1264 const asked = yield* store.placeAsked(place);
1265 yield* placesTaken(asked.given);
1266 if (asked.held) yield* placeWake(place.runId, place.name);
1267 return asked.held;
1268 }),
1269 placeLeft: Effect.fn("WorkflowEngine.placeLeft")(function* (runId, name) {
1270 yield* store.placeLeft(runId, name);
1271 yield* placesFreed;
1272 }),
1273 placesFreed,
1274 cancel: (runId, reason) => cancel(runId, reason),
1275 withdraw,
1276 list: Effect.fn("WorkflowEngine.list")(function* (filter) {
1277 return (yield* store.runsWhere(filter)).map((row) => ({
1278 id: row.run_id,
1279 workflow: row.workflow,
1280 key: row.idempotency_key,
1281 title: row.title,
1282 status: row.status,
1283 detail: row.detail,
1284 tags: WorkflowStore.jsonValue(row.tags_json) as ReadonlyArray<string>,
1285 subject: row.subject_json === null ? null : WorkflowStore.subjectOf(row.subject_json),
1286 startedAt: row.started_at,
1287 endedAt: row.ended_at,
1288 }));
1289 }),
1290 };
1291
1292 return Workflows.of({
1293 start,
1294 hooks: Effect.succeed(hooks.map(({ workflow, name, path }) => ({ workflow, name, path }))),
1295 // A cancelled run whose cleanup has not worked yet still needs its version to run it.
1296 unfinished: Effect.map(
1297 Effect.all([store.unfinished, store.runsToEnd(END_STEP, END_TRIES)]),
1298 ([open, ending]) => [
1299 ...open,
1300 ...ending
1301 .filter((row) => definitionByTag.get(row.engine_tag)?.onEnd !== undefined)
1302 .map((row) => ({ workflow: row.workflow, version: Number(row.version) })),
1303 ],
1304 ),
1305 deliver,
1306 signal,
1307 answer,
1308 resume,
1309 cancel,
1310 withdraw,
1311 get: Effect.fn("Workflows.get")(function* (runId) {
1312 const row = yield* requireRun(runId);
1313 const steps = yield* store.steps(runId);
1314 return {
1315 run: toRun(row),
1316 references: yield* store.references(runId),
1317 steps: steps.map((step) => ({
1318 name: step.name,
1319 kind: step.kind,
1320 status: step.status,
1321 attempts: Number(step.attempts),
1322 detail: step.detail,
1323 threadId: step.thread_id,
1324 environmentId: step.environment_id,
1325 result: step.result_json === null ? null : WorkflowStore.jsonValue(step.result_json),
1326 said: step.said,
1327 ...(step.ahead === null ? {} : { ahead: Number(step.ahead) }),
1328 startedAt: step.started_at,
1329 endedAt: step.ended_at,
1330 })),
1331 };
1332 }),
1333 list: Effect.fn("Workflows.list")(function* (filter) {
1334 if (filter?.tag === undefined && filter?.subject === undefined)
1335 return (yield* store.runs(filter?.status)).map(toRun);
1336 const where = { status: filter.status, tag: filter.tag, subject: filter.subject };
1337 if (filter.status !== undefined) return (yield* store.runsWhere(where)).map(toRun);
1338 // Skipped runs are counted apart, as in the unfiltered list, so they cannot push out the rest.
1339 const rows = [
1340 ...(yield* store.runsWhere({ ...where, skippedTopLevel: false })),
1341 ...(yield* store.runsWhere({ ...where, skippedTopLevel: true })),
1342 ];
1343 // The two reads are separate, so a run that turned skipped between them can be in both.
1344 return [...new Map(rows.map((row) => [row.run_id, row])).values()]
1345 .toSorted((a, b) => b.started_at.localeCompare(a.started_at))
1346 .map(toRun);
1347 }),
1348 about: Effect.fn("Workflows.about")(function* (item) {
1349 // Keyed as the subject was kept, so an item named without its address is found too.
1350 const identity =
1351 item.issue !== undefined
1352 ? issueReference(item.issue)
1353 : item.pullRequest !== undefined
1354 ? pullRequestReferenceOf(item.pullRequest, { url: item.subject })
1355 : undefined;
1356 // Each partition is capped on its own, as in `list`, so skipped runs cannot push out the rest.
1357 const newestFirst = (left: { started_at: string }, right: { started_at: string }) =>
1358 right.started_at.localeCompare(left.started_at);
1359 const found = [];
1360 for (const skippedTopLevel of [false, true]) {
1361 const rows = [
1362 ...(yield* store.runsWhere({ subject: item.subject, skippedTopLevel })),
1363 ...(identity === undefined
1364 ? []
1365 : yield* store.runsWhere({
1366 subject: { kind: identity.kind, key: identity.key },
1367 skippedTopLevel,
1368 })),
1369 ];
1370 found.push(
1371 ...[...new Map(rows.map((row) => [row.run_id, row])).values()]
1372 .toSorted(newestFirst)
1373 .slice(0, 500),
1374 );
1375 }
1376 // The two lookups are separate reads, so a run that turned skipped between them can be in both.
1377 const runs = [...new Map(found.map((row) => [row.run_id, row])).values()]
1378 .toSorted(newestFirst)
1379 .map(toRun);
1380 const about = new Set(runs.map((run) => run.runId));
1381 const open = yield* questions;
1382 return { runs, questions: open.filter((question) => about.has(question.runId)) };
1383 }),
1384 waitFor: Effect.fn("Workflows.waitFor")(function* (runId, done) {
1385 // Subscribed before the first look, so a change in between is not missed.
1386 const changes = yield* PubSub.subscribe(store.changes);
1387 while (true) {
1388 const row = yield* store.run(runId);
1389 if (row !== undefined && done(toRun(row))) return toRun(row);
1390 yield* Effect.repeat(PubSub.take(changes), { until: (changed) => changed === runId });
1391 }
1392 }, Effect.scoped),
1393 questions,
1394 counts,
1395 stored: Effect.fn("Workflows.stored")(function* (prefix) {
1396 return (yield* keyValues.list(prefix)).map((row) => ({
1397 key: row.key,
1398 value: WorkflowStore.jsonValue(row.valueJson),
1399 }));
1400 }),
1401 storeSet: Effect.fn("Workflows.storeSet")(function* (key, value) {
1402 yield* keyValues.set(key, WorkflowStore.jsonText(value));
1403 }),
1404 storeDelete: Effect.fn("Workflows.storeDelete")(function* (key) {
1405 yield* keyValues.delete(key);
1406 }),
1407 watch,
1408 sweep,
1409 });
1410});
1411
1412/**
1413 * The workflow service with these definitions registered, on the SQLite database provided to it.
1414 * Only one process may run this layer against a database.
1415 */
1416export const layer = (
1417 definitions: ReadonlyArray<WorkflowDefinition>,
1418 store: typeof WorkflowStore.layer = WorkflowStore.layer,
1419) => {
1420 const registered = definitions.map(
1421 (definition) => [definition, engineWorkflow(definition)] as const,
1422 );
1423 const layerDefinitions = Layer.mergeAll(
1424 Layer.empty,
1425 ...registered.map(([definition, engine]) => layerDefinition(definition, engine)),
1426 );
1427 return Layer.effect(Workflows, make(registered)).pipe(
1428 Layer.provide(layerDefinitions),
1429 Layer.provide(store),
1430 Layer.provide(Layer.merge(layerKeyValues, layerEngineLink)),
1431 Layer.provide(
1432 registered.length === 0
1433 ? WorkflowEngine.layerMemory
1434 : ClusterWorkflowEngine.layer.pipe(
1435 // Merged so the sweep can prune ended runs' journals from the same storage.
1436 Layer.provideMerge(SingleRunner.layer({ runnerStorage: "sql" })),
1437 ),
1438 ),
1439 Layer.provide(Layer.succeed(SqlClient.SafeIntegers, true)),
1440 // Engine fibers fork from this build, so polls, activities and their store calls are all marked.
1441 Layer.provide(Layer.succeed(References.TracerSpanAnnotations, routineSpan)),
1442 );
1443};