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

stepServices.ts

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