@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 300 lines 12 KB
Raw
1 import * as AWS from "@alchemy.run/aws";
2 import { Subnet } from "@alchemy.run/aws/EC2";
3 import { Cluster } from "@alchemy.run/aws/ECS/Cluster";
4 import { Service } from "@alchemy.run/aws/ECS/Service";
5 import { TaskDefinition } from "@alchemy.run/aws/ECS/TaskDefinition";
6 import { Role } from "@alchemy.run/aws/IAM/Role";
7 import { expect } from "@alchemy.run/test";
8 import * as Test from "@alchemy.run/test/Alchemy";
9 import * as logs from "@distilled.cloud/aws/cloudwatch-logs";
10 import * as ec2 from "@distilled.cloud/aws/ec2";
11 import * as ecs from "@distilled.cloud/aws/ecs";
12 import * as Effect from "effect/Effect";
13 import * as Schedule from "effect/Schedule";
14 import { getDefaultVpc } from "../DefaultVpc.ts";
15
16 const { test } = Test.make({ providers: AWS.providers() });
17
18 // Latest ACTIVE revision of a family, or undefined when none exists
19 // (describeTaskDefinition by family rejects with ClientException once every
20 // revision is INACTIVE/deleted).
21 const describeActive = (family: string) =>
22 ecs.describeTaskDefinition({ taskDefinition: family }).pipe(
23 Effect.map((d) => (d.taskDefinition?.status === "ACTIVE" ? d.taskDefinition : undefined)),
24 Effect.catchTag("ClientException", () => Effect.succeed(undefined)),
25 );
26
27 const listExactFamily = (family: string, status: "ACTIVE" | "INACTIVE") =>
28 ecs
29 .listTaskDefinitions({ familyPrefix: family, status })
30 .pipe(
31 Effect.map((result) =>
32 (result.taskDefinitionArns ?? []).filter((arn) => arn.includes(`/${family}:`)),
33 ),
34 );
35
36 // Lifecycle: register -> no-op redeploy (same revision) -> content change
37 // (new revision, same family) -> destroy (all revisions deregistered, managed
38 // log group deleted).
39 test.provider(
40 "registers immutable revisions per content change",
41 (stack) =>
42 Effect.gen(function* () {
43 yield* stack.destroy();
44
45 const family = "alchemy-test-ecs-taskdef-life";
46
47 const deployTaskDefinition = (env: string) =>
48 stack.deploy(
49 Effect.gen(function* () {
50 // Fargate rejects the awslogs driver without an execution role —
51 // also exercises passing an IAM Role resource as the role ref.
52 const executionRole = yield* Role("LifecycleExecutionRole", {
53 assumeRolePolicyDocument: {
54 Version: "2012-10-17",
55 Statement: [
56 {
57 Effect: "Allow",
58 Principal: { Service: "ecs-tasks.amazonaws.com" },
59 Action: ["sts:AssumeRole"],
60 },
61 ],
62 },
63 managedPolicyArns: [
64 "arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy",
65 ],
66 });
67 return yield* TaskDefinition("LifecycleTaskDef", {
68 family,
69 executionRoleArn: executionRole,
70 containerDefinitions: [
71 {
72 name: "app",
73 image: "public.ecr.aws/docker/library/busybox:stable",
74 essential: true,
75 command: ["sleep", "3600"],
76 environment: [{ name: "FOO", value: env }],
77 portMappings: [{ containerPort: 8080 }],
78 },
79 ],
80 awslogs: true,
81 tags: { env: "test" },
82 });
83 }),
84 );
85
86 // Create — registers the first revision for this run.
87 const created = yield* deployTaskDefinition("one");
88 expect(created.family).toBe(family);
89 expect(created.containerName).toBe("app");
90 expect(created.port).toBe(8080);
91 expect(created.logGroupName).toBe(`/ecs/${family}`);
92
93 // Out-of-band: revision is ACTIVE, awslogs config was injected, tags
94 // (internal + user) landed on the revision.
95 const observed = yield* ecs.describeTaskDefinition({
96 taskDefinition: created.taskDefinitionArn,
97 include: ["TAGS"],
98 });
99 expect(observed.taskDefinition?.status).toBe("ACTIVE");
100 const container = observed.taskDefinition?.containerDefinitions?.[0];
101 expect(container?.logConfiguration?.logDriver).toBe("awslogs");
102 expect(container?.logConfiguration?.options?.["awslogs-group"]).toBe(`/ecs/${family}`);
103 const tagMap = Object.fromEntries((observed.tags ?? []).map((t) => [t.key, t.value]));
104 expect(tagMap.env).toBe("test");
105 expect(tagMap["alchemy::id"]).toBe("LifecycleTaskDef");
106
107 // The managed log group exists.
108 const groups = yield* logs.describeLogGroups({ logGroupNamePrefix: `/ecs/${family}` });
109 expect(groups.logGroups?.some((g) => g.logGroupName === `/ecs/${family}`)).toBe(true);
110
111 // No-op redeploy — identical content must NOT register a new revision.
112 const same = yield* deployTaskDefinition("one");
113 expect(same.taskDefinitionArn).toBe(created.taskDefinitionArn);
114 expect(same.revision).toBe(created.revision);
115
116 // Content change — a new revision under the same family.
117 const changed = yield* deployTaskDefinition("two");
118 expect(changed.family).toBe(family);
119 expect(changed.revision).toBeGreaterThan(created.revision);
120 expect(changed.taskDefinitionArn).not.toBe(created.taskDefinitionArn);
121
122 // Destroy — every ACTIVE revision of the family is deregistered and the
123 // managed log group is deleted.
124 yield* stack.destroy();
125
126 const remaining = yield* describeActive(family);
127 expect(remaining).toBeUndefined();
128 expect(yield* listExactFamily(family, "ACTIVE")).toEqual([]);
129 expect(yield* listExactFamily(family, "INACTIVE")).toEqual([]);
130
131 const groupsAfter = yield* logs.describeLogGroups({ logGroupNamePrefix: `/ecs/${family}` });
132 expect(groupsAfter.logGroups?.some((g) => g.logGroupName === `/ecs/${family}`)).toBe(false);
133 }),
134 { tags: ["provider:aws", "provider:aws:ecs", "provider:aws:iam", "live"] },
135 );
136
137 // Family change replaces the resource: a fresh family is registered and the
138 // old family's revisions are deregistered by the replacement delete.
139 test.provider(
140 "replaces the resource when the family changes",
141 (stack) =>
142 Effect.gen(function* () {
143 yield* stack.destroy();
144
145 const familyA = "alchemy-test-ecs-taskdef-repl-a";
146 const familyB = "alchemy-test-ecs-taskdef-repl-b";
147
148 const deployTaskDefinition = (family: string) =>
149 stack.deploy(
150 Effect.gen(function* () {
151 return yield* TaskDefinition("ReplaceTaskDef", {
152 family,
153 containerDefinitions: [
154 {
155 name: "app",
156 image: "public.ecr.aws/docker/library/busybox:stable",
157 essential: true,
158 command: ["sleep", "3600"],
159 },
160 ],
161 });
162 }),
163 );
164
165 const created = yield* deployTaskDefinition(familyA);
166 expect(created.family).toBe(familyA);
167 expect(yield* describeActive(familyA)).toBeDefined();
168
169 const replaced = yield* deployTaskDefinition(familyB);
170 expect(replaced.family).toBe(familyB);
171 expect(replaced.taskDefinitionArn).not.toBe(created.taskDefinitionArn);
172 expect(yield* describeActive(familyB)).toBeDefined();
173 // Old family fully deregistered by the replacement delete.
174 expect(yield* describeActive(familyA)).toBeUndefined();
175 expect(yield* listExactFamily(familyA, "ACTIVE")).toEqual([]);
176 expect(yield* listExactFamily(familyA, "INACTIVE")).toEqual([]);
177
178 yield* stack.destroy();
179 expect(yield* describeActive(familyB)).toBeUndefined();
180 expect(yield* listExactFamily(familyB, "ACTIVE")).toEqual([]);
181 expect(yield* listExactFamily(familyB, "INACTIVE")).toEqual([]);
182 }),
183 { tags: ["provider:aws", "provider:aws:ecs", "live"] },
184 );
185
186 // BYO container end-to-end: a public nginx image (no build step) registered
187 // via TaskDefinition, wired into Service by passing the RESOURCE itself as the
188 // `task` prop (its taskDefinitionArn/containerName/port attributes satisfy the
189 // structural contract), launched on Fargate in a public subnet with a public
190 // IP, and observed reaching runningCount >= 1.
191 test.provider(
192 "service runs a BYO task definition on Fargate",
193 (stack) =>
194 Effect.gen(function* () {
195 yield* stack.destroy();
196
197 const azResult = yield* ec2.describeAvailabilityZones({});
198 const az = (azResult.AvailabilityZones ?? []).find((z) => z.State === "available")?.ZoneName!;
199 const defaultVpc = yield* getDefaultVpc;
200
201 const out = yield* stack.deploy(
202 Effect.gen(function* () {
203 // Reuse the default VPC's public routing. This is ECS coverage, so
204 // allocating another VPC only makes the suite contend for EC2's
205 // small regional VPC quota during high-concurrency sweeps.
206 const subnet = yield* Subnet("ByoSubnet", {
207 vpcId: defaultVpc.vpcId,
208 cidrBlock: defaultVpc.subnetCidrBlock(239),
209 availabilityZone: az,
210 mapPublicIpOnLaunch: true,
211 });
212
213 // BYO execution role (tests the IAM Role resource ref on
214 // executionRoleArn) — needed by the awslogs log driver.
215 const executionRole = yield* Role("ByoExecutionRole", {
216 assumeRolePolicyDocument: {
217 Version: "2012-10-17",
218 Statement: [
219 {
220 Effect: "Allow",
221 Principal: { Service: "ecs-tasks.amazonaws.com" },
222 Action: ["sts:AssumeRole"],
223 },
224 ],
225 },
226 managedPolicyArns: [
227 "arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy",
228 ],
229 });
230
231 const taskDefinition = yield* TaskDefinition("ByoNginx", {
232 family: "alchemy-test-ecs-taskdef-byo",
233 executionRoleArn: executionRole,
234 awslogs: true,
235 containerDefinitions: [
236 {
237 name: "nginx",
238 image: "public.ecr.aws/nginx/nginx:stable",
239 essential: true,
240 portMappings: [{ containerPort: 80, protocol: "tcp" }],
241 },
242 ],
243 });
244
245 const cluster = yield* Cluster("ByoCluster", {
246 clusterName: "alchemy-test-ecs-taskdef-byo",
247 });
248
249 const service = yield* Service("ByoService", {
250 cluster,
251 // Whole TaskDefinition resource as the `task` prop — the BYO
252 // wiring under test.
253 task: taskDefinition,
254 desiredCount: 1,
255 vpcId: defaultVpc.vpcId,
256 subnets: [subnet.subnetId],
257 assignPublicIp: true,
258 });
259
260 return {
261 clusterArn: service.clusterArn.as<string>(),
262 serviceName: service.serviceName.as<string>(),
263 serviceTaskDefinitionArn: service.taskDefinitionArn.as<string>(),
264 taskDefinitionArn: taskDefinition.taskDefinitionArn.as<string>(),
265 };
266 }),
267 );
268
269 // The service deploys exactly the BYO revision.
270 expect(out.serviceTaskDefinitionArn).toBe(out.taskDefinitionArn);
271
272 // The container actually starts: poll (bounded) until runningCount >= 1.
273 const running = yield* ecs
274 .describeServices({ cluster: out.clusterArn, services: [out.serviceName] })
275 .pipe(
276 Effect.map((d) => d.services?.[0]?.runningCount ?? 0),
277 Effect.repeat({
278 schedule: Schedule.spaced("8 seconds"),
279 until: (count) => count >= 1,
280 times: 20,
281 }),
282 );
283 expect(running).toBeGreaterThanOrEqual(1);
284
285 yield* stack.destroy();
286
287 // Out-of-band: the family has no ACTIVE revision left.
288 expect(yield* describeActive("alchemy-test-ecs-taskdef-byo")).toBeUndefined();
289
290 // And the cluster is gone too (deleted clusters report INACTIVE).
291 const clustersAfter = yield* ecs.describeClusters({
292 clusters: ["alchemy-test-ecs-taskdef-byo"],
293 });
294 expect((clustersAfter.clusters ?? []).some((c) => c.status === "ACTIVE")).toBe(false);
295 }),
296 {
297 tags: ["provider:aws", "provider:aws:ec2", "provider:aws:ecs", "provider:aws:iam", "live"],
298 timeout: 420_000,
299 },
300 );