Open History to see the last commit
1// What a step's own code may use besides plain Effect: state shared between runs, and a way to
2// wake a run that waits. Both touch the world, so they are for inside `step` and `onEnd`.
3import type { WorkflowRunSubject } from "@t3tools/contracts";
4import * as Context from "effect/Context";
5import * as DateTime from "effect/DateTime";
6import * as Deferred from "effect/Deferred";
7import type * as Duration from "effect/Duration";
8import * as Effect from "effect/Effect";
9import * as Layer from "effect/Layer";
10import * as Option from "effect/Option";
11import * as Schema from "effect/Schema";
12import * as SqlClient from "effect/sql/SqlClient";
13
14import { checkOptions } from "./options.ts";
15import { type StepReferences, stepReferences } from "./runReferences.ts";
16import type { WorkflowDefinition } from "./workflow.ts";
17import { type SubjectInput, subjectReference, WorkflowForge } from "./WorkflowForge.ts";
18import type { WorkflowError, WorkflowInputError } from "./Workflows.ts";
19import {
20 prefixUpperBound,
21 type ReferenceInput,
22 type RunParent,
23 type SignalAddress,
24 type WorkflowRunStatus,
25 type WorkflowStore,
26} from "./WorkflowStore.ts";
27
28/** The shared store as rows of JSON text. `store` puts schemas on top. */
29export class KeyValues extends Context.Service<
30 KeyValues,
31 {
32 readonly get: (key: string) => Effect.Effect<string | undefined>;
33 readonly set: (key: string, valueJson: string) => Effect.Effect<void>;
34 readonly delete: (key: string) => Effect.Effect<void>;
35 readonly list: (
36 prefix: string,
37 ) => Effect.Effect<ReadonlyArray<{ readonly key: string; readonly valueJson: string }>>;
38 readonly transaction: <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;
39 }
40>()("t3/workflows/stepServices/KeyValues") {}
41
42export type SendSignal = (
43 address: SignalAddress,
44 value: Schema.Json,
45 options: { readonly id: string; readonly ttl?: Duration.Input },
46) => Effect.Effect<"delivered" | "buffered", WorkflowInputError>;
47
48/** Everyone who waits on a key, in one workflow or in all of them. */
49export interface EveryoneAt {
50 readonly channel: string;
51 readonly workflow?: string | undefined;
52}
53export type SendSignalToAll = (address: EveryoneAt, value: Schema.Json) => Effect.Effect<number>;
54
55/** A run as a step of another run sees it. `key` is what it was started with. */
56export interface RunSummary {
57 readonly id: string;
58 readonly workflow: string;
59 readonly key: string;
60 readonly title: string;
61 readonly status: WorkflowRunStatus;
62 readonly detail: string | null;
63 readonly tags: ReadonlyArray<string>;
64 /** What the run is about; null when it declared nothing. */
65 readonly subject: WorkflowRunSubject | null;
66 readonly startedAt: string;
67 readonly endedAt: string | null;
68}
69export interface RunFilter {
70 readonly workflow?: string | undefined;
71 readonly status?: WorkflowRunStatus | undefined;
72 readonly keyPrefix?: string | undefined;
73 readonly kind?: string | undefined;
74 readonly tag?: string | undefined;
75 /** A subject's kind and key, or a web address matched as `t3 workflow list --subject` does. */
76 readonly subject?: { readonly kind: string; readonly key: string } | string | undefined;
77}
78
79/** Signals from the step that is running. Its signals are numbered, so a retry sends the same ones. */
80export class Signals extends Context.Service<
81 Signals,
82 {
83 readonly sendAll: SendSignalToAll;
84 readonly send: (
85 address: SignalAddress,
86 value: Schema.Json,
87 options?: { readonly id?: string; readonly ttl?: Duration.Input },
88 ) => Effect.Effect<"delivered" | "buffered", WorkflowInputError>;
89 }
90>()("t3/workflows/stepServices/Signals") {}
91
92export type StartRun = (
93 workflow: string,
94 input: unknown,
95 options: {
96 readonly idempotencyKey: string;
97 readonly parent?: RunParent;
98 /** The version the caller was written against. Without it, the newest registered. */
99 readonly version?: number;
100 readonly subject?: ReferenceInput;
101 },
102) => Effect.Effect<{ readonly runId: string }, WorkflowError>;
103
104export type CancelRun = (runId: string, reason: string) => Effect.Effect<void, WorkflowError>;
105export type WithdrawQuestion = (
106 runId: string,
107 name: string,
108 options: { readonly by: string; readonly reason?: string | undefined },
109) => Effect.Effect<"withdrawn" | "not_open", WorkflowError>;
110export type ListRuns = (filter: RunFilter) => Effect.Effect<ReadonlyArray<RunSummary>>;
111
112/** Other runs, from the step that is running: starting, finding and cancelling them. */
113export class Runs extends Context.Service<
114 Runs,
115 {
116 readonly start: StartRun;
117 readonly cancel: CancelRun;
118 readonly withdraw: (
119 runId: string,
120 name: string,
121 reason: string | undefined,
122 ) => Effect.Effect<"withdrawn" | "not_open", WorkflowError>;
123 readonly list: ListRuns;
124 }
125>()("t3/workflows/stepServices/Runs") {}
126
127export type InStep = KeyValues | Signals | Runs | WorkflowForge | StepReferences;
128
129/**
130 * What a step needs of the engine, which exists only once the engine does, while the workflows
131 * that use it are registered before. The engine fills this in when it starts.
132 */
133export class EngineLink extends Context.Service<
134 EngineLink,
135 {
136 current:
137 | {
138 readonly signal: SendSignal;
139 readonly signalAll: SendSignalToAll;
140 readonly start: StartRun;
141 readonly cancel: CancelRun;
142 readonly withdraw: WithdrawQuestion;
143 readonly list: ListRuns;
144 /** Tell the run that invoked `runId`, if one did, how it ended. */
145 readonly ended: (runId: string) => Effect.Effect<void>;
146 /** Watch the agent turn behind an open wait of `runId` until it ends. */
147 readonly watchTurn: (runId: string, wait: string) => Effect.Effect<void>;
148 /** Queue the step `name` of `runId` for a place in `pool`; true when it has one now. */
149 readonly placeAsked: (place: {
150 readonly runId: string;
151 readonly name: string;
152 readonly pool: string;
153 readonly size: number;
154 }) => Effect.Effect<boolean>;
155 /** The step is done with its place, which goes to the next in line. */
156 readonly placeLeft: (runId: string, name: string) => Effect.Effect<void>;
157 /** Hands out the places a pause or an end gave back. */
158 readonly placesFreed: Effect.Effect<void>;
159 }
160 | undefined;
161 /** The steps of each run that are running in this process right now. */
162 readonly inFlight: InFlight;
163 }
164>()("t3/workflows/stepServices/EngineLink") {}
165export interface InFlight {
166 readonly track: <A, E, R>(
167 runId: string,
168 effect: Effect.Effect<A, E, R>,
169 ) => Effect.Effect<A, E, R>;
170 /** Whether a step of `runId` is running now. */
171 readonly busy: (runId: string) => boolean;
172 /** Waits until no step of `runId` is running. */
173 readonly settled: (runId: string) => Effect.Effect<void>;
174}
175
176// A step cannot be interrupted, so whatever cleans up after a cancelled run waits for it here.
177const makeInFlight = (): InFlight => {
178 const running = new Map<string, { count: number; idle: Deferred.Deferred<void> }>();
179 return {
180 track: (runId, effect) =>
181 Effect.acquireUseRelease(
182 Effect.sync(() => {
183 const entry = running.get(runId) ?? { count: 0, idle: Deferred.makeUnsafe<void>() };
184 entry.count++;
185 running.set(runId, entry);
186 return entry;
187 }),
188 () => effect,
189 (entry) =>
190 Effect.suspend(() => {
191 if (--entry.count > 0) return Effect.void;
192 running.delete(runId);
193 return Deferred.succeed(entry.idle, undefined);
194 }),
195 ),
196 busy: (runId) => running.has(runId),
197 settled: (runId) =>
198 Effect.suspend(() => {
199 const entry = running.get(runId);
200 return entry === undefined ? Effect.void : Deferred.await(entry.idle);
201 }),
202 };
203};
204
205export const layerEngineLink = Layer.sync(EngineLink, () => ({
206 current: undefined,
207 inFlight: makeInFlight(),
208}));
209
210const engineOf = (link: EngineLink["Service"]) =>
211 link.current === undefined
212 ? Effect.die(new Error("The workflow engine is not up."))
213 : Effect.succeed(link.current);
214
215/**
216 * The services for the step `name` of `runId`. Each signal it sends is the two, where it goes,
217 * and how many it sent there before, so a retry that sends the same again is not new. What it
218 * touches through the forge is kept against it.
219 */
220export const forStep = (
221 store: WorkflowStore["Service"],
222 keyValues: KeyValues["Service"],
223 link: EngineLink["Service"],
224 forge: WorkflowForge["Service"],
225 runId: string,
226 name: string,
227): Context.Context<InStep> => {
228 const owner = `${runId}/${name}`;
229 const sent = new Map<string, number>();
230 return Context.make(KeyValues, keyValues).pipe(
231 Context.add(WorkflowForge, forge),
232 Context.merge(stepReferences(store, runId, name)),
233 Context.add(
234 Signals,
235 Signals.of({
236 send: Effect.fn("Signals.send")(function* (address, value, options) {
237 const { signal: send } = yield* engineOf(link);
238 const to = (
239 "runId" in address
240 ? ["run", address.runId, address.wait]
241 : ["key", address.workflow, address.channel]
242 )
243 .map(encodeURIComponent)
244 .join("/");
245 const before = sent.get(to) ?? 0;
246 sent.set(to, before + 1);
247 return yield* send(address, value, {
248 id: options?.id ?? `${owner}/signal/${to}/${before}`,
249 ...(options?.ttl === undefined ? {} : { ttl: options.ttl }),
250 });
251 }),
252 sendAll: Effect.fn("Signals.sendAll")(function* (address, value) {
253 const engine = yield* engineOf(link);
254 return yield* engine.signalAll(address, value);
255 }),
256 }),
257 ),
258 Context.add(
259 Runs,
260 Runs.of({
261 start: Effect.fn("Runs.start")(function* (workflow, input, options) {
262 const engine = yield* engineOf(link);
263 return yield* engine.start(workflow, input, options);
264 }),
265 cancel: Effect.fn("Runs.cancel")(function* (target, reason) {
266 // Cancelling interrupts the run, and this step is the run: it would cut itself off
267 // halfway through the cancel.
268 if (target === runId) {
269 return yield* Effect.die(
270 new Error("A run cannot cancel itself. End it from its body with `stop`."),
271 );
272 }
273 const engine = yield* engineOf(link);
274 return yield* engine.cancel(target, reason);
275 }),
276 withdraw: Effect.fn("Runs.withdraw")(function* (target, wait, reason) {
277 const engine = yield* engineOf(link);
278 return yield* engine.withdraw(target, wait, { by: `run ${runId}`, reason });
279 }),
280 list: Effect.fn("Runs.list")(function* (filter) {
281 const engine = yield* engineOf(link);
282 return yield* engine.list(filter);
283 }),
284 }),
285 ),
286 );
287};
288
289export const layerKeyValues = Layer.effect(
290 KeyValues,
291 Effect.gen(function* () {
292 const sql = yield* SqlClient.SqlClient;
293 return KeyValues.of({
294 get: Effect.fn("KeyValues.get")(function* (key) {
295 const rows = yield* sql<{ value_json: string }>`
296 SELECT value_json FROM workflow_store WHERE key = ${key}
297 `.pipe(Effect.orDie);
298 return rows[0]?.value_json;
299 }),
300 set: Effect.fn("KeyValues.set")(function* (key, valueJson) {
301 const at = DateTime.formatIso(yield* DateTime.now);
302 yield* sql`
303 INSERT INTO workflow_store (key, value_json, updated_at)
304 VALUES (${key}, ${valueJson}, ${at})
305 ON CONFLICT (key) DO UPDATE
306 SET value_json = excluded.value_json, updated_at = excluded.updated_at
307 `.pipe(Effect.orDie);
308 }),
309 delete: Effect.fn("KeyValues.delete")(function* (key) {
310 yield* sql`DELETE FROM workflow_store WHERE key = ${key}`.pipe(Effect.orDie);
311 }),
312 list: Effect.fn("KeyValues.list")(function* (prefix) {
313 // LIKE would read `%` and `_` in a prefix as patterns; a range does not.
314 const end = prefixUpperBound(prefix);
315 const rows = yield* sql<{ key: string; value_json: string }>`
316 SELECT key, value_json FROM workflow_store
317 WHERE ${sql.and([sql`key >= ${prefix}`, ...(end === null ? [] : [sql`key < ${end}`])])}
318 ORDER BY key
319 `.pipe(Effect.orDie);
320 return rows.map((row) => ({ key: row.key, valueJson: row.value_json }));
321 }),
322 transaction: Effect.fn("KeyValues.transaction")(function* (effect) {
323 return yield* sql.withTransaction(effect).pipe(Effect.catchTags({ SqlError: Effect.die }));
324 }),
325 });
326 }),
327);
328
329/** A value that no longer fits its schema, or never did. */
330export class StoreValueError extends Schema.TaggedError<StoreValueError>()("StoreValueError", {
331 key: Schema.String,
332 problem: Schema.String,
333}) {
334 override get message(): string {
335 return `The stored value at ${this.key} does not fit its schema: ${this.problem}`;
336 }
337}
338
339/**
340 * One key of the store, with the schema of what it holds. `update` reads and writes as one
341 * action, so two runs counting on the same key never lose a count; returning `undefined` from it
342 * deletes the key.
343 */
344const entry = <A, I>(key: string, schema: Schema.Codec<A, I>) => {
345 const codec = Schema.fromJsonString(Schema.toCodecJson(schema));
346 const decode = Schema.decodeEffect(codec);
347 const encode = Schema.encodeEffect(codec);
348 const invalid = (error: unknown) => new StoreValueError({ key, problem: String(error) });
349 const read = (store: KeyValues["Service"]) =>
350 Effect.flatMap(store.get(key), (text) =>
351 text === undefined
352 ? Effect.succeed(Option.none<A>())
353 : Effect.mapBoth(decode(text), { onFailure: invalid, onSuccess: Option.some }),
354 );
355 const write = (store: KeyValues["Service"], value: A) =>
356 encode(value).pipe(
357 Effect.mapError(invalid),
358 Effect.flatMap((text) => store.set(key, text)),
359 );
360 return {
361 key,
362 get: Effect.flatMap(KeyValues, read),
363 set: (value: A) => Effect.flatMap(KeyValues, (store) => write(store, value)),
364 delete: Effect.flatMap(KeyValues, (store) => store.delete(key)),
365 update: (change: (current: Option.Option<A>) => A | undefined) =>
366 Effect.flatMap(KeyValues, (store) =>
367 store.transaction(
368 Effect.gen(function* () {
369 const next = change(yield* read(store));
370 if (next === undefined) {
371 yield* store.delete(key);
372 return Option.none<A>();
373 }
374 yield* write(store, next);
375 return Option.some(next);
376 }),
377 ),
378 ),
379 };
380};
381
382/** Every key that starts with `prefix`, in key order, with what it holds. */
383const entries = <A, I>(prefix: string, schema: Schema.Codec<A, I>) => {
384 const codec = Schema.fromJsonString(Schema.toCodecJson(schema));
385 const decode = Schema.decodeEffect(codec);
386 return Effect.flatMap(KeyValues, (store) =>
387 Effect.flatMap(store.list(prefix), (rows) =>
388 Effect.forEach(rows, (row) =>
389 Effect.mapBoth(decode(row.valueJson), {
390 onFailure: (error) => new StoreValueError({ key: row.key, problem: String(error) }),
391 onSuccess: (value) => ({ key: row.key, value }),
392 }),
393 ),
394 ),
395 );
396};
397
398/** Several reads and writes as one: all of them happen, or none. */
399const transaction = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
400 Effect.flatMap(KeyValues, (store) => store.transaction(effect));
401
402/**
403 * State that outlives a run and is shared by every workflow on this server. Use it inside `step`
404 * or `onEnd`: what it returns changes over time, so the body itself must not read it.
405 */
406export const store = { entry, entries, transaction };
407
408/** A workflow by its name or its definition, wherever one is named. */
409export type WorkflowName = string | Pick<WorkflowDefinition, "name">;
410const nameOf = (workflow: WorkflowName) =>
411 typeof workflow === "string" ? workflow : workflow.name;
412
413/**
414 * Wake a run that waits: `{ runId, wait }` for one wait of one run, `{ workflow, channel }` for
415 * whichever run of a workflow waits on a channel. Inside `step` or `onEnd` only.
416 */
417export const signal = (
418 address:
419 | { readonly runId: string; readonly wait: string }
420 | { readonly workflow: WorkflowName; readonly channel: string },
421 value: Schema.Json,
422 options?: { readonly id?: string; readonly ttl?: Duration.Input },
423) =>
424 Effect.flatMap(Signals, (signals) => {
425 checkOptions(
426 "signal's address",
427 address,
428 "runId" in address ? ["runId", "wait"] : ["workflow", "channel"],
429 );
430 checkOptions("signal", options, ["id", "ttl"]);
431 return signals.send(
432 "runId" in address
433 ? address
434 : { workflow: nameOf(address.workflow), channel: address.channel },
435 value,
436 options,
437 );
438 });
439
440/**
441 * Start a run of another workflow and go on without it. The same `key` is the same run; a
442 * `subject` is what a new run is about, as its body's `subject` would say. Inside `step` or
443 * `onEnd` only; to wait for the run's result, use `invoke` in the body instead.
444 */
445export const start = <P>(
446 workflow: WorkflowDefinition<P>,
447 payload: P,
448 options: { readonly key: string; readonly subject?: SubjectInput },
449) =>
450 Effect.flatMap(Runs, (runs) => {
451 checkOptions("start", options, ["key", "subject"]);
452 return runs.start(workflow.name, payload, {
453 idempotencyKey: options.key,
454 version: workflow.version,
455 ...(options.subject === undefined
456 ? {}
457 : { subject: subjectReference("start's subject", options.subject) }),
458 });
459 });
460
461/**
462 * Wake every run that waits on `channel`, in one workflow or, without `workflow`, in all of them.
463 * Returns how many it woke. Nothing is kept for a wait that opens later, so a run that waits on
464 * a condition checks the condition in a step first, and gives its wait a timeout to check again.
465 * Inside `step` or `onEnd` only.
466 */
467export const signalAll = (
468 address: { readonly channel: string; readonly workflow?: WorkflowName },
469 value: Schema.Json,
470) =>
471 Effect.flatMap(Signals, (signals) => {
472 checkOptions("signalAll's address", address, ["channel", "workflow"]);
473 return signals.sendAll(
474 {
475 channel: address.channel,
476 workflow: address.workflow === undefined ? undefined : nameOf(address.workflow),
477 },
478 value,
479 );
480 });
481
482/**
483 * Cancel another run, as a person would: its agents are stopped, its questions withdrawn, what
484 * it invoked is cancelled, and its `onEnd` runs. A run that has ended is left alone. Inside
485 * `step` or `onEnd` only.
486 */
487export const cancel = (runId: string, reason: string) =>
488 Effect.flatMap(Runs, (runs) => runs.cancel(runId, reason));
489
490/**
491 * End a run's open question unanswered: its `ask` returns `None`, as on a timeout, and the run
492 * goes on. The step records that this run withdrew it, and why. `not_open` when there was no
493 * open question by that name. Inside `step` or `onEnd` only.
494 */
495export const withdraw = (options: {
496 readonly run: string;
497 readonly name: string;
498 readonly reason?: string;
499}) =>
500 Effect.flatMap(Runs, (runs) => {
501 checkOptions("withdraw", options, ["run", "name", "reason"]);
502 return runs.withdraw(options.run, options.name, options.reason);
503 });
504
505/**
506 * Find runs: of one workflow, in one status, started with a key that begins with `keyPrefix`,
507 * tagged with `tag`, about `subject`, or with an open question of `kind`. Newest first, 500 at
508 * most. Inside `step` or `onEnd` only: the answer changes over time.
509 */
510export const runs = (filter?: {
511 readonly workflow?: WorkflowName;
512 readonly status?: WorkflowRunStatus;
513 readonly keyPrefix?: string;
514 readonly kind?: string;
515 readonly tag?: string;
516 readonly subject?: SubjectInput;
517}) =>
518 Effect.flatMap(Runs, (all) => {
519 checkOptions("runs", filter, ["workflow", "status", "keyPrefix", "kind", "tag", "subject"]);
520 const about =
521 filter?.subject === undefined ? undefined : subjectReference("runs' subject", filter.subject);
522 return all.list({
523 // A web address also names an issue or pull request, which are kept under their own kind.
524 subject:
525 about === undefined
526 ? undefined
527 : typeof filter?.subject === "string"
528 ? filter.subject
529 : { kind: about.kind, key: about.key },
530 workflow: filter?.workflow === undefined ? undefined : nameOf(filter.workflow),
531 status: filter?.status,
532 keyPrefix: filter?.keyPrefix,
533 kind: filter?.kind,
534 tag: filter?.tag,
535 });
536 });