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

WorkflowRuntime.test.ts

1,024 lines46.4 KB

1import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import { assert, it } from "@effect/vitest";
4import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
5import * as Context from "effect/Context";
6import * as Deferred from "effect/Deferred";
7import * as Effect from "effect/Effect";
8import * as Exit from "effect/Exit";
9import * as Fiber from "effect/Fiber";
10import * as FileSystem from "effect/FileSystem";
11import * as Layer from "effect/Layer";
12import * as Latch from "effect/Latch";
13import * as Option from "effect/Option";
14import * as Queue from "effect/Queue";
15import * as Path from "effect/Path";
16import * as PlatformError from "effect/PlatformError";
17import * as Stream from "effect/Stream";
18import * as TestClock from "effect/testing/TestClock";
19import { ChildProcess, ChildProcessSpawner } from "effect/process";
20​
21import WorkflowsMigration from "../persistence/Migrations/110_Workflows.ts";
22import WorkflowSkippedRunsMigration from "../persistence/Migrations/113_WorkflowSkippedRuns.ts";
23import WorkflowRunTagsMigration from "../persistence/Migrations/115_WorkflowRunTags.ts";
24import WorkflowMailSenderMigration from "../persistence/Migrations/117_WorkflowMailSender.ts";
25import WorkflowPoolsMigration from "../persistence/Migrations/118_WorkflowPools.ts";
26import WorkflowRunSubjectMigration from "../persistence/Migrations/119_WorkflowRunSubject.ts";
27import WorkflowOpenedRunReceiptsMigration from "../persistence/Migrations/122_WorkflowOpenedRunReceipts.ts";
28import WorkflowRunTagIndexMigration from "../persistence/Migrations/123_WorkflowRunTagIndex.ts";
29import { type AgentResult, WorkflowAgentError, WorkflowAgents } from "./WorkflowAgents.ts";
30import * as WorkflowEngine from "./WorkflowEngine.ts";
31import * as WorkflowRuntime from "./WorkflowRuntime.ts";
32import { engineTag, type WorkflowDefinition } from "./workflow.ts";
33import * as Workflows from "./Workflows.ts";
34import * as WorkflowStore from "./WorkflowStore.ts";
35​
36/** Waits to be let go. */
37const hold = `T3.workflow("hold", { version: 1, payload: Schema.Struct({}), returns: Schema.String }, () =>
38 Effect.map(T3.wait("go", { returns: Schema.String }), (said) => Option.getOrElse(said, () => "nobody")),
39);
40`;
41const greet = (says: string) => `const { workflow } = T3;
42workflow("greet", { version: 1, payload: Schema.Struct({}), returns: Schema.String }, () =>
43 Effect.succeed(${JSON.stringify(says)}),
44);
45`;
46​
47/**
48 * A folder holding `hold.ts`, and the workflow runtime over it on a fresh database. `engine`
49 * stands in for the real one, which needs the clock to run for as long as it is up.
50 */
51const setup = Effect.fn("setup")(function* (
52 wrap: (
53 fileSystem: FileSystem.FileSystem,
54 folder: { readonly path: string; readonly info: FileSystem.File.Info },
55 ) => FileSystem.FileSystem = (fileSystem) => fileSystem,
56 engine?: (definitions: ReadonlyArray<WorkflowDefinition>) => Layer.Layer<Workflows.Workflows>,
57 agents?: WorkflowAgents["Service"],
58 store?: typeof WorkflowStore.layer,
59) {
60 const fileSystem = yield* FileSystem.FileSystem;
61 const path = yield* Path.Path;
62 const home = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-workflow-defs-" });
63 const directory = path.join(home, "workflows");
64 const at = (name: string) => path.join(directory, name);
65 yield* fileSystem.makeDirectory(directory);
66 yield* fileSystem.writeFileString(at("hold.ts"), hold);
67 const database = NodeSqliteClient.layer({ filename: path.join(home, "state.sqlite") });
68 yield* Effect.provide(
69 Effect.andThen(WorkflowsMigration, WorkflowSkippedRunsMigration).pipe(
70 Effect.andThen(WorkflowRunTagsMigration),
71 Effect.andThen(WorkflowMailSenderMigration),
72 Effect.andThen(WorkflowPoolsMigration),
73 Effect.andThen(WorkflowRunSubjectMigration),
74 Effect.andThen(WorkflowOpenedRunReceiptsMigration),
75 Effect.andThen(WorkflowRunTagIndexMigration),
76 ),
77 database,
78 );
79 const folder = { path: directory, info: yield* fileSystem.stat(directory) };
80 const made = WorkflowRuntime.make(
81 Effect.succeed(
82 (definitions: ReadonlyArray<WorkflowDefinition>) =>
83 engine?.(definitions) ??
84 WorkflowEngine.layer(definitions, store).pipe(
85 Layer.provide(
86 agents === undefined
87 ? Layer.mock(WorkflowAgents)({})
88 : Layer.succeed(WorkflowAgents, agents),
89 ),
90 Layer.provide(database),
91 Layer.provide(NodeCrypto.layer),
92 ),
93 ),
94 directory,
95 Effect.succeed(true),
96 ).pipe(Effect.provideService(FileSystem.FileSystem, wrap(fileSystem, folder)));
97 return { fileSystem, at, directory, made, runtime: Layer.effectContext(made) };
98});
99​
100it.effect(
101 "every file in the folder defines workflows, and a saved file is verified before it runs",
102 () =>
103 Effect.gen(function* () {
104 const changed = yield* Queue.unbounded<FileSystem.WatchEvent>();
105 const { fileSystem, at, runtime } = yield* setup((fileSystem) => ({
106 ...fileSystem,
107 watch: () => Stream.fromQueue(changed),
108 }));
109 const writeOutside = (name: string, contents: string) =>
110 fileSystem
111 .writeFileString(at(name), contents)
112 .pipe(Effect.andThen(Queue.offer(changed, { _tag: "Update", path: at(name) })));
113​
114 yield* Effect.gen(function* () {
115 const workflows = yield* Workflows.Workflows;
116 const definitions = yield* WorkflowRuntime.WorkflowDefinitions;
117 const held = yield* workflows.start("hold", {}, { idempotencyKey: "h" });
118 yield* workflows.waitFor(held.runId, (run) => run.status === "waiting");
119​
120 // A file that does not parse is not written, and says where it breaks.
121 const broken = yield* definitions.save("greet.ts", "T3.workflow(\n 'x',\n];\n");
122 assert.isFalse(broken.changed);
123 assert.deepStrictEqual(
124 broken.problems.map((problem) => [problem.file, problem.line]),
125 [["greet.ts", 3]],
126 );
127 // Nor is one that defines what another file already does, or drops what a run needs.
128 const twice = yield* definitions.save("again.ts", hold);
129 assert.include(
130 twice.problems[0]?.message ?? "",
131 "hold@1 is defined twice, in again.ts and hold.ts",
132 );
133 const dropped = yield* definitions.save("hold.ts", greet("hello"));
134 assert.include(
135 dropped.problems[0]?.message ?? "",
136 "hold@1 is no longer defined, and 1 of its runs",
137 );
138 // Nor one that exports something shaped like a workflow without what the engine walks.
139 const shaped = yield* definitions.save(
140 "shaped.ts",
141 'export default [{ name: "shaped", version: 1, body: () => Effect.void }];\n',
142 );
143 assert.include(shaped.problems[0]?.message ?? "", "is not a workflow");
144 // Nor one with an option nothing reads, or a time a schedule cannot fire at.
145 const misspelt = yield* definitions.save(
146 "misspelt.ts",
147 'T3.workflow("misspelt", { version: 1, payload: Schema.Struct({}), retries: 2 }, () => Effect.void);\n',
148 );
149 assert.include(misspelt.problems[0]?.message ?? "", "does not take `retries`");
150 const late = yield* definitions.save(
151 "late.ts",
152 'T3.workflow("late", { version: 1, payload: T3.Tick, triggers: [T3.daily("9am")] }, () => Effect.void);\n',
153 );
154 assert.include(late.problems[0]?.message ?? "", "24-hour time");
155 const banana = yield* definitions.save(
156 "banana.ts",
157 'T3.workflow("banana", { version: 1, payload: T3.Tick, triggers: [T3.every("banana")] }, () => Effect.void);\n',
158 );
159 assert.include(banana.problems[0]?.message ?? "", 'Write one such as "5 minutes"');
160 const twoHooks = yield* definitions.save(
161 "hooks.ts",
162 'T3.workflow("hooks", { version: 1, payload: T3.WebhookRequest, triggers: [T3.webhook("in"), T3.webhook("in")] }, () => Effect.void);\n',
163 );
164 assert.include(twoHooks.problems[0]?.message ?? "", 'two hooks named "in"');
165 assert.include((yield* definitions.remove("hold.ts")).problems[0]?.message ?? "", "hold@1");
166 assert.deepStrictEqual(
167 (yield* definitions.read).files.map((file) => file.name),
168 ["hold.ts"],
169 );
170 // The same change made outside the app is refused as a whole: the file still reads as the
171 // version that runs, until it is put back.
172 const told = (wanted: boolean) =>
173 Workflows.wholeLists(workflows.watch).pipe(
174 Stream.filter((snapshot) => (snapshot.definition?.problem != null) === wanted),
175 Stream.runHead,
176 );
177 yield* writeOutside("hold.ts", greet("hello"));
178 yield* told(true);
179 assert.deepStrictEqual(
180 (yield* definitions.read).files.map((file) => file.workflows),
181 [["hold@1"]],
182 );
183 // Only that file is held back: another file's change still runs, and the held one says why.
184 const other =
185 'T3.workflow("other", { version: 1, payload: Schema.Struct({}) }, () => Effect.void);\n';
186 // A file the folder's naming leaves out says so, instead of never running without a word.
187 yield* fileSystem.writeFileString(at("my flow.ts"), other);
188 assert.deepStrictEqual(yield* definitions.save("other.ts", other), {
189 changed: true,
190 problems: [],
191 });
192 yield* workflows.start("other", {}, { idempotencyKey: "o" });
193 assert.deepStrictEqual(
194 (yield* definitions.read).files.map((file) => [file.name, file.problems.length]),
195 [
196 ["hold.ts", 1],
197 ["other.ts", 0],
198 ],
199 );
200 assert.deepStrictEqual(
201 (yield* definitions.read).problems.map((problem) => problem.file),
202 ["my flow.ts"],
203 );
204 yield* fileSystem.remove(at("my flow.ts"));
205 assert.deepStrictEqual(yield* definitions.remove("other.ts"), {
206 changed: true,
207 problems: [],
208 });
209 yield* writeOutside("hold.ts", hold);
210 yield* told(false);
211 // A change outside the app that defines a version twice in one file is held back too.
212 yield* writeOutside("hold.ts", hold + hold);
213 yield* told(true);
214 assert.deepStrictEqual(
215 (yield* definitions.read).files.map((file) => file.workflows),
216 [["hold@1"]],
217 );
218 yield* writeOutside("hold.ts", hold);
219 yield* told(false);
220​
221 // A new file that passes is there from now on, and what it defines can be started.
222 const saved = { changed: true, problems: [] };
223 assert.deepStrictEqual(yield* definitions.save("greet.ts", greet("hello")), saved);
224 assert.equal(yield* fileSystem.readFileString(at("greet.ts")), greet("hello"));
225 const greeted = yield* workflows.start("greet", {}, { idempotencyKey: "g" });
226 const done = yield* workflows.waitFor(greeted.runId, (run) => run.status === "completed");
227 assert.equal(done.result, "hello");
228 // The run that was waiting came through the reload and can still be let go.
229 yield* workflows.signal({ runId: held.runId, wait: "go" }, "go on", { id: "s1" });
230 const freed = yield* workflows.waitFor(held.runId, (run) => run.status === "completed");
231 assert.equal(freed.result, "go on");
232​
233 // Someone breaks a file outside the app: its last good version keeps running, and the
234 // other files go on changing.
235 const problem = (wanted: boolean) =>
236 Workflows.wholeLists(workflows.watch).pipe(
237 Stream.filter((snapshot) => (snapshot.definition?.problem != null) === wanted),
238 Stream.runHead,
239 );
240 yield* writeOutside("greet.ts", "T3.workflow(");
241 yield* problem(true);
242 const read = yield* definitions.read;
243 assert.deepStrictEqual(
244 read.files.map((file) => [file.name, file.problems.length]),
245 [
246 ["greet.ts", 1],
247 ["hold.ts", 0],
248 ],
249 );
250 const still = yield* workflows.start("greet", {}, { idempotencyKey: "g2" });
251 assert.equal(
252 (yield* workflows.waitFor(still.runId, (run) => run.status === "completed")).result,
253 "hello",
254 );
255 // And fixes it, saying something else, this time as the file's one default export.
256 yield* writeOutside(
257 "greet.ts",
258 greet("hi").replace("\nworkflow(", "\nexport default workflow("),
259 );
260 yield* problem(false);
261 const fixed = yield* workflows.start("greet", {}, { idempotencyKey: "g3" });
262 assert.equal(
263 (yield* workflows.waitFor(fixed.runId, (run) => run.status === "completed")).result,
264 "hi",
265 );
266 // A file taken away takes its workflows with it.
267 assert.deepStrictEqual(yield* definitions.remove("greet.ts"), saved);
268 const gone = yield* workflows
269 .start("greet", {}, { idempotencyKey: "g4" })
270 .pipe(Effect.flip);
271 assert.equal(gone._tag, "WorkflowNotRegisteredError");
272 // With no file left, nothing runs, and the runs that ended can still be read.
273 assert.deepStrictEqual(yield* definitions.remove("hold.ts"), saved);
274 assert.equal((yield* workflows.get(held.runId)).run.status, "completed");
275 assert.includeMembers(
276 (yield* workflows.list()).map((run) => run.runId),
277 [held.runId, greeted.runId],
278 );
279 }).pipe(
280 Effect.provide(runtime),
281 Effect.scoped,
282 Effect.raceFirst(Effect.forever(TestClock.adjust("1 second"))),
283 );
284 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
285);
286​
287it.effect(
288 "a folder that cannot be listed keeps its workflows and is looked at again, and an engine that cannot start leaves the last one running",
289 () =>
290 Effect.gen(function* () {
291 let refuse = false;
292 // What each engine was built to run. One that registers `broken` does not come up.
293 const builds: Array<ReadonlyArray<string>> = [];
294 // No file events: only the runtime's own retry can pick up what changed.
295 const { at, fileSystem, runtime } = yield* setup(
296 (real) => ({
297 ...real,
298 exists: (target) =>
299 refuse
300 ? Effect.fail(
301 PlatformError.systemError({
302 _tag: "PermissionDenied",
303 module: "FileSystem",
304 method: "exists",
305 pathOrDescriptor: target,
306 }),
307 )
308 : real.exists(target),
309 watch: () => Stream.never,
310 }),
311 (definitions) =>
312 definitions.some((definition) => definition.name === "broken")
313 ? Layer.effect(Workflows.Workflows, Effect.die(new Error("broken took it down")))
314 : Layer.sync(Workflows.Workflows, () => {
315 builds.push(definitions.map(engineTag));
316 return Workflows.disabled;
317 }),
318 );
319​
320 yield* Effect.gen(function* () {
321 const workflows = yield* Workflows.Workflows;
322 const definitions = yield* WorkflowRuntime.WorkflowDefinitions;
323 const revision = Effect.map(
324 Stream.runHead(Workflows.wholeLists(workflows.watch)),
325 (snapshot) => Option.getOrThrow(snapshot).definition?.revision ?? 0,
326 );
327 refuse = true;
328 // Written, but the folder could not be listed, so it is not said to run.
329 const unlisted = yield* definitions.save("greet.ts", greet("hi"));
330 assert.isTrue(unlisted.changed);
331 assert.include(unlisted.problems[0]?.message ?? "", "could not be read");
332 // What was loaded stays, and greet is not taken in yet.
333 assert.deepStrictEqual(builds, [["hold@1"]]);
334 const before = yield* revision;
335 refuse = false;
336 yield* TestClock.adjust("30 seconds");
337 yield* Workflows.wholeLists(workflows.watch).pipe(
338 Stream.filter((snapshot) => (snapshot.definition?.revision ?? 0) > before),
339 Stream.runHead,
340 );
341 assert.deepStrictEqual(builds.at(-1), ["greet@1", "hold@1"]);
342​
343 // A definition that passes the checks but takes the engine down at start changes nothing.
344 yield* fileSystem.writeFileString(
345 at("broken.ts"),
346 'T3.workflow("broken", { version: 1, payload: Schema.Struct({}) }, () => Effect.void);\n',
347 );
348 const fellBack = yield* definitions.save("greet.ts", greet("hello"));
349 assert.isTrue(fellBack.changed);
350 assert.include(fellBack.problems[0]?.message ?? "", "did not start");
351 assert.deepStrictEqual(builds.slice(1), [
352 ["greet@1", "hold@1"],
353 ["greet@1", "hold@1"],
354 ]);
355 assert.include(
356 (yield* Stream.runHead(Workflows.wholeLists(workflows.watch))).pipe(Option.getOrThrow)
357 .definition?.problem ?? "",
358 "did not start",
359 );
360 }).pipe(Effect.provide(runtime), Effect.scoped);
361 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
362);
363​
364it.effect("a file that never finishes loading is given up on, and later files still load", () =>
365 Effect.gen(function* () {
366 const { at, fileSystem } = yield* setup();
367 yield* fileSystem.writeFileString(at("stuck.ts"), "await new Promise(() => {});\n");
368 yield* fileSystem.writeFileString(at("greet.ts"), greet("hi"));
369 const stuck = yield* WorkflowRuntime.loadDefinitions(at("stuck.ts"), 0, 50).pipe(Effect.flip);
370 assert.include(String(stuck.cause), "did not finish loading");
371 const loaded = yield* WorkflowRuntime.loadDefinitions(at("greet.ts"));
372 assert.deepStrictEqual(
373 loaded.map((definition) => definition.name),
374 ["greet"],
375 );
376 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
377);
378​
379it.effect("a file loads whatever kinds its asks name, and only a malformed `asks` is refused", () =>
380 Effect.gen(function* () {
381 const { at, fileSystem } = yield* setup();
382 const sorter = (asks: string) => `const { workflow, ask } = T3;
383workflow("sorter", { version: 1, payload: Schema.Struct({})${asks} }, () =>
384 ask("sort", { kind: "feture", title: "Which way?", choices: ["Yes", "No"] }),
385);
386`;
387 // A kind the workflow does not declare, and one on a workflow that declares none.
388 for (const asks of [', asks: { feature: "Feature wanted?" }', ""]) {
389 yield* fileSystem.writeFileString(at("sorter.ts"), sorter(asks));
390 const loaded = yield* WorkflowRuntime.loadDefinitions(at("sorter.ts"), asks.length);
391 assert.deepStrictEqual(
392 loaded.map((definition) => Object.keys(definition.asks)),
393 [asks === "" ? [] : ["feature"]],
394 );
395 }
396 yield* fileSystem.writeFileString(at("sorter.ts"), sorter(', asks: { feature: "" }'));
397 const refused = yield* WorkflowRuntime.loadDefinitions(at("sorter.ts"), 1).pipe(Effect.flip);
398 assert.include(String(refused.cause), 'asks gives the kind "feature" no label');
399 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
400);
401​
402it.effect("a file given up on registers nothing into the file that loads after it", () =>
403 Effect.gen(function* () {
404 const { at, fileSystem } = yield* setup();
405 yield* fileSystem.writeFileString(
406 at("slow.ts"),
407 'await new Promise((resolve) => { globalThis.t3TestResume = resolve; });\nT3.workflow("slow", { version: 1, payload: Schema.Struct({}) }, () => Effect.void);\n',
408 );
409 // The second file goes on loading until the first one's top level has run to its end.
410 yield* fileSystem.writeFileString(
411 at("next.ts"),
412 `${greet("hi")}globalThis.t3TestResume();\nawait new Promise((resolve) => setImmediate(resolve));\n`,
413 );
414 yield* WorkflowRuntime.loadDefinitions(at("slow.ts"), 0, 50).pipe(Effect.flip);
415 const loaded = yield* WorkflowRuntime.loadDefinitions(at("next.ts"));
416 assert.deepStrictEqual(
417 loaded.map((definition) => definition.name),
418 ["greet"],
419 );
420 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
421);
422​
423// Vitest's module runner loads a file its own way; only Node keeps a CommonJS file by its path.
424it.live("a file without imports or exports loads again after it changes", () =>
425 Effect.gen(function* () {
426 const { at, fileSystem } = yield* setup();
427 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
428 yield* fileSystem.writeFileString(at("greet.ts"), greet("hi"));
429 const twice = `
430 import * as NodeFS from "node:fs";
431 import * as NodeServices from "@effect/platform-node/NodeServices";
432 import * as Context from "effect/Context";
433import * as Effect from "effect/Effect";
434 import { loadDefinitions } from ${JSON.stringify(new URL("./WorkflowRuntime.ts", import.meta.url).href)};
435 const file = process.argv.at(-1);
436 const program = Effect.gen(function* () {
437 const first = yield* loadDefinitions(file, 1);
438 NodeFS.writeFileSync(file, NodeFS.readFileSync(file, "utf8").replace('"hi"', '"hello"'));
439 const second = yield* loadDefinitions(file, 2);
440 return [first.length, second.length];
441 });
442 console.log(JSON.stringify(await Effect.runPromise(Effect.provide(program, NodeServices.layer))));
443 `;
444 const child = yield* spawner.spawn(
445 ChildProcess.make(
446 process.execPath,
447 ["--input-type=module", "--eval", twice, at("greet.ts")],
448 { cwd: import.meta.dirname },
449 ),
450 );
451 const [stdout, stderr] = yield* Effect.all(
452 [
453 child.stdout.pipe(Stream.decodeText(), Stream.mkString),
454 child.stderr.pipe(Stream.decodeText(), Stream.mkString),
455 ],
456 { concurrency: "unbounded" },
457 );
458 assert.equal(stdout.trim(), "[1,1]", stderr);
459 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
460);
461​
462// Node keeps an imported module by its address, so a helper the file imports must load again too.
463it.live("a file loads again with the current version of the helpers it imports", () =>
464 Effect.gen(function* () {
465 const { at, fileSystem } = yield* setup();
466 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
467 yield* fileSystem.writeFileString(at("_helpers.ts"), 'export const x = "old";\n');
468 yield* fileSystem.writeFileString(
469 at("demo.ts"),
470 'import { x } from "./_helpers.ts";\nT3.workflow("demo", { version: 1, payload: Schema.Struct({}), returns: Schema.String }, () => Effect.succeed(x));\n',
471 );
472 const twice = `
473 import * as NodeFS from "node:fs";
474 import * as NodePath from "node:path";
475 import * as NodeServices from "@effect/platform-node/NodeServices";
476 import * as Effect from "effect/Effect";
477 import { loadDefinitions } from ${JSON.stringify(new URL("./WorkflowRuntime.ts", import.meta.url).href)};
478 const file = process.argv.at(-1);
479 const helpers = NodePath.join(NodePath.dirname(file), "_helpers.ts");
480 const program = Effect.gen(function* () {
481 const first = yield* loadDefinitions(file, 1);
482 NodeFS.writeFileSync(helpers, 'export const x = "new";\\nexport const y = "added";\\n');
483 NodeFS.writeFileSync(file, NodeFS.readFileSync(file, "utf8").replace("{ x }", "{ x, y }").replace("version: 1", "version: 2"));
484 const second = yield* loadDefinitions(file, 2).pipe(
485 Effect.map((loaded) => loaded.map((definition) => definition.version)),
486 Effect.catchCause((cause) => Effect.succeed(String(cause))),
487 );
488 return [first.map((definition) => definition.version), second];
489 });
490 console.log(JSON.stringify(await Effect.runPromise(Effect.provide(program, NodeServices.layer))));
491 `;
492 const child = yield* spawner.spawn(
493 ChildProcess.make(process.execPath, ["--input-type=module", "--eval", twice, at("demo.ts")], {
494 cwd: import.meta.dirname,
495 }),
496 );
497 const [stdout, stderr] = yield* Effect.all(
498 [
499 child.stdout.pipe(Stream.decodeText(), Stream.mkString),
500 child.stderr.pipe(Stream.decodeText(), Stream.mkString),
501 ],
502 { concurrency: "unbounded" },
503 );
504 assert.equal(stdout.trim(), "[[1],[2]]", stderr);
505 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
506);
507​
508it.live("a rescan takes a helper edit when the file that imports it is unchanged", () =>
509 Effect.gen(function* () {
510 const { at, directory, fileSystem } = yield* setup();
511 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
512 yield* fileSystem.remove(at("hold.ts"));
513 yield* fileSystem.writeFileString(at("_helpers.ts"), "export const version = 1;\n");
514 const demo =
515 'import { version } from "./_helpers.ts";\nT3.workflow("demo", { version, payload: Schema.Struct({}), returns: Schema.String }, () => Effect.succeed("x"));\n';
516 yield* fileSystem.writeFileString(at("demo.ts"), demo);
517 const rescan = `
518 import * as NodeFS from "node:fs";
519 import * as NodePath from "node:path";
520 import * as NodeServices from "@effect/platform-node/NodeServices";
521 import * as Context from "effect/Context";
522 import * as Effect from "effect/Effect";
523 import * as Layer from "effect/Layer";
524 import * as WorkflowRuntime from ${JSON.stringify(new URL("./WorkflowRuntime.ts", import.meta.url).href)};
525 import * as Workflows from ${JSON.stringify(new URL("./Workflows.ts", import.meta.url).href)};
526 const directory = process.argv.at(-2);
527 const demo = process.argv.at(-1);
528 const builds = [];
529 const program = Effect.gen(function* () {
530 const context = yield* WorkflowRuntime.make(
531 Effect.succeed((definitions) =>
532 Layer.sync(Workflows.Workflows, () => {
533 builds.push(definitions.map((definition) => definition.version));
534 return Workflows.disabled;
535 }),
536 ),
537 directory,
538 Effect.succeed(true),
539 );
540 NodeFS.writeFileSync(NodePath.join(directory, "_helpers.ts"), "export const version = 2;\\n");
541 const saved = yield* Context.get(context, WorkflowRuntime.WorkflowDefinitions).save("demo.ts", demo);
542 return { problems: saved.problems, builds };
543 });
544 console.log(JSON.stringify(await Effect.runPromise(Effect.scoped(Effect.provide(program, NodeServices.layer)))));
545 process.exit(0);
546 `;
547 const child = yield* spawner.spawn(
548 ChildProcess.make(
549 process.execPath,
550 ["--input-type=module", "--eval", rescan, directory, demo],
551 { cwd: import.meta.dirname },
552 ),
553 );
554 const [stdout, stderr] = yield* Effect.all(
555 [
556 child.stdout.pipe(Stream.decodeText(), Stream.mkString),
557 child.stderr.pipe(Stream.decodeText(), Stream.mkString),
558 ],
559 { concurrency: "unbounded" },
560 );
561 // Logs share stdout, so the result is its last line.
562 const { problems, builds } = JSON.parse(stdout.trim().split("\n").at(-1) || "{}");
563 assert.deepStrictEqual(problems, [], stderr);
564 assert.deepStrictEqual(builds?.at(-1), [2], stderr);
565 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
566);
567​
568it.live("the folder watch reloads a workflow when only a helper in a subfolder changes", () =>
569 Effect.gen(function* () {
570 const { at, directory, fileSystem } = yield* setup();
571 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
572 yield* fileSystem.remove(at("hold.ts"));
573 yield* fileSystem.makeDirectory(at("helpers"));
574 yield* fileSystem.writeFileString(at("helpers/version.ts"), "export const version = 1;\n");
575 yield* fileSystem.writeFileString(
576 at("demo.ts"),
577 'import { version } from "./helpers/version.ts";\nT3.workflow("demo", { version, payload: Schema.Struct({}), returns: Schema.String }, () => Effect.succeed("x"));\n',
578 );
579 const watched = `
580 import * as NodeFS from "node:fs";
581 import * as NodePath from "node:path";
582 import * as NodeServices from "@effect/platform-node/NodeServices";
583 import * as Effect from "effect/Effect";
584 import * as Layer from "effect/Layer";
585 import * as WorkflowRuntime from ${JSON.stringify(new URL("./WorkflowRuntime.ts", import.meta.url).href)};
586 import * as Workflows from ${JSON.stringify(new URL("./Workflows.ts", import.meta.url).href)};
587 const directory = process.argv.at(-1);
588 const builds = [];
589 let waiting;
590 const built = (tag) =>
591 new Promise((resolve) => {
592 waiting = { tag, resolve };
593 setTimeout(resolve, 15_000);
594 });
595 const program = Effect.gen(function* () {
596 yield* WorkflowRuntime.make(
597 Effect.succeed((definitions) =>
598 Layer.sync(Workflows.Workflows, () => {
599 const tags = definitions.map((definition) => definition.name + "@" + definition.version);
600 builds.push(tags);
601 if (waiting !== undefined && tags.includes(waiting.tag)) waiting.resolve();
602 return Workflows.disabled;
603 }),
604 ),
605 directory,
606 Effect.succeed(true),
607 );
608 // Only the watch loads a new file, so once it runs the watch is live.
609 const live = built("ready@1");
610 NodeFS.writeFileSync(
611 NodePath.join(directory, "ready.ts"),
612 'T3.workflow("ready", { version: 1, payload: Schema.Struct({}), returns: Schema.String }, () => Effect.succeed("x"));\\n',
613 );
614 yield* Effect.promise(() => live);
615 const reloaded = built("demo@2");
616 NodeFS.writeFileSync(NodePath.join(directory, "helpers", "version.ts"), "export const version = 2;\\n");
617 yield* Effect.promise(() => reloaded);
618 return builds;
619 });
620 console.log(JSON.stringify(await Effect.runPromise(Effect.scoped(Effect.provide(program, NodeServices.layer)))));
621 process.exit(0);
622 `;
623 const child = yield* spawner.spawn(
624 ChildProcess.make(process.execPath, ["--input-type=module", "--eval", watched, directory], {
625 cwd: import.meta.dirname,
626 }),
627 );
628 const [stdout, stderr] = yield* Effect.all(
629 [
630 child.stdout.pipe(Stream.decodeText(), Stream.mkString),
631 child.stderr.pipe(Stream.decodeText(), Stream.mkString),
632 ],
633 { concurrency: "unbounded" },
634 );
635 // Logs share stdout, so the result is its last line.
636 const builds = JSON.parse(stdout.trim().split("\n").at(-1) || "[]");
637 assert.deepStrictEqual(builds.at(-1), ["demo@2", "ready@1"], stderr);
638 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
639);
640​
641it.effect("loads a workflow edited on disk after the folder watch recovers", () =>
642 Effect.gen(function* () {
643 const lost = yield* Deferred.make<void>();
644 let attempts = 0;
645 const { fileSystem, at, runtime } = yield* setup(
646 (real, folder) => ({
647 ...real,
648 // The once-a-second probe that reopens the watch must not wait on real I/O: the test
649 // clock moves on without it, and the probe's next tick would never come.
650 stat: (entry) => (entry === folder.path ? Effect.succeed(folder.info) : real.stat(entry)),
651 readLink: (entry) =>
652 entry === folder.path
653 ? Effect.fail(
654 PlatformError.systemError({
655 _tag: "InvalidData",
656 module: "FileSystem",
657 method: "readLink",
658 pathOrDescriptor: entry,
659 }),
660 )
661 : real.readLink(entry),
662 watch: (directory, options) =>
663 Stream.unwrap(
664 Effect.suspend(() => {
665 if (++attempts > 1)
666 return Effect.succeed(
667 Stream.never.pipe(Stream.onStart(Effect.sync(() => options?.onReady?.()))),
668 );
669 return Effect.as(
670 Deferred.succeed(lost, undefined),
671 Stream.fail(
672 PlatformError.systemError({
673 _tag: "NotFound",
674 module: "FileSystem",
675 method: "watch",
676 pathOrDescriptor: directory,
677 }),
678 ),
679 );
680 }),
681 ),
682 }),
683 () => Layer.succeed(Workflows.Workflows, Workflows.disabled),
684 );
685 yield* Effect.gen(function* () {
686 const definitions = yield* WorkflowRuntime.WorkflowDefinitions;
687 const workflows = yield* Workflows.Workflows;
688 const before = (yield* definitions.read).revision;
689 yield* Deferred.await(lost);
690 yield* fileSystem.writeFileString(at("greet.ts"), greet("hello"));
691 // Recovery probes the folder with real I/O between ticks, so one big adjust can end before
692 // the next tick or the reload's debounce is waiting on the clock.
693 yield* Workflows.wholeLists(workflows.watch).pipe(
694 Stream.filter((snapshot) => (snapshot.definition?.revision ?? 0) > before),
695 Stream.runHead,
696 Effect.raceFirst(Effect.forever(TestClock.adjust("1 second"))),
697 );
698 const loaded = (yield* definitions.read).files.find((file) => file.name === "greet.ts");
699 assert.deepStrictEqual(loaded?.workflows, ["greet@1"]);
700 }).pipe(Effect.provide(runtime), Effect.scoped);
701 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
702);
703​
704it.effect("a change held back by a run goes in once that run ends, with no further edit", () =>
705 Effect.gen(function* () {
706 // The folder's changes are told by hand, so the test does not hang on a watcher starting.
707 const changed = yield* Queue.unbounded<FileSystem.WatchEvent>();
708 const { fileSystem, at, runtime } = yield* setup((fileSystem) => ({
709 ...fileSystem,
710 watch: () => Stream.fromQueue(changed),
711 }));
712 yield* Effect.gen(function* () {
713 const workflows = yield* Workflows.Workflows;
714 const definitions = yield* WorkflowRuntime.WorkflowDefinitions;
715 const held = yield* workflows.start("hold", {}, { idempotencyKey: "h" });
716 yield* workflows.waitFor(held.runId, (run) => run.status === "waiting");
717 const problem = (wanted: boolean) =>
718 Workflows.wholeLists(workflows.watch).pipe(
719 Stream.filter((snapshot) => (snapshot.definition?.problem != null) === wanted),
720 Stream.runHead,
721 );
722 yield* fileSystem.writeFileString(at("hold.ts"), greet("hello"));
723 yield* Queue.offer(changed, { _tag: "Update", path: at("hold.ts") });
724 yield* problem(true);
725 yield* workflows.signal({ runId: held.runId, wait: "go" }, "go on", { id: "s1" });
726 yield* workflows.waitFor(held.runId, (run) => run.status === "completed");
727 // Nothing is told of the folder now: the held change goes in on its own.
728 yield* problem(false);
729 assert.deepStrictEqual(
730 (yield* definitions.read).files.map((file) => file.workflows),
731 [["greet@1"]],
732 );
733 }).pipe(
734 Effect.provide(runtime),
735 Effect.scoped,
736 Effect.raceFirst(Effect.forever(TestClock.adjust("1 second"))),
737 );
738 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
739);
740​
741it.effect(
742 "a reload does not wait for an agent that is still at work, and its step ends with the turn",
743 () =>
744 Effect.gen(function* () {
745 const ended = yield* Deferred.make<AgentResult>();
746 const started = yield* Deferred.make<void>();
747 const { fileSystem, at, runtime } = yield* setup(undefined, undefined, {
748 start: (input) =>
749 Effect.as(Deferred.succeed(started, undefined), {
750 threadId: "thread",
751 turnId: input.key,
752 }),
753 result: () => Deferred.await(ended),
754 interrupt: () => Effect.succeed("stopped" as const),
755 });
756 yield* fileSystem.writeFileString(
757 at("helper.ts"),
758 `T3.workflow("helper", { version: 1, payload: Schema.Struct({}), returns: Schema.String }, () =>
759 Effect.map(T3.agent("work", { brief: "Do it.", project: "p" }), (done) => done.value),
760);
761`,
762 );
763 const ticking = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
764 Effect.raceFirst(effect, Effect.forever(TestClock.adjust("1 second")));
765 yield* Effect.gen(function* () {
766 const workflows = yield* Workflows.Workflows;
767 const definitions = yield* WorkflowRuntime.WorkflowDefinitions;
768 const helped = yield* ticking(
769 Effect.gen(function* () {
770 const run = yield* workflows.start("helper", {}, { idempotencyKey: "a" });
771 yield* Deferred.await(started);
772 yield* workflows.waitFor(run.runId, (row) => row.status === "waiting");
773 return run;
774 }),
775 );
776​
777 // The test clock stands still during the save, so an engine that waited for the agent's
778 // step to finish would never stop: the step is not given up on, and the turn does not end.
779 // The swap cannot be interrupted, so a stuck save is unblocked by ending the turn.
780 const saving = yield* Effect.forkChild(definitions.save("greet.ts", greet("hello")));
781 const saved = yield* Fiber.await(saving).pipe(
782 Effect.timeoutOption("10 seconds"),
783 TestClock.withLive,
784 );
785 if (Option.isNone(saved)) {
786 yield* Deferred.succeed(ended, { ending: "completed", detail: "", reply: "late" });
787 yield* ticking(Fiber.await(saving));
788 assert.fail("The reload waited for the agent's turn to end.");
789 }
790 assert.isTrue(Exit.isSuccess(saved.value) && saved.value.value.changed);
791 assert.equal((yield* workflows.get(helped.runId)).run.status, "waiting");
792​
793 // The turn ends after the reload, and the new engine carries its result into the run.
794 yield* Deferred.succeed(ended, { ending: "completed", detail: "", reply: "all done" });
795 const done = yield* ticking(
796 workflows.waitFor(helped.runId, (run) => run.status === "completed"),
797 );
798 assert.equal(done.result, "all done");
799 }).pipe(Effect.provide(runtime), Effect.scoped);
800 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
801);
802​
803it.effect("cancellation stops linked launches and corrections acknowledged late", () =>
804 Effect.gen(function* () {
805 for (const late of ["work/0", "work/0/correct/0"]) {
806 const started = yield* Deferred.make<void>();
807 const reply = yield* Deferred.make<void>();
808 const recorded = yield* Deferred.make<void>();
809 const stops: Array<Parameters<WorkflowAgents["Service"]["interrupt"]>[0]> = [];
810 const store = Layer.effect(
811 WorkflowStore.WorkflowStore,
812 Effect.map(WorkflowStore.make, (real) =>
813 WorkflowStore.WorkflowStore.of({
814 ...real,
815 stepThread: (...args) =>
816 real
817 .stepThread(...args)
818 .pipe(
819 Effect.tap(() =>
820 args[4].endsWith(`/${late}`)
821 ? Deferred.succeed(recorded, undefined)
822 : Effect.void,
823 ),
824 ),
825 }),
826 ),
827 );
828 const { fileSystem, at, runtime } = yield* setup(
829 undefined,
830 undefined,
831 {
832 start: (input) =>
833 (input.key.endsWith(`/${late}`)
834 ? Deferred.succeed(started, undefined).pipe(Effect.andThen(Deferred.await(reply)))
835 : Effect.void
836 ).pipe(Effect.as({ threadId: "thread", environment: "env-b", turnId: input.key })),
837 result: () => Effect.succeed({ ending: "completed", detail: "", reply: "" }),
838 interrupt: (turn) =>
839 Effect.sync(() => {
840 if (!turn.turnId?.endsWith(`/${late}`)) return "ended" as const;
841 stops.push(turn);
842 return "stopped" as const;
843 }),
844 },
845 store,
846 );
847 yield* fileSystem.writeFileString(
848 at("helper.ts"),
849 `T3.workflow("helper", { version: 1, payload: Schema.Struct({}) }, () =>
850 Effect.asVoid(T3.agent("work", { brief: "Do it.", project: "p", environment: "env-b", returns: Schema.Struct({ head: Schema.String }) })),
851);
852`,
853 );
854 yield* Effect.gen(function* () {
855 const workflows = yield* Workflows.Workflows;
856 const { runId } = yield* workflows.start("helper", {}, { idempotencyKey: late });
857 yield* Deferred.await(started);
858 yield* workflows.cancel(runId);
859 yield* Deferred.succeed(reply, undefined);
860 yield* Deferred.await(recorded);
861 yield* workflows.sweep;
862 assert.deepStrictEqual(stops, [
863 { threadId: "thread", environment: "env-b", turnId: `${runId}/${late}` },
864 ]);
865 }).pipe(
866 Effect.provide(runtime),
867 Effect.scoped,
868 Effect.raceFirst(Effect.forever(TestClock.adjust("1 second"))),
869 );
870 }
871 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
872);
873​
874const linkedWorkflow = (cleanup: boolean) => `T3.workflow("linked", {
875 version: 1, payload: Schema.Struct({})${cleanup ? ", onEnd: () => Effect.void" : ""}
876}, () => Effect.asVoid(T3.agent("work", { brief: "Do it.", project: "p", environment: "env-b" })));
877`;
878​
879it.effect("a pending stop survives removing the last workflow definition", () =>
880 Effect.gen(function* () {
881 const stopped = yield* Deferred.make<string | undefined>();
882 let online = false;
883 const { fileSystem, at, runtime } = yield* setup(undefined, undefined, {
884 start: (input) =>
885 Effect.succeed({ threadId: "thread", environment: "env-b", turnId: input.key }),
886 result: () => Effect.never,
887 interrupt: (turn) =>
888 Effect.suspend(() =>
889 online
890 ? Deferred.succeed(stopped, turn.turnId).pipe(Effect.as("stopped" as const))
891 : Effect.fail(new WorkflowAgentError({ reason: "the link is down" })),
892 ),
893 });
894 yield* fileSystem.writeFileString(at("linked.ts"), linkedWorkflow(false));
895 yield* Effect.gen(function* () {
896 const workflows = yield* Workflows.Workflows;
897 const definitions = yield* WorkflowRuntime.WorkflowDefinitions;
898 const { runId } = yield* workflows.start("linked", {}, { idempotencyKey: "last-definition" });
899 yield* workflows.waitFor(runId, (run) => run.detail === "agent work");
900 yield* workflows.cancel(runId);
901 assert.isTrue((yield* definitions.remove("hold.ts")).changed);
902 assert.isTrue((yield* definitions.remove("linked.ts")).changed);
903 online = true;
904 assert.equal(yield* Deferred.await(stopped), `${runId}/work/0`);
905 }).pipe(
906 Effect.provide(runtime),
907 Effect.scoped,
908 Effect.raceFirst(Effect.forever(TestClock.adjust("1 second"))),
909 );
910 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
911);
912​
913it.effect("cleanup waits for the first recovery stop after cancellation is interrupted", () =>
914 Effect.gen(function* () {
915 const entered = yield* Deferred.make<void>();
916 const recoveryEntered = yield* Deferred.make<void>();
917 const release = yield* Deferred.make<void>();
918 const swept = yield* Deferred.make<void>();
919 const clock = yield* Latch.make(true);
920 let first = true;
921 let checking = false;
922 const store = Layer.effect(
923 WorkflowStore.WorkflowStore,
924 Effect.map(WorkflowStore.make, (real) =>
925 WorkflowStore.WorkflowStore.of({
926 ...real,
927 pruneSkipped: (...args) =>
928 real
929 .pruneSkipped(...args)
930 .pipe(
931 Effect.tap(() => (checking ? Deferred.succeed(swept, undefined) : Effect.void)),
932 ),
933 }),
934 ),
935 );
936 const { fileSystem, at, runtime } = yield* setup(
937 undefined,
938 undefined,
939 {
940 start: (input) =>
941 Effect.succeed({ threadId: "thread", environment: "env-b", turnId: input.key }),
942 result: () => Effect.never,
943 interrupt: () =>
944 Effect.suspend(() => {
945 if (first) {
946 first = false;
947 return Deferred.succeed(entered, undefined).pipe(Effect.andThen(Effect.never));
948 }
949 return Deferred.succeed(recoveryEntered, undefined).pipe(
950 Effect.andThen(Deferred.await(release)),
951 Effect.as("stopped" as const),
952 );
953 }),
954 },
955 store,
956 );
957 yield* fileSystem.writeFileString(at("linked.ts"), linkedWorkflow(true));
958 yield* Effect.gen(function* () {
959 const workflows = yield* Workflows.Workflows;
960 const { runId } = yield* workflows.start("linked", {}, { idempotencyKey: "unfinished-stop" });
961 yield* workflows.waitFor(runId, (run) => run.detail === "agent work");
962 const cancel = yield* Effect.forkChild(workflows.cancel(runId));
963 yield* Deferred.await(entered);
964 yield* clock.close;
965 yield* Fiber.interrupt(cancel);
966​
967 checking = true;
968 const sweep = yield* Effect.forkChild(workflows.sweep);
969 yield* Deferred.await(recoveryEntered);
970 yield* Deferred.await(swept);
971 assert.isFalse((yield* workflows.get(runId)).steps.some((step) => step.name === "onEnd"));
972​
973 yield* Deferred.succeed(release, undefined);
974 yield* Fiber.join(sweep);
975 yield* workflows.sweep;
976 const cleanup = (yield* workflows.get(runId)).steps.find((step) => step.name === "onEnd");
977 assert.deepStrictEqual([cleanup?.status, cleanup?.attempts], ["completed", 1]);
978 }).pipe(
979 Effect.ensuring(clock.open),
980 Effect.provide(runtime),
981 Effect.scoped,
982 Effect.raceFirst(Effect.forever(Effect.andThen(clock.await, TestClock.adjust("1 second")))),
983 );
984 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
985);
986​
987it.effect(
988 "workflows are off until turned on, and a run left waiting when they are turned off goes on once they are on again",
989 () =>
990 Effect.gen(function* () {
991 const { fileSystem, at, directory, made } = yield* setup();
992 // Its top level counts the times it was loaded.
993 yield* fileSystem.writeFileString(
994 at("counted.ts"),
995 "globalThis.t3GatedLoads = (globalThis.t3GatedLoads ?? 0) + 1;\nexport default [];\n",
996 );
997 const loads = () => (globalThis as { t3GatedLoads?: number }).t3GatedLoads ?? 0;
998 yield* Effect.gen(function* () {
999 const { turn, context } = yield* WorkflowRuntime.gate(made, directory);
1000 const workflows = Context.get(context, Workflows.Workflows);
1001 const definitions = Context.get(context, WorkflowRuntime.WorkflowDefinitions);
1002 const start = workflows.start("hold", {}, { idempotencyKey: "h" });
1003​
1004 assert.equal((yield* Effect.flip(start)).message, Workflows.OFF);
1005 assert.equal((yield* Effect.flip(workflows.list())).message, Workflows.OFF);
1006 assert.deepStrictEqual((yield* definitions.read).files, []);
1007 assert.equal(loads(), 0);
1008​
1009 yield* turn(true);
1010 assert.equal(loads(), 1);
1011 const held = yield* start;
1012 yield* workflows.waitFor(held.runId, (run) => run.status === "waiting");
1013​
1014 yield* turn(false);
1015 const signal = workflows.signal({ runId: held.runId, wait: "go" }, "go on", { id: "s1" });
1016 assert.equal((yield* Effect.flip(signal)).message, Workflows.OFF);
1017​
1018 yield* turn(true);
1019 yield* signal;
1020 const freed = yield* workflows.waitFor(held.runId, (run) => run.status === "completed");
1021 assert.equal(freed.result, "go on");
1022 }).pipe(Effect.scoped, Effect.raceFirst(Effect.forever(TestClock.adjust("1 second"))));
1023 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),