@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 176 lines 6.95 KB
Raw
1 import * as AWS from "@alchemy.run/aws";
2 import { createContainerRuntimeContext } from "@alchemy.run/aws/ECS/Task";
3 import { expect } from "@alchemy.run/test";
4 import * as Test from "@alchemy.run/test/Alchemy";
5 import { isResolved } from "alchemy/Diff";
6 import * as Plan from "alchemy/Plan";
7 import * as Provider from "alchemy/Provider";
8 import * as Stack from "alchemy/Stack";
9 import { Stage } from "alchemy/Stage";
10 import { inMemoryState, State } from "alchemy/State";
11 import * as Effect from "effect/Effect";
12 import * as HttpServerResponse from "effect/http/HttpServerResponse";
13 import * as Layer from "effect/Layer";
14
15 // Regression for the container-platform serve OOM (fixed in c35217c2b):
16 // `createContainerRuntimeContext` wrapped the host `serve`, but the wrapper
17 // body read `base.serve` at CALL time — after `Object.assign(base, { serve })`
18 // had already replaced it with the wrapper itself. The moment any Task/
19 // Service impl declared `{ fetch }` (any props form: plain object, Effect,
20 // inline class, or tagged `.make`), evaluating `serve` re-entered itself
21 // without bound, exhausting the heap (JSC MemoryExhaustion, ~8GB in ~60s)
22 // while the platform instance was being constructed at plan time.
23 //
24 // These tests run WITHOUT live AWS (stub provider + in-memory state) and are
25 // wrapped in `Effect.timeout`, so a reintroduced recursion fails fast with a
26 // TimeoutException instead of OOMing the whole test process.
27
28 // ── unit: the serve wrapper must not re-enter itself ────────────────────────
29 // Pre-fix this recursed unboundedly; the 2s timeout interrupts it long before
30 // memory becomes a problem. Post-fix it completes in microseconds (the base
31 // serve just registers a runner; `Http.serve` is a no-op without a server).
32
33 const noopProvider = (platform: any) =>
34 Provider.succeed(platform, {
35 list: () => Effect.succeed([]),
36 diff: Effect.fn(function* ({ news }) {
37 if (!isResolved(news)) return undefined;
38 }),
39 reconcile: Effect.fn(function* ({ output }) {
40 return output ?? ({ ok: true } as any);
41 }),
42 delete: Effect.fn(function* () {}),
43 });
44
45 const providers = () =>
46 Layer.mergeAll(noopProvider(AWS.ECS.Service), noopProvider(AWS.ECS.Cluster));
47
48 const { test } = Test.make({
49 providers: providers(),
50 state: inMemoryState(),
51 });
52
53 test(
54 "container runtime context serve terminates when the shape declares fetch",
55 Effect.gen(function* () {
56 const ctx = createContainerRuntimeContext("AWS.ECS.Service")("probe");
57 const handler = Effect.succeed(HttpServerResponse.text("ok"));
58 yield* ctx.serve(handler, { shape: { fetch: handler } }).pipe(Effect.timeout(2_000));
59 // The handler was registered exactly once as a runner.
60 const { program } = yield* ctx.exports;
61 expect(program).toBeDefined();
62 }),
63 {
64 tags: ["unit", "provider:aws", "provider:aws:ecs", "local"],
65 timeout: 10_000,
66 },
67 );
68
69 // ── plan/apply-level: the inline class form with Effect-valued props ────────
70 // The design-doc-promised form: `class X extends Service<X>()(id, propsEffect,
71 // impl) {}` where the props are an Effect yielding another resource. This is
72 // the exact shape that surfaced the serve recursion (the impl declares
73 // `fetch`, so plan-time construction evaluates the container serve wrapper).
74 // The stub provider keeps it entirely off the cloud; the shared in-memory
75 // state store lets us assert the resolved props that were persisted.
76
77 const ProbeCluster = AWS.ECS.Cluster("ProbeCluster", {
78 clusterName: "inline-class-probe",
79 });
80
81 class InlineService extends AWS.ECS.Service<InlineService>()(
82 "InlineService",
83 // Props as an Effect — resolved through `transformProps` inside the
84 // platform's Self layer, unlike plain-object props.
85 Effect.gen(function* () {
86 const cluster = yield* ProbeCluster;
87 return { cluster, image: "nginx:1.27", port: 80 };
88 }),
89 Effect.gen(function* () {
90 return {
91 fetch: Effect.succeed(HttpServerResponse.text("ok")),
92 };
93 }),
94 ) {}
95
96 test.provider(
97 "inline class form with Effect props constructs, plans, and applies",
98 (stack) =>
99 Effect.gen(function* () {
100 // Class construction itself is eager (`cls.make(props, impl)` runs at
101 // class-definition time); reaching this line proves it didn't blow up.
102 // `LogicalId` is stamped on the class at runtime (see Platform.ts's
103 // eager inline branch) but not declared on the inline-form class type.
104 expect((InlineService as unknown as { LogicalId: string }).LogicalId).toBe("InlineService");
105
106 const deployed = yield* stack
107 .deploy(
108 Effect.gen(function* () {
109 yield* ProbeCluster;
110 return yield* InlineService;
111 }),
112 )
113 // Pre-fix, plan-time construction recursed inside serve; interrupt
114 // fast instead of exhausting the heap.
115 .pipe(Effect.timeout(30_000));
116
117 expect(deployed).toEqual({ ok: true });
118
119 // The Effect-valued props resolved through the cluster yield and were
120 // persisted: the service's stored props reference the cluster attrs.
121 const state = yield* yield* State;
122 const row = yield* state.get({
123 stack: stack.name,
124 stage: stack.stage,
125 fqn: "InlineService",
126 });
127 const props = (row as { props?: Record<string, unknown> } | undefined)?.props as
128 | { cluster?: { clusterName?: string }; image?: string; port?: number }
129 | undefined;
130 expect(props?.image).toBe("nginx:1.27");
131 expect(props?.port).toBe(80);
132 }),
133 {
134 tags: ["unit", "provider:aws", "provider:aws:ecs", "local"],
135 timeout: 60_000,
136 },
137 );
138
139 // ── plan-only: multiple yields of the inline class stay stable ──────────────
140 // Each `yield*` of an inline-form class rebuilds its Self layer in a transient
141 // region; the resource is memoized by logical id, so repeated yields must
142 // converge on one resource and one plan entry (no growth, no divergence).
143 const makePlan = <A, Err, Req>(
144 effect: Effect.Effect<A, Err, Req>,
145 ): Effect.Effect<Plan.Plan<A>, Err, State> =>
146 effect.pipe(
147 // @ts-expect-error - Stack.make's typing erases R unsoundly here
148 Stack.make({
149 name: "inline-class-plan",
150 providers: providers(),
151 state: inMemoryState(),
152 }),
153 Effect.provideService(Stage, "test"),
154 Effect.flatMap((compiled: any) => Plan.make(compiled).pipe(Effect.provide(compiled.services))),
155 );
156
157 test(
158 "repeated yields of the inline class produce a single plan entry",
159 Effect.gen(function* () {
160 const plan = yield* Effect.gen(function* () {
161 yield* ProbeCluster;
162 yield* InlineService;
163 yield* InlineService;
164 return yield* InlineService;
165 }).pipe(makePlan, Effect.timeout(30_000));
166
167 expect(plan.resources["InlineService"]?.action).toBe("create");
168 expect(Object.keys(plan.resources).filter((fqn) => fqn.includes("InlineService"))).toEqual([
169 "InlineService",
170 ]);
171 }),
172 {
173 tags: ["unit", "provider:aws", "provider:aws:ecs", "local"],
174 timeout: 60_000,
175 },
176 );