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

WorkflowRuntime.ts

981 lines40.6 KB

1// Workflows in the running server: every file in one folder defines some, and the folder can
2// change while the server runs. A file that loads replaces what it defined before; one that does
3// not keeps its last good version running. With no definitions there is no engine, unless runs
4// from before are kept: then one with nothing registered serves their history.
5import * as NodeAsyncHooks from "node:async_hooks";
6// @effect-diagnostics-next-line nodeBuiltinImport:off -- the CommonJS cache is cleared in the same tick as the import.
7import * as NodeFS from "node:fs";
8import * as NodeModule from "node:module";
9import * as NodeURL from "node:url";
10​
11import type {
12 WorkflowDefinitionChangeResult,
13 WorkflowDefinitionFiles,
14 WorkflowDefinitionProblem,
15} from "@t3tools/contracts";
16import * as Cause from "effect/Cause";
17import * as Config from "effect/Config";
18import * as Context from "effect/Context";
19import * as Deferred from "effect/Deferred";
20import * as Effect from "effect/Effect";
21import * as Exit from "effect/Exit";
22import * as FileSystem from "effect/FileSystem";
23import * as Layer from "effect/Layer";
24import * as Option from "effect/Option";
25import * as Path from "effect/Path";
26import * as Schema from "effect/Schema";
27import * as Scope from "effect/Scope";
28import * as Semaphore from "effect/Semaphore";
29import * as SqlClient from "effect/sql/SqlClient";
30import * as Stream from "effect/Stream";
31import * as SubscriptionRef from "effect/SubscriptionRef";
32​
33import * as ServerConfig from "../config.ts";
34import * as ServerSettings from "../serverSettings.ts";
35import { engineTag, text, type WorkflowDefinition } from "./workflow.ts";
36import type * as WorkflowEngine from "./WorkflowEngine.ts";
37import * as WorkflowAgentThreads from "./WorkflowAgentThreads.ts";
38import * as WorkflowForge from "./WorkflowForge.ts";
39import * as Workflows from "./Workflows.ts";
40​
41/** A folder of definition files, or one file, in place of the folder in the T3 home. */
42const definitionsOverride = Config.String("T3CODE_WORKFLOWS").pipe(Config.option);
43​
44// An editor saves in several writes, and a save from here is followed by its own file event.
45const RELOAD_SETTLE = "300 millis";
46// How often a change held back by unfinished runs is tried again, so it goes in once they end.
47const HELD_RETRY = "15 seconds";
48// A folder that could not be listed is looked at again, since no file event may follow.
49const LIST_RETRY = "30 seconds";
50// A leading dot is how a file is kept out: a draft being checked, an editor's swap file.
51// One name in the folder, never a path: the name is also the key a save and a removal go by.
52const DEFINITION_FILE = /^[A-Za-z0-9_][\w.-]*\.(ts|mts|js|mjs)$/;
53const NAMING =
54 "Name the file with letters, digits, dashes, underscores and dots, ending in .ts: for example release.ts.";
55​
56export class WorkflowDefinitionsLoadError extends Schema.TaggedError<WorkflowDefinitionsLoadError>()(
57 "WorkflowDefinitionsLoadError",
58 { module: Schema.String, cause: Schema.Defect() },
59) {
60 override get message(): string {
61 return `Could not load workflow definitions from ${this.module}.`;
62 }
64​
65/** The definition files of this server, for a person to read and change. */
66export class WorkflowDefinitions extends Context.Service<
67 WorkflowDefinitions,
68 {
69 /** The files as they are on disk now, with what is wrong with them. */
70 readonly read: Effect.Effect<WorkflowDefinitionFiles>;
71 /**
72 * Verify `source` as the file `name`, and when nothing is wrong write it and run it from now
73 * on. A file that was written can still fail to run, and then says why.
74 */
75 readonly save: (name: string, source: string) => Effect.Effect<WorkflowDefinitionChangeResult>;
76 /** Take a file away, unless runs still need what it defines. */
77 readonly remove: (name: string) => Effect.Effect<WorkflowDefinitionChangeResult>;
78 }
79>()("t3/workflows/WorkflowRuntime/WorkflowDefinitions") {}
80​
81const isDefinition = (value: unknown): value is WorkflowDefinition =>
82 typeof value === "object" &&
83 value !== null &&
84 typeof (value as WorkflowDefinition).name === "string" &&
85 typeof (value as WorkflowDefinition).version === "number" &&
86 typeof (value as WorkflowDefinition).body === "function" &&
87 // The engine walks these at start, and a file can export an object that only looks like one.
88 Array.isArray((value as WorkflowDefinition).triggers) &&
89 Array.isArray((value as WorkflowDefinition).resumeAfter) &&
90 typeof (value as WorkflowDefinition).asks === "object" &&
91 (value as WorkflowDefinition).asks !== null;
92​
93// The API is handed to a file as globals, which the whole process shares, so files load one at
94// a time. A load that was given up on still runs, so `T3.workflow` registers with the load whose
95// code calls it, and with none once that load is over.
96const loading = Semaphore.makeUnsafe(1);
97// A file whose top-level code never settles would otherwise hold every later load. Real time,
98// since importing a module is.
99const LOAD_DEADLINE_MS = 20_000;
100​
101interface Evaluation {
102 readonly registered: Array<unknown>;
103 open: boolean;
105const evaluating = new NodeAsyncHooks.AsyncLocalStorage<Evaluation>();
106// Counts loads across runtimes: one started again would otherwise get back the modules of the last.
107let loads = 0;
108const required = NodeModule.createRequire(import.meta.url);
109​
110/** A file with no `import` or `export` loads as CommonJS, which Node keeps by path, not address. */
111const forget = (file: string) => {
112 delete required.cache[file];
113 try {
114 delete required.cache[NodeFS.realpathSync(file)];
115 } catch {
116 // Gone already, so nothing can be kept under its real path either.
117 }
118};
119​
120const within = <A>(work: Promise<A>, ms: number): Promise<A | undefined> => {
121 let timer: ReturnType<typeof setTimeout> | undefined;
122 const late = new Promise<undefined>((resolve) => {
123 // @effect-diagnostics-next-line globalTimers:off -- an import runs on real time, not a test clock.
124 timer = setTimeout(resolve, ms, undefined);
125 });
126 return Promise.race([work, late]).finally(() => clearTimeout(timer));
127};
128​
129const evaluate = async (url: string, evaluation: Evaluation): Promise<ReadonlyArray<unknown>> => {
130 const api = await import("./api.ts");
131 const { Duration, Effect: effect, Option: option, Schedule, Schema: schema, ...t3 } = api;
132 const workflow = ((...input: Parameters<typeof api.workflow>) => {
133 const current = evaluating.getStore();
134 if (current === undefined || !current.open) {
135 throw new Error(
136 "T3.workflow was called after its file finished loading. Call it at the top of the file.",
137 );
138 }
139 const definition = api.workflow(...input);
140 current.registered.push(definition);
141 return definition;
142 }) as typeof api.workflow;
143 Object.assign(globalThis, {
144 T3: { ...t3, workflow },
145 Effect: effect,
146 Schema: schema,
147 Option: option,
148 Duration,
149 Schedule,
150 });
151 const loaded = (await evaluating.run(evaluation, () => import(url))) as {
152 readonly default?: unknown;
153 "module.exports"?: unknown;
154 };
155 // A file with no `import` or `export` loads as CommonJS, whose default is its `module.exports`:
156 // an empty object unless the file set one, which says nothing about what it defines.
157 const commonJs = "module.exports" in loaded;
158 const exported =
159 commonJs &&
160 typeof loaded.default === "object" &&
161 loaded.default !== null &&
162 !Array.isArray(loaded.default) &&
163 Object.keys(loaded.default).length === 0
164 ? undefined
165 : loaded.default;
166 // One workflow exported by itself is as good as a list of one.
167 const listed =
168 exported === undefined
169 ? []
170 : Array.isArray(exported)
171 ? exported
172 : isDefinition(exported)
173 ? [exported]
174 : undefined;
175 if (listed === undefined) {
176 throw new Error(
177 "The default export is not a workflow or a list of them. Call T3.workflow(…), or export what it returned.",
178 );
179 }
180 return [...new Set([...evaluation.registered, ...listed])];
181};
182​
183/**
184 * The workflows a file defines: every `T3.workflow(…)` it calls, and any list it exports.
185 * `load` tells one loading of a file from the next: Node keeps a module by its address, so the
186 * same address would give back the file as it was the first time.
187 */
188export const loadDefinitions = Effect.fn("WorkflowRuntime.loadDefinitions")(function* (
189 module: string,
190 load = 0,
191 deadlineMs = LOAD_DEADLINE_MS,
192) {
193 const path = yield* Path.Path;
194 const file = path.resolve(module);
195 const url = NodeURL.pathToFileURL(file).href + (load === 0 ? "" : `?${load}`);
196 const definitions = yield* Effect.tryPromise({
197 try: () => {
198 const evaluation: Evaluation = { registered: [], open: true };
199 forget(file);
200 return within(evaluate(url, evaluation), deadlineMs).finally(() => {
201 evaluation.open = false;
202 forget(file);
203 });
204 },
205 catch: (cause) => new WorkflowDefinitionsLoadError({ module, cause }),
206 }).pipe(loading.withPermits(1));
207 if (definitions === undefined) {
208 return yield* new WorkflowDefinitionsLoadError({
209 module,
210 cause: `It did not finish loading within ${deadlineMs / 1000} seconds. Something at the top of the file waits for good.`,
211 });
212 }
213 if (!definitions.every(isDefinition)) {
214 return yield* new WorkflowDefinitionsLoadError({
215 module,
216 cause: "Something it exports is not a workflow. Export only what `T3.workflow` returned.",
217 });
218 }
219 return definitions;
220});
221​
222/** What a load error says, with the line of `file` it points at when it names one. */
223const loadProblem = (
224 error: WorkflowDefinitionsLoadError,
225 loadedFrom: string,
226 file: string,
227): WorkflowDefinitionProblem => {
228 const cause = error.cause;
229 const stack = cause instanceof Error ? (cause.stack ?? "") : "";
230 const name = loadedFrom.split(/[\\/]/).at(-1) ?? loadedFrom;
231 // Node names the place as `file:///…/name.ts:12` or `…/name.ts:12:5`, with a `?n` when reloaded.
232 const at = stack.split(name).find((rest) => /^(\?\d+)?:\d+/.test(rest));
233 const line = at === undefined ? undefined : Number(/^(?:\?\d+)?:(\d+)/.exec(at)?.[1]);
234 return { message: text(cause), file, ...(line === undefined ? {} : { line }) };
235};
236​
237/**
238 * What is wrong between files that each loaded, given the runs that have not ended, with the
239 * files that could each be the cause.
240 */
241const definitionProblems = (
242 files: ReadonlyArray<{
243 readonly name: string;
244 readonly definitions: ReadonlyArray<WorkflowDefinition>;
245 }>,
246 unfinished: ReadonlyArray<{ readonly workflow: string; readonly version: number }>,
247 before: ReadonlyMap<string, ReadonlyArray<WorkflowDefinition>> = new Map(),
248): ReadonlyArray<{
249 readonly problem: WorkflowDefinitionProblem;
250 readonly files: ReadonlyArray<string>;
251 readonly clash: boolean;
252}> => {
253 const where = new Map<string, Array<string>>();
254 for (const file of files) {
255 for (const definition of file.definitions) {
256 where.set(engineTag(definition), [...(where.get(engineTag(definition)) ?? []), file.name]);
257 }
258 }
259 const waiting = new Map<string, number>();
260 for (const run of unfinished) {
261 const tag = engineTag({ name: run.workflow, version: run.version });
262 if (!where.has(tag)) waiting.set(tag, (waiting.get(tag) ?? 0) + 1);
263 }
264 return [
265 ...[...where]
266 .filter(([, names]) => names.length > 1)
267 .map(([tag, names]) => ({
268 problem: {
269 message: `${tag} is defined twice, in ${[...new Set(names)].join(" and ")}. A workflow's name and version name one body.`,
270 },
271 files: [...new Set(names)],
272 clash: true,
273 })),
274 ...[...waiting].map(([tag, runs]) => ({
275 problem: {
276 message: `${tag} is no longer defined, and ${runs} of its runs ${runs === 1 ? "has" : "have"} not ended. Keep that version until they end, or cancel them first.`,
277 },
278 files: [...before]
279 .filter(([, definitions]) =>
280 definitions.some((definition) => engineTag(definition) === tag),
281 )
282 .map(([name]) => name),
283 clash: false,
284 })),
285 ];
286};
287​
288/**
289 * `engine` gives the layer that runs a set of definitions. It is asked for only once there is
290 * something to run or `kept` says there are runs to read, since the engine's modules are not worth
291 * loading for nothing. `where` is the folder of definition files, or one file.
292 */
293export const make = Effect.fn("WorkflowRuntime.make")(function* <E, R>(
294 engine: Effect.Effect<
295 (definitions: ReadonlyArray<WorkflowDefinition>) => Layer.Layer<Workflows.Workflows, E, R>
296 >,
297 where: string,
298 kept: Effect.Effect<boolean>,
299) {
300 const fileSystem = yield* FileSystem.FileSystem;
301 const path = yield* Path.Path;
302 const target = path.resolve(where);
303 const single = DEFINITION_FILE.test(path.basename(target));
304 const directory = single ? path.dirname(target) : target;
305 yield* Effect.ignore(fileSystem.makeDirectory(directory, { recursive: true }));
306 const outer = yield* Scope.Scope;
307 const services = yield* Effect.context<R | Path.Path>();
308​
309 // One reload at a time, and callers during one wait for the engine that comes out of it.
310 const lock = yield* Semaphore.make(1);
311 let ready = Deferred.makeUnsafe<Workflows.Workflows["Service"]>();
312 let engineScope: Scope.Closeable | undefined;
313 let running: ReadonlyArray<WorkflowDefinition> = [];
314 let imported = false;
315 /** Each file as it was last looked at, so one that did not change is not loaded again. */
316 const seen = new Map<string, string>();
317 /** The last version of each file that loaded, which runs while a newer one does not. */
318 const good = new Map<string, ReadonlyArray<WorkflowDefinition>>();
319 /** Files that loaded or went away since, kept apart until the change as a whole is taken. */
320 const pending = new Map<string, ReadonlyArray<WorkflowDefinition> | null>();
321 const broken = new Map<string, WorkflowDefinitionProblem>();
322 /** Files whose change clashes with another file or drops what a run needs, and why. */
323 const held = new Map<string, Array<WorkflowDefinitionProblem>>();
324 let between: ReadonlyArray<WorkflowDefinitionProblem> = [];
325 /** Code files in the folder that are not loaded because of their name. */
326 let misnamed: ReadonlyArray<WorkflowDefinitionProblem> = [];
327 let retrying = false;
328 let unstarted = false;
329 const state = yield* SubscriptionRef.make<{ revision: number; problem: string | null }>({
330 revision: 0,
331 problem: null,
332 });
333 const told = (problem: WorkflowDefinitionProblem) =>
334 problem.file === undefined ? problem.message : `${problem.file}: ${problem.message}`;
335 const report = Effect.suspend(() => {
336 const problems = [...broken.values(), ...[...held.values()].flat(), ...misnamed, ...between];
337 return SubscriptionRef.update(state, (current) => ({
338 revision: current.revision + 1,
339 problem: problems.length === 0 ? null : problems.map(told).join("\n"),
340 }));
341 });
342​
343 /** Every name in the folder, or the one file. */
344 const entries = Effect.gen(function* () {
345 if (single) {
346 return (yield* fileSystem.exists(target)) ? [path.basename(target)] : [];
347 }
348 // A folder that is not there yet is empty. One that cannot be read just now is not: it
349 // fails, and what was loaded stays.
350 if (!(yield* fileSystem.exists(directory))) return [];
351 return (yield* fileSystem.readDirectory(directory)).toSorted();
352 });
353 const definitionNames = (all: ReadonlyArray<string>) =>
354 all.filter((entry) => DEFINITION_FILE.test(entry));
355 const names = Effect.map(entries, definitionNames);
356​
357 /** A fresh engine for these definitions in its own scope, or the failure that stopped it. */
358 const build = Effect.fn("WorkflowRuntime.build")(function* (
359 definitions: ReadonlyArray<WorkflowDefinition>,
360 ) {
361 const scope = yield* Scope.fork(outer);
362 const layerEngine = yield* engine;
363 imported = true;
364 const built = yield* Effect.suspend(() =>
365 Layer.buildWithScope(layerEngine(definitions), scope),
366 ).pipe(Effect.provideContext(services), Effect.exit);
367 if (Exit.isFailure(built)) yield* Scope.close(scope, Exit.void);
368 else engineScope = scope;
369 return built;
370 });
371​
372 const boot = Effect.fn("WorkflowRuntime.boot")(
373 function* (definitions: ReadonlyArray<WorkflowDefinition>) {
374 const next = Deferred.makeUnsafe<Workflows.Workflows["Service"]>();
375 ready = next;
376 const previous = running;
377 if (engineScope !== undefined) yield* Scope.close(engineScope, Exit.void);
378 engineScope = undefined;
379 running = [];
380 if (definitions.length === 0 && !imported && !(yield* kept)) {
381 yield* Deferred.succeed(next, Workflows.disabled);
382 return null;
383 }
384 const built = yield* build(definitions);
385 if (Exit.isSuccess(built)) {
386 running = definitions;
387 yield* Deferred.succeed(next, Context.get(built.value, Workflows.Workflows));
388 if (definitions.length > 0) {
389 yield* Effect.logInfo("Workflows registered", {
390 directory,
391 workflows: definitions.map(engineTag),
392 });
393 }
394 return null;
395 }
396 // What ran before comes back, so definitions that cannot start take nothing down.
397 const restored = yield* build(previous);
398 if (Exit.isSuccess(restored)) {
399 running = previous;
400 yield* Deferred.succeed(next, Context.get(restored.value, Workflows.Workflows));
401 } else {
402 // Nobody may be left waiting on an engine that never came up.
403 yield* Deferred.succeed(next, Workflows.disabled);
404 }
405 return `The workflow engine did not start: ${text(Cause.squash(built.cause))}`;
406 },
407 // Once `ready` is replaced it must be settled, or every caller waits on it for good.
408 Effect.uninterruptible,
409 );
410​
411 const unfinished = Effect.suspend(() =>
412 running.length === 0
413 ? Effect.succeed([])
414 : Effect.flatMap(Deferred.await(ready), (service) => service.unfinished),
415 );
416 /** The workflows the file at `from` defines, or what is wrong with it as the file `name`. */
417 const load = Effect.fn("WorkflowRuntime.load")(function* (from: string, name: string) {
418 const definitions = yield* loadDefinitions(from, ++loads).pipe(
419 Effect.provideContext(services),
420 Effect.result,
421 );
422 return definitions._tag === "Failure"
423 ? ({ problem: loadProblem(definitions.failure, from, name) } as const)
424 : ({ definitions: definitions.success } as const);
425 });
426 /** What would run with these files, in the folder's order. */
427 const gathered = (files: ReadonlyMap<string, ReadonlyArray<WorkflowDefinition>>) =>
428 [...files]
429 .toSorted(([left], [right]) => left.localeCompare(right))
430 .map(([name, definitions]) => ({ name, definitions }));
431​
432 // Set once `reload` exists, which it schedules again; the indirection keeps its type inferred.
433 let retryLater: Effect.Effect<void> = Effect.void;
434 /** Take in what changed in the folder, and run the result unless something is wrong with it. */
435 const reload = Effect.fn("WorkflowRuntime.reload")(function* () {
436 const listed = yield* Effect.option(entries);
437 if (Option.isNone(listed)) {
438 yield* Effect.logWarning(
439 "The workflows folder could not be read; its workflows stay as they are",
440 );
441 yield* retryLater;
442 return false;
443 }
444 const present = definitionNames(listed.value);
445 // A leading dot keeps a file out on purpose; any other code file left out is a surprise.
446 const wasMisnamed = misnamed;
447 misnamed = listed.value
448 .filter((entry) => /^[^.].*\.(ts|mts|js|mjs)$/.test(entry) && !DEFINITION_FILE.test(entry))
449 .map((entry) => ({ message: `It is not loaded. ${NAMING}`, file: entry }));
450 const renamed =
451 misnamed.map((problem) => problem.file).join("/") !==
452 wasMisnamed.map((problem) => problem.file).join("/");
453 let changed = false;
454 for (const problem of misnamed) {
455 if (!wasMisnamed.some((known) => known.file === problem.file)) {
456 yield* Effect.logWarning(
457 "A file in the workflows folder is not loaded because of its name",
458 problem,
459 );
460 }
461 }
462 for (const name of present) {
463 const file = path.join(directory, name);
464 const source = yield* fileSystem.readFileString(file).pipe(Effect.option);
465 if (Option.isNone(source) || seen.get(name) === source.value) continue;
466 seen.set(name, source.value);
467 changed = true;
468 const loaded = yield* load(file, name);
469 if (loaded.definitions === undefined) {
470 broken.set(name, loaded.problem);
471 pending.delete(name);
472 yield* Effect.logWarning("A workflow definitions file was not loaded", loaded.problem);
473 continue;
474 }
475 broken.delete(name);
476 pending.set(name, loaded.definitions);
477 }
478 for (const name of [...seen.keys()].filter((known) => !present.includes(known))) {
479 seen.delete(name);
480 pending.set(name, null);
481 broken.delete(name);
482 changed = true;
483 }
484 // Asked again while something stands between files: the runs that held a version may be over.
485 if (!changed && between.length === 0 && held.size === 0) {
486 if (renamed) yield* report;
487 return true;
488 }
489 const runs = yield* unfinished;
490 // A change that clashes is held back like a file that does not load: that file keeps its last
491 // good version, a new one stays out, and every other change is taken.
492 held.clear();
493 let next = new Map(good);
494 let problems: ReturnType<typeof definitionProblems> = [];
495 let blamed = true;
496 while (blamed) {
497 blamed = false;
498 next = new Map(good);
499 for (const [name, definitions] of pending) {
500 if (held.has(name)) continue;
501 if (definitions === null) next.delete(name);
502 else next.set(name, definitions);
503 }
504 problems = definitionProblems(gathered(next), runs, good);
505 for (const { problem, files: involved, clash } of problems) {
506 const changing = involved.filter((name) => pending.has(name) && !held.has(name));
507 // Between new files that define the same workflow, the first in the folder's order stays.
508 const culprits =
509 clash && changing.length === involved.length ? changing.slice(1) : changing;
510 for (const name of culprits) {
511 held.set(name, [...(held.get(name) ?? []), { ...problem, file: name }]);
512 blamed = true;
513 }
514 }
515 }
516 if (held.size > 0) {
517 yield* Effect.logWarning("Some workflow definition changes were not taken", {
518 problems: [...held.values()].flat(),
519 });
520 }
521 // What is left was so before any of these changes, so it holds none of them back.
522 const standing = problems.map((entry) => entry.problem);
523 if (standing.length > 0) {
524 yield* Effect.logWarning("Workflow definitions have problems", { problems: standing });
525 }
526 const taking = [...pending.keys()].filter((name) => !held.has(name));
527 // An engine that did not start is tried again, as the runs it tripped on may have ended.
528 if (taking.length === 0 && !unstarted) {
529 between = standing;
530 yield* report;
531 return true;
532 }
533 good.clear();
534 for (const [name, definitions] of next) good.set(name, definitions);
535 for (const name of taking) pending.delete(name);
536 const failed = yield* boot(gathered(next).flatMap((file) => file.definitions));
537 unstarted = failed !== null;
538 between = failed === null ? standing : [...standing, { message: failed }];
539 yield* report;
540 return true;
541 });
542​
543 retryLater = Effect.suspend(() => {
544 if (retrying) return Effect.void;
545 retrying = true;
546 return Effect.suspend(() => {
547 retrying = false;
548 return lock.withPermits(1)(reload());
549 }).pipe(
550 Effect.delay(LIST_RETRY),
551 Effect.catchCause((cause) =>
552 Effect.logWarning("Reloading workflow definitions failed", Cause.pretty(cause)),
553 ),
554 Effect.forkIn(outer),
555 Effect.asVoid,
556 );
557 });
558​
559 yield* lock.withPermits(1)(reload());
560 // No file defines anything yet, though runs kept from before may still be read.
561 if (!(yield* Deferred.isDone(ready))) yield* boot([]);
562​
563 // The folder, not a file: an editor that saves by renaming replaces the file it was watching.
564 yield* fileSystem.watch(directory).pipe(
565 Stream.debounce(RELOAD_SETTLE),
566 Stream.runForEach(() =>
567 lock
568 .withPermits(1)(reload())
569 .pipe(
570 Effect.catchCause((cause) =>
571 Effect.logWarning("Reloading workflow definitions failed", Cause.pretty(cause)),
572 ),
573 ),
574 ),
575 Effect.catchCause((cause) =>
576 Effect.logWarning("Workflow definitions are not watched for changes", Cause.pretty(cause)),
577 ),
578 Effect.forkIn(outer),
579 );
580​
581 yield* Effect.sleep(HELD_RETRY).pipe(
582 Effect.andThen(
583 Effect.suspend(() => (held.size > 0 ? lock.withPermits(1)(reload()) : Effect.void)),
584 ),
585 Effect.catchCause((cause) =>
586 Effect.logWarning("Reloading workflow definitions failed", Cause.pretty(cause)),
587 ),
588 Effect.forever,
589 Effect.forkIn(outer),
590 );
591​
592 const current = Effect.suspend(() => Deferred.await(ready));
593 // A watcher outlives the engine it began on: each reload hands it the next one's stream.
594 const followed = <A>(pick: (service: Workflows.Workflows["Service"]) => Stream.Stream<A>) =>
595 SubscriptionRef.changes(state).pipe(
596 Stream.switchMap((at) =>
597 Stream.unwrap(Effect.map(current, pick)).pipe(Stream.map((value) => [value, at] as const)),
598 ),
599 );
600 const service = Workflows.Workflows.of({
601 start: Effect.fn("Workflows.start")(function* (...input) {
602 return yield* (yield* current).start(...input);
603 }),
604 signal: Effect.fn("Workflows.signal")(function* (...input) {
605 return yield* (yield* current).signal(...input);
606 }),
607 answer: Effect.fn("Workflows.answer")(function* (...input) {
608 return yield* (yield* current).answer(...input);
609 }),
610 resume: Effect.fn("Workflows.resume")(function* (...input) {
611 return yield* (yield* current).resume(...input);
612 }),
613 cancel: Effect.fn("Workflows.cancel")(function* (...input) {
614 return yield* (yield* current).cancel(...input);
615 }),
616 get: Effect.fn("Workflows.get")(function* (...input) {
617 return yield* (yield* current).get(...input);
618 }),
619 list: Effect.fn("Workflows.list")(function* (...input) {
620 return yield* (yield* current).list(...input);
621 }),
622 waitFor: Effect.fn("Workflows.waitFor")(function* (...input) {
623 // A reload replaces the engine, and a wait on the old one would never hear of the run again.
624 while (true) {
625 // Noted before the engine is read, so a reload that lands in between is still heard of.
626 const { revision } = yield* SubscriptionRef.get(state);
627 const live = yield* current;
628 const reloaded = SubscriptionRef.changes(state).pipe(
629 Stream.filter((at) => at.revision !== revision),
630 Stream.runHead,
631 );
632 const waited = yield* live
633 .waitFor(...input)
634 .pipe(Effect.asSome, Effect.raceFirst(Effect.as(reloaded, Option.none())));
635 if (Option.isSome(waited)) return waited.value;
636 }
637 }),
638 questions: Effect.flatMap(current, (live) => live.questions),
639 unfinished: Effect.flatMap(current, (live) => live.unfinished),
640 hooks: Effect.flatMap(current, (live) => live.hooks),
641 deliver: Effect.fn("Workflows.deliver")(function* (...input) {
642 return yield* (yield* current).deliver(...input);
643 }),
644 stored: Effect.fn("Workflows.stored")(function* (...input) {
645 return yield* (yield* current).stored(...input);
646 }),
647 storeSet: Effect.fn("Workflows.storeSet")(function* (...input) {
648 return yield* (yield* current).storeSet(...input);
649 }),
650 storeDelete: Effect.fn("Workflows.storeDelete")(function* (...input) {
651 return yield* (yield* current).storeDelete(...input);
652 }),
653 // Every reload starts a watcher over on a whole list, which is where the definition rides.
654 watch: followed((live) => live.watch).pipe(
655 Stream.map(([update, at]) => ("_tag" in update ? update : { ...update, definition: at })),
656 ),
657 counts: followed((live) => live.counts).pipe(Stream.map(([counts]) => counts)),
658 sweep: Effect.flatMap(current, (live) => live.sweep),
659 });
660​
661 const alone = { message: `This server reads its workflows from ${target} alone.` };
662 /** Why `name` cannot be a file here, if it cannot. */
663 const refused = (name: string): WorkflowDefinitionProblem | undefined =>
664 single && name !== path.basename(target)
665 ? alone
666 : DEFINITION_FILE.test(name)
667 ? undefined
668 : { message: NAMING };
669 /** What is wrong with the folder once `change` is made to the files that load. */
670 const wouldBreak = Effect.fn("WorkflowRuntime.wouldBreak")(function* (
671 change: (files: Map<string, ReadonlyArray<WorkflowDefinition>>) => void,
672 ) {
673 const files = new Map(good);
674 change(files);
675 return definitionProblems(gathered(files), yield* unfinished, good).map(
676 (entry) => entry.problem,
677 );
678 });
679​
680 const refusal = (problems: ReadonlyArray<WorkflowDefinitionProblem>) => ({
681 changed: false,
682 problems,
683 });
684 /** What keeps a change to the file `name` from running, once it is made on disk. */
685 const taken = Effect.fn("WorkflowRuntime.taken")(function* (name: string) {
686 const listed = yield* reload();
687 const problem = broken.get(name);
688 return {
689 changed: true,
690 problems: listed
691 ? [...(problem === undefined ? [] : [problem]), ...(held.get(name) ?? []), ...between]
692 : [{ message: `${directory} could not be read just now, so the change does not run yet.` }],
693 };
694 });
695​
696 const save = Effect.fn("WorkflowRuntime.save")(function* (name: string, source: string) {
697 const no = refused(name);
698 if (no !== undefined) return refusal([no]);
699 const file = path.join(directory, name);
700 // Beside the real file, so what it imports resolves the same way. The dot keeps it out.
701 const draft = path.join(directory, `.${name}.check-${loads + 1}${path.extname(name)}`);
702 const checked = yield* fileSystem.writeFileString(draft, source).pipe(
703 Effect.andThen(load(draft, name)),
704 Effect.ensuring(Effect.ignore(fileSystem.remove(draft))),
705 Effect.catchTags({
706 PlatformError: (error) =>
707 Effect.succeed({
708 problem: { message: `Could not write in ${directory}: ${text(error)}` },
709 } as const),
710 }),
711 );
712 if (!("definitions" in checked)) return refusal([checked.problem]);
713 const definitions = checked.definitions;
714 const problems = yield* wouldBreak((files) => files.set(name, definitions));
715 if (problems.length > 0) return refusal(problems);
716 const written = yield* fileSystem.writeFileString(file, source).pipe(Effect.result);
717 if (written._tag === "Failure") {
718 return refusal([{ message: `Could not write ${file}: ${text(written.failure)}` }]);
719 }
720 return yield* taken(name);
721 });
722​
723 const remove = Effect.fn("WorkflowRuntime.remove")(function* (name: string) {
724 const no = single ? alone : refused(name);
725 if (no !== undefined) return refusal([no]);
726 const problems = yield* wouldBreak((files) => files.delete(name));
727 if (problems.length > 0) return refusal(problems);
728 const removed = yield* fileSystem.remove(path.join(directory, name)).pipe(Effect.result);
729 if (removed._tag === "Failure") {
730 return refusal([{ message: `Could not delete ${name}: ${text(removed.failure)}` }]);
731 }
732 return yield* taken(name);
733 });
734​
735 return Context.make(Workflows.Workflows, service).pipe(
736 Context.add(
737 WorkflowDefinitions,
738 WorkflowDefinitions.of({
739 read: Effect.gen(function* () {
740 const files = yield* Effect.forEach(
741 yield* Effect.orElseSucceed(names, () => []),
742 (name) =>
743 fileSystem.readFileString(path.join(directory, name)).pipe(
744 Effect.orElseSucceed(() => ""),
745 Effect.map((source) => {
746 const problem = broken.get(name);
747 return {
748 name,
749 source,
750 workflows: (good.get(name) ?? []).map(engineTag),
751 problems: [
752 ...(problem === undefined ? [] : [problem]),
753 ...(held.get(name) ?? []),
754 ],
755 };
756 }),
757 ),
758 );
759 const at = yield* SubscriptionRef.get(state);
760 // A file held back after it was deleted has no entry of its own to say so.
761 const gone = [...held]
762 .filter(([name]) => !files.some((file) => file.name === name))
763 .flatMap(([, problems]) => problems);
764 return { directory, single, files, problems: [...misnamed, ...between, ...gone], ...at };
765 }),
766 save: Effect.fn("WorkflowDefinitions.save")(function* (name, source) {
767 return yield* lock.withPermits(1)(save(name, source));
768 }),
769 remove: Effect.fn("WorkflowDefinitions.remove")(function* (name) {
770 return yield* lock.withPermits(1)(remove(name));
771 }),
772 }),
773 ),
774 );
775});
776​
777/**
778 * Workflows behind the Labs switch. While off, `runtime` is not run: no definition file loads and
779 * no engine runs, and every request is refused. Turning on runs it in a scope of its own, which
780 * turning off closes; runs stay stored and go on once it is on again. `where` is as for `make`.
781 */
782export const gate = Effect.fn("WorkflowRuntime.gate")(function* <E, R>(
783 runtime: Effect.Effect<
784 Context.Context<Workflows.Workflows | WorkflowDefinitions>,
785 E,
786 R | Scope.Scope
787 >,
788 where: string,
789) {
790 const path = yield* Path.Path;
791 const outer = yield* Scope.Scope;
792 const services = yield* Effect.context<R>();
793 const target = path.resolve(where);
794 const single = DEFINITION_FILE.test(path.basename(target));
795 const off = { message: Workflows.OFF };
796 const offDefinitions = WorkflowDefinitions.of({
797 read: Effect.succeed({
798 directory: single ? path.dirname(target) : target,
799 single,
800 files: [],
801 problems: [off],
802 revision: 0,
803 problem: null,
804 }),
805 save: Effect.fn("WorkflowDefinitions.save")(function* () {
806 return yield* Effect.succeed({ changed: false, problems: [off] });
807 }),
808 remove: Effect.fn("WorkflowDefinitions.remove")(function* () {
809 return yield* Effect.succeed({ changed: false, problems: [off] });
810 }),
811 });
812 const offContext = Context.make(Workflows.Workflows, Workflows.off).pipe(
813 Context.add(WorkflowDefinitions, offDefinitions),
814 );
815​
816 const lock = yield* Semaphore.make(1);
817 let ready = Deferred.makeUnsafe<Context.Context<Workflows.Workflows | WorkflowDefinitions>>();
818 Deferred.doneUnsafe(ready, Exit.succeed(offContext));
819 let scope: Scope.Closeable | undefined;
820 const turns = yield* SubscriptionRef.make(0);
821​
822 const turn = Effect.fn("WorkflowRuntime.turn")(
823 function* (on: boolean) {
824 if (on === (scope !== undefined)) return;
825 const next =
826 Deferred.makeUnsafe<Context.Context<Workflows.Workflows | WorkflowDefinitions>>();
827 ready = next;
828 if (scope !== undefined) yield* Scope.close(scope, Exit.void);
829 scope = undefined;
830 if (on) {
831 const opened = yield* Scope.fork(outer);
832 const started = yield* runtime.pipe(
833 Effect.provideService(Scope.Scope, opened),
834 Effect.provideContext(services),
835 Effect.exit,
836 );
837 if (Exit.isSuccess(started)) {
838 scope = opened;
839 yield* Deferred.succeed(next, started.value);
840 } else {
841 yield* Scope.close(opened, Exit.void);
842 yield* Effect.logWarning("Workflows did not start", Cause.pretty(started.cause));
843 }
844 }
845 if (scope === undefined) yield* Deferred.succeed(next, offContext);
846 yield* SubscriptionRef.update(turns, (count) => count + 1);
847 yield* Effect.logInfo(scope === undefined ? "Workflows are off" : "Workflows are on");
848 },
849 // Once `ready` is replaced it must be settled, or every caller waits on it for good.
850 Effect.uninterruptible,
851 lock.withPermits(1),
852 );
853​
854 const live = Effect.suspend(() => Deferred.await(ready));
855 const current = Effect.map(live, Context.get(Workflows.Workflows));
856 const definitions = Effect.map(live, Context.get(WorkflowDefinitions));
857 // A watcher outlives a turn: each one hands it the next service's stream.
858 const followed = <A>(pick: (service: Workflows.Workflows["Service"]) => Stream.Stream<A>) =>
859 SubscriptionRef.changes(turns).pipe(
860 Stream.switchMap(() => Stream.unwrap(Effect.map(current, pick))),
861 );
862 const service = Workflows.Workflows.of({
863 start: Effect.fn("Workflows.start")(function* (...input) {
864 return yield* (yield* current).start(...input);
865 }),
866 signal: Effect.fn("Workflows.signal")(function* (...input) {
867 return yield* (yield* current).signal(...input);
868 }),
869 answer: Effect.fn("Workflows.answer")(function* (...input) {
870 return yield* (yield* current).answer(...input);
871 }),
872 resume: Effect.fn("Workflows.resume")(function* (...input) {
873 return yield* (yield* current).resume(...input);
874 }),
875 cancel: Effect.fn("Workflows.cancel")(function* (...input) {
876 return yield* (yield* current).cancel(...input);
877 }),
878 get: Effect.fn("Workflows.get")(function* (...input) {
879 return yield* (yield* current).get(...input);
880 }),
881 list: Effect.fn("Workflows.list")(function* (...input) {
882 return yield* (yield* current).list(...input);
883 }),
884 waitFor: Effect.fn("Workflows.waitFor")(function* (...input) {
885 // Off, nothing changes a run; a wait goes on once workflows are on again.
886 while (true) {
887 const turned = yield* SubscriptionRef.get(turns);
888 const service = yield* current;
889 const next = SubscriptionRef.changes(turns).pipe(
890 Stream.filter((count) => count !== turned),
891 Stream.runHead,
892 );
893 const waited = yield* service
894 .waitFor(...input)
895 .pipe(Effect.asSome, Effect.raceFirst(Effect.as(next, Option.none())));
896 if (Option.isSome(waited)) return waited.value;
897 }
898 }),
899 questions: Effect.flatMap(current, (service) => service.questions),
900 unfinished: Effect.flatMap(current, (service) => service.unfinished),
901 hooks: Effect.flatMap(current, (service) => service.hooks),
902 deliver: Effect.fn("Workflows.deliver")(function* (...input) {
903 return yield* (yield* current).deliver(...input);
904 }),
905 stored: Effect.fn("Workflows.stored")(function* (...input) {
906 return yield* (yield* current).stored(...input);
907 }),
908 storeSet: Effect.fn("Workflows.storeSet")(function* (...input) {
909 return yield* (yield* current).storeSet(...input);
910 }),
911 storeDelete: Effect.fn("Workflows.storeDelete")(function* (...input) {
912 return yield* (yield* current).storeDelete(...input);
913 }),
914 watch: followed((service) => service.watch),
915 counts: followed((service) => service.counts),
916 sweep: Effect.flatMap(current, (service) => service.sweep),
917 });
918​
919 return {
920 turn,
921 context: Context.make(Workflows.Workflows, service).pipe(
922 Context.add(
923 WorkflowDefinitions,
924 WorkflowDefinitions.of({
925 read: Effect.flatMap(definitions, (files) => files.read),
926 save: Effect.fn("WorkflowDefinitions.save")(function* (name, source) {
927 return yield* (yield* definitions).save(name, source);
928 }),
929 remove: Effect.fn("WorkflowDefinitions.remove")(function* (name) {
930 return yield* (yield* definitions).remove(name);
931 }),
932 }),
933 ),
934 ),
935 };
936});
937​
938/**
939 * The workflow service for this server, and its definition files: those in the `workflows`
940 * folder of the T3 home, or wherever `T3CODE_WORKFLOWS` points instead. A file that does not
941 * load is reported and never stops the server. Nothing runs until `workflowsEnabled` is on.
942 */
943export const layer = Layer.effectContext(
944 Effect.gen(function* () {
945 const override = yield* definitionsOverride;
946 const config = yield* ServerConfig.ServerConfig;
947 const forge = Layer.succeed(WorkflowForge.WorkflowForge, yield* WorkflowForge.WorkflowForge);
948 const sql = yield* SqlClient.SqlClient;
949 const settings = yield* ServerSettings.ServerSettingsService;
950 const where = Option.getOrElse(override, () => config.workflowsDir);
951 const changes = yield* settings.subscribeChanges;
952 const gated = yield* gate(
953 make(
954 Effect.map(
955 Effect.promise((): Promise<typeof WorkflowEngine> => import("./WorkflowEngine.ts")),
956 (engine) => (definitions) =>
957 engine
958 .layer(definitions)
959 .pipe(Layer.provide(WorkflowAgentThreads.layer), Layer.provide(forge)),
960 ),
961 where,
962 sql`SELECT 1 FROM workflow_runs LIMIT 1`.pipe(
963 Effect.map((rows) => rows.length > 0),
964 Effect.orElseSucceed(() => true),
965 ),
966 ),
967 where,
968 );
969 const enabled = yield* settings.getSettings.pipe(
970 Effect.map((current) => current.workflowsEnabled),
971 Effect.orElseSucceed(() => false),
972 );
973 yield* gated.turn(enabled);
974 yield* changes.pipe(
975 Stream.map((current) => current.workflowsEnabled),
976 Stream.runForEach(gated.turn),
977 Effect.forkScoped,
978 );
979 return gated.context;
980 }),
981);