@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 489 lines 19.4 KB
Raw
1 import * as ecs from "@distilled.cloud/aws/ecs";
2 import { isResolved } from "alchemy/Diff";
3 import { createPhysicalName } from "alchemy/PhysicalName";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import { createInternalTags, diffTags } from "alchemy/Tags";
7 import * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import * as Schedule from "effect/Schedule";
10 import * as Stream from "effect/Stream";
11 import { AWSEnvironment, type AccountID } from "../Environment.ts";
12 import type { Providers } from "../Providers.ts";
13 import type { RegionID } from "../Region.ts";
14
15 export type ClusterName = string;
16 export type ClusterArn = `arn:aws:ecs:${RegionID}:${AccountID}:cluster/${ClusterName}`;
17
18 export interface ClusterProps {
19 /**
20 * Cluster name. If omitted, a unique name is generated.
21 */
22 clusterName?: string;
23 /**
24 * ECS cluster settings such as container insights.
25 */
26 settings?: ecs.ClusterSetting[];
27 /**
28 * Cluster configuration such as execute command logging.
29 */
30 configuration?: ecs.ClusterConfiguration;
31 /**
32 * Optional capacity providers associated with the cluster.
33 */
34 capacityProviders?: string[];
35 /**
36 * Default capacity provider strategy for the cluster.
37 */
38 defaultCapacityProviderStrategy?: ecs.CapacityProviderStrategyItem[];
39 /**
40 * Optional Service Connect defaults for the cluster.
41 */
42 serviceConnectDefaults?: ecs.ClusterServiceConnectDefaultsRequest;
43 /**
44 * User-defined tags to apply to the cluster.
45 */
46 tags?: Record<string, string>;
47 }
48
49 export interface Cluster extends Resource<
50 "AWS.ECS.Cluster",
51 ClusterProps,
52 {
53 /** The ARN of the cluster. */
54 clusterArn: ClusterArn;
55 /** The name of the cluster. */
56 clusterName: ClusterName;
57 /** The current status of the cluster, e.g. `ACTIVE`. */
58 status: string;
59 /** The cluster settings, e.g. Container Insights. */
60 settings: ecs.ClusterSetting[];
61 /** The execute-command configuration of the cluster. */
62 configuration?: ecs.ClusterConfiguration;
63 /** The capacity providers associated with the cluster. */
64 capacityProviders: string[];
65 /** The default capacity provider strategy for the cluster. */
66 defaultCapacityProviderStrategy: ecs.CapacityProviderStrategyItem[];
67 /** The default Service Connect namespace. */
68 serviceConnectDefaults?: ecs.ClusterServiceConnectDefaultsRequest;
69 /** The tags attached to the cluster. */
70 tags: Record<string, string>;
71 },
72 never,
73 Providers
74 > {}
75
76 /**
77 * An Amazon ECS cluster for running tasks and services.
78 * ### Creating Clusters
79 * **Example:** Default Cluster
80 * ```typescript
81 * const cluster = yield* Cluster("AppCluster", {});
82 * ```
83 *
84 * @resource
85 */
86 export const Cluster = Resource<Cluster>("AWS.ECS.Cluster");
87
88 class ClusterStillActive extends Data.TaggedError("ClusterStillActive")<{
89 readonly cluster: string;
90 readonly status: string | undefined;
91 }> {}
92
93 class ClusterNotActive extends Data.TaggedError("ClusterNotActive")<{
94 readonly cluster: string;
95 readonly status: string | undefined;
96 }> {}
97
98 export const ClusterProvider = () =>
99 Provider.effect(
100 Cluster,
101 Effect.gen(function* () {
102 const toEcsTags = (tags: Record<string, string>): ecs.Tag[] =>
103 Object.entries(tags).map(([key, value]) => ({
104 key,
105 value,
106 }));
107
108 // The one projection of a described cluster onto Attributes, shared by
109 // read, list and reconcile so drift compares like with like.
110 const toAttrs = (cluster: ecs.Cluster, tags: Record<string, string>) => ({
111 clusterArn: cluster.clusterArn as ClusterArn,
112 clusterName: cluster.clusterName!,
113 status: cluster.status ?? "ACTIVE",
114 settings: cluster.settings ?? [],
115 configuration: cluster.configuration,
116 capacityProviders: cluster.capacityProviders ?? [],
117 defaultCapacityProviderStrategy: cluster.defaultCapacityProviderStrategy ?? [],
118 serviceConnectDefaults: cluster.serviceConnectDefaults?.namespace
119 ? { namespace: cluster.serviceConnectDefaults.namespace }
120 : undefined,
121 tags,
122 });
123
124 const toClusterName = (id: string, props: { clusterName?: string } = {}) =>
125 props.clusterName
126 ? Effect.succeed(props.clusterName)
127 : createPhysicalName({ id, maxLength: 255, lowercase: true });
128
129 const applyCapacityProviders = Effect.fn(function* ({
130 cluster,
131 capacityProviders,
132 defaultCapacityProviderStrategy,
133 }: {
134 cluster: string;
135 capacityProviders?: string[];
136 defaultCapacityProviderStrategy?: ecs.CapacityProviderStrategyItem[];
137 }) {
138 if (capacityProviders !== undefined || defaultCapacityProviderStrategy !== undefined) {
139 yield* ecs
140 .putClusterCapacityProviders({
141 cluster,
142 capacityProviders: capacityProviders ?? [],
143 defaultCapacityProviderStrategy: defaultCapacityProviderStrategy ?? [],
144 })
145 .pipe(
146 // The first CreateCluster in an account creates the
147 // AWSServiceRoleForECS service-linked role asynchronously. Until
148 // it is usable, this call rejects the cluster we just observed
149 // ACTIVE as unassumable or not found.
150 Effect.retry({
151 while: (e) =>
152 e._tag === "ServiceLinkedRoleNotAssumable" ||
153 e._tag === "ClusterNotFoundException",
154 schedule: Schedule.spaced("3 seconds"),
155 times: 15,
156 }),
157 );
158 }
159 });
160
161 return {
162 stables: ["clusterArn", "clusterName"],
163 diff: Effect.fn(function* ({ id, olds, news }) {
164 if (!isResolved(news)) return;
165 if ((yield* toClusterName(id, olds ?? {})) !== (yield* toClusterName(id, news ?? {}))) {
166 return { action: "replace" } as const;
167 }
168 }),
169 read: Effect.fn(function* ({ id, olds, output }) {
170 const clusterName = output?.clusterName ?? (yield* toClusterName(id, olds ?? {}));
171 const described = yield* ecs.describeClusters({
172 clusters: [output?.clusterArn ?? clusterName],
173 include: ["SETTINGS", "TAGS", "CONFIGURATIONS"],
174 });
175 const cluster = described.clusters?.[0];
176 // ECS deletion is a transition to INACTIVE. AWS may continue to
177 // return an inactive cluster from DescribeClusters for a while, but
178 // it is no longer a usable resource and must not be resurrected in
179 // state during refresh.
180 if (!cluster?.clusterArn || cluster.status === "INACTIVE") {
181 return undefined;
182 }
183 return toAttrs(
184 cluster,
185 Object.fromEntries(
186 (cluster.tags ?? []).flatMap((t) =>
187 typeof t.key === "string" && typeof t.value === "string" ? [[t.key, t.value]] : [],
188 ),
189 ),
190 );
191 }),
192 list: () =>
193 Effect.gen(function* () {
194 // Enumerate every cluster ARN in the account/region, paginating
195 // listClusters exhaustively.
196 const arns = yield* ecs.listClusters.pages({}).pipe(
197 Stream.runCollect,
198 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.clusterArns ?? [])),
199 );
200 if (arns.length === 0) {
201 return [];
202 }
203 // describeClusters accepts at most 100 clusters per call; batch.
204 const batches: string[][] = [];
205 for (let i = 0; i < arns.length; i += 100) {
206 batches.push(arns.slice(i, i + 100));
207 }
208 const described = yield* Effect.forEach(
209 batches,
210 (clusters) =>
211 ecs
212 .describeClusters({
213 clusters,
214 include: ["SETTINGS", "TAGS", "CONFIGURATIONS"],
215 })
216 .pipe(Effect.map((res) => res.clusters ?? [])),
217 { concurrency: 5 },
218 );
219 return described.flat().flatMap((cluster) => {
220 // DeleteCluster does not immediately erase a cluster. Inactive
221 // clusters can remain discoverable according to the ECS API,
222 // so exclude that terminal state from nuke/provider inventory.
223 if (!cluster.clusterArn || cluster.status === "INACTIVE") {
224 return [];
225 }
226 const tags = Object.fromEntries(
227 (cluster.tags ?? [])
228 .filter(
229 (t): t is { key: string; value: string } =>
230 typeof t.key === "string" && typeof t.value === "string",
231 )
232 .map((t) => [t.key, t.value]),
233 );
234 return [toAttrs(cluster, tags)];
235 });
236 }),
237 reconcile: Effect.fn(function* ({ id, news: rawNews, session }) {
238 // Every ClusterProps field is optional, so `Cluster("Id")` (no
239 // props object at all) is a legal instantiation — normalize.
240 const news = rawNews ?? {};
241 const { accountId, region } = yield* AWSEnvironment.current;
242 const clusterName = yield* toClusterName(id, news);
243 const clusterArn =
244 `arn:aws:ecs:${region}:${accountId}:cluster/${clusterName}` as ClusterArn;
245 const internalTags = yield* createInternalTags(id);
246 const desiredTags = { ...internalTags, ...news.tags };
247
248 // Observe — fetch live cloud state.
249 let described = yield* ecs.describeClusters({
250 clusters: [clusterArn],
251 include: ["SETTINGS", "TAGS", "CONFIGURATIONS"],
252 });
253 let cluster = described.clusters?.find(
254 (c) =>
255 c.clusterName === clusterName &&
256 (c.status === "ACTIVE" || c.status === "PROVISIONING"),
257 );
258
259 // Ensure — create if missing. ECS createCluster is idempotent for
260 // identical params and returns the existing cluster on conflict;
261 // we always sync below regardless.
262 if (!cluster?.clusterArn) {
263 const created = yield* ecs.createCluster({
264 clusterName,
265 settings: news.settings,
266 configuration: news.configuration,
267 serviceConnectDefaults: news.serviceConnectDefaults,
268 tags: toEcsTags(desiredTags),
269 });
270 cluster = created.cluster;
271 }
272
273 // CreateCluster may return before the cluster is ready for updates.
274 // Re-read its status before configuration, capacity-provider or tag writes.
275 cluster = yield* ecs
276 .describeClusters({
277 clusters: [clusterArn],
278 include: ["SETTINGS", "TAGS", "CONFIGURATIONS"],
279 })
280 .pipe(
281 Effect.flatMap((response) => {
282 const observed = response.clusters?.find(
283 (candidate) => candidate.clusterArn === clusterArn,
284 );
285 return observed?.status === "ACTIVE"
286 ? Effect.succeed(observed)
287 : Effect.fail(
288 new ClusterNotActive({
289 cluster: clusterArn,
290 status: observed?.status,
291 }),
292 );
293 }),
294 Effect.retry({
295 while: (error) => error._tag === "ClusterNotActive",
296 schedule: Schedule.spaced("2 seconds"),
297 times: 10,
298 }),
299 );
300
301 // Sync cluster config — call updateCluster to converge settings,
302 // configuration, and serviceConnectDefaults to desired state.
303 yield* ecs.updateCluster({
304 cluster: clusterArn,
305 settings: news.settings,
306 configuration: news.configuration,
307 serviceConnectDefaults: news.serviceConnectDefaults,
308 });
309
310 // Sync capacity providers — observed ↔ desired.
311 yield* applyCapacityProviders({
312 cluster: clusterArn,
313 capacityProviders: news.capacityProviders,
314 defaultCapacityProviderStrategy: news.defaultCapacityProviderStrategy,
315 });
316
317 // Sync tags — diff observed cloud tags against desired.
318 const observedTags = Object.fromEntries(
319 (cluster?.tags ?? [])
320 .filter(
321 (t): t is { key: string; value: string } =>
322 typeof t.key === "string" && typeof t.value === "string",
323 )
324 .map((t) => [t.key, t.value]),
325 );
326 const { removed, upsert } = diffTags(observedTags, desiredTags);
327 if (upsert.length > 0) {
328 yield* ecs.tagResource({
329 resourceArn: clusterArn,
330 tags: upsert.map((tag) => ({ key: tag.Key, value: tag.Value })),
331 });
332 }
333 if (removed.length > 0) {
334 yield* ecs.untagResource({
335 resourceArn: clusterArn,
336 tagKeys: removed,
337 });
338 }
339
340 yield* session.note(clusterArn);
341 // Return what ECS reports, not the props: it fills in account
342 // defaults (e.g. `containerInsights`) that `read` observes, so
343 // echoing the props would report drift on an untouched cluster.
344 const final = (yield* ecs.describeClusters({
345 clusters: [clusterArn],
346 include: ["SETTINGS", "TAGS", "CONFIGURATIONS"],
347 })).clusters?.find((candidate) => candidate.clusterArn === clusterArn);
348 return toAttrs(final ?? cluster, desiredTags);
349 }),
350 delete: Effect.fn(function* ({ output }) {
351 const cluster = output.clusterArn;
352
353 // Observe mutable associations instead of trusting persisted output:
354 // capacity providers can be attached out of band or output can be
355 // stale after a prior interrupted reconcile.
356 const observedCluster = (yield* ecs.describeClusters({
357 clusters: [cluster],
358 })).clusters?.find((candidate) => candidate.clusterArn === cluster);
359
360 // A cluster cannot be deleted while it still contains services,
361 // running tasks, or registered container instances — empty it
362 // first so deletion actually converges instead of silently
363 // leaving the cluster behind.
364
365 // 1. Delete services (force skips the scale-to-zero dance).
366 const serviceArns = yield* ecs.listServices.pages({ cluster }).pipe(
367 Stream.runCollect,
368 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.serviceArns ?? [])),
369 Effect.catchTag("ClusterNotFoundException", () => Effect.succeed([] as string[])),
370 );
371 yield* Effect.forEach(
372 serviceArns,
373 (service) =>
374 ecs.deleteService({ cluster, service, force: true }).pipe(
375 Effect.catchTag(
376 ["ServiceNotFoundException", "ClusterNotFoundException"],
377 () => Effect.undefined,
378 ),
379 Effect.asVoid,
380 ),
381 { discard: true },
382 );
383
384 // 2. Stop any remaining standalone tasks.
385 const taskArns = yield* ecs.listTasks.pages({ cluster }).pipe(
386 Stream.runCollect,
387 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.taskArns ?? [])),
388 Effect.catchTag("ClusterNotFoundException", () => Effect.succeed([] as string[])),
389 );
390 yield* Effect.forEach(
391 taskArns,
392 (task) =>
393 ecs.stopTask({ cluster, task, reason: "alchemy delete" }).pipe(
394 Effect.catchTag("ClusterNotFoundException", () => Effect.undefined),
395 Effect.asVoid,
396 ),
397 { discard: true },
398 );
399
400 // 3. Deregister container instances (EC2 launch type).
401 const instanceArns = yield* ecs.listContainerInstances.pages({ cluster }).pipe(
402 Stream.runCollect,
403 Effect.map((chunk) =>
404 Array.from(chunk).flatMap((page) => page.containerInstanceArns ?? []),
405 ),
406 Effect.catchTag("ClusterNotFoundException", () => Effect.succeed([] as string[])),
407 );
408 yield* Effect.forEach(
409 instanceArns,
410 (containerInstance) =>
411 ecs
412 .deregisterContainerInstance({
413 cluster,
414 containerInstance,
415 force: true,
416 })
417 .pipe(
418 Effect.catchTag("ClusterNotFoundException", () => Effect.undefined),
419 Effect.asVoid,
420 ),
421 { discard: true },
422 );
423
424 // 4. Remove custom capacity-provider associations. A cluster with
425 // an associated provider cannot be deleted even after its
426 // services, tasks, and container instances have drained.
427 if ((observedCluster?.capacityProviders ?? output.capacityProviders).length > 0) {
428 yield* ecs
429 .putClusterCapacityProviders({
430 cluster,
431 capacityProviders: [],
432 defaultCapacityProviderStrategy: [],
433 })
434 .pipe(
435 Effect.retry({
436 while: (e) =>
437 e._tag === "UpdateInProgressException" || e._tag === "ResourceInUseException",
438 schedule: Schedule.max([Schedule.fixed("3 seconds"), Schedule.recurs(10)]),
439 }),
440 Effect.catchTag("ClusterNotFoundException", () => Effect.void),
441 );
442 }
443
444 // 5. Delete the (now empty) cluster. Draining services/tasks is
445 // asynchronous, so retry the contains-* rejections briefly.
446 yield* ecs
447 .deleteCluster({
448 cluster,
449 })
450 .pipe(
451 Effect.retry({
452 while: (e): boolean =>
453 e._tag === "ClusterContainsServicesException" ||
454 e._tag === "ClusterContainsTasksException" ||
455 e._tag === "ClusterContainsContainerInstancesException" ||
456 e._tag === "ClusterContainsCapacityProviderException" ||
457 e._tag === "UpdateInProgressException",
458 schedule: Schedule.max([Schedule.fixed("3 seconds"), Schedule.recurs(15)]),
459 }),
460 Effect.catchTag("ClusterNotFoundException", () => Effect.void),
461 );
462
463 // DeleteCluster's successful response only means that ECS accepted
464 // the transition. Observe the terminal INACTIVE state (or absence)
465 // before reporting deletion so dependent teardown and a following
466 // nuke pass do not race the cluster lifecycle.
467 yield* ecs.describeClusters({ clusters: [cluster] }).pipe(
468 Effect.flatMap((response) => {
469 const observed = response.clusters?.find(
470 (candidate) => candidate.clusterArn === cluster,
471 );
472 return !observed || observed.status === "INACTIVE"
473 ? Effect.void
474 : Effect.fail(
475 new ClusterStillActive({
476 cluster,
477 status: observed.status,
478 }),
479 );
480 }),
481 Effect.retry({
482 while: (error) => error._tag === "ClusterStillActive",
483 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(15)]),
484 }),
485 );
486 }),
487 };
488 }),
489 );