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

main
ts 164 lines 6.61 KB
Raw
1 import * as AWS from "@alchemy.run/aws";
2 import { Cluster } from "@alchemy.run/aws/ECS/Cluster";
3 import { Service } from "@alchemy.run/aws/ECS/Service";
4 import { expect } from "@alchemy.run/test";
5 import * as Test from "@alchemy.run/test/Alchemy";
6 import * as ec2 from "@distilled.cloud/aws/ec2";
7 import * as ecs from "@distilled.cloud/aws/ecs";
8 import * as elbv2 from "@distilled.cloud/aws/elastic-load-balancing-v2";
9 import * as Data from "effect/Data";
10 import * as Effect from "effect/Effect";
11 import * as HttpClient from "effect/http/HttpClient";
12 import * as Schedule from "effect/Schedule";
13 import { getDefaultVpcNetwork } from "../DefaultVpc.ts";
14
15 const { test } = Test.make({ providers: AWS.providers() });
16
17 class RouteMismatch extends Data.TaggedError("RouteMismatch")<{
18 readonly status: number;
19 readonly body: string;
20 }> {}
21
22 // NLB + capacity: a `"80/tcp"` listen rule derives a Network Load Balancer
23 // (type, TCP listener, TCP target group), proven by a live HTTP-over-TCP
24 // round-trip through the NLB's DNS; a second service on the same cluster
25 // runs `capacity: "spot"` (describe-level — the strategy is visible on
26 // `describeServices`, no need to place a task).
27 //
28 // Requires a local Docker daemon (the `image:` sources mirror into ECR).
29 // NLB provisioning + target registration is slower than ALB (~3-4 min).
30 test.provider.skipIf(!!process.env.FAST)(
31 "tcp rules compose an NLB (live round-trip); capacity 'spot' maps to FARGATE_SPOT",
32 (stack) =>
33 Effect.gen(function* () {
34 yield* stack.destroy();
35 const net = yield* getDefaultVpcNetwork;
36 const client = yield* HttpClient.HttpClient;
37
38 // Only the per-AZ default subnets: concurrent suites create extra
39 // subnets, and a load balancer rejects two subnets in one AZ.
40 const azSubnets = yield* ec2
41 .describeSubnets({
42 Filters: [
43 { Name: "vpc-id", Values: [net.vpcId] },
44 { Name: "default-for-az", Values: ["true"] },
45 ],
46 })
47 .pipe(
48 Effect.map((r) => (r.Subnets ?? []).flatMap((s) => (s.SubnetId ? [s.SubnetId] : []))),
49 );
50
51 const deployed = yield* stack.deploy(
52 Effect.gen(function* () {
53 const cluster = yield* Cluster("NlbCluster", {
54 clusterName: "alchemy-test-ecs-nlb",
55 capacityProviders: ["FARGATE", "FARGATE_SPOT"],
56 });
57 const base = {
58 cluster,
59 vpcId: net.vpcId as string,
60 subnets: azSubnets,
61 // Default-VPC public subnets: tasks need a public IP to pull
62 // the mirrored image from ECR without a NAT.
63 assignPublicIp: true,
64 };
65 const echo = yield* Service("NlbEcho", {
66 ...base,
67 image: "hashicorp/http-echo",
68 command: ["-text=nlb-echo"],
69 port: 5678,
70 desiredCount: 1,
71 loadBalancer: { rules: [{ listen: "80/tcp" }] },
72 });
73 const spot = yield* Service("SpotWorker", {
74 ...base,
75 image: "busybox:stable",
76 command: ["sh", "-c", "while true; do sleep 30; done"],
77 desiredCount: 0,
78 capacity: "spot",
79 });
80 return {
81 url: echo.url.as<string>(),
82 loadBalancerArn: echo.loadBalancerArn.as<string>(),
83 targetGroupArn: echo.targetGroupArn.as<string>(),
84 listenerArn: echo.listenerArn.as<string>(),
85 clusterArn: echo.clusterArn.as<string>(),
86 spotServiceName: spot.serviceName.as<string>(),
87 };
88 }),
89 );
90
91 // ── the composed LB is a Network Load Balancer ────────────────────
92 const loadBalancers = yield* elbv2.describeLoadBalancers({
93 LoadBalancerArns: [deployed.loadBalancerArn],
94 });
95 const nlb = loadBalancers.LoadBalancers?.[0];
96 expect(nlb?.Type).toBe("network");
97 // Non-HTTP protocols always carry the port (there is no well-known
98 // default for tcp://).
99 expect(deployed.url).toBe(`tcp://${nlb?.DNSName}:80`);
100
101 // TCP listener on 80, TCP target group on the container port.
102 const listeners = yield* elbv2.describeListeners({
103 LoadBalancerArn: deployed.loadBalancerArn,
104 });
105 const listener = (listeners.Listeners ?? []).find((l) => l.Port === 80);
106 expect(listener?.Protocol).toBe("TCP");
107 const targetGroups = yield* elbv2.describeTargetGroups({
108 TargetGroupArns: [deployed.targetGroupArn],
109 });
110 expect(targetGroups.TargetGroups?.[0]?.Protocol).toBe("TCP");
111 expect(targetGroups.TargetGroups?.[0]?.Port).toBe(5678);
112
113 // ── live round-trip: HTTP over the NLB's TCP listener ─────────────
114 yield* client.get(`http://${nlb!.DNSName}/`).pipe(
115 Effect.flatMap((res) =>
116 Effect.flatMap(res.text, (body) =>
117 res.status === 200 && body.includes("nlb-echo")
118 ? Effect.void
119 : Effect.fail(new RouteMismatch({ status: res.status, body })),
120 ),
121 ),
122 // NLB provisioning + target registration: ~3-4 min worst case.
123 Effect.retry({ schedule: Schedule.spaced("5 seconds"), times: 60 }),
124 );
125
126 // ── capacity: "spot" arrives as a FARGATE_SPOT strategy ───────────
127 const services = yield* ecs.describeServices({
128 cluster: deployed.clusterArn,
129 services: [deployed.spotServiceName],
130 });
131 const spotService = services.services?.[0];
132 expect(spotService?.capacityProviderStrategy).toEqual([
133 { capacityProvider: "FARGATE_SPOT", weight: 1, base: 0 },
134 ]);
135 expect(spotService?.launchType).toBeUndefined();
136
137 // ── destroy + zero-orphan proofs ──────────────────────────────────
138 yield* stack.destroy();
139
140 const nlbGone = yield* elbv2
141 .describeLoadBalancers({
142 LoadBalancerArns: [deployed.loadBalancerArn],
143 })
144 .pipe(
145 Effect.map((r) => (r.LoadBalancers ?? []).length === 0),
146 Effect.catchTag("LoadBalancerNotFoundException", () => Effect.succeed(true)),
147 );
148 expect(nlbGone).toBe(true);
149
150 const targetGroupGone = yield* elbv2
151 .describeTargetGroups({
152 TargetGroupArns: [deployed.targetGroupArn],
153 })
154 .pipe(
155 Effect.map((r) => (r.TargetGroups ?? []).length === 0),
156 Effect.catchTag("TargetGroupNotFoundException", () => Effect.succeed(true)),
157 );
158 expect(targetGroupGone).toBe(true);
159 }),
160 {
161 tags: ["provider:aws", "provider:aws:ec2", "provider:aws:ecs", "live"],
162 timeout: 900_000,
163 },
164 );