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