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

stepServices.ts

460 lines16.9 KB

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