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

WorkflowRuntime.test.ts

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