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