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

WorkflowRuntime.ts

1,065 lines44.0 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 return definitions._tag === "Failure"
470 ? ({ problem: loadProblem(definitions.failure, from, name), helpers } as const)
471 : ({ definitions: definitions.success, helpers } as const);
472 });
473 /** What would run with these files, in the folder's order. */
474 const gathered = (files: ReadonlyMap<string, ReadonlyArray<WorkflowDefinition>>) =>
475 [...files]
476 .toSorted(([left], [right]) => left.localeCompare(right))
477 .map(([name, definitions]) => ({ name, definitions }));
478​
479 // Set once `reload` exists, which it schedules again; the indirection keeps its type inferred.
480 let retryLater: Effect.Effect<void> = Effect.void;
481 /** Take in what changed in the folder, and run the result unless something is wrong with it. */
482 const reload = Effect.fn("WorkflowRuntime.reload")(function* () {
483 const listed = yield* Effect.option(entries);
484 if (Option.isNone(listed)) {
485 yield* Effect.logWarning(
486 "The workflows folder could not be read; its workflows stay as they are",
487 );
488 yield* retryLater;
489 return false;
490 }
491 const present = definitionNames(listed.value);
492 // A leading dot keeps a file out on purpose; any other code file left out is a surprise.
493 const wasMisnamed = misnamed;
494 misnamed = listed.value
495 .filter((entry) => /^[^.].*\.(ts|mts|js|mjs)$/.test(entry) && !DEFINITION_FILE.test(entry))
496 .map((entry) => ({ message: `It is not loaded. ${NAMING}`, file: entry }));
497 const renamed =
498 misnamed.map((problem) => problem.file).join("/") !==
499 wasMisnamed.map((problem) => problem.file).join("/");
500 let changed = false;
501 for (const problem of misnamed) {
502 if (!wasMisnamed.some((known) => known.file === problem.file)) {
503 yield* Effect.logWarning(
504 "A file in the workflows folder is not loaded because of its name",
505 problem,
506 );
507 }
508 }
509 for (const name of present) {
510 const file = path.join(directory, name);
511 const source = yield* fileSystem.readFileString(file).pipe(Effect.option);
512 if (Option.isNone(source)) continue;
513 if (seen.get(name) === (yield* snapshot(source.value, helpers.get(name) ?? []))) continue;
514 changed = true;
515 const loaded = yield* load(file, name);
516 helpers.set(name, loaded.helpers);
517 seen.set(name, yield* snapshot(source.value, loaded.helpers));
518 if (loaded.definitions === undefined) {
519 broken.set(name, loaded.problem);
520 pending.delete(name);
521 yield* Effect.logWarning("A workflow definitions file was not loaded", loaded.problem);
522 continue;
523 }
524 broken.delete(name);
525 pending.set(name, loaded.definitions);
526 }
527 for (const name of [...seen.keys()].filter((known) => !present.includes(known))) {
528 seen.delete(name);
529 helpers.delete(name);
530 pending.set(name, null);
531 broken.delete(name);
532 changed = true;
533 }
534 // Asked again while something stands between files: the runs that held a version may be over.
535 if (!changed && between.length === 0 && held.size === 0) {
536 if (renamed) yield* report;
537 return true;
538 }
539 const runs = yield* unfinished;
540 // A change that clashes is held back like a file that does not load: that file keeps its last
541 // good version, a new one stays out, and every other change is taken.
542 held.clear();
543 let next = new Map(good);
544 let problems: ReturnType<typeof definitionProblems> = [];
545 let blamed = true;
546 while (blamed) {
547 blamed = false;
548 next = new Map(good);
549 for (const [name, definitions] of pending) {
550 if (held.has(name)) continue;
551 if (definitions === null) next.delete(name);
552 else next.set(name, definitions);
553 }
554 problems = definitionProblems(gathered(next), runs, good);
555 for (const { problem, files: involved, clash } of problems) {
556 const changing = involved.filter((name) => pending.has(name) && !held.has(name));
557 // Between new files that define the same workflow, the first in the folder's order stays.
558 const culprits =
559 clash && changing.length === involved.length ? changing.slice(1) : changing;
560 for (const name of culprits) {
561 held.set(name, [...(held.get(name) ?? []), { ...problem, file: name }]);
562 blamed = true;
563 }
564 }
565 }
566 if (held.size > 0) {
567 yield* Effect.logWarning("Some workflow definition changes were not taken", {
568 problems: [...held.values()].flat(),
569 });
570 }
571 // What is left was so before any of these changes, so it holds none of them back.
572 const standing = problems.map((entry) => entry.problem);
573 if (standing.length > 0) {
574 yield* Effect.logWarning("Workflow definitions have problems", { problems: standing });
575 }
576 const taking = [...pending.keys()].filter((name) => !held.has(name));
577 // An engine that did not start is tried again, as the runs it tripped on may have ended.
578 if (taking.length === 0 && !unstarted) {
579 between = standing;
580 yield* report;
581 return true;
582 }
583 good.clear();
584 for (const [name, definitions] of next) good.set(name, definitions);
585 for (const name of taking) pending.delete(name);
586 const failed = yield* boot(gathered(next).flatMap((file) => file.definitions));
587 unstarted = failed !== null;
588 between = failed === null ? standing : [...standing, { message: failed }];
589 yield* report;
590 return true;
591 });
592​
593 retryLater = Effect.suspend(() => {
594 if (retrying) return Effect.void;
595 retrying = true;
596 return Effect.suspend(() => {
597 retrying = false;
598 return lock.withPermits(1)(reload());
599 }).pipe(
600 Effect.delay(LIST_RETRY),
601 Effect.catchCause((cause) =>
602 Effect.logWarning("Reloading workflow definitions failed", Cause.pretty(cause)),
603 ),
604 Effect.forkIn(outer),
605 Effect.asVoid,
606 );
607 });
608​
609 yield* lock.withPermits(1)(reload());
610 // No file defines anything yet, though runs kept from before may still be read.
611 if (!(yield* Deferred.isDone(ready))) yield* boot([]);
612​
613 // The folder, not a file: an editor that saves by renaming replaces the file it was watching.
614 // Its subfolders too, where shared helpers live, so a helper edit alone reaches the rescan.
615 // A watch that fails ends; `watchDirectoryPath` opens it again, and its first event rescans
616 // for edits made while nothing was watching.
617 const watchFolder = Stream.unwrap(
618 Effect.gen(function* () {
619 const watching = yield* Deferred.make<void>();
620 const onReady = () => Deferred.doneUnsafe(watching, Exit.void);
621 return Stream.merge(
622 fileSystem.watch(directory, { onReady, recursive: !single }).pipe(Stream.as(undefined)),
623 Stream.fromEffect(Deferred.await(watching)),
624 { haltStrategy: "left" },
625 );
626 }),
627 ).pipe(
628 Stream.catchCause((cause) =>
629 Cause.hasInterruptsOnly(cause)
630 ? Stream.empty
631 : Stream.fromEffectDrain(
632 Effect.logWarning(
633 "Workflow definitions are not watched for changes",
634 Cause.pretty(cause),
635 ),
636 ),
637 ),
638 );
639 yield* watchDirectoryPath(directory, watchFolder, Ref.getAndSet(directoryMissing, false)).pipe(
640 Stream.debounce(RELOAD_SETTLE),
641 Stream.runForEach(() =>
642 lock
643 .withPermits(1)(reload())
644 .pipe(
645 Effect.catchCause((cause) =>
646 Effect.logWarning("Reloading workflow definitions failed", Cause.pretty(cause)),
647 ),
648 ),
649 ),
650 Effect.forkIn(outer),
651 );
652​
653 yield* Effect.sleep(HELD_RETRY).pipe(
654 Effect.andThen(
655 Effect.suspend(() => (held.size > 0 ? lock.withPermits(1)(reload()) : Effect.void)),
656 ),
657 Effect.catchCause((cause) =>
658 Effect.logWarning("Reloading workflow definitions failed", Cause.pretty(cause)),
659 ),
660 Effect.forever,
661 Effect.forkIn(outer),
662 );
663​
664 const current = Effect.suspend(() => Deferred.await(ready));
665 // A watcher outlives the engine it began on: each reload hands it the next one's stream.
666 const followed = <A>(pick: (service: Workflows.Workflows["Service"]) => Stream.Stream<A>) =>
667 SubscriptionRef.changes(state).pipe(
668 Stream.switchMap((at) =>
669 Stream.unwrap(Effect.map(current, pick)).pipe(Stream.map((value) => [value, at] as const)),
670 ),
671 );
672 const service = Workflows.Workflows.of({
673 start: Effect.fn("Workflows.start")(function* (...input) {
674 return yield* (yield* current).start(...input);
675 }),
676 signal: Effect.fn("Workflows.signal")(function* (...input) {
677 return yield* (yield* current).signal(...input);
678 }),
679 answer: Effect.fn("Workflows.answer")(function* (...input) {
680 return yield* (yield* current).answer(...input);
681 }),
682 resume: Effect.fn("Workflows.resume")(function* (...input) {
683 return yield* (yield* current).resume(...input);
684 }),
685 cancel: Effect.fn("Workflows.cancel")(function* (...input) {
686 return yield* (yield* current).cancel(...input);
687 }),
688 withdraw: Effect.fn("Workflows.withdraw")(function* (...input) {
689 return yield* (yield* current).withdraw(...input);
690 }),
691 get: Effect.fn("Workflows.get")(function* (...input) {
692 return yield* (yield* current).get(...input);
693 }),
694 list: Effect.fn("Workflows.list")(function* (...input) {
695 return yield* (yield* current).list(...input);
696 }),
697 about: Effect.fn("Workflows.about")(function* (...input) {
698 return yield* (yield* current).about(...input);
699 }),
700 waitFor: Effect.fn("Workflows.waitFor")(function* (...input) {
701 // A reload replaces the engine, and a wait on the old one would never hear of the run again.
702 while (true) {
703 // Noted before the engine is read, so a reload that lands in between is still heard of.
704 const { revision } = yield* SubscriptionRef.get(state);
705 const live = yield* current;
706 const reloaded = SubscriptionRef.changes(state).pipe(
707 Stream.filter((at) => at.revision !== revision),
708 Stream.runHead,
709 );
710 const waited = yield* live
711 .waitFor(...input)
712 .pipe(Effect.asSome, Effect.raceFirst(Effect.as(reloaded, Option.none())));
713 if (Option.isSome(waited)) return waited.value;
714 }
715 }),
716 questions: Effect.flatMap(current, (live) => live.questions),
717 unfinished: Effect.flatMap(current, (live) => live.unfinished),
718 hooks: Effect.flatMap(current, (live) => live.hooks),
719 deliver: Effect.fn("Workflows.deliver")(function* (...input) {
720 return yield* (yield* current).deliver(...input);
721 }),
722 stored: Effect.fn("Workflows.stored")(function* (...input) {
723 return yield* (yield* current).stored(...input);
724 }),
725 storeSet: Effect.fn("Workflows.storeSet")(function* (...input) {
726 return yield* (yield* current).storeSet(...input);
727 }),
728 storeDelete: Effect.fn("Workflows.storeDelete")(function* (...input) {
729 return yield* (yield* current).storeDelete(...input);
730 }),
731 // Every reload starts a watcher over on a whole list, which is where the definition rides.
732 watch: followed((live) => live.watch).pipe(
733 Stream.map(([update, at]) => ("_tag" in update ? update : { ...update, definition: at })),
734 ),
735 counts: followed((live) => live.counts).pipe(Stream.map(([counts]) => counts)),
736 sweep: Effect.flatMap(current, (live) => live.sweep),
737 });
738​
739 const alone = { message: `This server reads its workflows from ${target} alone.` };
740 /** Why `name` cannot be a file here, if it cannot. */
741 const refused = (name: string): WorkflowDefinitionProblem | undefined =>
742 single && name !== path.basename(target)
743 ? alone
744 : DEFINITION_FILE.test(name)
745 ? undefined
746 : { message: NAMING };
747 /** What is wrong with the folder once `change` is made to the files that load. */
748 const wouldBreak = Effect.fn("WorkflowRuntime.wouldBreak")(function* (
749 change: (files: Map<string, ReadonlyArray<WorkflowDefinition>>) => void,
750 ) {
751 const files = new Map(good);
752 change(files);
753 return definitionProblems(gathered(files), yield* unfinished, good).map(
754 (entry) => entry.problem,
755 );
756 });
757​
758 const refusal = (problems: ReadonlyArray<WorkflowDefinitionProblem>) => ({
759 changed: false,
760 problems,
761 });
762 /** What keeps a change to the file `name` from running, once it is made on disk. */
763 const taken = Effect.fn("WorkflowRuntime.taken")(function* (name: string) {
764 const listed = yield* reload();
765 const problem = broken.get(name);
766 return {
767 changed: true,
768 problems: listed
769 ? [...(problem === undefined ? [] : [problem]), ...(held.get(name) ?? []), ...between]
770 : [{ message: `${directory} could not be read just now, so the change does not run yet.` }],
771 };
772 });
773​
774 const save = Effect.fn("WorkflowRuntime.save")(function* (name: string, source: string) {
775 const no = refused(name);
776 if (no !== undefined) return refusal([no]);
777 const file = path.join(directory, name);
778 // Beside the real file, so what it imports resolves the same way. The dot keeps it out.
779 const draft = path.join(directory, `.${name}.check-${loads + 1}${path.extname(name)}`);
780 const checked = yield* fileSystem.writeFileString(draft, source).pipe(
781 Effect.andThen(load(draft, name)),
782 Effect.ensuring(Effect.ignore(fileSystem.remove(draft))),
783 Effect.catchTags({
784 PlatformError: (error) =>
785 Effect.succeed({
786 problem: { message: `Could not write in ${directory}: ${text(error)}` },
787 } as const),
788 }),
789 );
790 if (!("definitions" in checked)) return refusal([checked.problem]);
791 const definitions = checked.definitions;
792 const problems = yield* wouldBreak((files) => files.set(name, definitions));
793 if (problems.length > 0) return refusal(problems);
794 const written = yield* fileSystem.writeFileString(file, source).pipe(Effect.result);
795 if (written._tag === "Failure") {
796 return refusal([{ message: `Could not write ${file}: ${text(written.failure)}` }]);
797 }
798 return yield* taken(name);
799 });
800​
801 const remove = Effect.fn("WorkflowRuntime.remove")(function* (name: string) {
802 const no = single ? alone : refused(name);
803 if (no !== undefined) return refusal([no]);
804 const problems = yield* wouldBreak((files) => files.delete(name));
805 if (problems.length > 0) return refusal(problems);
806 const removed = yield* fileSystem.remove(path.join(directory, name)).pipe(Effect.result);
807 if (removed._tag === "Failure") {
808 return refusal([{ message: `Could not delete ${name}: ${text(removed.failure)}` }]);
809 }
810 return yield* taken(name);
811 });
812​
813 return Context.make(Workflows.Workflows, service).pipe(
814 Context.add(
815 WorkflowDefinitions,
816 WorkflowDefinitions.of({
817 read: Effect.gen(function* () {
818 const files = yield* Effect.forEach(
819 yield* Effect.orElseSucceed(names, () => []),
820 (name) =>
821 fileSystem.readFileString(path.join(directory, name)).pipe(
822 Effect.orElseSucceed(() => ""),
823 Effect.map((source) => {
824 const problem = broken.get(name);
825 return {
826 name,
827 source,
828 workflows: (good.get(name) ?? []).map(engineTag),
829 problems: [
830 ...(problem === undefined ? [] : [problem]),
831 ...(held.get(name) ?? []),
832 ],
833 };
834 }),
835 ),
836 );
837 const at = yield* SubscriptionRef.get(state);
838 // A file held back after it was deleted has no entry of its own to say so.
839 const gone = [...held]
840 .filter(([name]) => !files.some((file) => file.name === name))
841 .flatMap(([, problems]) => problems);
842 return { directory, single, files, problems: [...misnamed, ...between, ...gone], ...at };
843 }),
844 save: Effect.fn("WorkflowDefinitions.save")(function* (name, source) {
845 return yield* lock.withPermits(1)(save(name, source));
846 }),
847 remove: Effect.fn("WorkflowDefinitions.remove")(function* (name) {
848 return yield* lock.withPermits(1)(remove(name));
849 }),
850 }),
851 ),
852 );
853});
854​
855/**
856 * Workflows behind the Labs switch. While off, `runtime` is not run: no definition file loads and
857 * no engine runs, and every request is refused. Turning on runs it in a scope of its own, which
858 * turning off closes; runs stay stored and go on once it is on again. `where` is as for `make`.
859 */
860export const gate = Effect.fn("WorkflowRuntime.gate")(function* <E, R>(
861 runtime: Effect.Effect<
862 Context.Context<Workflows.Workflows | WorkflowDefinitions>,
863 E,
864 R | Scope.Scope
865 >,
866 where: string,
867) {
868 const path = yield* Path.Path;
869 const outer = yield* Scope.Scope;
870 const services = yield* Effect.context<R>();
871 const target = path.resolve(where);
872 const single = DEFINITION_FILE.test(path.basename(target));
873 const off = { message: Workflows.OFF };
874 const offDefinitions = WorkflowDefinitions.of({
875 read: Effect.succeed({
876 directory: single ? path.dirname(target) : target,
877 single,
878 files: [],
879 problems: [off],
880 revision: 0,
881 problem: null,
882 }),
883 save: Effect.fn("WorkflowDefinitions.save")(function* () {
884 return yield* Effect.succeed({ changed: false, problems: [off] });
885 }),
886 remove: Effect.fn("WorkflowDefinitions.remove")(function* () {
887 return yield* Effect.succeed({ changed: false, problems: [off] });
888 }),
889 });
890 const offContext = Context.make(Workflows.Workflows, Workflows.off).pipe(
891 Context.add(WorkflowDefinitions, offDefinitions),
892 );
893​
894 const lock = yield* Semaphore.make(1);
895 let ready = Deferred.makeUnsafe<Context.Context<Workflows.Workflows | WorkflowDefinitions>>();
896 Deferred.doneUnsafe(ready, Exit.succeed(offContext));
897 let scope: Scope.Closeable | undefined;
898 const turns = yield* SubscriptionRef.make(0);
899​
900 const turn = Effect.fn("WorkflowRuntime.turn")(
901 function* (on: boolean) {
902 if (on === (scope !== undefined)) return;
903 const next =
904 Deferred.makeUnsafe<Context.Context<Workflows.Workflows | WorkflowDefinitions>>();
905 ready = next;
906 if (scope !== undefined) yield* Scope.close(scope, Exit.void);
907 scope = undefined;
908 if (on) {
909 const opened = yield* Scope.fork(outer);
910 const started = yield* runtime.pipe(
911 Effect.provideService(Scope.Scope, opened),
912 Effect.provideContext(services),
913 Effect.exit,
914 );
915 if (Exit.isSuccess(started)) {
916 scope = opened;
917 yield* Deferred.succeed(next, started.value);
918 } else {
919 yield* Scope.close(opened, Exit.void);
920 yield* Effect.logWarning("Workflows did not start", Cause.pretty(started.cause));
921 }
922 }
923 if (scope === undefined) yield* Deferred.succeed(next, offContext);
924 yield* SubscriptionRef.update(turns, (count) => count + 1);
925 yield* Effect.logInfo(scope === undefined ? "Workflows are off" : "Workflows are on");
926 },
927 // Once `ready` is replaced it must be settled, or every caller waits on it for good.
928 Effect.uninterruptible,
929 lock.withPermits(1),
930 );
931​
932 const live = Effect.suspend(() => Deferred.await(ready));
933 const current = Effect.map(live, Context.get(Workflows.Workflows));
934 const definitions = Effect.map(live, Context.get(WorkflowDefinitions));
935 // A watcher outlives a turn: each one hands it the next service's stream.
936 const followed = <A>(pick: (service: Workflows.Workflows["Service"]) => Stream.Stream<A>) =>
937 SubscriptionRef.changes(turns).pipe(
938 Stream.switchMap(() => Stream.unwrap(Effect.map(current, pick))),
939 );
940 const service = Workflows.Workflows.of({
941 start: Effect.fn("Workflows.start")(function* (...input) {
942 return yield* (yield* current).start(...input);
943 }),
944 signal: Effect.fn("Workflows.signal")(function* (...input) {
945 return yield* (yield* current).signal(...input);
946 }),
947 answer: Effect.fn("Workflows.answer")(function* (...input) {
948 return yield* (yield* current).answer(...input);
949 }),
950 resume: Effect.fn("Workflows.resume")(function* (...input) {
951 return yield* (yield* current).resume(...input);
952 }),
953 cancel: Effect.fn("Workflows.cancel")(function* (...input) {
954 return yield* (yield* current).cancel(...input);
955 }),
956 withdraw: Effect.fn("Workflows.withdraw")(function* (...input) {
957 return yield* (yield* current).withdraw(...input);
958 }),
959 get: Effect.fn("Workflows.get")(function* (...input) {
960 return yield* (yield* current).get(...input);
961 }),
962 list: Effect.fn("Workflows.list")(function* (...input) {
963 return yield* (yield* current).list(...input);
964 }),
965 about: Effect.fn("Workflows.about")(function* (...input) {
966 return yield* (yield* current).about(...input);
967 }),
968 waitFor: Effect.fn("Workflows.waitFor")(function* (...input) {
969 // Off, nothing changes a run; a wait goes on once workflows are on again.
970 while (true) {
971 const turned = yield* SubscriptionRef.get(turns);
972 const service = yield* current;
973 const next = SubscriptionRef.changes(turns).pipe(
974 Stream.filter((count) => count !== turned),
975 Stream.runHead,
976 );
977 const waited = yield* service
978 .waitFor(...input)
979 .pipe(Effect.asSome, Effect.raceFirst(Effect.as(next, Option.none())));
980 if (Option.isSome(waited)) return waited.value;
981 }
982 }),
983 questions: Effect.flatMap(current, (service) => service.questions),
984 unfinished: Effect.flatMap(current, (service) => service.unfinished),
985 hooks: Effect.flatMap(current, (service) => service.hooks),
986 deliver: Effect.fn("Workflows.deliver")(function* (...input) {
987 return yield* (yield* current).deliver(...input);
988 }),
989 stored: Effect.fn("Workflows.stored")(function* (...input) {
990 return yield* (yield* current).stored(...input);
991 }),
992 storeSet: Effect.fn("Workflows.storeSet")(function* (...input) {
993 return yield* (yield* current).storeSet(...input);
994 }),
995 storeDelete: Effect.fn("Workflows.storeDelete")(function* (...input) {
996 return yield* (yield* current).storeDelete(...input);
997 }),
998 watch: followed((service) => service.watch),
999 counts: followed((service) => service.counts),
1000 sweep: Effect.flatMap(current, (service) => service.sweep),
1001 });
1002​
1003 return {
1004 turn,
1005 context: Context.make(Workflows.Workflows, service).pipe(
1006 Context.add(
1007 WorkflowDefinitions,
1008 WorkflowDefinitions.of({
1009 read: Effect.flatMap(definitions, (files) => files.read),
1010 save: Effect.fn("WorkflowDefinitions.save")(function* (name, source) {
1011 return yield* (yield* definitions).save(name, source);
1012 }),
1013 remove: Effect.fn("WorkflowDefinitions.remove")(function* (name) {
1014 return yield* (yield* definitions).remove(name);
1015 }),
1016 }),
1017 ),
1018 ),
1019 };
1020});
1021​
1022/**
1023 * The workflow service for this server, and its definition files: those in the `workflows`
1024 * folder of the T3 home, or wherever `T3CODE_WORKFLOWS` points instead. A file that does not
1025 * load is reported and never stops the server. Nothing runs until `workflowsEnabled` is on.
1026 */
1027export const layer = Layer.effectContext(
1028 Effect.gen(function* () {
1029 const override = yield* definitionsOverride;
1030 const config = yield* ServerConfig.ServerConfig;
1031 const forge = Layer.succeed(WorkflowForge.WorkflowForge, yield* WorkflowForge.WorkflowForge);
1032 const sql = yield* SqlClient.SqlClient;
1033 const settings = yield* ServerSettings.ServerSettingsService;
1034 const where = Option.getOrElse(override, () => config.workflowsDir);
1035 const changes = yield* settings.subscribeChanges;
1036 const gated = yield* gate(
1037 make(
1038 Effect.map(
1039 Effect.promise((): Promise<typeof WorkflowEngine> => import("./WorkflowEngine.ts")),
1040 (engine) => (definitions) =>
1041 engine
1042 .layer(definitions)
1043 .pipe(Layer.provide(WorkflowAgentThreads.layer), Layer.provide(forge)),
1044 ),
1045 where,
1046 sql`SELECT 1 FROM workflow_runs LIMIT 1`.pipe(
1047 Effect.map((rows) => rows.length > 0),
1048 Effect.orElseSucceed(() => true),
1049 ),
1050 ),
1051 where,
1052 );
1053 const enabled = yield* settings.getSettings.pipe(
1054 Effect.map((current) => current.workflowsEnabled),
1055 Effect.orElseSucceed(() => false),
1056 );
1057 yield* gated.turn(enabled);
1058 yield* changes.pipe(
1059 Stream.map((current) => current.workflowsEnabled),
1060 Stream.runForEach(gated.turn),
1061 Effect.forkScoped,
1062 );
1063 return gated.context;
1064 }),