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

WorkflowRuntime.ts

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