@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 507 lines 15.5 KB
Raw
1 import { describe, expect } from "@alchemy.run/test";
2 import * as Test from "@alchemy.run/test/Alchemy";
3 import * as Context from "effect/Context";
4 import * as Effect from "effect/Effect";
5 import * as Layer from "effect/Layer";
6 import * as Option from "effect/Option";
7 import * as Ref from "effect/Ref";
8 import { Action } from "@/Action";
9 import * as Plan from "@/Plan";
10 import * as Stack from "@/Stack";
11 import { Stage } from "@/Stage";
12 import {
13 InMemoryService,
14 inMemoryState,
15 State,
16 type ActionState,
17 type RanActionState,
18 } from "@/State";
19 import { Bucket, TestLayers } from "./test.resources";
20
21 const TEST_STACK = "task-test";
22 const TEST_STAGE = "test";
23
24 // Fresh in-memory state per test so persisted task rows don't leak between
25 // runs in the same file.
26 const freshState = () =>
27 Layer.effect(
28 State,
29 Effect.sync(() => InMemoryService({})),
30 );
31
32 const { test } = Test.make({
33 providers: TestLayers(),
34 state: freshState(),
35 });
36
37 const resolveStackId = Effect.gen(function* () {
38 const ambient = yield* Effect.serviceOption(Stack.Stack);
39 return Option.match(ambient, {
40 onNone: () => ({ name: TEST_STACK, stage: TEST_STAGE }),
41 onSome: (s) => ({ name: s.name, stage: s.stage }),
42 });
43 });
44
45 const seed = (rows: Record<string, ActionState>) =>
46 Effect.gen(function* () {
47 const { name, stage } = yield* resolveStackId;
48 const state = yield* yield* State;
49 for (const [fqn, value] of Object.entries(rows)) {
50 yield* state.set({ stack: name, stage, fqn, value });
51 }
52 });
53
54 const makePlan = <A, Err = never, Req = never>(
55 effect: Effect.Effect<A, Err, Req>,
56 options?: Plan.MakePlanOptions,
57 ): Effect.Effect<Plan.Plan<A>, Err, State> =>
58 // @ts-expect-error - Stack.make's typing erases R unsoundly here
59 Effect.gen(function* () {
60 const { name, stage } = yield* resolveStackId;
61 // @ts-expect-error
62 return yield* effect.pipe(
63 // @ts-expect-error
64 Stack.make({
65 name,
66 providers: Layer.empty,
67 state: inMemoryState(),
68 }),
69 Effect.provideService(Stage, stage),
70 Effect.flatMap((stackSpec: any) => Plan.make(stackSpec, options)),
71 Effect.provide(TestLayers()),
72 );
73 });
74
75 // ── Plan tests ────────────────────────────────────────────────────────────
76
77 describe("Plan", { tags: ["unit", "local"] }, () => {
78 test(
79 "first-time task -> run",
80 Effect.gen(function* () {
81 const Sync = Action("Sync", (input: { table: string }) =>
82 Effect.succeed({ rows: 1, table: input.table }),
83 );
84
85 const plan = yield* Effect.gen(function* () {
86 return yield* Sync({ table: "users" });
87 }).pipe(makePlan);
88
89 expect(plan.actions.Sync).toMatchObject({
90 kind: "action",
91 action: "run",
92 state: undefined,
93 forced: false,
94 });
95 expect(plan.actions.Sync.def.LogicalId).toBe("Sync");
96 }),
97 );
98
99 test(
100 "same input hash -> noop (skip)",
101 Effect.gen(function* () {
102 const Sync = Action("Sync", (_: { table: string }) => Effect.succeed({ rows: 1 }));
103
104 // Pre-seed a `ran` row with a hash that matches { table: "users" }.
105 const { hashInput } = yield* Effect.promise(() => import("@/Util/sha256"));
106 const inputHash = yield* hashInput({ table: "users" });
107 yield* seed({
108 Sync: {
109 kind: "action",
110 status: "ran",
111 fqn: "Sync",
112 logicalId: "Sync",
113 namespace: undefined,
114 actionType: "Sync",
115 inputHash,
116 input: { table: "users" },
117 output: { rows: 1 },
118 downstream: [],
119 } satisfies RanActionState,
120 });
121
122 const plan = yield* Effect.gen(function* () {
123 return yield* Sync({ table: "users" });
124 }).pipe(makePlan);
125
126 expect(plan.actions.Sync.action).toBe("noop");
127 }),
128 );
129
130 test(
131 "changed input hash -> run",
132 Effect.gen(function* () {
133 const Sync = Action("Sync", (_: { table: string }) => Effect.succeed({ rows: 1 }));
134
135 const { hashInput } = yield* Effect.promise(() => import("@/Util/sha256"));
136 const oldHash = yield* hashInput({ table: "users" });
137 yield* seed({
138 Sync: {
139 kind: "action",
140 status: "ran",
141 fqn: "Sync",
142 logicalId: "Sync",
143 namespace: undefined,
144 actionType: "Sync",
145 inputHash: oldHash,
146 input: { table: "users" },
147 output: { rows: 1 },
148 downstream: [],
149 } satisfies RanActionState,
150 });
151
152 const plan = yield* Effect.gen(function* () {
153 return yield* Sync({ table: "orders" });
154 }).pipe(makePlan);
155
156 expect(plan.actions.Sync.action).toBe("run");
157 }),
158 );
159
160 test(
161 "force flips noop -> run",
162 Effect.gen(function* () {
163 const Sync = Action("Sync", (_: { table: string }) => Effect.succeed({ rows: 1 }));
164
165 const { hashInput } = yield* Effect.promise(() => import("@/Util/sha256"));
166 const inputHash = yield* hashInput({ table: "users" });
167 yield* seed({
168 Sync: {
169 kind: "action",
170 status: "ran",
171 fqn: "Sync",
172 logicalId: "Sync",
173 namespace: undefined,
174 actionType: "Sync",
175 inputHash,
176 input: { table: "users" },
177 output: { rows: 1 },
178 downstream: [],
179 } satisfies RanActionState,
180 });
181
182 const plan = yield* Effect.gen(function* () {
183 return yield* Sync({ table: "users" });
184 }).pipe((eff) => makePlan(eff, { force: true }));
185
186 expect(plan.actions.Sync.action).toBe("run");
187 expect((plan.actions.Sync as Plan.ActionRun).forced).toBe(true);
188 }),
189 );
190
191 test(
192 "task removed from stack -> taskDeletions",
193 Effect.gen(function* () {
194 const { hashInput } = yield* Effect.promise(() => import("@/Util/sha256"));
195 const inputHash = yield* hashInput({ table: "users" });
196 yield* seed({
197 Sync: {
198 kind: "action",
199 status: "ran",
200 fqn: "Sync",
201 logicalId: "Sync",
202 namespace: undefined,
203 actionType: "Sync",
204 inputHash,
205 input: { table: "users" },
206 output: { rows: 1 },
207 downstream: [],
208 } satisfies RanActionState,
209 });
210
211 // The new stack has no tasks at all.
212 const plan = yield* Effect.gen(function* () {
213 return undefined;
214 }).pipe(makePlan);
215
216 expect(plan.actionDeletions.Sync).toMatchObject({
217 kind: "action",
218 action: "delete",
219 });
220 expect(plan.actions.Sync).toBeUndefined();
221 }),
222 );
223
224 test(
225 "resource depends on task: task is upstream of resource",
226 Effect.gen(function* () {
227 const Compute = Action("Compute", (_: {}) => Effect.succeed({ value: "computed" }));
228
229 const plan = yield* Effect.gen(function* () {
230 const computed = yield* Compute({});
231 const bucket = yield* Bucket("MyBucket", { name: computed.value });
232 return bucket;
233 }).pipe(makePlan);
234
235 // Action is run (first time), bucket is created and lists Compute as upstream.
236 expect(plan.actions.Compute.action).toBe("run");
237 expect(plan.actions.Compute.downstream).toContain("MyBucket");
238 }),
239 );
240
241 test(
242 "task depends on resource: resource is upstream of task",
243 Effect.gen(function* () {
244 const Sync = Action("Sync", (_: { name: string }) => Effect.succeed({ ok: true }));
245
246 const plan = yield* Effect.gen(function* () {
247 const bucket = yield* Bucket("MyBucket", { name: "b" });
248 return yield* Sync({ name: bucket.name });
249 }).pipe(makePlan);
250
251 expect(plan.resources.MyBucket.action).toBe("create");
252 expect(plan.actions.Sync.action).toBe("run");
253 // MyBucket's downstream includes the task FQN.
254 expect(plan.resources.MyBucket.downstream).toContain("Sync");
255 }),
256 );
257
258 test(
259 "explicit logical id allows multiple instances",
260 Effect.gen(function* () {
261 const Sync = Action("Sync", (_: { which: string }) => Effect.succeed({ ok: true }));
262
263 const plan = yield* Effect.gen(function* () {
264 yield* Sync("nightly", { which: "n" });
265 yield* Sync("hourly", { which: "h" });
266 }).pipe(makePlan);
267
268 expect(plan.actions.nightly.action).toBe("run");
269 expect(plan.actions.hourly.action).toBe("run");
270 expect(plan.actions.Sync).toBeUndefined();
271 }),
272 );
273 });
274
275 // ── Apply tests ───────────────────────────────────────────────────────────
276
277 describe("Apply", { tags: ["unit", "local"] }, () => {
278 test.provider("first run invokes body and persists ran state", (stack) =>
279 Effect.gen(function* () {
280 const counter = yield* Ref.make(0);
281 const Sync = Action("Sync", (input: { n: number }) =>
282 Effect.gen(function* () {
283 yield* Ref.update(counter, (c) => c + 1);
284 return { doubled: input.n * 2 };
285 }),
286 );
287
288 const out = yield* stack.deploy(
289 Effect.gen(function* () {
290 return yield* Sync({ n: 21 });
291 }),
292 );
293
294 expect(out).toEqual({ doubled: 42 });
295 expect(yield* Ref.get(counter)).toBe(1);
296
297 // Persisted state is `ran` with the materialized output.
298 const state = yield* yield* State;
299 const persisted = yield* state.get({
300 stack: stack.name,
301 stage: stack.stage,
302 fqn: "Sync",
303 });
304 expect(persisted).toMatchObject({
305 kind: "action",
306 status: "ran",
307 output: { doubled: 42 },
308 });
309 }),
310 );
311
312 test.provider("same input across deploys -> body not re-invoked", (stack) =>
313 Effect.gen(function* () {
314 const counter = yield* Ref.make(0);
315 const program = Effect.gen(function* () {
316 const Sync = Action("Sync", (input: { n: number }) =>
317 Effect.gen(function* () {
318 yield* Ref.update(counter, (c) => c + 1);
319 return { doubled: input.n * 2 };
320 }),
321 );
322 return yield* Sync({ n: 21 });
323 });
324
325 const first = yield* stack.deploy(program);
326 const second = yield* stack.deploy(program);
327
328 expect(first).toEqual({ doubled: 42 });
329 expect(second).toEqual({ doubled: 42 });
330 expect(yield* Ref.get(counter)).toBe(1);
331 }),
332 );
333
334 test.provider("changed input -> body re-invoked", (stack) =>
335 Effect.gen(function* () {
336 const counter = yield* Ref.make(0);
337 const programFor = (n: number) =>
338 Effect.gen(function* () {
339 const Sync = Action("Sync", (input: { n: number }) =>
340 Effect.gen(function* () {
341 yield* Ref.update(counter, (c) => c + 1);
342 return { doubled: input.n * 2 };
343 }),
344 );
345 return yield* Sync({ n });
346 });
347
348 yield* stack.deploy(programFor(21));
349 const second = yield* stack.deploy(programFor(50));
350
351 expect(second).toEqual({ doubled: 100 });
352 expect(yield* Ref.get(counter)).toBe(2);
353 }),
354 );
355
356 test.provider("task output flows to downstream resource input", (stack) =>
357 Effect.gen(function* () {
358 const Name = Action("Name", (_: {}) => Effect.succeed({ name: "computed-bucket-name" }));
359
360 const out = yield* stack.deploy(
361 Effect.gen(function* () {
362 const computed = yield* Name({});
363 return yield* Bucket("MyBucket", { name: computed.name });
364 }),
365 );
366
367 expect(out.name).toBe("computed-bucket-name");
368 }),
369 );
370
371 test.provider("resource attr flows to task input", (stack) =>
372 Effect.gen(function* () {
373 const Echo = Action("Echo", (input: { name: string }) =>
374 Effect.succeed({ echoed: input.name }),
375 );
376
377 const out = yield* stack.deploy(
378 Effect.gen(function* () {
379 const bucket = yield* Bucket("MyBucket", { name: "from-resource" });
380 return yield* Echo({ name: bucket.name });
381 }),
382 );
383
384 expect(out).toEqual({ echoed: "from-resource" });
385 }),
386 );
387
388 test.provider("removing task from stack drops state without invoking body", (stack) =>
389 Effect.gen(function* () {
390 const deleteSpy = yield* Ref.make(0);
391 const Sync = Action("Sync", (_: { n: number }) => Effect.succeed({ ok: true }));
392
393 yield* stack.deploy(
394 Effect.gen(function* () {
395 return yield* Sync({ n: 1 });
396 }),
397 );
398
399 const state = yield* yield* State;
400 expect(
401 yield* state.get({
402 stack: stack.name,
403 stage: stack.stage,
404 fqn: "Sync",
405 }),
406 ).toMatchObject({ kind: "action", status: "ran" });
407
408 // Re-deploy WITHOUT the task — state should be dropped.
409 // (Use a tracker hook to confirm body wasn't called.)
410 yield* stack.deploy(Effect.succeed(undefined));
411 void deleteSpy;
412
413 expect(
414 yield* state.get({
415 stack: stack.name,
416 stage: stack.stage,
417 fqn: "Sync",
418 }),
419 ).toBeUndefined();
420 }),
421 );
422
423 test.provider("init captures a resource Output; body resolves it at apply", (stack) =>
424 Effect.gen(function* () {
425 const out = yield* stack.deploy(
426 Effect.gen(function* () {
427 const bucket = yield* Bucket("Cap", { name: "cap-bucket" });
428
429 const Seed = Action(
430 "Seed",
431 Effect.gen(function* () {
432 // Capture the resource Output at init — before the bucket
433 // exists. `arn` is a deferred accessor.
434 const arn = yield* bucket.bucketArn;
435 const name = yield* bucket.name;
436 return Effect.fn(function* () {
437 // Resolve at apply, after the bucket is materialized.
438 return { arn: yield* arn, name: yield* name };
439 });
440 }),
441 );
442
443 return yield* Seed({});
444 }),
445 );
446
447 expect(out).toEqual({
448 arn: "arn:test:bucket:us-east-1:123456789:Cap",
449 name: "cap-bucket",
450 });
451 }),
452 );
453
454 test.provider("init-effect form: deps satisfied at apply", (stack) =>
455 Effect.gen(function* () {
456 class Multiplier extends Context.Service<Multiplier, number>()("test/Multiplier") {}
457
458 const Sync = Action(
459 "Sync",
460 Effect.gen(function* () {
461 const m = yield* Multiplier;
462 return (input: { n: number }) => Effect.succeed({ result: input.n * m });
463 }),
464 );
465
466 const out = yield* stack
467 .deploy(
468 Effect.gen(function* () {
469 return yield* Sync({ n: 21 });
470 }),
471 )
472 .pipe(Effect.provideService(Multiplier, 3));
473
474 expect(out).toEqual({ result: 63 });
475 }),
476 );
477
478 test.provider("tagged .make form: init captures a resource Output; body resolves it", (stack) =>
479 Effect.gen(function* () {
480 interface SeedAction extends Action<"Seed", {}, { arn: string }> {}
481 const Seed = Action<SeedAction, {}, { arn: string }>()("Seed");
482
483 const out = yield* stack.deploy(
484 Effect.gen(function* () {
485 const bucket = yield* Bucket("Cap", { name: "cap-bucket" });
486
487 // `.make` called inside the builder with `bucket` in scope, then
488 // provided locally — its init runs under the capture context.
489 const SeedLive = Seed.make(
490 Effect.gen(function* () {
491 const arn = yield* bucket.bucketArn;
492 return Effect.fn(function* () {
493 return { arn: yield* arn };
494 });
495 }),
496 );
497
498 return yield* Seed({}).pipe(Effect.provide(SeedLive));
499 }),
500 );
501
502 expect(out).toEqual({
503 arn: "arn:test:bucket:us-east-1:123456789:Cap",
504 });
505 }),
506 );
507 });