Open History to see the last commit
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 Effect from "effect/Effect";
7import * as FileSystem from "effect/FileSystem";
8import * as Layer from "effect/Layer";
9import * as Option from "effect/Option";
10import * as Queue from "effect/Queue";
11import * as Path from "effect/Path";
12import * as PlatformError from "effect/PlatformError";
13import * as Stream from "effect/Stream";
14import * as TestClock from "effect/testing/TestClock";
15import { ChildProcess, ChildProcessSpawner } from "effect/process";
16
17import WorkflowsMigration from "../persistence/Migrations/110_Workflows.ts";
18import { WorkflowAgents } from "./WorkflowAgents.ts";
19import * as WorkflowEngine from "./WorkflowEngine.ts";
20import * as WorkflowRuntime from "./WorkflowRuntime.ts";
21import { engineTag, type WorkflowDefinition } from "./workflow.ts";
22import * as Workflows from "./Workflows.ts";
23
24/** Waits to be let go. */
25const hold = `T3.workflow("hold", { version: 1, payload: Schema.Struct({}), returns: Schema.String }, () =>
26 Effect.map(T3.wait("go", { returns: Schema.String }), (said) => Option.getOrElse(said, () => "nobody")),
27);
28`;
29const greet = (says: string) => `const { workflow } = T3;
30workflow("greet", { version: 1, payload: Schema.Struct({}), returns: Schema.String }, () =>
31 Effect.succeed(${JSON.stringify(says)}),
32);
33`;
34
35/**
36 * A folder holding `hold.ts`, and the workflow runtime over it on a fresh database. `engine`
37 * stands in for the real one, which needs the clock to run for as long as it is up.
38 */
39const setup = Effect.fn("setup")(function* (
40 wrap: (fileSystem: FileSystem.FileSystem) => FileSystem.FileSystem = (fileSystem) => fileSystem,
41 engine?: (definitions: ReadonlyArray<WorkflowDefinition>) => Layer.Layer<Workflows.Workflows>,
42) {
43 const fileSystem = yield* FileSystem.FileSystem;
44 const path = yield* Path.Path;
45 const home = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-workflow-defs-" });
46 const directory = path.join(home, "workflows");
47 const at = (name: string) => path.join(directory, name);
48 yield* fileSystem.makeDirectory(directory);
49 yield* fileSystem.writeFileString(at("hold.ts"), hold);
50 const database = NodeSqliteClient.layer({ filename: path.join(home, "state.sqlite") });
51 yield* Effect.provide(WorkflowsMigration, database);
52 const made = WorkflowRuntime.make(
53 Effect.succeed(
54 (definitions: ReadonlyArray<WorkflowDefinition>) =>
55 engine?.(definitions) ??
56 WorkflowEngine.layer(definitions).pipe(
57 Layer.provide(Layer.mock(WorkflowAgents)({})),
58 Layer.provide(database),
59 Layer.provide(NodeCrypto.layer),
60 ),
61 ),
62 directory,
63 Effect.succeed(true),
64 ).pipe(Effect.provideService(FileSystem.FileSystem, wrap(fileSystem)));
65 return { fileSystem, at, directory, made, runtime: Layer.effectContext(made) };
66});
67
68it.effect(
69 "every file in the folder defines workflows, and a saved file is verified before it runs",
70 () =>
71 Effect.gen(function* () {
72 const { fileSystem, at, runtime } = yield* setup();
73
74 yield* Effect.gen(function* () {
75 const workflows = yield* Workflows.Workflows;
76 const definitions = yield* WorkflowRuntime.WorkflowDefinitions;
77 const held = yield* workflows.start("hold", {}, { idempotencyKey: "h" });
78 yield* workflows.waitFor(held.runId, (run) => run.status === "waiting");
79
80 // A file that does not parse is not written, and says where it breaks.
81 const broken = yield* definitions.save("greet.ts", "T3.workflow(\n 'x',\n];\n");
82 assert.isFalse(broken.changed);
83 assert.deepStrictEqual(
84 broken.problems.map((problem) => [problem.file, problem.line]),
85 [["greet.ts", 3]],
86 );
87 // Nor is one that defines what another file already does, or drops what a run needs.
88 const twice = yield* definitions.save("again.ts", hold);
89 assert.include(
90 twice.problems[0]?.message ?? "",
91 "hold@1 is defined twice, in again.ts and hold.ts",
92 );
93 const dropped = yield* definitions.save("hold.ts", greet("hello"));
94 assert.include(
95 dropped.problems[0]?.message ?? "",
96 "hold@1 is no longer defined, and 1 of its runs",
97 );
98 // Nor one that exports something shaped like a workflow without what the engine walks.
99 const shaped = yield* definitions.save(
100 "shaped.ts",
101 'export default [{ name: "shaped", version: 1, body: () => Effect.void }];\n',
102 );
103 assert.include(shaped.problems[0]?.message ?? "", "is not a workflow");
104 // Nor one with an option nothing reads, or a time a schedule cannot fire at.
105 const misspelt = yield* definitions.save(
106 "misspelt.ts",
107 'T3.workflow("misspelt", { version: 1, payload: Schema.Struct({}), retries: 2 }, () => Effect.void);\n',
108 );
109 assert.include(misspelt.problems[0]?.message ?? "", "does not take `retries`");
110 const late = yield* definitions.save(
111 "late.ts",
112 'T3.workflow("late", { version: 1, payload: T3.Tick, triggers: [T3.daily("9am")] }, () => Effect.void);\n',
113 );
114 assert.include(late.problems[0]?.message ?? "", "24-hour time");
115 const banana = yield* definitions.save(
116 "banana.ts",
117 'T3.workflow("banana", { version: 1, payload: T3.Tick, triggers: [T3.every("banana")] }, () => Effect.void);\n',
118 );
119 assert.include(banana.problems[0]?.message ?? "", 'Write one such as "5 minutes"');
120 const twoHooks = yield* definitions.save(
121 "hooks.ts",
122 'T3.workflow("hooks", { version: 1, payload: T3.WebhookRequest, triggers: [T3.webhook("in"), T3.webhook("in")] }, () => Effect.void);\n',
123 );
124 assert.include(twoHooks.problems[0]?.message ?? "", 'two hooks named "in"');
125 assert.include((yield* definitions.remove("hold.ts")).problems[0]?.message ?? "", "hold@1");
126 assert.deepStrictEqual(
127 (yield* definitions.read).files.map((file) => file.name),
128 ["hold.ts"],
129 );
130 // The same change made outside the app is refused as a whole: the file still reads as the
131 // version that runs, until it is put back.
132 const told = (wanted: boolean) =>
133 workflows.watch.pipe(
134 Stream.filter((snapshot) => (snapshot.definition?.problem != null) === wanted),
135 Stream.runHead,
136 );
137 yield* fileSystem.writeFileString(at("hold.ts"), greet("hello"));
138 yield* told(true);
139 assert.deepStrictEqual(
140 (yield* definitions.read).files.map((file) => file.workflows),
141 [["hold@1"]],
142 );
143 // Only that file is held back: another file's change still runs, and the held one says why.
144 const other =
145 'T3.workflow("other", { version: 1, payload: Schema.Struct({}) }, () => Effect.void);\n';
146 // A file the folder's naming leaves out says so, instead of never running without a word.
147 yield* fileSystem.writeFileString(at("my flow.ts"), other);
148 assert.deepStrictEqual(yield* definitions.save("other.ts", other), {
149 changed: true,
150 problems: [],
151 });
152 yield* workflows.start("other", {}, { idempotencyKey: "o" });
153 assert.deepStrictEqual(
154 (yield* definitions.read).files.map((file) => [file.name, file.problems.length]),
155 [
156 ["hold.ts", 1],
157 ["other.ts", 0],
158 ],
159 );
160 assert.deepStrictEqual(
161 (yield* definitions.read).problems.map((problem) => problem.file),
162 ["my flow.ts"],
163 );
164 yield* fileSystem.remove(at("my flow.ts"));
165 assert.deepStrictEqual(yield* definitions.remove("other.ts"), {
166 changed: true,
167 problems: [],
168 });
169 yield* fileSystem.writeFileString(at("hold.ts"), hold);
170 yield* told(false);
171
172 // A new file that passes is there from now on, and what it defines can be started.
173 const saved = { changed: true, problems: [] };
174 assert.deepStrictEqual(yield* definitions.save("greet.ts", greet("hello")), saved);
175 assert.equal(yield* fileSystem.readFileString(at("greet.ts")), greet("hello"));
176 const greeted = yield* workflows.start("greet", {}, { idempotencyKey: "g" });
177 const done = yield* workflows.waitFor(greeted.runId, (run) => run.status === "completed");
178 assert.equal(done.result, "hello");
179 // The run that was waiting came through the reload and can still be let go.
180 yield* workflows.signal({ runId: held.runId, wait: "go" }, "go on", { id: "s1" });
181 const freed = yield* workflows.waitFor(held.runId, (run) => run.status === "completed");
182 assert.equal(freed.result, "go on");
183
184 // Someone breaks a file outside the app: its last good version keeps running, and the
185 // other files go on changing.
186 const problem = (wanted: boolean) =>
187 workflows.watch.pipe(
188 Stream.filter((snapshot) => (snapshot.definition?.problem != null) === wanted),
189 Stream.runHead,
190 );
191 yield* fileSystem.writeFileString(at("greet.ts"), "T3.workflow(");
192 yield* problem(true);
193 const read = yield* definitions.read;
194 assert.deepStrictEqual(
195 read.files.map((file) => [file.name, file.problems.length]),
196 [
197 ["greet.ts", 1],
198 ["hold.ts", 0],
199 ],
200 );
201 const still = yield* workflows.start("greet", {}, { idempotencyKey: "g2" });
202 assert.equal(
203 (yield* workflows.waitFor(still.runId, (run) => run.status === "completed")).result,
204 "hello",
205 );
206 // And fixes it, saying something else, this time as the file's one default export.
207 yield* fileSystem.writeFileString(
208 at("greet.ts"),
209 greet("hi").replace("\nworkflow(", "\nexport default workflow("),
210 );
211 yield* problem(false);
212 const fixed = yield* workflows.start("greet", {}, { idempotencyKey: "g3" });
213 assert.equal(
214 (yield* workflows.waitFor(fixed.runId, (run) => run.status === "completed")).result,
215 "hi",
216 );
217 // A file taken away takes its workflows with it.
218 assert.deepStrictEqual(yield* definitions.remove("greet.ts"), saved);
219 const gone = yield* workflows
220 .start("greet", {}, { idempotencyKey: "g4" })
221 .pipe(Effect.flip);
222 assert.equal(gone._tag, "WorkflowNotRegisteredError");
223 // With no file left, nothing runs, and the runs that ended can still be read.
224 assert.deepStrictEqual(yield* definitions.remove("hold.ts"), saved);
225 assert.equal((yield* workflows.get(held.runId)).run.status, "completed");
226 assert.includeMembers(
227 (yield* workflows.list()).map((run) => run.runId),
228 [held.runId, greeted.runId],
229 );
230 }).pipe(
231 Effect.provide(runtime),
232 Effect.scoped,
233 Effect.raceFirst(Effect.forever(TestClock.adjust("1 second"))),
234 );
235 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
236);
237
238it.effect(
239 "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",
240 () =>
241 Effect.gen(function* () {
242 let refuse = false;
243 // What each engine was built to run. One that registers `broken` does not come up.
244 const builds: Array<ReadonlyArray<string>> = [];
245 // No file events: only the runtime's own retry can pick up what changed.
246 const { at, fileSystem, runtime } = yield* setup(
247 (real) => ({
248 ...real,
249 exists: (target) =>
250 refuse
251 ? Effect.fail(
252 PlatformError.systemError({
253 _tag: "PermissionDenied",
254 module: "FileSystem",
255 method: "exists",
256 pathOrDescriptor: target,
257 }),
258 )
259 : real.exists(target),
260 watch: () => Stream.never,
261 }),
262 (definitions) =>
263 definitions.some((definition) => definition.name === "broken")
264 ? Layer.effect(Workflows.Workflows, Effect.die(new Error("broken took it down")))
265 : Layer.sync(Workflows.Workflows, () => {
266 builds.push(definitions.map(engineTag));
267 return Workflows.disabled;
268 }),
269 );
270
271 yield* Effect.gen(function* () {
272 const workflows = yield* Workflows.Workflows;
273 const definitions = yield* WorkflowRuntime.WorkflowDefinitions;
274 const revision = Effect.map(
275 Stream.runHead(workflows.watch),
276 (snapshot) => Option.getOrThrow(snapshot).definition?.revision ?? 0,
277 );
278 refuse = true;
279 // Written, but the folder could not be listed, so it is not said to run.
280 const unlisted = yield* definitions.save("greet.ts", greet("hi"));
281 assert.isTrue(unlisted.changed);
282 assert.include(unlisted.problems[0]?.message ?? "", "could not be read");
283 // What was loaded stays, and greet is not taken in yet.
284 assert.deepStrictEqual(builds, [["hold@1"]]);
285 const before = yield* revision;
286 refuse = false;
287 yield* TestClock.adjust("30 seconds");
288 yield* workflows.watch.pipe(
289 Stream.filter((snapshot) => (snapshot.definition?.revision ?? 0) > before),
290 Stream.runHead,
291 );
292 assert.deepStrictEqual(builds.at(-1), ["greet@1", "hold@1"]);
293
294 // A definition that passes the checks but takes the engine down at start changes nothing.
295 yield* fileSystem.writeFileString(
296 at("broken.ts"),
297 'T3.workflow("broken", { version: 1, payload: Schema.Struct({}) }, () => Effect.void);\n',
298 );
299 const fellBack = yield* definitions.save("greet.ts", greet("hello"));
300 assert.isTrue(fellBack.changed);
301 assert.include(fellBack.problems[0]?.message ?? "", "did not start");
302 assert.deepStrictEqual(builds.slice(1), [
303 ["greet@1", "hold@1"],
304 ["greet@1", "hold@1"],
305 ]);
306 assert.include(
307 (yield* Stream.runHead(workflows.watch)).pipe(Option.getOrThrow).definition?.problem ??
308 "",
309 "did not start",
310 );
311 }).pipe(Effect.provide(runtime), Effect.scoped);
312 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
313);
314
315it.effect("a file that never finishes loading is given up on, and later files still load", () =>
316 Effect.gen(function* () {
317 const { at, fileSystem } = yield* setup();
318 yield* fileSystem.writeFileString(at("stuck.ts"), "await new Promise(() => {});\n");
319 yield* fileSystem.writeFileString(at("greet.ts"), greet("hi"));
320 const stuck = yield* WorkflowRuntime.loadDefinitions(at("stuck.ts"), 0, 50).pipe(Effect.flip);
321 assert.include(String(stuck.cause), "did not finish loading");
322 const loaded = yield* WorkflowRuntime.loadDefinitions(at("greet.ts"));
323 assert.deepStrictEqual(
324 loaded.map((definition) => definition.name),
325 ["greet"],
326 );
327 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
328);
329
330it.effect("a file given up on registers nothing into the file that loads after it", () =>
331 Effect.gen(function* () {
332 const { at, fileSystem } = yield* setup();
333 yield* fileSystem.writeFileString(
334 at("slow.ts"),
335 'await new Promise((resolve) => { globalThis.t3TestResume = resolve; });\nT3.workflow("slow", { version: 1, payload: Schema.Struct({}) }, () => Effect.void);\n',
336 );
337 // The second file goes on loading until the first one's top level has run to its end.
338 yield* fileSystem.writeFileString(
339 at("next.ts"),
340 `${greet("hi")}globalThis.t3TestResume();\nawait new Promise((resolve) => setImmediate(resolve));\n`,
341 );
342 yield* WorkflowRuntime.loadDefinitions(at("slow.ts"), 0, 50).pipe(Effect.flip);
343 const loaded = yield* WorkflowRuntime.loadDefinitions(at("next.ts"));
344 assert.deepStrictEqual(
345 loaded.map((definition) => definition.name),
346 ["greet"],
347 );
348 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
349);
350
351// Vitest's module runner loads a file its own way; only Node keeps a CommonJS file by its path.
352it.live("a file without imports or exports loads again after it changes", () =>
353 Effect.gen(function* () {
354 const { at, fileSystem } = yield* setup();
355 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
356 yield* fileSystem.writeFileString(at("greet.ts"), greet("hi"));
357 const twice = `
358 import * as NodeFS from "node:fs";
359 import * as NodeServices from "@effect/platform-node/NodeServices";
360 import * as Context from "effect/Context";
361import * as Effect from "effect/Effect";
362 import { loadDefinitions } from ${JSON.stringify(new URL("./WorkflowRuntime.ts", import.meta.url).href)};
363 const file = process.argv.at(-1);
364 const program = Effect.gen(function* () {
365 const first = yield* loadDefinitions(file, 1);
366 NodeFS.writeFileSync(file, NodeFS.readFileSync(file, "utf8").replace('"hi"', '"hello"'));
367 const second = yield* loadDefinitions(file, 2);
368 return [first.length, second.length];
369 });
370 console.log(JSON.stringify(await Effect.runPromise(Effect.provide(program, NodeServices.layer))));
371 `;
372 const child = yield* spawner.spawn(
373 ChildProcess.make(
374 process.execPath,
375 ["--input-type=module", "--eval", twice, at("greet.ts")],
376 { cwd: import.meta.dirname },
377 ),
378 );
379 const [stdout, stderr] = yield* Effect.all(
380 [
381 child.stdout.pipe(Stream.decodeText(), Stream.mkString),
382 child.stderr.pipe(Stream.decodeText(), Stream.mkString),
383 ],
384 { concurrency: "unbounded" },
385 );
386 assert.equal(stdout.trim(), "[1,1]", stderr);
387 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
388);
389
390it.effect("a change held back by a run goes in once that run ends, with no further edit", () =>
391 Effect.gen(function* () {
392 // The folder's changes are told by hand, so the test does not hang on a watcher starting.
393 const changed = yield* Queue.unbounded<FileSystem.WatchEvent>();
394 const { fileSystem, at, runtime } = yield* setup((fileSystem) => ({
395 ...fileSystem,
396 watch: () => Stream.fromQueue(changed),
397 }));
398 yield* Effect.gen(function* () {
399 const workflows = yield* Workflows.Workflows;
400 const definitions = yield* WorkflowRuntime.WorkflowDefinitions;
401 const held = yield* workflows.start("hold", {}, { idempotencyKey: "h" });
402 yield* workflows.waitFor(held.runId, (run) => run.status === "waiting");
403 const problem = (wanted: boolean) =>
404 workflows.watch.pipe(
405 Stream.filter((snapshot) => (snapshot.definition?.problem != null) === wanted),
406 Stream.runHead,
407 );
408 yield* fileSystem.writeFileString(at("hold.ts"), greet("hello"));
409 yield* Queue.offer(changed, { _tag: "Update", path: at("hold.ts") });
410 yield* problem(true);
411 yield* workflows.signal({ runId: held.runId, wait: "go" }, "go on", { id: "s1" });
412 yield* workflows.waitFor(held.runId, (run) => run.status === "completed");
413 // Nothing is told of the folder now: the held change goes in on its own.
414 yield* problem(false);
415 assert.deepStrictEqual(
416 (yield* definitions.read).files.map((file) => file.workflows),
417 [["greet@1"]],
418 );
419 }).pipe(
420 Effect.provide(runtime),
421 Effect.scoped,
422 Effect.raceFirst(Effect.forever(TestClock.adjust("1 second"))),
423 );
424 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
425);
426
427it.effect(
428 "workflows are off until turned on, and a run left waiting when they are turned off goes on once they are on again",
429 () =>
430 Effect.gen(function* () {
431 const { fileSystem, at, directory, made } = yield* setup();
432 // Its top level counts the times it was loaded.
433 yield* fileSystem.writeFileString(
434 at("counted.ts"),
435 "globalThis.t3GatedLoads = (globalThis.t3GatedLoads ?? 0) + 1;\nexport default [];\n",
436 );
437 const loads = () => (globalThis as { t3GatedLoads?: number }).t3GatedLoads ?? 0;
438 yield* Effect.gen(function* () {
439 const { turn, context } = yield* WorkflowRuntime.gate(made, directory);
440 const workflows = Context.get(context, Workflows.Workflows);
441 const definitions = Context.get(context, WorkflowRuntime.WorkflowDefinitions);
442 const start = workflows.start("hold", {}, { idempotencyKey: "h" });
443
444 assert.equal((yield* Effect.flip(start)).message, Workflows.OFF);
445 assert.equal((yield* Effect.flip(workflows.list())).message, Workflows.OFF);
446 assert.deepStrictEqual((yield* definitions.read).files, []);
447 assert.equal(loads(), 0);
448
449 yield* turn(true);
450 assert.equal(loads(), 1);
451 const held = yield* start;
452 yield* workflows.waitFor(held.runId, (run) => run.status === "waiting");
453
454 yield* turn(false);
455 const signal = workflows.signal({ runId: held.runId, wait: "go" }, "go on", { id: "s1" });
456 assert.equal((yield* Effect.flip(signal)).message, Workflows.OFF);
457
458 yield* turn(true);
459 yield* signal;
460 const freed = yield* workflows.waitFor(held.runId, (run) => run.status === "completed");
461 assert.equal(freed.result, "go on");
462 }).pipe(Effect.scoped, Effect.raceFirst(Effect.forever(TestClock.adjust("1 second"))));
463 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
464);