The best way to control Claude Code, Codex and more from any computer or phone

main
ts 367 lines 14.4 KB
Raw
1 import * as ecs from "@distilled.cloud/aws/ecs";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import type { Input } from "alchemy/Input";
5 import { createPhysicalName } from "alchemy/PhysicalName";
6 import * as Provider from "alchemy/Provider";
7 import { Resource } from "alchemy/Resource";
8 import { createInternalTags, diffTags, hasTags } from "alchemy/Tags";
9 import * as Effect from "effect/Effect";
10 import * as Option from "effect/Option";
11 import * as Stream from "effect/Stream";
12 import { AWSEnvironment, type AccountID } from "../Environment.ts";
13 import type { Providers } from "../Providers.ts";
14 import type { RegionID } from "../Region.ts";
15
16 export type CapacityProviderName = string;
17 export type CapacityProviderArn =
18 `arn:aws:ecs:${RegionID}:${AccountID}:capacity-provider/${CapacityProviderName}`;
19
20 export interface CapacityProviderProps {
21 /**
22 * Capacity provider name. If omitted, a deterministic name is generated;
23 * a generated name that would begin with a reserved prefix gets `cp-`
24 * prepended.
25 *
26 * Names beginning with `aws`, `ecs`, or `fargate` are reserved by AWS.
27 * Changing this triggers a replacement.
28 */
29 name?: string;
30 /**
31 * ARN of the EC2 Auto Scaling Group that backs this capacity provider.
32 *
33 * Cannot be changed after creation; changing this triggers a replacement.
34 */
35 autoScalingGroupArn: Input<string>;
36 /**
37 * Managed scaling configuration applied by ECS to the underlying ASG.
38 */
39 managedScaling?: ecs.ManagedScaling;
40 /**
41 * Whether ECS protects in-use container instances from ASG scale-in.
42 * @default "DISABLED"
43 */
44 managedTerminationProtection?: ecs.ManagedTerminationProtection;
45 /**
46 * Whether ECS sets container instances to DRAINING when terminated by ASG.
47 * @default "DISABLED"
48 */
49 managedDraining?: ecs.ManagedDraining;
50 /**
51 * User-defined tags to apply to the capacity provider.
52 */
53 tags?: Record<string, string>;
54 }
55
56 export interface CapacityProvider extends Resource<
57 "AWS.ECS.CapacityProvider",
58 CapacityProviderProps,
59 {
60 /** The ARN of the capacity provider. */
61 capacityProviderArn: CapacityProviderArn;
62 /** The name of the capacity provider. */
63 name: CapacityProviderName;
64 /** The current status, e.g. `ACTIVE`. */
65 status: ecs.CapacityProviderStatus;
66 /** The status of the most recent update to the provider. */
67 updateStatus: ecs.CapacityProviderUpdateStatus | undefined;
68 /** The Auto Scaling group backing the provider. */
69 autoScalingGroupArn: string;
70 /** The managed scaling configuration. */
71 managedScaling: ecs.ManagedScaling | undefined;
72 /** Whether managed termination protection is enabled. */
73 managedTerminationProtection: ecs.ManagedTerminationProtection | undefined;
74 /** Whether managed instance draining is enabled. */
75 managedDraining: ecs.ManagedDraining | undefined;
76 /** The tags attached to the capacity provider. */
77 tags: Record<string, string>;
78 },
79 never,
80 Providers
81 > {}
82
83 /**
84 * An Amazon ECS capacity provider backed by an EC2 Auto Scaling Group.
85 *
86 * Capacity providers are associated with one or more ECS clusters via
87 * {@link Cluster#capacityProviders} and are referenced by a service or task's
88 * capacity provider strategy.
89 *
90 * Only EC2 Auto Scaling Group-backed capacity providers are currently
91 * supported. The reserved AWS providers `FARGATE` and `FARGATE_SPOT` do not
92 * need to be created and can be referenced by name on a `Cluster` directly.
93 * ### Creating Capacity Providers
94 * **Example:** ASG-Backed Capacity Provider
95 * ```typescript
96 * const provider = yield* CapacityProvider("AppCapacityProvider", {
97 * autoScalingGroupArn: asg.autoScalingGroupArn,
98 * managedScaling: {
99 * status: "ENABLED",
100 * targetCapacity: 80,
101 * minimumScalingStepSize: 1,
102 * maximumScalingStepSize: 10,
103 * },
104 * managedTerminationProtection: "ENABLED",
105 * });
106 *
107 * yield* Cluster("AppCluster", {
108 * capacityProviders: [provider.name],
109 * defaultCapacityProviderStrategy: [
110 * { capacityProvider: provider.name, weight: 1 },
111 * ],
112 * });
113 * ```
114 *
115 * ### Adopting Existing Capacity Providers
116 * Foreign-tagged capacity providers (i.e. providers that exist in AWS but were
117 * not created by this stack/stage/logical-id) are surfaced as `Unowned` by
118 * `read`, and the engine fails with `OwnedBySomeoneElse` unless adoption is
119 * explicitly opted in via `--adopt` or {@link adopt}.
120 * **Example:** Adopt an existing provider
121 * ```typescript
122 * import { adopt } from "alchemy/AdoptPolicy";
123 *
124 * yield* CapacityProvider("AppCapacityProvider", {
125 * name: "existing-provider",
126 * autoScalingGroupArn: asg.autoScalingGroupArn,
127 * }).pipe(adopt());
128 * ```
129 *
130 * @resource
131 */
132 export const CapacityProvider = Resource<CapacityProvider>("AWS.ECS.CapacityProvider");
133
134 export const CapacityProviderProvider = () =>
135 Provider.effect(
136 CapacityProvider,
137 Effect.gen(function* () {
138 const toEcsTags = (tags: Record<string, string>): ecs.Tag[] =>
139 Object.entries(tags).map(([key, value]) => ({ key, value }));
140
141 const fromEcsTags = (tags: ecs.Tag[] | undefined): Record<string, string> =>
142 Object.fromEntries(
143 (tags ?? [])
144 .filter(
145 (t): t is { key: string; value: string } =>
146 t.key !== undefined && t.value !== undefined,
147 )
148 .map((t) => [t.key, t.value]),
149 );
150
151 const toName = (id: string, props: { name?: string } = {}) =>
152 props.name
153 ? Effect.succeed(props.name)
154 : createPhysicalName({ id, maxLength: 252, lowercase: true }).pipe(
155 // AWS rejects generated names that start with a reserved prefix
156 // (e.g. a stack named "AWS-...").
157 Effect.map((name) => (/^(aws|ecs|fargate)/.test(name) ? `cp-${name}` : name)),
158 );
159
160 const describe = (name: string) =>
161 ecs
162 .describeCapacityProviders({
163 capacityProviders: [name],
164 include: ["TAGS"],
165 })
166 .pipe(
167 // A deleted provider stays describable as INACTIVE for a while
168 // and can no longer be updated, so treat it as missing.
169 Effect.map((res) =>
170 res.capacityProviders?.find((p) => p.name === name && p.status !== "INACTIVE"),
171 ),
172 );
173
174 return {
175 stables: ["capacityProviderArn", "name"],
176
177 diff: Effect.fn(function* ({ id, news, olds }) {
178 if (!isResolved(news)) return;
179 const oldName = yield* toName(id, olds ?? {});
180 const newName = yield* toName(id, news);
181 if (oldName !== newName) {
182 return { action: "replace" } as const;
183 }
184 if (
185 isResolved(olds.autoScalingGroupArn) &&
186 olds.autoScalingGroupArn !== news.autoScalingGroupArn
187 ) {
188 return { action: "replace" } as const;
189 }
190 }),
191
192 read: Effect.fn(function* ({ id, olds, output }) {
193 const name = output?.name ?? (yield* toName(id, olds ?? {}));
194 const found = yield* describe(name);
195 if (!found?.name || !found.capacityProviderArn) {
196 return undefined;
197 }
198 const internalTags = yield* createInternalTags(id);
199 const existingTags = fromEcsTags(found.tags);
200 const attrs = {
201 capacityProviderArn: found.capacityProviderArn as CapacityProviderArn,
202 name: found.name,
203 status: (found.status ?? "ACTIVE") as ecs.CapacityProviderStatus,
204 updateStatus: found.updateStatus,
205 autoScalingGroupArn: found.autoScalingGroupProvider?.autoScalingGroupArn ?? "",
206 managedScaling: found.autoScalingGroupProvider?.managedScaling,
207 managedTerminationProtection:
208 found.autoScalingGroupProvider?.managedTerminationProtection,
209 managedDraining: found.autoScalingGroupProvider?.managedDraining,
210 tags: existingTags,
211 };
212 return hasTags(internalTags, existingTags) ? attrs : Unowned(attrs);
213 }),
214
215 reconcile: Effect.fn(function* ({ id, news, session }) {
216 const { accountId, region } = yield* AWSEnvironment.current;
217 const name = yield* toName(id, news);
218 const internalTags = yield* createInternalTags(id);
219 const desiredTags = { ...internalTags, ...news.tags };
220 const autoScalingGroupArn = news.autoScalingGroupArn as string;
221
222 // Observe — fetch live cloud state. We fetch fresh on every
223 // reconcile so adoption, drift, and partial-prior-runs all
224 // converge.
225 let existing = yield* describe(name);
226
227 // Ensure — create the capacity provider if missing.
228 if (!existing?.name || !existing.capacityProviderArn) {
229 yield* ecs
230 .createCapacityProvider({
231 name,
232 autoScalingGroupProvider: {
233 autoScalingGroupArn,
234 managedScaling: news.managedScaling,
235 managedTerminationProtection: news.managedTerminationProtection,
236 managedDraining: news.managedDraining,
237 },
238 tags: toEcsTags(desiredTags),
239 })
240 .pipe(
241 // ECS may surface concurrent creation either as
242 // `LimitExceededException` or a generic `ClientException`
243 // with name conflict semantics — re-describe and continue.
244 Effect.catchTag("LimitExceededException", () => Effect.void),
245 );
246 existing = yield* describe(name);
247 }
248
249 const capacityProviderArn = (existing?.capacityProviderArn ??
250 `arn:aws:ecs:${region}:${accountId}:capacity-provider/${name}`) as CapacityProviderArn;
251
252 // Sync managed scaling — observed ↔ desired. ECS
253 // updateCapacityProvider only mutates managed* fields; ASG ARN is
254 // immutable (replacement-triggering, handled in diff).
255 yield* ecs.updateCapacityProvider({
256 name,
257 autoScalingGroupProvider: {
258 managedScaling: news.managedScaling,
259 managedTerminationProtection: news.managedTerminationProtection,
260 managedDraining: news.managedDraining,
261 },
262 });
263
264 // Sync tags — diff observed cloud tags against desired.
265 const observedTags = fromEcsTags(existing?.tags);
266 const { removed, upsert } = diffTags(observedTags, desiredTags);
267 if (upsert.length > 0) {
268 yield* ecs.tagResource({
269 resourceArn: capacityProviderArn,
270 tags: upsert.map((t) => ({ key: t.Key, value: t.Value })),
271 });
272 }
273 if (removed.length > 0) {
274 yield* ecs.untagResource({
275 resourceArn: capacityProviderArn,
276 tagKeys: removed,
277 });
278 }
279
280 // Re-read to capture status / updateStatus reflecting our changes.
281 const found = yield* describe(name);
282 yield* session.note(capacityProviderArn);
283
284 return {
285 capacityProviderArn,
286 name,
287 status: (found?.status ?? "ACTIVE") as ecs.CapacityProviderStatus,
288 updateStatus: found?.updateStatus,
289 autoScalingGroupArn:
290 found?.autoScalingGroupProvider?.autoScalingGroupArn ?? autoScalingGroupArn,
291 managedScaling: found?.autoScalingGroupProvider?.managedScaling ?? news.managedScaling,
292 managedTerminationProtection:
293 found?.autoScalingGroupProvider?.managedTerminationProtection ??
294 news.managedTerminationProtection,
295 managedDraining:
296 found?.autoScalingGroupProvider?.managedDraining ?? news.managedDraining,
297 tags: desiredTags,
298 };
299 }),
300
301 list: () =>
302 Effect.gen(function* () {
303 // Enumerate every capacity provider in the account/region.
304 // `describeCapacityProviders` with no filter returns all providers
305 // and paginates via `nextToken`; it is a plain operation (no
306 // `.pages`), so drive the pagination with `Stream.paginate`.
307 const all = yield* Stream.paginate(undefined as string | undefined, (token) =>
308 ecs
309 .describeCapacityProviders({
310 include: ["TAGS"],
311 ...(token ? { nextToken: token } : {}),
312 })
313 .pipe(
314 Effect.map(
315 (res) =>
316 [
317 res.capacityProviders ?? [],
318 res.nextToken ? Option.some(res.nextToken) : Option.none<string>(),
319 ] as const,
320 ),
321 ),
322 ).pipe(
323 Stream.runCollect,
324 Effect.map((chunk) => Array.from(chunk)),
325 );
326
327 return all
328 .filter(
329 (
330 p,
331 ): p is ecs.CapacityProvider & {
332 name: string;
333 capacityProviderArn: string;
334 } =>
335 p.name != null &&
336 p.capacityProviderArn != null &&
337 // FARGATE / FARGATE_SPOT are AWS-managed reserved providers
338 // that this resource does not create or own.
339 p.name !== "FARGATE" &&
340 p.name !== "FARGATE_SPOT",
341 )
342 .map((p) => ({
343 capacityProviderArn: p.capacityProviderArn as CapacityProviderArn,
344 name: p.name,
345 status: (p.status ?? "ACTIVE") as ecs.CapacityProviderStatus,
346 updateStatus: p.updateStatus,
347 autoScalingGroupArn: p.autoScalingGroupProvider?.autoScalingGroupArn ?? "",
348 managedScaling: p.autoScalingGroupProvider?.managedScaling,
349 managedTerminationProtection:
350 p.autoScalingGroupProvider?.managedTerminationProtection,
351 managedDraining: p.autoScalingGroupProvider?.managedDraining,
352 tags: fromEcsTags(p.tags),
353 }));
354 }),
355
356 delete: Effect.fn(function* ({ output }) {
357 yield* ecs.deleteCapacityProvider({ capacityProvider: output.name }).pipe(
358 // Already gone — treat as success.
359 Effect.catchTags({
360 InvalidParameterException: () => Effect.void,
361 ClientException: () => Effect.void,
362 }),
363 );
364 }),
365 };
366 }),
367 );