@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, 04:45 UTC

main
ts 806 lines 30.1 KB
Raw
1 import * as logs from "@distilled.cloud/aws/cloudwatch-logs";
2 import * as ecs from "@distilled.cloud/aws/ecs";
3 import { Unowned } from "alchemy/AdoptPolicy";
4 import { deepEqual, isResolved } from "alchemy/Diff";
5 import { createPhysicalName } from "alchemy/PhysicalName";
6 import * as Provider from "alchemy/Provider";
7 import { Resource } from "alchemy/Resource";
8 import { createInternalTags, diffTags, hasAlchemyTags } from "alchemy/Tags";
9 import * as Data from "effect/Data";
10 import * as Effect from "effect/Effect";
11 import * as Schedule from "effect/Schedule";
12 import * as Stream from "effect/Stream";
13 import { AWSEnvironment } from "../Environment.ts";
14 import type { Providers } from "../Providers.ts";
15
16 /**
17 * Reference to an IAM role: a raw role ARN or anything exposing a `roleArn`
18 * attribute (e.g. an `AWS.IAM.Role` resource).
19 */
20 export type RoleRef = string | { roleArn: string };
21
22 export interface TaskDefinitionProps {
23 /**
24 * Task definition family. All revisions registered by this resource share
25 * this family. If omitted, a unique family is generated.
26 *
27 * Changing the family replaces the resource.
28 */
29 family?: string;
30
31 /**
32 * Container definitions for the task (bring-your-own images: ECR
33 * repository URIs, `public.ecr.aws/...`, Docker Hub, etc.).
34 *
35 * The first container is treated as the primary container: its `name` and
36 * first `portMappings[].containerPort` are surfaced as the `containerName`
37 * and `port` attributes so the task definition can be wired directly into
38 * `AWS.ECS.Service`'s `task` prop.
39 */
40 containerDefinitions: ecs.ContainerDefinition[];
41
42 /**
43 * Task-level CPU units. Required by Fargate.
44 * @default 256 when `requiresCompatibilities` includes `FARGATE`
45 */
46 cpu?: number | string;
47
48 /**
49 * Task-level memory (MiB). Required by Fargate.
50 * @default 512 when `requiresCompatibilities` includes `FARGATE`
51 */
52 memory?: number | string;
53
54 /**
55 * IAM role assumed by the containers at runtime (application permissions).
56 * Accepts a role ARN or an `AWS.IAM.Role` resource.
57 */
58 taskRoleArn?: RoleRef;
59
60 /**
61 * IAM role used by the ECS agent to pull images and ship logs. Accepts a
62 * role ARN or an `AWS.IAM.Role` resource. Required by Fargate when private
63 * registries or the `awslogs` log driver are used.
64 */
65 executionRoleArn?: RoleRef;
66
67 /**
68 * Docker network mode.
69 * @default "awsvpc" when `requiresCompatibilities` includes `FARGATE`
70 */
71 networkMode?: ecs.NetworkMode;
72
73 /**
74 * Launch-type compatibilities the task definition must support
75 * (`FARGATE` and/or `EC2`/`EXTERNAL`).
76 * @default ["FARGATE"]
77 */
78 requiresCompatibilities?: ecs.Compatibility[];
79
80 /**
81 * Convenience CloudWatch Logs wiring. When set, Alchemy creates (and owns)
82 * a log group and injects an `awslogs` `logConfiguration` into every
83 * container definition that does not declare its own.
84 *
85 * `true` uses the default group name `/ecs/{family}`; pass an object to
86 * override the group name or stream prefix. The log group is deleted when
87 * the resource is destroyed.
88 */
89 awslogs?:
90 | boolean
91 | {
92 /**
93 * Log group name.
94 * @default `/ecs/${family}`
95 */
96 group?: string;
97 /**
98 * awslogs stream prefix.
99 * @default the task family
100 */
101 streamPrefix?: string;
102 };
103
104 /**
105 * Task-level data volumes (host / docker / EFS / FSx Windows). Containers
106 * reference these via `mountPoints`.
107 */
108 volumes?: ecs.Volume[];
109
110 /**
111 * Task definition placement constraints (`memberOf` expressions). Only
112 * applies to EC2/EXTERNAL launch types.
113 */
114 placementConstraints?: ecs.TaskDefinitionPlacementConstraint[];
115
116 /**
117 * CPU architecture and operating-system family the task runs on, e.g.
118 * `{ cpuArchitecture: "ARM64", operatingSystemFamily: "LINUX" }`.
119 */
120 runtimePlatform?: ecs.RuntimePlatform;
121
122 /**
123 * Amount of ephemeral storage to allocate for the task on Fargate.
124 */
125 ephemeralStorage?: ecs.EphemeralStorage;
126
127 /**
128 * IPC resource namespace to use for the containers in the task.
129 */
130 ipcMode?: ecs.IpcMode;
131
132 /**
133 * Process namespace to use for the containers in the task.
134 */
135 pidMode?: ecs.PidMode;
136
137 /**
138 * App Mesh proxy configuration.
139 */
140 proxyConfiguration?: ecs.ProxyConfiguration;
141
142 /**
143 * Elastic Inference accelerators to attach to the task.
144 */
145 inferenceAccelerators?: ecs.InferenceAccelerator[];
146
147 /**
148 * Whether to enable AWS Fault Injection (FIS) actions on the task.
149 * @default false
150 */
151 enableFaultInjection?: boolean;
152
153 /**
154 * User-defined tags applied to each registered revision.
155 */
156 tags?: Record<string, string>;
157 }
158
159 export interface TaskDefinition extends Resource<
160 "AWS.ECS.TaskDefinition",
161 TaskDefinitionProps,
162 {
163 /**
164 * ARN of the latest revision registered by this resource.
165 */
166 taskDefinitionArn: string;
167 /**
168 * Task definition family.
169 */
170 family: string;
171 /**
172 * Revision number of {@link taskDefinitionArn}.
173 */
174 revision: number;
175 /**
176 * Name of the primary (first) container — for `AWS.ECS.Service` wiring.
177 */
178 containerName: string;
179 /**
180 * First `containerPort` of the primary container (0 when the container
181 * declares no port mappings) — for `AWS.ECS.Service` wiring.
182 */
183 port: number;
184 /**
185 * Resolved task role ARN, when configured.
186 */
187 taskRoleArn: string | undefined;
188 /**
189 * Resolved execution role ARN, when configured.
190 */
191 executionRoleArn: string | undefined;
192 /**
193 * Name of the Alchemy-managed log group, when `awslogs` is enabled.
194 */
195 logGroupName: string | undefined;
196 /**
197 * ARN of the Alchemy-managed log group, when `awslogs` is enabled.
198 */
199 logGroupArn: string | undefined;
200 },
201 never,
202 Providers
203 > {}
204
205 /**
206 * A standalone ECS task definition for bring-your-own-container workloads.
207 *
208 * Unlike the Effect-native `AWS.ECS.Task` (which bundles an inline program and
209 * builds/pushes a Docker image), `TaskDefinition` registers user-supplied
210 * `containerDefinitions` — any image URI from ECR, `public.ecr.aws`, or an
211 * external registry — with full control over Fargate/EC2 compatibility,
212 * volumes, runtime platform, and IAM roles.
213 *
214 * Task definitions are immutable revisions under a family:
215 *
216 * - reconcile registers a **new revision only when the definition content
217 * changed** (compared against the observed latest `ACTIVE` revision), so a
218 * no-op redeploy keeps the same revision;
219 * - changing the `family` replaces the resource;
220 * - destroy deregisters and hard-deletes every revision of the family. ECS
221 * may retain referenced revisions in `DELETE_IN_PROGRESS` until their tasks
222 * and services terminate; that is a successful terminal state.
223 *
224 * **Layering — why `TaskDefinition` is deliberately *not* a Platform.** ECS
225 * splits "what runs" from "how it runs": a task definition is the immutable
226 * container spec, while `Task` (runs to completion) and `Service`
227 * (long-running) are
228 * the execution vehicles. The effectful Platform abstraction requires
229 * Alchemy to own the container image and entrypoint so it can bundle the
230 * inline Effect program — that is exactly what `AWS.ECS.Task` does (bundle →
231 * Docker build/push → register definition → serve the program). Making
232 * `TaskDefinition` *also* a Platform would duplicate `Task` while
233 * contradicting this resource's purpose: user-supplied images whose
234 * entrypoint Alchemy must not rewrite. So the effectful path is
235 * `AWS.ECS.Task`; the bring-your-own-container path is `TaskDefinition`.
236 * Both surface `taskDefinitionArn` / `containerName` / `port`, so either
237 * plugs into `AWS.ECS.Service`'s `task` prop unchanged.
238 * ### Creating a Task Definition
239 * **Example:** Public Image on Fargate
240 * ```typescript
241 * const taskDef = yield* TaskDefinition("Nginx", {
242 * containerDefinitions: [
243 * {
244 * name: "nginx",
245 * image: "public.ecr.aws/nginx/nginx:stable",
246 * essential: true,
247 * portMappings: [{ containerPort: 80, protocol: "tcp" }],
248 * },
249 * ],
250 * });
251 * ```
252 *
253 * **Example:** With IAM Roles and CloudWatch Logs
254 * ```typescript
255 * const taskDef = yield* TaskDefinition("Api", {
256 * cpu: 512,
257 * memory: 1024,
258 * taskRoleArn: taskRole, // AWS.IAM.Role resource or raw ARN
259 * executionRoleArn: executionRole, // needed for awslogs / private images
260 * awslogs: true, // creates /ecs/{family} and injects awslogs config
261 * containerDefinitions: [
262 * {
263 * name: "api",
264 * image: image.imageUri,
265 * essential: true,
266 * portMappings: [{ containerPort: 8080 }],
267 * environment: [{ name: "STAGE", value: "prod" }],
268 * },
269 * ],
270 * });
271 * ```
272 *
273 * ### Running with a Service
274 * **Example:** Wire into AWS.ECS.Service
275 * ```typescript
276 * const service = yield* Service("ApiService", {
277 * cluster,
278 * task: taskDef, // exposes taskDefinitionArn / containerName / port
279 * vpcId: vpc.vpcId,
280 * subnets: [subnet.subnetId],
281 * assignPublicIp: true,
282 * });
283 * ```
284 *
285 * ### EC2 Launch Type
286 * **Example:** EC2 Task with a Host Volume
287 * ```typescript
288 * const taskDef = yield* TaskDefinition("Agent", {
289 * requiresCompatibilities: ["EC2"],
290 * networkMode: "bridge",
291 * volumes: [{ name: "docker-sock", host: { sourcePath: "/var/run/docker.sock" } }],
292 * containerDefinitions: [
293 * {
294 * name: "agent",
295 * image: "public.ecr.aws/docker/library/busybox:stable",
296 * memory: 128,
297 * essential: true,
298 * mountPoints: [{ sourceVolume: "docker-sock", containerPath: "/var/run/docker.sock" }],
299 * },
300 * ],
301 * });
302 * ```
303 *
304 * @resource
305 */
306 export const TaskDefinition = Resource<TaskDefinition>("AWS.ECS.TaskDefinition");
307
308 // Deeply drop undefined-valued keys and empty arrays so that "not set" and
309 // "AWS returned nothing" compare equal.
310 const canonicalize = (value: unknown): unknown => {
311 if (Array.isArray(value)) {
312 return value.map(canonicalize);
313 }
314 if (value !== null && typeof value === "object") {
315 const out: Record<string, unknown> = {};
316 for (const [k, v] of Object.entries(value)) {
317 if (v === undefined) continue;
318 if (Array.isArray(v) && v.length === 0) continue;
319 out[k] = canonicalize(v);
320 }
321 return out;
322 }
323 return value;
324 };
325
326 // Compare the desired request against the observed task definition, treating
327 // the desired shape as a projection: keys the desired request does not set are
328 // ignored (AWS default-fills many fields — container `cpu: 0`, `essential`,
329 // empty collections, `requiresAttributes`, timestamps, ...). Removed props are
330 // caught separately by diffing the old desired request against the new one.
331 const projectionEquals = (desired: unknown, observed: unknown): boolean => {
332 if (desired === undefined) return true;
333 if (Array.isArray(desired)) {
334 if (!Array.isArray(observed) || observed.length !== desired.length) {
335 return false;
336 }
337 return desired.every((d, i) => projectionEquals(d, observed[i]));
338 }
339 if (desired !== null && typeof desired === "object") {
340 if (observed === null || typeof observed !== "object" || Array.isArray(observed)) {
341 return false;
342 }
343 return Object.entries(desired).every(([k, v]) =>
344 projectionEquals(v, (observed as Record<string, unknown>)[k]),
345 );
346 }
347 return desired === observed;
348 };
349
350 // Normalize container definitions on both sides before comparing: sort
351 // environment entries by name and fill the wire defaults AWS applies to port
352 // mappings (protocol "tcp"; in awsvpc mode hostPort mirrors containerPort).
353 const normalizeContainers = (
354 defs: ecs.ContainerDefinition[] | undefined,
355 networkMode: ecs.NetworkMode | undefined,
356 ): ecs.ContainerDefinition[] =>
357 (defs ?? []).map((cd) => ({
358 ...cd,
359 environment:
360 cd.environment !== undefined && cd.environment.length > 0
361 ? [...cd.environment].sort((a, b) => (a.name ?? "").localeCompare(b.name ?? ""))
362 : undefined,
363 portMappings: cd.portMappings?.map((pm) => ({
364 ...pm,
365 protocol: pm.protocol ?? "tcp",
366 hostPort: networkMode === "awsvpc" ? (pm.hostPort ?? pm.containerPort) : pm.hostPort,
367 })),
368 }));
369
370 export const TaskDefinitionProvider = () =>
371 Provider.effect(
372 TaskDefinition,
373 Effect.gen(function* () {
374 const toFamily = (id: string, props: { family?: string } = {}) =>
375 props.family
376 ? Effect.succeed(props.family)
377 : createPhysicalName({
378 id,
379 maxLength: 255,
380 lowercase: true,
381 });
382
383 const roleArnOf = (ref: RoleRef | undefined): string | undefined =>
384 typeof ref === "string"
385 ? ref
386 : typeof (ref as { roleArn?: unknown } | undefined)?.roleArn === "string"
387 ? (ref as { roleArn: string }).roleArn
388 : undefined;
389
390 const logGroupNameOf = (family: string, props: TaskDefinitionProps): string | undefined =>
391 props.awslogs
392 ? ((typeof props.awslogs === "object" ? props.awslogs.group : undefined) ??
393 `/ecs/${family}`)
394 : undefined;
395
396 // The desired registerTaskDefinition request (sans tags), fully
397 // defaulted so it can be compared against the observed revision.
398 const desiredRequestOf = (
399 family: string,
400 props: TaskDefinitionProps,
401 region: string,
402 ): Omit<ecs.RegisterTaskDefinitionRequest, "tags"> => {
403 const requiresCompatibilities = props.requiresCompatibilities ?? ["FARGATE"];
404 const fargate = requiresCompatibilities.includes("FARGATE");
405 const networkMode = props.networkMode ?? (fargate ? "awsvpc" : undefined);
406 const logGroupName = logGroupNameOf(family, props);
407 const streamPrefix =
408 (typeof props.awslogs === "object" ? props.awslogs.streamPrefix : undefined) ?? family;
409 const containerDefinitions = props.containerDefinitions.map((cd) =>
410 logGroupName !== undefined && cd.logConfiguration === undefined
411 ? {
412 ...cd,
413 logConfiguration: {
414 logDriver: "awslogs",
415 options: {
416 "awslogs-group": logGroupName,
417 "awslogs-region": region,
418 "awslogs-stream-prefix": streamPrefix,
419 },
420 } satisfies ecs.LogConfiguration,
421 }
422 : cd,
423 );
424 return {
425 family,
426 taskRoleArn: roleArnOf(props.taskRoleArn),
427 executionRoleArn: roleArnOf(props.executionRoleArn),
428 networkMode,
429 containerDefinitions,
430 volumes: props.volumes,
431 placementConstraints: props.placementConstraints,
432 requiresCompatibilities,
433 cpu: props.cpu !== undefined ? String(props.cpu) : fargate ? "256" : undefined,
434 memory: props.memory !== undefined ? String(props.memory) : fargate ? "512" : undefined,
435 pidMode: props.pidMode,
436 ipcMode: props.ipcMode,
437 proxyConfiguration: props.proxyConfiguration,
438 inferenceAccelerators: props.inferenceAccelerators,
439 ephemeralStorage: props.ephemeralStorage,
440 runtimePlatform: props.runtimePlatform,
441 enableFaultInjection: props.enableFaultInjection,
442 };
443 };
444
445 const matchesObserved = (
446 desired: Omit<ecs.RegisterTaskDefinitionRequest, "tags">,
447 observed: ecs.TaskDefinition,
448 ): boolean =>
449 projectionEquals(
450 canonicalize({
451 ...desired,
452 containerDefinitions: normalizeContainers(
453 desired.containerDefinitions,
454 desired.networkMode,
455 ),
456 }),
457 canonicalize({
458 family: observed.family,
459 taskRoleArn: observed.taskRoleArn,
460 executionRoleArn: observed.executionRoleArn,
461 networkMode: observed.networkMode,
462 containerDefinitions: normalizeContainers(
463 observed.containerDefinitions,
464 observed.networkMode,
465 ),
466 volumes: observed.volumes,
467 placementConstraints: observed.placementConstraints,
468 requiresCompatibilities: observed.requiresCompatibilities,
469 cpu: observed.cpu,
470 memory: observed.memory,
471 pidMode: observed.pidMode,
472 ipcMode: observed.ipcMode,
473 proxyConfiguration: observed.proxyConfiguration,
474 inferenceAccelerators: observed.inferenceAccelerators,
475 ephemeralStorage: observed.ephemeralStorage,
476 runtimePlatform: observed.runtimePlatform,
477 enableFaultInjection: observed.enableFaultInjection,
478 }),
479 );
480
481 const describeLatestActive = (taskDefinition: string) =>
482 ecs.describeTaskDefinition({ taskDefinition }).pipe(
483 Effect.map((described) =>
484 described.taskDefinition?.status === "ACTIVE" ? described.taskDefinition : undefined,
485 ),
486 // "Unable to describe task definition" — no ACTIVE revision exists.
487 Effect.catchTag("ClientException", () => Effect.undefined),
488 );
489
490 const attrsOf = (
491 td: ecs.TaskDefinition,
492 logGroup: { logGroupName?: string; logGroupArn?: string } = {},
493 ): TaskDefinition["Attributes"] | undefined => {
494 if (!td.taskDefinitionArn || !td.family || td.revision === undefined) {
495 return undefined;
496 }
497 const container = td.containerDefinitions?.[0];
498 return {
499 taskDefinitionArn: td.taskDefinitionArn,
500 family: td.family,
501 revision: td.revision,
502 containerName: container?.name ?? td.family,
503 port: container?.portMappings?.[0]?.containerPort ?? 0,
504 taskRoleArn: td.taskRoleArn,
505 executionRoleArn: td.executionRoleArn,
506 logGroupName: logGroup.logGroupName,
507 logGroupArn: logGroup.logGroupArn,
508 };
509 };
510
511 const observedTagsOf = Effect.fn(function* (resourceArn: string) {
512 const listed = yield* ecs
513 .listTagsForResource({ resourceArn })
514 .pipe(
515 Effect.catchTag("ClientException", () =>
516 Effect.succeed({ tags: undefined } as { tags?: ecs.Tag[] }),
517 ),
518 );
519 return Object.fromEntries(
520 (listed.tags ?? [])
521 .filter(
522 (t): t is { key: string; value: string } =>
523 typeof t.key === "string" && typeof t.value === "string",
524 )
525 .map((t) => [t.key, t.value]),
526 );
527 });
528
529 const listFamilyArns = Effect.fn(function* (family: string, status: "ACTIVE" | "INACTIVE") {
530 const arns = yield* ecs.listTaskDefinitions.pages({ familyPrefix: family, status }).pipe(
531 Stream.runCollect,
532 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.taskDefinitionArns ?? [])),
533 );
534 // familyPrefix is a prefix match — filter to the exact family.
535 return arns.filter((arn) => arn.split("/").pop()?.split(":")[0] === family);
536 });
537
538 class TaskDefinitionRevisionNotTerminal extends Data.TaggedError(
539 "TaskDefinitionRevisionNotTerminal",
540 )<{
541 readonly taskDefinitionArn: string;
542 readonly status: ecs.TaskDefinitionStatus | undefined;
543 }> {}
544
545 const deletionObservationSchedule = Schedule.max([
546 Schedule.spaced("1 second"),
547 Schedule.recurs(15),
548 ]);
549
550 const waitUntilRevisionDeregistered = Effect.fn(function* (taskDefinitionArn: string) {
551 yield* ecs.describeTaskDefinition({ taskDefinition: taskDefinitionArn }).pipe(
552 Effect.flatMap(({ taskDefinition }) =>
553 taskDefinition?.status !== "ACTIVE"
554 ? Effect.void
555 : Effect.fail(
556 new TaskDefinitionRevisionNotTerminal({
557 taskDefinitionArn,
558 status: taskDefinition.status,
559 }),
560 ),
561 ),
562 Effect.retry({
563 while: (error) => error._tag === "TaskDefinitionRevisionNotTerminal",
564 schedule: deletionObservationSchedule,
565 }),
566 Effect.catchTag("ClientException", () => Effect.void),
567 );
568 });
569
570 const waitUntilRevisionDeletionStarted = Effect.fn(function* (taskDefinitionArn: string) {
571 yield* ecs.describeTaskDefinition({ taskDefinition: taskDefinitionArn }).pipe(
572 Effect.flatMap(({ taskDefinition }) =>
573 taskDefinition?.status === "DELETE_IN_PROGRESS"
574 ? Effect.void
575 : Effect.fail(
576 new TaskDefinitionRevisionNotTerminal({
577 taskDefinitionArn,
578 status: taskDefinition?.status,
579 }),
580 ),
581 ),
582 Effect.retry({
583 while: (error) => error._tag === "TaskDefinitionRevisionNotTerminal",
584 schedule: deletionObservationSchedule,
585 }),
586 // ECS eventually removes an unreferenced DELETE_IN_PROGRESS
587 // revision. Not-found is therefore also a successful terminal
588 // observation; literal absence is not required because referenced
589 // revisions may legitimately remain DELETE_IN_PROGRESS.
590 Effect.catchTag("ClientException", () => Effect.void),
591 );
592 });
593
594 return {
595 stables: ["family"],
596 diff: Effect.fn(function* ({ id, olds, news }) {
597 if (!isResolved(news)) return;
598 if ((yield* toFamily(id, olds ?? {})) !== (yield* toFamily(id, news ?? {}))) {
599 return { action: "replace" } as const;
600 }
601 }),
602 read: Effect.fn(function* ({ id, olds, output }) {
603 const family = output?.family ?? (yield* toFamily(id, olds ?? {}));
604 const td = yield* describeLatestActive(family);
605 if (!td?.taskDefinitionArn) {
606 return undefined;
607 }
608 const attrs = attrsOf(td, {
609 logGroupName: output?.logGroupName,
610 logGroupArn: output?.logGroupArn,
611 });
612 if (!attrs) {
613 return undefined;
614 }
615 const tags = yield* observedTagsOf(td.taskDefinitionArn);
616 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
617 }),
618 reconcile: Effect.fn(function* ({ id, news, olds, output, session }) {
619 const { accountId, region } = yield* AWSEnvironment.current;
620 const family = yield* toFamily(id, news);
621 const desired = desiredRequestOf(family, news, region);
622 const desiredTags = {
623 ...(yield* createInternalTags(id)),
624 ...news.tags,
625 };
626
627 // Alchemy-managed log group (awslogs convenience). Create the
628 // desired group if requested; drop a previously-managed group whose
629 // name no longer matches (renamed or awslogs disabled).
630 const logGroupName = logGroupNameOf(family, news);
631 if (output?.logGroupName && output.logGroupName !== logGroupName) {
632 yield* logs
633 .deleteLogGroup({ logGroupName: output.logGroupName })
634 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
635 }
636 let logGroup: { logGroupName?: string; logGroupArn?: string } = {};
637 if (logGroupName !== undefined) {
638 yield* logs
639 .createLogGroup({ logGroupName, tags: desiredTags })
640 .pipe(Effect.catchTag("ResourceAlreadyExistsException", () => Effect.void));
641 logGroup = {
642 logGroupName,
643 logGroupArn: `arn:aws:logs:${region}:${accountId}:log-group:${logGroupName}`,
644 };
645 }
646
647 // Observe — the latest ACTIVE revision of the family is the
648 // authoritative current state (output is only an identity cache).
649 const observed = yield* describeLatestActive(family);
650
651 // A new revision is needed when the observed revision drifted from
652 // the desired definition, or when a prop was *removed* relative to
653 // the previous desired state (removal falls back to an AWS default
654 // that the projection comparison intentionally ignores).
655 const removedProps =
656 olds !== undefined &&
657 !deepEqual(canonicalize(desiredRequestOf(family, olds, region)), canonicalize(desired));
658 const upToDate =
659 observed !== undefined && !removedProps && matchesObserved(desired, observed);
660
661 if (upToDate) {
662 // No-op redeploy — reuse the observed revision; converge tags.
663 const revisionArn = observed.taskDefinitionArn!;
664 const observedTags = yield* observedTagsOf(revisionArn);
665 const { removed, upsert } = diffTags(observedTags, desiredTags);
666 if (upsert.length > 0) {
667 yield* ecs.tagResource({
668 resourceArn: revisionArn,
669 tags: upsert.map((t) => ({ key: t.Key, value: t.Value })),
670 });
671 }
672 if (removed.length > 0) {
673 yield* ecs.untagResource({
674 resourceArn: revisionArn,
675 tagKeys: removed,
676 });
677 }
678 yield* session.note(revisionArn);
679 return attrsOf(observed, logGroup)!;
680 }
681
682 // Register a new immutable revision. Prior revisions stay ACTIVE
683 // (running tasks/services keep working) and are deregistered when
684 // the resource is deleted.
685 const registered = yield* ecs.registerTaskDefinition({
686 ...desired,
687 tags: Object.entries(desiredTags).map(([key, value]) => ({
688 key,
689 value,
690 })),
691 });
692 const td = registered.taskDefinition;
693 const attrs = td && attrsOf(td, logGroup);
694 if (!attrs) {
695 return yield* Effect.die(
696 new Error("registerTaskDefinition returned no task definition"),
697 );
698 }
699 yield* session.note(attrs.taskDefinitionArn);
700 return attrs;
701 }),
702 // Enumerate the latest ACTIVE revision of every task definition
703 // family in the account/region.
704 list: () =>
705 Effect.gen(function* () {
706 const arns = yield* ecs.listTaskDefinitions.pages({ status: "ACTIVE" }).pipe(
707 Stream.runCollect,
708 Effect.map((chunk) =>
709 Array.from(chunk).flatMap((page) => page.taskDefinitionArns ?? []),
710 ),
711 );
712 const latest = new Map<string, { arn: string; revision: number }>();
713 for (const arn of arns) {
714 const suffix = arn.split("/").pop();
715 if (!suffix) continue;
716 const sep = suffix.lastIndexOf(":");
717 const family = suffix.slice(0, sep);
718 const revision = Number(suffix.slice(sep + 1));
719 const current = latest.get(family);
720 if (!current || revision > current.revision) {
721 latest.set(family, { arn, revision });
722 }
723 }
724 const rows = yield* Effect.forEach(
725 [...latest.values()],
726 ({ arn }) =>
727 ecs.describeTaskDefinition({ taskDefinition: arn }).pipe(
728 Effect.map((described) =>
729 described.taskDefinition ? attrsOf(described.taskDefinition) : undefined,
730 ),
731 Effect.catchTag("ClientException", () => Effect.undefined),
732 ),
733 { concurrency: 10 },
734 );
735 return rows.filter((row): row is TaskDefinition["Attributes"] => row !== undefined);
736 }),
737 delete: Effect.fn(function* ({ output }) {
738 // Deregister every ACTIVE revision of the family (the family is
739 // this resource's physical identity), tolerating already-INACTIVE
740 // races, then hard-delete all revisions. AWS can retain a referenced
741 // revision in DELETE_IN_PROGRESS, so observe that exact terminal
742 // status rather than waiting indefinitely for physical absence.
743 const active = yield* listFamilyArns(output.family, "ACTIVE").pipe(
744 Effect.catchTag("ClientException", () => Effect.succeed([] as string[])),
745 );
746 const alreadyInactive = yield* listFamilyArns(output.family, "INACTIVE").pipe(
747 Effect.catchTag("ClientException", () => Effect.succeed([] as string[])),
748 );
749 for (const arn of active) {
750 yield* ecs
751 .deregisterTaskDefinition({ taskDefinition: arn })
752 .pipe(
753 Effect.catchTag(
754 ["ClientException", "InvalidParameterException"],
755 () => Effect.void,
756 ),
757 );
758 }
759 yield* Effect.forEach(active, waitUntilRevisionDeregistered, {
760 concurrency: 10,
761 });
762 const inactive = [
763 ...new Set([
764 ...active,
765 ...alreadyInactive,
766 ...(yield* listFamilyArns(output.family, "INACTIVE").pipe(
767 Effect.catchTag("ClientException", () => Effect.succeed([] as string[])),
768 )),
769 ]),
770 ];
771 for (let i = 0; i < inactive.length; i += 10) {
772 const deleted = yield* ecs
773 .deleteTaskDefinitions({
774 taskDefinitions: inactive.slice(i, i + 10),
775 })
776 .pipe(
777 Effect.catchTag(
778 ["ClientException", "InvalidParameterException"],
779 () => Effect.void,
780 ),
781 );
782 if (deleted && (deleted.failures?.length ?? 0) > 0) {
783 return yield* Effect.die(
784 new Error(
785 `ECS failed to delete task definition revisions: ${deleted.failures
786 ?.map(
787 (failure) =>
788 `${failure.arn ?? "unknown"}: ${failure.reason ?? "unknown"} (${failure.detail ?? "no detail"})`,
789 )
790 .join(", ")}`,
791 ),
792 );
793 }
794 }
795 yield* Effect.forEach(inactive, waitUntilRevisionDeletionStarted, {
796 concurrency: 10,
797 });
798 if (output.logGroupName) {
799 yield* logs
800 .deleteLogGroup({ logGroupName: output.logGroupName })
801 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
802 }
803 }),
804 };
805 }),
806 );