@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 816 lines 33.6 KB
Raw
1 import * as AWS from "@alchemy.run/aws";
2 import { Subnet } from "@alchemy.run/aws/EC2/Subnet";
3 import { Cluster } from "@alchemy.run/aws/ECS/Cluster";
4 import { Service, ServiceDidNotStabilize } from "@alchemy.run/aws/ECS/Service";
5 import { expect } from "@alchemy.run/test";
6 import * as Test from "@alchemy.run/test/Alchemy";
7 import * as ec2 from "@distilled.cloud/aws/ec2";
8 import * as ecs from "@distilled.cloud/aws/ecs";
9 import * as elbv2 from "@distilled.cloud/aws/elastic-load-balancing-v2";
10 import * as iam from "@distilled.cloud/aws/iam";
11 import * as Provider from "alchemy/Provider";
12 import { isResourceState, State, type ResourceState } from "alchemy/State";
13 import * as Effect from "effect/Effect";
14 import * as Result from "effect/Result";
15 import * as Schedule from "effect/Schedule";
16 import { getDefaultVpc } from "../DefaultVpc.ts";
17 import { driftActions, repairDrift, waitForDrift } from "../drift.ts";
18 import { reclaimTaskDefinitionFamily } from "./reclaimTaskDefinitionFamily.ts";
19
20 const { test } = Test.make({ providers: AWS.providers() });
21
22 // Canonical `list()` test (AWS account/region collection, fanned out per
23 // cluster): deploy a real cluster + service, resolve the provider from context
24 // via the typed `findProvider`, call `list()`, and assert the deployed service
25 // appears in the exhaustively-paginated result
26 // (listClusters -> listServices -> describeServices hydration).
27 //
28 // To stay inside the speed budget we avoid building/pushing a Docker image
29 // (the canonical `AWS.ECS.Task` resource) and instead register a minimal task
30 // definition against a public image and run the service at `desiredCount: 0`,
31 // so `createService` returns immediately without waiting for Fargate task
32 // placement. Networking is a stack-owned subnet in the standing default VPC
33 // (no NAT/IGW needed since no task is ever launched).
34 test.provider(
35 "list enumerates the deployed service",
36 (stack) =>
37 Effect.gen(function* () {
38 yield* stack.destroy();
39
40 // Reclaim any revisions a previously-killed run left behind, and
41 // guarantee full deletion (deregister + delete) on success, failure,
42 // and interruption.
43 const family = "alchemy-test-ecs-service-list";
44 yield* reclaimTaskDefinitionFamily(family);
45 yield* Effect.addFinalizer(() => reclaimTaskDefinitionFamily(family).pipe(Effect.ignore));
46
47 // Register a minimal Fargate task definition pointing at a public image.
48 const registered = yield* ecs.registerTaskDefinition({
49 family,
50 networkMode: "awsvpc",
51 requiresCompatibilities: ["FARGATE"],
52 cpu: "256",
53 memory: "512",
54 containerDefinitions: [
55 {
56 name: "app",
57 image: "public.ecr.aws/nginx/nginx:stable",
58 essential: true,
59 portMappings: [{ containerPort: 80, protocol: "tcp" }],
60 },
61 ],
62 });
63 const taskDefinitionArn = registered.taskDefinition?.taskDefinitionArn;
64 if (!taskDefinitionArn) {
65 return yield* Effect.die(
66 new Error("registerTaskDefinition returned no task definition ARN"),
67 );
68 }
69 const defaultVpc = yield* getDefaultVpc;
70
71 const service = yield* stack.deploy(
72 Effect.gen(function* () {
73 const subnet = yield* Subnet("ListServiceSubnet", {
74 vpcId: defaultVpc.vpcId,
75 cidrBlock: defaultVpc.subnetCidrBlock(234),
76 });
77 const cluster = yield* Cluster("ListServiceCluster", {
78 clusterName: "alchemy-test-ecs-service-list",
79 });
80 return yield* Service("ListService", {
81 cluster,
82 task: { taskDefinitionArn, containerName: "app", port: 80 },
83 desiredCount: 0,
84 vpcId: defaultVpc.vpcId,
85 subnets: [subnet.subnetId],
86 });
87 }),
88 );
89
90 const provider = yield* Provider.findProvider(Service);
91 const all = yield* provider.list();
92
93 expect(all.some((s) => s.serviceArn === service.serviceArn)).toBe(true);
94 const found = all.find((s) => s.serviceArn === service.serviceArn);
95 expect(found?.serviceName).toEqual(service.serviceName);
96 expect(found?.clusterArn).toEqual(service.clusterArn);
97
98 yield* stack.destroy();
99
100 yield* reclaimTaskDefinitionFamily(family);
101
102 // Out-of-band gone-proof: the cluster (deleted after its service) is
103 // INACTIVE or absent, so nothing this test created is left ACTIVE.
104 const after = yield* ecs.describeClusters({ clusters: ["alchemy-test-ecs-service-list"] });
105 expect((after.clusters ?? []).some((c) => c.status === "ACTIVE")).toBe(false);
106 }),
107 { tags: ["provider:aws", "provider:aws:ec2", "provider:aws:ecs", "live"] },
108 );
109
110 // In-place reconcile coverage: create a service at desiredCount 0 (so
111 // createService returns immediately without waiting on Fargate placement),
112 // then update the network configuration (assignPublicIp), desiredCount, the
113 // deployment circuit breaker, and tags — and assert the service was updated in
114 // place (SAME serviceArn, no replacement). This exercises the per-aspect
115 // updateService + tag-sync path and the narrowed `diff` (these fields must NOT
116 // force a replace).
117 test.provider(
118 "service applies network / desiredCount / deployment / tag changes in place",
119 (stack) =>
120 Effect.gen(function* () {
121 yield* stack.destroy();
122
123 const family = "alchemy-test-ecs-service-inplace";
124 yield* reclaimTaskDefinitionFamily(family);
125 yield* Effect.addFinalizer(() => reclaimTaskDefinitionFamily(family).pipe(Effect.ignore));
126
127 const registered = yield* ecs.registerTaskDefinition({
128 family,
129 networkMode: "awsvpc",
130 requiresCompatibilities: ["FARGATE"],
131 cpu: "256",
132 memory: "512",
133 containerDefinitions: [
134 {
135 name: "app",
136 image: "public.ecr.aws/nginx/nginx:stable",
137 essential: true,
138 portMappings: [{ containerPort: 80, protocol: "tcp" }],
139 },
140 ],
141 });
142 const taskDefinitionArn = registered.taskDefinition?.taskDefinitionArn!;
143 const defaultVpc = yield* getDefaultVpc;
144
145 const deployService = (props: {
146 desiredCount: number;
147 assignPublicIp: boolean;
148 tags: Record<string, string>;
149 circuitBreaker: boolean;
150 }) =>
151 stack.deploy(
152 Effect.gen(function* () {
153 const subnet = yield* Subnet("InPlaceSubnet", {
154 vpcId: defaultVpc.vpcId,
155 cidrBlock: defaultVpc.subnetCidrBlock(235),
156 });
157 const cluster = yield* Cluster("InPlaceCluster", {
158 clusterName: "alchemy-test-ecs-service-inplace",
159 });
160 return yield* Service("InPlaceService", {
161 cluster,
162 task: { taskDefinitionArn, containerName: "app", port: 80 },
163 desiredCount: props.desiredCount,
164 vpcId: defaultVpc.vpcId,
165 subnets: [subnet.subnetId],
166 assignPublicIp: props.assignPublicIp,
167 tags: props.tags,
168 deploymentConfiguration: {
169 minimumHealthyPercent: 100,
170 maximumPercent: 200,
171 deploymentCircuitBreaker: {
172 enable: props.circuitBreaker,
173 rollback: props.circuitBreaker,
174 },
175 },
176 });
177 }),
178 );
179
180 const created = yield* deployService({
181 desiredCount: 0,
182 assignPublicIp: false,
183 tags: { env: "test", keep: "v1" },
184 circuitBreaker: false,
185 });
186
187 const updated = yield* deployService({
188 desiredCount: 0,
189 assignPublicIp: true,
190 tags: { env: "test", added: "new" },
191 circuitBreaker: true,
192 });
193
194 // No replacement — identity is stable.
195 expect(updated.serviceArn).toEqual(created.serviceArn);
196
197 // Verify out-of-band that updateService applied the changes.
198 const described = yield* ecs.describeServices({
199 cluster: updated.clusterArn,
200 services: [updated.serviceName],
201 include: ["TAGS"],
202 });
203 const svc = described.services?.[0];
204 expect(svc?.serviceArn).toEqual(created.serviceArn);
205 expect(svc?.taskDefinition).toEqual(taskDefinitionArn);
206 expect(svc?.runningCount).toBe(0);
207 expect(svc?.pendingCount).toBe(0);
208 expect(svc?.deployments).toHaveLength(1);
209 expect(svc?.deployments?.[0]?.status).toBe("PRIMARY");
210 expect(svc?.deployments?.[0]?.rolloutState).toBe("COMPLETED");
211 expect(svc?.deploymentConfiguration?.deploymentCircuitBreaker?.enable).toBe(true);
212 expect(svc?.networkConfiguration?.awsvpcConfiguration?.assignPublicIp).toBe("ENABLED");
213
214 // Tag reconcile: `keep` removed, `added` present, `env` retained.
215 const tagMap = Object.fromEntries((svc?.tags ?? []).map((t) => [t.key, t.value]));
216 expect(tagMap.added).toBe("new");
217 expect(tagMap.env).toBe("test");
218 expect(tagMap.keep).toBeUndefined();
219
220 // #2688: `read` must observe the service's deployment settings and the
221 // cluster's tags, or out-of-band changes read as `unchanged`.
222 const allUnchanged = (actions: Record<string, string | undefined>) =>
223 Object.values(actions).every((action) => action === "unchanged");
224 expect(allUnchanged(yield* driftActions(stack))).toBe(true);
225 yield* ecs.updateService({
226 cluster: updated.clusterArn,
227 service: updated.serviceName,
228 deploymentConfiguration: {
229 minimumHealthyPercent: 100,
230 maximumPercent: 200,
231 deploymentCircuitBreaker: { enable: false, rollback: false },
232 },
233 });
234 yield* ecs.tagResource({
235 resourceArn: updated.clusterArn,
236 tags: [{ key: "team", value: "out-of-band" }],
237 });
238 expect(
239 (yield* waitForDrift(stack, "InPlaceService", "drifted"))?.attr?.configuration
240 ?.deploymentConfiguration?.deploymentCircuitBreaker?.enable,
241 ).toBe(false);
242 expect((yield* waitForDrift(stack, "InPlaceCluster", "drifted"))?.attr?.tags?.team).toBe(
243 "out-of-band",
244 );
245 yield* repairDrift(stack);
246 expect(allUnchanged(yield* driftActions(stack))).toBe(true);
247 const repairedService = yield* ecs.describeServices({
248 cluster: updated.clusterArn,
249 services: [updated.serviceName],
250 });
251 expect(
252 repairedService.services?.[0]?.deploymentConfiguration?.deploymentCircuitBreaker?.enable,
253 ).toBe(true);
254
255 yield* stack.destroy();
256 yield* reclaimTaskDefinitionFamily(family);
257
258 // Out-of-band gone-proof: the cluster (deleted after its service) is
259 // INACTIVE or absent.
260 const after = yield* ecs.describeClusters({ clusters: ["alchemy-test-ecs-service-inplace"] });
261 expect((after.clusters ?? []).some((c) => c.status === "ACTIVE")).toBe(false);
262 }),
263 { tags: ["provider:aws", "provider:aws:ec2", "provider:aws:ecs", "live"], timeout: 420_000 },
264 );
265
266 test.provider(
267 "a stale failed deployment does not fail the replacement deployment",
268 (stack) =>
269 Effect.gen(function* () {
270 const family = "alchemy-test-ecs-service-failed-rollout";
271 const stableImage = "public.ecr.aws/nginx/nginx:stable";
272 const failingImage = "public.ecr.aws/docker/library/alpine:3.20";
273
274 const registerTaskDefinition = (image: string, command?: string[]) =>
275 ecs.registerTaskDefinition({
276 family,
277 networkMode: "awsvpc",
278 requiresCompatibilities: ["FARGATE"],
279 cpu: "256",
280 memory: "512",
281 containerDefinitions: [
282 {
283 name: "app",
284 image,
285 command,
286 essential: true,
287 portMappings: [{ containerPort: 80, protocol: "tcp" }],
288 },
289 ],
290 });
291
292 const deployService = (taskDefinitionArn: string, generation: string, desiredCount: number) =>
293 stack.deploy(
294 Effect.gen(function* () {
295 const defaultVpc = yield* getDefaultVpc;
296 const subnet = yield* Subnet("FailedRolloutSubnet", {
297 vpcId: defaultVpc.vpcId,
298 cidrBlock: defaultVpc.subnetCidrBlock(246),
299 });
300 const cluster = yield* Cluster("FailedRolloutCluster", { clusterName: family });
301 return yield* Service("FailedRolloutService", {
302 cluster,
303 task: { taskDefinitionArn, containerName: "app", port: 80 },
304 desiredCount,
305 vpcId: defaultVpc.vpcId,
306 subnets: [subnet.subnetId],
307 assignPublicIp: true,
308 tags: { generation },
309 deploymentStabilizationTimeout: "8 minutes",
310 deploymentConfiguration: {
311 minimumHealthyPercent: 0,
312 maximumPercent: 200,
313 deploymentCircuitBreaker: { enable: true, rollback: false },
314 },
315 });
316 }),
317 );
318
319 // Register cleanup before creating out-of-band task definitions.
320 yield* stack.destroy();
321 yield* reclaimTaskDefinitionFamily(family);
322 yield* Effect.addFinalizer(() =>
323 Effect.gen(function* () {
324 yield* stack.destroy().pipe(Effect.ignore);
325 yield* reclaimTaskDefinitionFamily(family).pipe(Effect.ignore);
326 }),
327 );
328
329 const initialTask = yield* registerTaskDefinition(stableImage);
330 const failingTask = yield* registerTaskDefinition(failingImage, ["sh", "-c", "exit 1"]);
331 const recoveryTask = yield* registerTaskDefinition(stableImage);
332 const initialTaskArn = initialTask.taskDefinition?.taskDefinitionArn!;
333 const failingTaskArn = failingTask.taskDefinition?.taskDefinitionArn!;
334 const recoveryTaskArn = recoveryTask.taskDefinition?.taskDefinitionArn!;
335
336 const created = yield* deployService(initialTaskArn, "initial", 0);
337 const describeService = ecs.describeServices({
338 cluster: created.clusterArn,
339 services: [created.serviceName],
340 });
341 const initialSnapshot = yield* describeService;
342
343 const failed = yield* deployService(failingTaskArn, "failed", 1).pipe(Effect.result);
344 expect(Result.isFailure(failed)).toBe(true);
345 if (Result.isFailure(failed)) {
346 expect(failed.failure).toBeInstanceOf(ServiceDidNotStabilize);
347 if (failed.failure instanceof ServiceDidNotStabilize) {
348 expect(failed.failure.message).toContain("reported a failed deployment");
349 expect(failed.failure.expectedTaskDefinitionArn).toBe(failingTaskArn);
350 }
351 }
352 const failedSnapshot = yield* describeService;
353 const failedDeployment = failedSnapshot.services?.[0]?.deployments?.find(
354 (deployment) => deployment.status === "PRIMARY",
355 );
356 expect(failedDeployment?.id).toBeDefined();
357 expect(failedDeployment?.taskDefinition).toBe(failingTaskArn);
358 expect(failedDeployment?.rolloutState).toBe("FAILED");
359 const failedDeploymentId = failedDeployment!.id!;
360
361 const [recovered, overlapping] = yield* Effect.all(
362 [
363 deployService(recoveryTaskArn, "recovered", 1),
364 describeService.pipe(
365 Effect.repeat({
366 schedule: Schedule.spaced("1 second"),
367 times: 120,
368 until: (response) => {
369 const deployments = response.services?.[0]?.deployments ?? [];
370 const primary = deployments.find((d) => d.status === "PRIMARY");
371 return (
372 primary?.taskDefinition === recoveryTaskArn &&
373 primary.id !== failedDeploymentId &&
374 (primary.rolloutState === "COMPLETED" ||
375 deployments.some(
376 (d) => d.id === failedDeploymentId && d.rolloutState === "FAILED",
377 ))
378 );
379 },
380 }),
381 ),
382 ],
383 { concurrency: 2 },
384 );
385 expect(recovered.serviceArn).toBe(created.serviceArn);
386 expect(recovered.taskDefinitionArn).toBe(recoveryTaskArn);
387 const overlappingDeployments = overlapping.services?.[0]?.deployments ?? [];
388 expect(
389 overlappingDeployments.some(
390 (d) => d.id === failedDeploymentId && d.rolloutState === "FAILED",
391 ),
392 ).toBe(true);
393 const recoveryDeploymentId = overlappingDeployments.find((d) => d.status === "PRIMARY")?.id;
394 expect(recoveryDeploymentId).toBeDefined();
395 expect(recoveryDeploymentId).not.toBe(failedDeploymentId);
396
397 const recoveredSnapshot = yield* describeService;
398 const recoveredService = recoveredSnapshot.services?.[0];
399 expect(recoveredService?.createdAt).toEqual(initialSnapshot.services?.[0]?.createdAt);
400 expect(recoveredService?.deployments).toHaveLength(1);
401 expect(recoveredService?.deployments?.[0]?.id).toBe(recoveryDeploymentId);
402 expect(recoveredService?.deployments?.[0]?.rolloutState).toBe("COMPLETED");
403 expect(recoveredService?.runningCount).toBe(1);
404 expect(recoveredService?.pendingCount).toBe(0);
405
406 yield* deployService(recoveryTaskArn, "forced-same-revision", 1);
407 const forcedSnapshot = yield* describeService;
408 const forcedService = forcedSnapshot.services?.[0];
409 expect(forcedService?.deployments).toHaveLength(1);
410 expect(forcedService?.deployments?.[0]?.id).not.toBe(recoveryDeploymentId);
411 expect(forcedService?.deployments?.[0]?.taskDefinition).toBe(recoveryTaskArn);
412 expect(forcedService?.deployments?.[0]?.rolloutState).toBe("COMPLETED");
413 expect(forcedService?.runningCount).toBe(1);
414 expect(forcedService?.pendingCount).toBe(0);
415
416 yield* stack.destroy();
417 yield* reclaimTaskDefinitionFamily(family);
418
419 const after = yield* ecs.describeClusters({ clusters: [family] });
420 expect((after.clusters ?? []).some((c) => c.status === "ACTIVE")).toBe(false);
421 }),
422 { tags: ["provider:aws", "provider:aws:ec2", "provider:aws:ecs", "live"], timeout: 900_000 },
423 );
424
425 // Manual (user-supplied) load balancer: create an ALB + target group OUT OF
426 // BAND, pass it explicitly via `loadBalancers` with `public: false`, and assert
427 // (a) no Alchemy-managed ALB was created (no `url`/`loadBalancerArn` on the
428 // attributes) and (b) the service is wired to the supplied target group.
429 //
430 // ECS `createService` rejects a target group that is not associated with a load
431 // balancer (`InvalidParameterException`), so we provision a real (but minimal)
432 // ALB + listener + target group out of band across two AZ subnets, wire the
433 // service to that target group with `public: false`, and assert no
434 // Alchemy-managed ALB was created.
435 test.provider(
436 "service wires a user-supplied target group without creating an ALB",
437 (stack) =>
438 Effect.gen(function* () {
439 // Clean up any out-of-band ELBv2 leftovers from a prior interrupted run
440 // BEFORE destroying the stack: a stale ALB holds ENIs in the
441 // stack-owned subnets and prevents their deletion. It also keeps the
442 // fresh ALB, target group, and listener consistently wired (a stale,
443 // unassociated target group would make `createService` reject with
444 // `InvalidParameterException`).
445 const existingLbs = yield* elbv2
446 .describeLoadBalancers({ Names: ["alchemy-test-ecs-manuallb"] })
447 .pipe(Effect.catch(() => Effect.succeed({ LoadBalancers: [] })));
448 for (const lb of existingLbs.LoadBalancers ?? []) {
449 const ls = yield* elbv2
450 .describeListeners({ LoadBalancerArn: lb.LoadBalancerArn! })
451 .pipe(Effect.catch(() => Effect.succeed({ Listeners: [] })));
452 for (const l of ls.Listeners ?? []) {
453 yield* elbv2
454 .deleteListener({ ListenerArn: l.ListenerArn! })
455 .pipe(Effect.catch(() => Effect.void));
456 }
457 yield* elbv2
458 .deleteLoadBalancer({ LoadBalancerArn: lb.LoadBalancerArn! })
459 .pipe(Effect.catch(() => Effect.void));
460 }
461 if ((existingLbs.LoadBalancers ?? []).length > 0) {
462 yield* Effect.sleep("8 seconds");
463 }
464 const existingTgs = yield* elbv2
465 .describeTargetGroups({ Names: ["alchemy-test-ecs-manuallb"] })
466 .pipe(Effect.catch(() => Effect.succeed({ TargetGroups: [] })));
467 for (const tg of existingTgs.TargetGroups ?? []) {
468 yield* elbv2.deleteTargetGroup({ TargetGroupArn: tg.TargetGroupArn! }).pipe(
469 Effect.retry({
470 while: (e) => e._tag === "ResourceInUseException",
471 schedule: Schedule.max([Schedule.spaced("3 seconds"), Schedule.recurs(5)]),
472 }),
473 Effect.catch(() => Effect.void),
474 );
475 }
476
477 yield* stack.destroy();
478
479 const family = "alchemy-test-ecs-service-manuallb";
480 yield* reclaimTaskDefinitionFamily(family);
481 yield* Effect.addFinalizer(() => reclaimTaskDefinitionFamily(family).pipe(Effect.ignore));
482
483 const registered = yield* ecs.registerTaskDefinition({
484 family,
485 networkMode: "awsvpc",
486 requiresCompatibilities: ["FARGATE"],
487 cpu: "256",
488 memory: "512",
489 containerDefinitions: [
490 {
491 name: "app",
492 image: "public.ecr.aws/nginx/nginx:stable",
493 essential: true,
494 portMappings: [{ containerPort: 80, protocol: "tcp" }],
495 },
496 ],
497 });
498 const taskDefinitionArn = registered.taskDefinition?.taskDefinitionArn!;
499 const defaultVpc = yield* getDefaultVpc;
500
501 // Resolve two available AZs in the active region — hardcoding zone
502 // names breaks as soon as the profile targets a different region.
503 const azResult = yield* ec2.describeAvailabilityZones({});
504 const availableAzs = (azResult.AvailabilityZones ?? []).filter(
505 (az) => az.State === "available",
506 );
507 const az1 = availableAzs[0]?.ZoneName!;
508 const az2 = availableAzs[1]?.ZoneName!;
509
510 // Deploy networking first so we can resolve concrete ids for the
511 // out-of-band ELBv2 resources.
512 const net = yield* stack.deploy(
513 Effect.gen(function* () {
514 const subnetA = yield* Subnet("ManualLbSubnetA", {
515 vpcId: defaultVpc.vpcId,
516 cidrBlock: defaultVpc.subnetCidrBlock(236),
517 availabilityZone: az1,
518 });
519 const subnetB = yield* Subnet("ManualLbSubnetB", {
520 vpcId: defaultVpc.vpcId,
521 cidrBlock: defaultVpc.subnetCidrBlock(237),
522 availabilityZone: az2,
523 });
524 const cluster = yield* Cluster("ManualLbCluster", {
525 clusterName: "alchemy-test-ecs-service-manuallb",
526 });
527 return {
528 vpcId: defaultVpc.vpcId,
529 subnetAId: subnetA.subnetId.as<string>(),
530 subnetBId: subnetB.subnetId.as<string>(),
531 clusterArn: cluster.clusterArn.as<string>(),
532 };
533 }),
534 );
535
536 // Create a real (internal) ALB + target group + listener out of band so
537 // the target group is associated with a load balancer.
538 const loadBalancer = yield* elbv2.createLoadBalancer({
539 Name: "alchemy-test-ecs-manuallb",
540 Type: "application",
541 Scheme: "internal",
542 Subnets: [net.subnetAId, net.subnetBId],
543 });
544 const loadBalancerArn = loadBalancer.LoadBalancers?.[0]?.LoadBalancerArn!;
545 // Safety-net finalizers (run LIFO on scope close): listener -> TG -> ALB,
546 // so the out-of-band ELBv2 resources are reclaimed even if the body fails.
547 yield* Effect.addFinalizer(() =>
548 elbv2.deleteLoadBalancer({ LoadBalancerArn: loadBalancerArn }).pipe(Effect.ignore),
549 );
550
551 const targetGroup = yield* elbv2.createTargetGroup({
552 Name: "alchemy-test-ecs-manuallb",
553 VpcId: net.vpcId,
554 TargetType: "ip",
555 Protocol: "HTTP",
556 Port: 80,
557 });
558 const targetGroupArn = targetGroup.TargetGroups?.[0]?.TargetGroupArn!;
559 yield* Effect.addFinalizer(() =>
560 elbv2.deleteTargetGroup({ TargetGroupArn: targetGroupArn }).pipe(Effect.ignore),
561 );
562
563 const listener = yield* elbv2.createListener({
564 LoadBalancerArn: loadBalancerArn,
565 Port: 80,
566 Protocol: "HTTP",
567 DefaultActions: [{ Type: "forward", TargetGroupArn: targetGroupArn }],
568 });
569 const listenerArn = listener.Listeners?.[0]?.ListenerArn!;
570 yield* Effect.addFinalizer(() =>
571 elbv2.deleteListener({ ListenerArn: listenerArn }).pipe(Effect.ignore),
572 );
573
574 // Re-declare the same networking (idempotent — same logical ids) plus the
575 // Service wired to the user-supplied target group.
576 const service = yield* stack.deploy(
577 Effect.gen(function* () {
578 const subnetA = yield* Subnet("ManualLbSubnetA", {
579 vpcId: defaultVpc.vpcId,
580 cidrBlock: defaultVpc.subnetCidrBlock(236),
581 availabilityZone: az1,
582 });
583 const subnetB = yield* Subnet("ManualLbSubnetB", {
584 vpcId: defaultVpc.vpcId,
585 cidrBlock: defaultVpc.subnetCidrBlock(237),
586 availabilityZone: az2,
587 });
588 const cluster = yield* Cluster("ManualLbCluster", {
589 clusterName: "alchemy-test-ecs-service-manuallb",
590 });
591 return yield* Service("ManualLbService", {
592 cluster,
593 task: { taskDefinitionArn, containerName: "app", port: 80 },
594 desiredCount: 0,
595 public: false,
596 vpcId: defaultVpc.vpcId,
597 subnets: [subnetA.subnetId, subnetB.subnetId],
598 loadBalancers: [{ targetGroupArn, containerName: "app", containerPort: 80 }],
599 // Duration.Input audit coverage: only valid on services with a
600 // load balancer — assert the wire value round-trips as seconds.
601 healthCheckGracePeriod: "45 seconds",
602 });
603 }),
604 );
605
606 // No Alchemy-managed ALB.
607 expect(service.loadBalancerArn).toBeUndefined();
608 expect(service.url).toBeUndefined();
609
610 const described = yield* ecs.describeServices({
611 cluster: service.clusterArn,
612 services: [service.serviceName],
613 });
614 const lbs = described.services?.[0]?.loadBalancers ?? [];
615 expect(lbs.length).toBe(1);
616 expect(lbs[0]?.containerName).toBe("app");
617 expect(lbs[0]?.targetGroupArn).toBe(targetGroupArn);
618
619 // Duration.Input round-trip: `"45 seconds"` landed on the wire as 45.
620 expect(described.services?.[0]?.healthCheckGracePeriodSeconds).toBe(45);
621
622 // Delete the service first (it references the target group), then tear
623 // down the out-of-band ELBv2 resources, then the rest of the stack.
624 yield* ecs
625 .deleteService({ cluster: service.clusterArn, service: service.serviceName, force: true })
626 .pipe(Effect.catch(() => Effect.void));
627 yield* elbv2
628 .deleteListener({ ListenerArn: listenerArn })
629 .pipe(Effect.catch(() => Effect.void));
630 yield* elbv2
631 .deleteLoadBalancer({ LoadBalancerArn: loadBalancerArn })
632 .pipe(Effect.catch(() => Effect.void));
633 yield* elbv2
634 .deleteTargetGroup({ TargetGroupArn: targetGroupArn })
635 .pipe(Effect.catch(() => Effect.void));
636
637 yield* stack.destroy();
638 yield* reclaimTaskDefinitionFamily(family);
639 }),
640 { tags: ["provider:aws", "provider:aws:ec2", "provider:aws:ecs", "live"], timeout: 240_000 },
641 );
642
643 // Regression test for https://github.com/alchemy-run/alchemy/issues/736.
644 //
645 // An interrupted first deploy persists the service as `status: "creating"`
646 // with no attributes — and the Output-valued props (`cluster` passed as a
647 // resource object, `task`, `vpcId`, `subnets`) do not survive the state
648 // round-trip: they deserialize as `undefined`. Plan's recovery branch then
649 // calls `provider.read` with those junk props, which crashed in
650 // `clusterArnOf(undefined)` and wedged the stack (plan/deploy/destroy all
651 // build a plan, so there was no CLI escape hatch).
652 //
653 // Simulate exactly that state row after a real deploy and assert the next
654 // deploy recovers: `read` reports "not found", the engine re-drives the
655 // create, and reconcile converges on the half-created service by name —
656 // SAME serviceArn, no replacement.
657 test.provider(
658 "recovers a half-created service whose creating-state lost Output-valued props (#736)",
659 (stack) =>
660 Effect.gen(function* () {
661 yield* stack.destroy();
662
663 const family = "alchemy-test-ecs-service-wedged";
664 yield* reclaimTaskDefinitionFamily(family);
665 yield* Effect.addFinalizer(() => reclaimTaskDefinitionFamily(family).pipe(Effect.ignore));
666
667 const registered = yield* ecs.registerTaskDefinition({
668 family,
669 networkMode: "awsvpc",
670 requiresCompatibilities: ["FARGATE"],
671 cpu: "256",
672 memory: "512",
673 containerDefinitions: [
674 {
675 name: "app",
676 image: "public.ecr.aws/nginx/nginx:stable",
677 essential: true,
678 portMappings: [{ containerPort: 80, protocol: "tcp" }],
679 },
680 ],
681 });
682 const taskDefinitionArn = registered.taskDefinition?.taskDefinitionArn!;
683 const defaultVpc = yield* getDefaultVpc;
684
685 const deployService = () =>
686 stack.deploy(
687 Effect.gen(function* () {
688 const subnet = yield* Subnet("WedgedSubnet", {
689 vpcId: defaultVpc.vpcId,
690 cidrBlock: defaultVpc.subnetCidrBlock(238),
691 });
692 const cluster = yield* Cluster("WedgedCluster", {
693 clusterName: "alchemy-test-ecs-service-wedged",
694 });
695 return yield* Service("WedgedService", {
696 // Whole resource object, NOT a string ARN — the #736 shape.
697 cluster,
698 task: { taskDefinitionArn, containerName: "app", port: 80 },
699 desiredCount: 0,
700 vpcId: defaultVpc.vpcId,
701 subnets: [subnet.subnetId],
702 });
703 }),
704 );
705
706 const created = yield* deployService();
707
708 // Rewrite the service's persisted row into the wedged shape an
709 // interrupted deploy leaves behind: `creating`, no attributes, and
710 // every Output-valued prop lost in the round-trip.
711 const state = yield* yield* State;
712 const stage = stack.stage;
713 const fqns = yield* state.list({ stack: stack.name, stage });
714 const rows = yield* Effect.forEach(fqns, (fqn) =>
715 state.get({ stack: stack.name, stage, fqn }).pipe(Effect.map((row) => ({ fqn, row }))),
716 );
717 const wedged = rows.find(
718 (r): r is { fqn: string; row: ResourceState } =>
719 isResourceState(r.row) && r.row.resourceType === "AWS.ECS.Service",
720 );
721 if (!wedged) {
722 return yield* Effect.die(new Error("no AWS.ECS.Service state row found after deploy"));
723 }
724 yield* state.set({
725 stack: stack.name,
726 stage,
727 fqn: wedged.fqn,
728 value: {
729 ...wedged.row,
730 status: "creating",
731 attr: undefined,
732 props: {
733 ...wedged.row.props,
734 cluster: undefined,
735 task: undefined,
736 vpcId: undefined,
737 subnets: undefined,
738 },
739 },
740 });
741
742 // Before the fix this crashed in plan with
743 // `TypeError: undefined is not an object (evaluating 'cluster.clusterArn')`.
744 const recovered = yield* deployService();
745 expect(recovered.serviceArn).toEqual(created.serviceArn);
746 expect(recovered.clusterArn).toEqual(created.clusterArn);
747
748 yield* stack.destroy();
749 yield* reclaimTaskDefinitionFamily(family);
750 }),
751 { tags: ["provider:aws", "provider:aws:ec2", "provider:aws:ecs", "live"], timeout: 240_000 },
752 );
753
754 // Regression: the image-owning `ServiceProps` form inherits
755 // `taskRoleManagedPolicyArns` from `TaskDefinitionConfig`, but reconcile
756 // used to honor only its sibling `executionRoleManagedPolicyArns` — services
757 // deployed with task roles silently missing their declared permissions.
758 // Deploy an image-form service (desiredCount 0, no ingress) declaring an
759 // AWS-managed policy, verify out of band that the policy is attached to the
760 // task role, redeploy to prove the attach is idempotent, and verify destroy
761 // detaches the policy and deletes the role.
762 test.provider(
763 "attaches taskRoleManagedPolicyArns to the task role (image form)",
764 (stack) =>
765 Effect.gen(function* () {
766 yield* stack.destroy();
767
768 const managedPolicyArn = "arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess";
769
770 const deployService = () =>
771 stack.deploy(
772 Effect.gen(function* () {
773 const cluster = yield* Cluster("TaskRolePolicyCluster", {
774 clusterName: "alchemy-test-ecs-service-task-role-policy",
775 });
776 return yield* Service("TaskRolePolicyService", {
777 cluster,
778 image: "busybox:stable",
779 command: ["sh", "-c", "while true; do sleep 30; done"],
780 port: 80,
781 desiredCount: 0,
782 taskRoleManagedPolicyArns: [managedPolicyArn],
783 });
784 }),
785 );
786
787 const created = yield* deployService();
788 const taskRoleName = created.taskRoleName;
789 if (!taskRoleName) {
790 return yield* Effect.die(new Error("image-form service returned no taskRoleName"));
791 }
792
793 const listAttachedArns = iam
794 .listAttachedRolePolicies({ RoleName: taskRoleName })
795 .pipe(Effect.map((r) => (r.AttachedPolicies ?? []).map((p) => p.PolicyArn)));
796
797 expect(yield* listAttachedArns).toContain(managedPolicyArn);
798
799 // Second deploy re-runs the attach against an already-attached ARN —
800 // `attachRolePolicy` is idempotent, so reconcile must not fail.
801 const updated = yield* deployService();
802 expect(updated.serviceArn).toEqual(created.serviceArn);
803 expect(yield* listAttachedArns).toContain(managedPolicyArn);
804
805 yield* stack.destroy();
806
807 // Gone-proof: destroy detached the managed policy and deleted the
808 // task role.
809 const roleGone = yield* iam.getRole({ RoleName: taskRoleName }).pipe(
810 Effect.map(() => false),
811 Effect.catchTag("NoSuchEntityException", () => Effect.succeed(true)),
812 );
813 expect(roleGone).toBe(true);
814 }),
815 { tags: ["provider:aws", "provider:aws:ecs", "provider:aws:iam", "live"], timeout: 240_000 },
816 );