@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 275 lines 11.4 KB
Raw
1 import * as AWS from "@alchemy.run/aws";
2 import { SecurityGroup } from "@alchemy.run/aws/EC2/SecurityGroup";
3 import { Cluster } from "@alchemy.run/aws/ECS/Cluster";
4 import { deriveRulePriority, Service } from "@alchemy.run/aws/ECS/Service";
5 import { Listener } from "@alchemy.run/aws/ELBv2/Listener";
6 import { LoadBalancer } from "@alchemy.run/aws/ELBv2/LoadBalancer";
7 import { expect } from "@alchemy.run/test";
8 import * as Test from "@alchemy.run/test/Alchemy";
9 import * as ec2 from "@distilled.cloud/aws/ec2";
10 import * as elbv2 from "@distilled.cloud/aws/elastic-load-balancing-v2";
11 import * as Data from "effect/Data";
12 import * as Effect from "effect/Effect";
13 import * as HttpClient from "effect/http/HttpClient";
14 import * as Schedule from "effect/Schedule";
15 import { getDefaultVpcNetwork } from "../DefaultVpc.ts";
16
17 const { test } = Test.make({ providers: AWS.providers() });
18
19 // ── auto-priority determinism (pure, no cloud) ──────────────────────────────
20 //
21 // Rules that omit `priority` get one derived from the rule's namespaced
22 // logical id via a stable FNV-1a hash into 1–50000. The exact values are
23 // pinned so the derivation can never silently change between runs/releases —
24 // a changed hash would re-prioritize (replace) every auto-prioritized rule.
25 test(
26 "auto-derived rule priorities are deterministic and distinct",
27 Effect.sync(() => {
28 // Pinned values (computed once; stable forever).
29 expect(deriveRulePriority("SharedAlbStack/EchoA/Rule-0")).toBe(21915);
30 expect(deriveRulePriority("SharedAlbStack/EchoB/Rule-0")).toBe(6262);
31 expect(deriveRulePriority("Api/Rule-0")).toBe(13044);
32 expect(deriveRulePriority("Api/Rule-1")).toBe(35425);
33
34 // Same input ⇒ same output; distinct inputs ⇒ distinct outputs.
35 const ids = [
36 "SharedAlbStack/EchoA/Rule-0",
37 "SharedAlbStack/EchoA/Rule-1",
38 "SharedAlbStack/EchoB/Rule-0",
39 "SharedAlbStack/EchoB/Rule-1",
40 "Api/Rule-0",
41 "Api/Rule-1",
42 ];
43 const first = ids.map(deriveRulePriority);
44 expect(ids.map(deriveRulePriority)).toEqual(first);
45 expect(new Set(first).size).toBe(ids.length);
46 for (const priority of first) {
47 expect(Number.isInteger(priority)).toBe(true);
48 expect(priority).toBeGreaterThanOrEqual(1);
49 expect(priority).toBeLessThanOrEqual(50000);
50 }
51 }),
52 { tags: ["provider:aws", "provider:aws:ecs", "live"] },
53 );
54
55 class RouteMismatch extends Data.TaggedError("RouteMismatch")<{
56 readonly path: string;
57 readonly status: number;
58 readonly body: string;
59 }> {}
60
61 // ── shared-ALB end-to-end ───────────────────────────────────────────────────
62 //
63 // One stack owns an ALB + HTTP listener at stack level; TWO cheap external
64 // `image:` services share that listener with distinct `path` rules. Each
65 // service composes only its own TargetGroup + ListenerRule (+ managed SG).
66 // We assert both paths route through the ALB DNS, then destroy ONE service
67 // and assert its rule + target group are gone while the other service still
68 // routes and the ALB/listener are untouched. Finally a full destroy with
69 // out-of-band zero-orphan proofs.
70 //
71 // Requires a local Docker daemon (the `image:` source mirrors into ECR).
72 // FAST runs skip it: ALB provisioning + Fargate startup + ENI release put it
73 // well past the fast budget.
74 test.provider.skipIf(!!process.env.FAST)(
75 "two services share one listener; destroying one leaves the other routing",
76 (stack) =>
77 Effect.gen(function* () {
78 yield* stack.destroy();
79 const net = yield* getDefaultVpcNetwork;
80 const client = yield* HttpClient.HttpClient;
81
82 // Only the per-AZ default subnets (one per AZ): concurrent suite runs
83 // create extra subnets in the default VPC, and an ALB rejects two
84 // subnets in the same Availability Zone.
85 const azSubnets = yield* ec2
86 .describeSubnets({
87 Filters: [
88 { Name: "vpc-id", Values: [net.vpcId] },
89 { Name: "default-for-az", Values: ["true"] },
90 ],
91 })
92 .pipe(
93 Effect.map((r) => (r.Subnets ?? []).flatMap((s) => (s.SubnetId ? [s.SubnetId] : []))),
94 );
95
96 const program = (includeEchoB: boolean) =>
97 Effect.gen(function* () {
98 const cluster = yield* Cluster("SharedAlbCluster", {
99 clusterName: "alchemy-test-ecs-shared-alb",
100 });
101 // The shared ALB + listener are stack-level resources owned by
102 // NEITHER service. Unmatched requests hit the 404 default action.
103 const albSg = yield* SecurityGroup("SharedAlbSg", {
104 vpcId: net.vpcId,
105 description: "shared ALB ingress for alchemy ECS tests",
106 ingress: [
107 {
108 ipProtocol: "tcp",
109 fromPort: 80,
110 toPort: 80,
111 cidrIpv4: "0.0.0.0/0",
112 },
113 ],
114 });
115 const alb = yield* LoadBalancer("SharedAlb", {
116 type: "application",
117 scheme: "internet-facing",
118 subnets: azSubnets as `subnet-${string}`[],
119 securityGroups: [albSg.groupId],
120 });
121 const listener = yield* Listener("SharedHttp", {
122 loadBalancerArn: alb.loadBalancerArn,
123 port: 80,
124 protocol: "HTTP",
125 defaultActions: [
126 {
127 type: "fixedResponse",
128 statusCode: "404",
129 contentType: "text/plain",
130 messageBody: "no rule",
131 },
132 ],
133 });
134
135 const base = {
136 cluster,
137 image: "hashicorp/http-echo",
138 port: 5678,
139 desiredCount: 1,
140 vpcId: net.vpcId as string,
141 subnets: azSubnets,
142 // Default-VPC public subnets: tasks need a public IP to pull
143 // the mirrored image from ECR without a NAT.
144 assignPublicIp: true,
145 };
146 const echoA = yield* Service("EchoA", {
147 ...base,
148 command: ["-text=svc-a"],
149 loadBalancer: { listener, rules: [{ path: "/a*" }] },
150 });
151 const echoB = includeEchoB
152 ? yield* Service("EchoB", {
153 ...base,
154 command: ["-text=svc-b"],
155 loadBalancer: { listener, rules: [{ path: "/b*" }] },
156 })
157 : undefined;
158 return {
159 albArn: alb.loadBalancerArn.as<string>(),
160 albDns: alb.dnsName.as<string>(),
161 listenerArn: listener.listenerArn.as<string>(),
162 aTargetGroupArn: echoA.targetGroupArn.as<string>(),
163 aUrl: echoA.url.as<string>(),
164 bTargetGroupArn: echoB?.targetGroupArn.as<string>(),
165 };
166 });
167
168 const fetchRoute = (dns: string, path: string) =>
169 client
170 .get(`http://${dns}${path}`)
171 .pipe(
172 Effect.flatMap((res) => Effect.map(res.text, (body) => ({ status: res.status, body }))),
173 );
174 // Bounded route poll: ALB provisioning (~2 min) + Fargate task start +
175 // fast-converge health checks (~20s). Under a saturated full-suite run
176 // ALB DNS propagation alone can eat several minutes, so the budget is
177 // generous (~7 min) — the happy path exits on the first 200.
178 const awaitRoute = (dns: string, path: string, expected: string) =>
179 fetchRoute(dns, path).pipe(
180 Effect.flatMap(({ status, body }) =>
181 status === 200 && body.includes(expected)
182 ? Effect.void
183 : Effect.fail(new RouteMismatch({ path, status, body })),
184 ),
185 Effect.retry({ schedule: Schedule.spaced("5 seconds"), times: 84 }),
186 );
187
188 // ── deploy both services on the shared listener ────────────────────
189 const deployed = yield* stack.deploy(program(true));
190 expect(deployed.aTargetGroupArn).toBeTruthy();
191 expect(deployed.bTargetGroupArn).toBeTruthy();
192 expect(deployed.aTargetGroupArn).not.toBe(deployed.bTargetGroupArn);
193 // Shared ingress derives the service URL from the shared ALB's DNS.
194 expect(deployed.aUrl).toBe(`http://${deployed.albDns}`);
195
196 // Both paths route to their service; unmatched paths hit the
197 // listener's own 404 default action.
198 yield* awaitRoute(deployed.albDns, "/a", "svc-a");
199 yield* awaitRoute(deployed.albDns, "/b", "svc-b");
200 const unmatched = yield* fetchRoute(deployed.albDns, "/c");
201 expect(unmatched.status).toBe(404);
202
203 // Out-of-band: exactly two non-default rules on the shared listener.
204 const rulesBefore = yield* elbv2.describeRules({
205 ListenerArn: deployed.listenerArn,
206 });
207 expect((rulesBefore.Rules ?? []).filter((r) => !r.IsDefault).length).toBe(2);
208
209 // ── destroy ONE service (EchoB) ────────────────────────────────────
210 yield* stack.deploy(program(false));
211
212 // Its rule + target group are gone...
213 const bTargetGroupGone = yield* elbv2
214 .describeTargetGroups({
215 TargetGroupArns: [deployed.bTargetGroupArn!],
216 })
217 .pipe(
218 Effect.map((r) => (r.TargetGroups ?? []).length === 0),
219 Effect.catchTag("TargetGroupNotFoundException", () => Effect.succeed(true)),
220 );
221 expect(bTargetGroupGone).toBe(true);
222 const rulesAfter = yield* elbv2.describeRules({
223 ListenerArn: deployed.listenerArn,
224 });
225 expect((rulesAfter.Rules ?? []).filter((r) => !r.IsDefault).length).toBe(1);
226
227 // ...the shared ALB + listener are untouched...
228 const albAfter = yield* elbv2.describeLoadBalancers({
229 LoadBalancerArns: [deployed.albArn],
230 });
231 expect((albAfter.LoadBalancers ?? []).length).toBe(1);
232
233 // ...EchoA still routes, and /b now falls through to the 404 default.
234 yield* awaitRoute(deployed.albDns, "/a", "svc-a");
235 yield* fetchRoute(deployed.albDns, "/b").pipe(
236 Effect.flatMap(({ status, body }) =>
237 status === 404
238 ? Effect.void
239 : Effect.fail(new RouteMismatch({ path: "/b", status, body })),
240 ),
241 Effect.retry({ schedule: Schedule.spaced("3 seconds"), times: 20 }),
242 );
243
244 // ── full destroy + zero-orphan proofs ──────────────────────────────
245 yield* stack.destroy();
246
247 const albGone = yield* elbv2
248 .describeLoadBalancers({ LoadBalancerArns: [deployed.albArn] })
249 .pipe(
250 Effect.map((r) => (r.LoadBalancers ?? []).length === 0),
251 Effect.catchTag("LoadBalancerNotFoundException", () => Effect.succeed(true)),
252 );
253 expect(albGone).toBe(true);
254
255 const aTargetGroupGone = yield* elbv2
256 .describeTargetGroups({
257 TargetGroupArns: [deployed.aTargetGroupArn],
258 })
259 .pipe(
260 Effect.map((r) => (r.TargetGroups ?? []).length === 0),
261 Effect.catchTag("TargetGroupNotFoundException", () => Effect.succeed(true)),
262 );
263 expect(aTargetGroupGone).toBe(true);
264
265 const listenerGone = yield* elbv2.describeRules({ ListenerArn: deployed.listenerArn }).pipe(
266 Effect.map(() => false),
267 Effect.catchTag("ListenerNotFoundException", () => Effect.succeed(true)),
268 );
269 expect(listenerGone).toBe(true);
270 }),
271 {
272 tags: ["provider:aws", "provider:aws:ec2", "provider:aws:ecs", "provider:aws:elbv2", "live"],
273 timeout: 900_000,
274 },
275 );