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

stepServices.ts

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