@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 309 lines 12.3 KB
Raw
1 import * as AWS from "@alchemy.run/aws";
2 import { Task } from "@alchemy.run/aws/ECS/Task";
3 import { AWSEnvironment } from "@alchemy.run/aws/Environment";
4 import { expect } from "@alchemy.run/test";
5 import * as Test from "@alchemy.run/test/Alchemy";
6 import * as ecs from "@distilled.cloud/aws/ecs";
7 import * as iam from "@distilled.cloud/aws/iam";
8 import * as Provider from "alchemy/Provider";
9 import * as Effect from "effect/Effect";
10 import { reclaimTaskDefinitionFamily } from "./reclaimTaskDefinitionFamily.ts";
11
12 const { test } = Test.make({ providers: AWS.providers() });
13
14 // Deploying a full `Task` requires a Docker build + ECR push, which is far too
15 // heavy for a `list()` test. Instead we register a task definition out-of-band
16 // in the exact shape the provider produces (single container whose image is an
17 // ECR `<repoUri>:<hash>`, task/execution role ARNs, an awslogs log group), then
18 // assert `list()` reconstructs the full Attributes and includes it, and finally
19 // deregister it. This live-verifies the listTaskDefinitions -> describe ->
20 // Attributes reconstruction path without the container build overhead.
21 test.provider(
22 "list enumerates registered task definitions",
23 () =>
24 Effect.gen(function* () {
25 const { accountId, region } = yield* AWSEnvironment.current;
26
27 const family = "alchemy-test-ecs-task-list";
28 const repositoryName = "alchemy-test-ecs-task-list-repo";
29 const repositoryUri = `${accountId}.dkr.ecr.${region}.amazonaws.com/${repositoryName}`;
30 const hash = "listtest";
31 const imageUri = `${repositoryUri}:${hash}`;
32 const logGroupName = "/alchemy/test/ecs-task-list";
33 const taskRoleName = "alchemy-test-ecs-task-list-task-role";
34 const executionRoleName = "alchemy-test-ecs-task-list-execution-role";
35
36 // Reclaim any revisions a previously-killed run left behind, and
37 // guarantee full deletion (deregister + delete) on success, failure,
38 // and interruption.
39 yield* reclaimTaskDefinitionFamily(family);
40 yield* Effect.addFinalizer(() => reclaimTaskDefinitionFamily(family).pipe(Effect.ignore));
41
42 const registered = yield* ecs.registerTaskDefinition({
43 family,
44 taskRoleArn: `arn:aws:iam::${accountId}:role/${taskRoleName}`,
45 executionRoleArn: `arn:aws:iam::${accountId}:role/${executionRoleName}`,
46 networkMode: "awsvpc",
47 requiresCompatibilities: ["FARGATE"],
48 cpu: "256",
49 memory: "512",
50 containerDefinitions: [
51 {
52 name: family,
53 image: imageUri,
54 essential: true,
55 portMappings: [{ containerPort: 3000, hostPort: 3000, protocol: "tcp" }],
56 logConfiguration: {
57 logDriver: "awslogs",
58 options: {
59 "awslogs-group": logGroupName,
60 "awslogs-region": region,
61 "awslogs-stream-prefix": family,
62 },
63 },
64 },
65 ],
66 });
67 const arn = registered.taskDefinition?.taskDefinitionArn;
68 expect(arn).toBeDefined();
69
70 const provider = yield* Provider.findProvider(Task);
71 const all = yield* provider.list();
72
73 const found = all.find((t) => t.taskDefinitionArn === arn);
74 expect(found).toBeDefined();
75 expect(found?.taskFamily).toBe(family);
76 expect(found?.containerName).toBe(family);
77 expect(found?.port).toBe(3000);
78 expect(found?.imageUri).toBe(imageUri);
79 expect(found?.repositoryName).toBe(repositoryName);
80 expect(found?.repositoryUri).toBe(repositoryUri);
81 expect(found?.code.hash).toBe(hash);
82 expect(found?.logGroupName).toBe(logGroupName);
83 expect(found?.logGroupArn).toBe(
84 `arn:aws:logs:${region}:${accountId}:log-group:${logGroupName}`,
85 );
86 expect(found?.taskRoleName).toBe(taskRoleName);
87 expect(found?.executionRoleName).toBe(executionRoleName);
88
89 yield* reclaimTaskDefinitionFamily(family);
90 }),
91 { tags: ["provider:aws", "provider:aws:ecs", "live"], timeout: 240_000 },
92 );
93
94 // Multi-container + task-level props round-trip. Registering a task definition
95 // is cheap (no Docker build), so we exercise the full typed surface
96 // out-of-band: a 2-container task (app + sidecar with dependsOn/portMappings/
97 // logConfiguration), task-level ephemeralStorage, runtimePlatform (ARM64), and
98 // an EFS-less host volume, then describe it back and assert the shapes
99 // survived, then deregister. This validates that the distilled
100 // registerTaskDefinition surface we wire in `Task` is correct.
101 test.provider(
102 "multi-container task definition round-trips task-level props",
103 () =>
104 Effect.gen(function* () {
105 const family = "alchemy-test-ecs-task-multicontainer";
106
107 // Reclaim any revisions a previously-killed run left behind, and
108 // guarantee full deletion of BOTH revisions registered below on
109 // success, failure, and interruption.
110 yield* reclaimTaskDefinitionFamily(family);
111 yield* Effect.addFinalizer(() => reclaimTaskDefinitionFamily(family).pipe(Effect.ignore));
112
113 const registered = yield* ecs.registerTaskDefinition({
114 family,
115 networkMode: "awsvpc",
116 requiresCompatibilities: ["FARGATE"],
117 cpu: "256",
118 memory: "512",
119 runtimePlatform: {
120 cpuArchitecture: "ARM64",
121 operatingSystemFamily: "LINUX",
122 },
123 ephemeralStorage: { sizeInGiB: 25 },
124 volumes: [{ name: "scratch", host: {} }],
125 containerDefinitions: [
126 {
127 name: "app",
128 image: "public.ecr.aws/nginx/nginx:stable",
129 essential: true,
130 portMappings: [{ containerPort: 80, protocol: "tcp" }],
131 mountPoints: [{ sourceVolume: "scratch", containerPath: "/scratch" }],
132 dependsOn: [{ containerName: "sidecar", condition: "START" }],
133 },
134 {
135 name: "sidecar",
136 image: "public.ecr.aws/docker/library/busybox:latest",
137 essential: false,
138 command: ["sh", "-c", "while true; do sleep 30; done"],
139 },
140 ],
141 });
142 const td = registered.taskDefinition;
143 const arn = td?.taskDefinitionArn;
144 expect(arn).toBeDefined();
145
146 const described = yield* ecs.describeTaskDefinition({
147 taskDefinition: arn!,
148 });
149 const def = described.taskDefinition;
150 expect(def?.containerDefinitions?.length).toBe(2);
151 expect(def?.containerDefinitions?.map((c) => c.name)).toEqual(["app", "sidecar"]);
152 expect(def?.containerDefinitions?.[0]?.dependsOn?.[0]?.containerName).toBe("sidecar");
153 expect(def?.runtimePlatform?.cpuArchitecture).toBe("ARM64");
154 expect(def?.ephemeralStorage?.sizeInGiB).toBe(25);
155 expect(def?.volumes?.[0]?.name).toBe("scratch");
156
157 // Update one container (new image) → new revision number.
158 const updated = yield* ecs.registerTaskDefinition({
159 family,
160 networkMode: "awsvpc",
161 requiresCompatibilities: ["FARGATE"],
162 cpu: "256",
163 memory: "512",
164 containerDefinitions: [
165 {
166 name: "app",
167 image: "public.ecr.aws/nginx/nginx:latest",
168 essential: true,
169 portMappings: [{ containerPort: 80, protocol: "tcp" }],
170 },
171 ],
172 });
173 expect(updated.taskDefinition?.revision).toBeGreaterThan(td!.revision!);
174
175 yield* reclaimTaskDefinitionFamily(family);
176 }),
177 { tags: ["provider:aws", "provider:aws:ecs", "live"], timeout: 120_000 },
178 );
179
180 // Revision hygiene: every reconcile registers a NEW task-definition
181 // revision, so the superseded revision must be reaped (deregistered + hard
182 // deleted) on the spot, and destroy must sweep every remaining revision of
183 // the family. Uses the registry-image form (`image:` mirrored into ECR via a
184 // local docker pull/tag/push of a tiny busybox) — no Fargate placement, no
185 // bundling. Requires a local Docker daemon (same as the Service platform
186 // tests).
187 test.provider(
188 "superseded task-definition revisions are reaped on reconcile and destroy",
189 (stack) =>
190 Effect.gen(function* () {
191 yield* stack.destroy();
192
193 const program = (marker: string) =>
194 Effect.gen(function* () {
195 return yield* Task("RevisionReapTask", {
196 // Docker Hub busybox: the public.ecr.aws mirror aggressively
197 // rate-limits anonymous pulls during local builds.
198 image: "busybox:stable",
199 command: ["sh", "-c", "true"],
200 cpu: 256,
201 memory: 512,
202 env: { MARKER: marker },
203 });
204 });
205
206 const deployed = yield* stack.deploy(program("one"));
207 expect(deployed.taskDefinitionArn).toBeTruthy();
208
209 // Redeploy with a changed env var → a new revision in the same family.
210 const redeployed = yield* stack.deploy(program("two"));
211 expect(redeployed.taskFamily).toBe(deployed.taskFamily);
212 expect(redeployed.taskDefinitionArn).not.toBe(deployed.taskDefinitionArn);
213
214 const newRevision = yield* ecs.describeTaskDefinition({
215 taskDefinition: redeployed.taskDefinitionArn,
216 });
217 expect(newRevision.taskDefinition?.status).toBe("ACTIVE");
218 expect(
219 newRevision.taskDefinition?.containerDefinitions?.[0]?.environment?.find(
220 (e) => e.name === "MARKER",
221 )?.value,
222 ).toBe("two");
223
224 // The superseded revision was reaped by the redeploy, not left ACTIVE.
225 const supersededReaped = yield* ecs
226 .describeTaskDefinition({
227 taskDefinition: deployed.taskDefinitionArn,
228 })
229 .pipe(
230 Effect.map((r) => r.taskDefinition?.status !== "ACTIVE"),
231 Effect.catchTag("ClientException", () => Effect.succeed(true)),
232 );
233 expect(supersededReaped).toBe(true);
234
235 yield* stack.destroy();
236
237 // Zero-orphan proof: no revision of the family survives destroy as
238 // ACTIVE.
239 const activeRevisions = yield* ecs
240 .listTaskDefinitions({
241 familyPrefix: deployed.taskFamily,
242 status: "ACTIVE",
243 })
244 .pipe(
245 Effect.map((r) =>
246 (r.taskDefinitionArns ?? []).filter((arn) => arn.includes(`/${deployed.taskFamily}:`)),
247 ),
248 );
249 expect(activeRevisions).toEqual([]);
250 }),
251 { tags: ["provider:aws", "provider:aws:ecs", "live"], timeout: 240_000 },
252 );
253
254 // `environmentFiles` parity: the prop lands on the primary container of the
255 // registered task definition, and the execution role is granted read access
256 // to the referenced S3 objects via the `alchemy-environment-files` inline
257 // policy (registration does not require the S3 object to exist). Requires a
258 // local Docker daemon (registry-image mirror, cached busybox).
259 test.provider(
260 "environmentFiles land on the primary container with execution-role read access",
261 (stack) =>
262 Effect.gen(function* () {
263 yield* stack.destroy();
264
265 const envFileArn = "arn:aws:s3:::alchemy-test-ecs-env-files/app.env";
266 const deployed = yield* stack.deploy(
267 Effect.gen(function* () {
268 return yield* Task("EnvFilesTask", {
269 image: "busybox:stable",
270 command: ["sh", "-c", "true"],
271 cpu: 256,
272 memory: 512,
273 environmentFiles: [{ value: envFileArn, type: "s3" }],
274 });
275 }),
276 );
277
278 // Out-of-band: the registered revision carries the environment file.
279 const described = yield* ecs.describeTaskDefinition({
280 taskDefinition: deployed.taskDefinitionArn,
281 });
282 expect(described.taskDefinition?.containerDefinitions?.[0]?.environmentFiles).toEqual([
283 { value: envFileArn, type: "s3" },
284 ]);
285
286 // Out-of-band: the execution role can read the referenced object.
287 const policy = yield* iam.getRolePolicy({
288 RoleName: deployed.executionRoleName,
289 PolicyName: "alchemy-environment-files",
290 });
291 const document = decodeURIComponent(policy.PolicyDocument ?? "");
292 expect(document).toContain("s3:GetObject");
293 expect(document).toContain(envFileArn);
294 expect(document).toContain("arn:aws:s3:::alchemy-test-ecs-env-files");
295
296 yield* stack.destroy();
297
298 // Destroy sweeps the role (inline policy included) and the family.
299 const roleGone = yield* iam.getRole({ RoleName: deployed.executionRoleName }).pipe(
300 Effect.map(() => false),
301 Effect.catchTag("NoSuchEntityException", () => Effect.succeed(true)),
302 );
303 expect(roleGone).toBe(true);
304 }),
305 {
306 tags: ["provider:aws", "provider:aws:ecs", "provider:aws:iam", "live"],
307 timeout: 240_000,
308 },
309 );