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

main
ts 557 lines 21.4 KB
Raw
1 import * as ec2 from "@distilled.cloud/aws/ec2";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import * as Provider from "alchemy/Provider";
4 import type { ScopedPlanStatusSession } from "alchemy/Report";
5 import { Resource } from "alchemy/Resource";
6 import {
7 createAlchemyTagFilters,
8 createInternalTags,
9 createTagsList,
10 diffTags,
11 hasAlchemyTags,
12 } from "alchemy/Tags";
13 import * as Data from "effect/Data";
14 import * as Effect from "effect/Effect";
15 import * as Schedule from "effect/Schedule";
16 import * as Stream from "effect/Stream";
17 import { AWSEnvironment, type AccountID } from "../Environment.ts";
18 import { tagListRecord } from "../internal/Observe.ts";
19 import type { Providers } from "../Providers.ts";
20 import type { RegionID } from "../Region.ts";
21 import { getDefaultVpcScope } from "./defaultVpcScope.ts";
22 import { retryWhileLingeringEnis } from "./LingeringEnis.ts";
23 import type { VpcId } from "./Vpc.ts";
24
25 export type InternetGatewayId<ID extends string = string> = `igw-${ID}`;
26 export const InternetGatewayId = <ID extends string>(id: ID): ID & InternetGatewayId<ID> =>
27 `igw-${id}` as ID & InternetGatewayId<ID>;
28
29 export interface InternetGatewayProps {
30 /**
31 * The VPC to attach the internet gateway to.
32 * If provided, the internet gateway will be automatically attached to the VPC.
33 * Optional - you can create an unattached internet gateway and attach it later.
34 */
35 vpcId?: VpcId;
36
37 /**
38 * Tags to assign to the internet gateway.
39 * These will be merged with alchemy auto-tags (alchemy::stack, alchemy::stage, alchemy::id).
40 */
41 tags?: Record<string, string>;
42 }
43
44 export interface InternetGateway extends Resource<
45 "AWS.EC2.InternetGateway",
46 InternetGatewayProps,
47 {
48 /**
49 * The ID of the internet gateway.
50 */
51 internetGatewayId: InternetGatewayId;
52 /**
53 * The Amazon Resource Name (ARN) of the internet gateway.
54 */
55 internetGatewayArn: `arn:aws:ec2:${RegionID}:${AccountID}:internet-gateway/${string}`;
56 /**
57 * The ID of the VPC the internet gateway is attached to (if any).
58 */
59 vpcId?: VpcId;
60 /**
61 * The ID of the AWS account that owns the internet gateway.
62 */
63 ownerId?: string;
64 /**
65 * The attachments for the internet gateway.
66 */
67 attachments?: Array<{
68 state: "attaching" | "available" | "detaching" | "detached";
69 vpcId: string;
70 }>;
71 /**
72 * Tags on the internet gateway, as observed. Lets `alchemy drift`
73 * detect out-of-band changes.
74 */
75 tags?: Record<string, string>;
76 },
77 never,
78 Providers
79 > {}
80 /**
81 * An internet gateway provides a target for internet-routable traffic in a
82 * VPC, enabling bidirectional IPv4 and IPv6 connectivity between resources in
83 * your VPC and the public internet. A VPC can have at most one internet
84 * gateway attached at a time.
85 *
86 * The only inputs are the optional `vpcId` to attach to and `tags`. Attaching a
87 * gateway is not enough on its own to make a subnet public — you also need a
88 * `0.0.0.0/0` {@link Route} pointing at the gateway and a
89 * {@link RouteTableAssociation} binding the subnet to that route table.
90 *
91 * ### Creating an Internet Gateway
92 * Pass `vpcId` to create and attach the gateway in one step, or omit it to
93 * create a standalone gateway and attach it later by setting the prop. Updating
94 * `vpcId` moves the gateway between VPCs (detach then attach) without
95 * recreating it.
96 *
97 * **Example:** Internet Gateway Attached to a VPC
98 * ```typescript
99 * const internetGateway = yield* AWS.EC2.InternetGateway("InternetGateway", {
100 * vpcId: myVpc.vpcId,
101 * });
102 * ```
103 * Creates the gateway and attaches it to the VPC immediately. The resulting
104 * `internetGatewayId` (prefixed `igw-`) is what you reference from a route's
105 * `gatewayId`.
106 *
107 * **Example:** Detached Internet Gateway
108 * ```typescript
109 * const internetGateway = yield* AWS.EC2.InternetGateway("InternetGateway", {});
110 * ```
111 * Omitting `vpcId` creates an unattached gateway. This is occasionally useful
112 * when the VPC is provisioned separately; add the `vpcId` prop later to attach
113 * it.
114 *
115 * **Example:** Internet Gateway with Tags
116 * ```typescript
117 * const internetGateway = yield* AWS.EC2.InternetGateway("InternetGateway", {
118 * vpcId: myVpc.vpcId,
119 * tags: { Name: "production-igw" },
120 * });
121 * ```
122 * The `tags` map is merged with the alchemy auto-tags and can be changed in
123 * place. A `Name` tag makes the gateway easy to identify in the AWS console.
124 *
125 * ### Enabling Public Internet Access
126 * An internet gateway only carries traffic once a route table sends traffic to
127 * it and a subnet is associated with that table. The full pattern below makes a
128 * subnet public.
129 *
130 * **Example:** Internet Gateway with a Default Route
131 * ```typescript
132 * const internetGateway = yield* AWS.EC2.InternetGateway("InternetGateway", {
133 * vpcId: myVpc.vpcId,
134 * });
135 *
136 * const publicRouteTable = yield* AWS.EC2.RouteTable("PublicRouteTable", {
137 * vpcId: myVpc.vpcId,
138 * });
139 *
140 * const internetRoute = yield* AWS.EC2.Route("InternetRoute", {
141 * routeTableId: publicRouteTable.routeTableId,
142 * destinationCidrBlock: "0.0.0.0/0",
143 * gatewayId: internetGateway.internetGatewayId,
144 * });
145 * ```
146 * With the default route in place, any subnet associated with
147 * `publicRouteTable` can send and receive internet traffic. Add an analogous
148 * route with `destinationIpv6CidrBlock: "::/0"` to enable IPv6.
149 *
150 * @resource
151 */
152 export const InternetGateway = Resource<InternetGateway>("AWS.EC2.InternetGateway");
153
154 export const InternetGatewayProvider = () =>
155 Provider.effect(
156 InternetGateway,
157 Effect.gen(function* () {
158 const findInternetGatewayByTags = Effect.fn(function* (id: string) {
159 const filters = yield* createAlchemyTagFilters(id);
160 const pages = yield* ec2.describeInternetGateways
161 .pages({ Filters: filters })
162 .pipe(Stream.runCollect);
163 return Array.from(pages)
164 .flatMap((page) => page.InternetGateways ?? [])
165 .find((candidate) => candidate.InternetGatewayId !== undefined);
166 });
167
168 /**
169 * The attributes `read` and `reconcile` both report, so a converged
170 * gateway reads unchanged. The VPC is the one the gateway is attached
171 * (or attaching) to.
172 */
173 const toAttributes = (
174 igw: ec2.InternetGateway,
175 region: RegionID,
176 accountId: AccountID,
177 ): InternetGateway["Attributes"] => {
178 const internetGatewayId = igw.InternetGatewayId as InternetGatewayId;
179 return {
180 internetGatewayId,
181 internetGatewayArn: `arn:aws:ec2:${region}:${accountId}:internet-gateway/${internetGatewayId}`,
182 vpcId: igw.Attachments?.find((a) => a.State === "available" || a.State === "attaching")
183 ?.VpcId as VpcId | undefined,
184 ownerId: igw.OwnerId,
185 attachments: igw.Attachments?.map((a) => ({
186 state: a.State! as "attaching" | "available" | "detaching" | "detached",
187 vpcId: a.VpcId!,
188 })),
189 tags: tagListRecord(igw.Tags),
190 };
191 };
192
193 return {
194 stables: ["internetGatewayId", "internetGatewayArn", "ownerId"],
195 read: Effect.fn(function* ({ id, output }) {
196 const { accountId, region } = yield* AWSEnvironment.current;
197 const igw = output?.internetGatewayId
198 ? (yield* ec2
199 .describeInternetGateways({ InternetGatewayIds: [output.internetGatewayId] })
200 .pipe(
201 Effect.catchTag("InvalidInternetGatewayID.NotFound", () =>
202 Effect.succeed({ InternetGateways: [] }),
203 ),
204 )).InternetGateways?.[0]
205 : yield* findInternetGatewayByTags(id);
206 if (!igw?.InternetGatewayId) return undefined;
207 const attrs = toAttributes(igw, region, accountId);
208 return (yield* hasAlchemyTags(id, attrs.tags)) ? attrs : Unowned(attrs);
209 }),
210
211 list: () =>
212 Effect.gen(function* () {
213 const { accountId, region } = yield* AWSEnvironment.current;
214 // The default VPC's internet gateway is account furniture AWS
215 // provisions; never census/nuke it.
216 const defaultVpc = yield* getDefaultVpcScope;
217 return yield* ec2.describeInternetGateways.pages({}).pipe(
218 Stream.runCollect,
219 Effect.map((chunk) =>
220 Array.from(chunk).flatMap((page) =>
221 (page.InternetGateways ?? [])
222 .filter(
223 (
224 igw,
225 ): igw is ec2.InternetGateway & {
226 InternetGatewayId: string;
227 } => igw.InternetGatewayId != null,
228 )
229 .filter(
230 (igw) =>
231 defaultVpc.vpcId === undefined ||
232 !igw.Attachments?.some((a) => a.VpcId === defaultVpc.vpcId),
233 )
234 .map((igw) => {
235 const internetGatewayId = igw.InternetGatewayId as InternetGatewayId;
236 const attachedVpcId = igw.Attachments?.find(
237 (a) => a.State === "available" || a.State === "attaching",
238 )?.VpcId as VpcId | undefined;
239 return {
240 internetGatewayId,
241 internetGatewayArn:
242 `arn:aws:ec2:${region}:${accountId}:internet-gateway/${internetGatewayId}` as const,
243 vpcId: attachedVpcId,
244 ownerId: igw.OwnerId,
245 attachments: igw.Attachments?.map((a) => ({
246 state: a.State! as "attaching" | "available" | "detaching" | "detached",
247 vpcId: a.VpcId!,
248 })),
249 };
250 }),
251 ),
252 ),
253 );
254 }),
255
256 reconcile: Effect.fn(function* ({ id, instanceId, news = {}, output, session }) {
257 const { accountId, region } = yield* AWSEnvironment.current;
258 const alchemyTags = yield* createInternalTags(id);
259 const desiredTags = {
260 ...news.tags,
261 ...alchemyTags,
262 "alchemy::instance": instanceId,
263 };
264
265 // Observe — find the IGW via cached id, else fall through to create.
266 let igw: ec2.InternetGateway | undefined;
267 if (output?.internetGatewayId) {
268 const lookup = yield* ec2
269 .describeInternetGateways({
270 InternetGatewayIds: [output.internetGatewayId],
271 })
272 .pipe(
273 Effect.catchTag("InvalidInternetGatewayID.NotFound", () =>
274 Effect.succeed({ InternetGateways: [] }),
275 ),
276 );
277 igw = lookup.InternetGateways?.[0];
278 }
279 if (igw === undefined) {
280 // CreateInternetGateway has no idempotency token and this provider
281 // never replaces an IGW. Recover a create that succeeded before
282 // state persistence by stable stack/stage/logical-id ownership.
283 // Older interrupted creates predate the instance tag, so requiring
284 // it here would strand exactly the resources recovery must adopt.
285 igw = yield* findInternetGatewayByTags(id);
286 }
287
288 // Ensure — create the IGW if missing.
289 if (igw === undefined) {
290 const createResult = yield* ec2.createInternetGateway({
291 TagSpecifications: [
292 {
293 ResourceType: "internet-gateway",
294 Tags: createTagsList(desiredTags),
295 },
296 ],
297 DryRun: false,
298 });
299 const newIgwId = createResult.InternetGateway!.InternetGatewayId! as InternetGatewayId;
300 yield* session.note(`Internet gateway created: ${newIgwId}`);
301 // EC2 can return the new ID before DescribeInternetGateways sees
302 // it. Retain and poll that ID rather than failing the reconcile
303 // after creation and losing the cleanup handle.
304 igw = yield* describeInternetGateway(newIgwId);
305 }
306
307 const internetGatewayId = igw.InternetGatewayId! as InternetGatewayId;
308
309 // Sync VPC attachment — observed attachment vs desired.
310 const attachedVpcId = igw.Attachments?.find(
311 (a) => a.State === "available" || a.State === "attaching",
312 )?.VpcId;
313 if (attachedVpcId !== news.vpcId) {
314 if (attachedVpcId) {
315 yield* ec2
316 .detachInternetGateway({
317 InternetGatewayId: internetGatewayId,
318 VpcId: attachedVpcId,
319 })
320 .pipe(Effect.catchTag("Gateway.NotAttached", () => Effect.void));
321 yield* session.note(`Detached from VPC: ${attachedVpcId}`);
322 }
323 if (news.vpcId) {
324 yield* ec2
325 .attachInternetGateway({
326 InternetGatewayId: internetGatewayId,
327 VpcId: news.vpcId,
328 })
329 .pipe(
330 Effect.retry({
331 while: (e) =>
332 e._tag === "InvalidVpcID.NotFound" ||
333 e._tag === "InvalidInternetGatewayID.NotFound",
334 schedule: Schedule.max([Schedule.fixed(500), Schedule.recurs(10)]),
335 }),
336 );
337 yield* session.note(`Attached to VPC: ${news.vpcId}`);
338 }
339 }
340 if (news.vpcId) {
341 // AttachInternetGateway is asynchronous. Also check this when the
342 // observed attachment was already `attaching`, as can happen when
343 // a reconcile resumes after interruption. Do not publish outputs
344 // to a dependent Route until AWS reports it as available.
345 igw = yield* waitForInternetGatewayAttached(internetGatewayId, news.vpcId, session);
346 }
347
348 // Sync tags — observed cloud tags vs desired.
349 const currentTags = Object.fromEntries(
350 (igw.Tags ?? []).map((t) => [t.Key!, t.Value!]),
351 ) as Record<string, string>;
352 const { removed, upsert } = diffTags(currentTags, desiredTags);
353 if (removed.length > 0) {
354 yield* ec2.deleteTags({
355 Resources: [internetGatewayId],
356 Tags: removed.map((key) => ({ Key: key })),
357 });
358 }
359 if (upsert.length > 0) {
360 yield* ec2.createTags({
361 Resources: [internetGatewayId],
362 Tags: upsert,
363 });
364 }
365
366 // Re-read final state.
367 const final = yield* describeInternetGateway(internetGatewayId);
368 return { ...toAttributes(final, region, accountId), tags: desiredTags };
369 }),
370
371 delete: Effect.fn(function* ({ output, session }) {
372 const internetGatewayId = output.internetGatewayId;
373
374 yield* session.note(`Deleting internet gateway: ${internetGatewayId}`);
375
376 // Re-describe to get current attachments from AWS (don't rely on stored state)
377 // This handles cases where state is incomplete from a previous crashed run
378 const igw = yield* findInternetGateway(internetGatewayId);
379 if (igw === undefined) {
380 yield* session.note(`Internet gateway ${internetGatewayId} is already absent`);
381 return;
382 }
383 const attachments = igw.Attachments ?? [];
384
385 // 1. Detach from all VPCs first. DetachInternetGateway fails with
386 // DependencyViolation ("has some mapped public address(es)") while
387 // any ENI in the VPC still holds a public IP — a just-deleted VPC
388 // Lambda's Hyperplane ENIs or draining Fargate task ENIs can hold
389 // theirs for 5-20 minutes after the owner is gone. Ride that
390 // window out on the same budget the subnet delete uses, reaping
391 // detached Lambda ENIs between attempts to accelerate the release.
392 if (attachments.length > 0) {
393 for (const attachment of attachments) {
394 yield* retryWhileLingeringEnis(
395 ec2
396 .detachInternetGateway({
397 InternetGatewayId: internetGatewayId,
398 VpcId: attachment.VpcId!,
399 })
400 .pipe(
401 Effect.tapError(Effect.logDebug),
402 Effect.catchTags({
403 "Gateway.NotAttached": () => Effect.void,
404 "InvalidInternetGatewayID.NotFound": () => Effect.void,
405 }),
406 ),
407 {
408 scope: { name: "vpc-id", value: attachment.VpcId! },
409 isDependencyViolation: (e) => e._tag === "DependencyViolation",
410 session,
411 },
412 );
413 yield* session.note(`Detached from VPC: ${attachment.VpcId}`);
414 }
415 }
416
417 // 2. Delete the internet gateway
418 yield* ec2
419 .deleteInternetGateway({
420 InternetGatewayId: internetGatewayId,
421 DryRun: false,
422 })
423 .pipe(
424 Effect.tapError(Effect.logDebug),
425 Effect.catchTag("InvalidInternetGatewayID.NotFound", () => Effect.void),
426 // Retry on dependency violations. Public addresses on a
427 // draining EKS/HyperPod control plane's ENIs can take
428 // several minutes to release — 5s x 60 = ~5 min.
429 Effect.retry({
430 while: (e) =>
431 e._tag === "DependencyViolation" ||
432 (e._tag === "ValidationError" && e.message?.includes("DependencyViolation")),
433 schedule: Schedule.max([Schedule.fixed(5000), Schedule.recurs(60)]).pipe(
434 Schedule.tap(({ attempt }) =>
435 session.note(`Waiting for dependencies to clear... (attempt ${attempt})`),
436 ),
437 ),
438 }),
439 );
440
441 // 3. Wait for internet gateway to be fully deleted
442 yield* waitForInternetGatewayDeleted(internetGatewayId, session);
443
444 yield* session.note(`Internet gateway ${internetGatewayId} deleted successfully`);
445 }),
446 };
447 }),
448 );
449
450 /**
451 * Describe an internet gateway by ID
452 */
453 const findInternetGateway = (internetGatewayId: string) =>
454 Effect.gen(function* () {
455 const result = yield* ec2
456 .describeInternetGateways({ InternetGatewayIds: [internetGatewayId] })
457 .pipe(
458 Effect.catchTag("InvalidInternetGatewayID.NotFound", () =>
459 Effect.succeed({ InternetGateways: [] }),
460 ),
461 );
462
463 return result.InternetGateways?.[0];
464 });
465
466 const describeInternetGateway = (internetGatewayId: string) =>
467 findInternetGateway(internetGatewayId).pipe(
468 Effect.flatMap((igw) =>
469 igw ? Effect.succeed(igw) : Effect.fail(new InternetGatewayNotVisible({ internetGatewayId })),
470 ),
471 Effect.retry({
472 while: (error) => error instanceof InternetGatewayNotVisible,
473 schedule: Schedule.max([Schedule.fixed(500), Schedule.recurs(10)]),
474 }),
475 );
476
477 class InternetGatewayStillListed extends Data.TaggedError("InternetGatewayStillListed")<{
478 internetGatewayId: string;
479 }> {}
480
481 class InternetGatewayNotVisible extends Data.TaggedError("InternetGatewayNotVisible")<{
482 internetGatewayId: string;
483 }> {}
484
485 class InternetGatewayAttachmentPending extends Data.TaggedError(
486 "InternetGatewayAttachmentPending",
487 )<{
488 internetGatewayId: string;
489 vpcId: string;
490 state: string;
491 }> {}
492
493 const waitForInternetGatewayAttached = (
494 internetGatewayId: string,
495 vpcId: string,
496 session: ScopedPlanStatusSession,
497 ) =>
498 Effect.gen(function* () {
499 const igw = yield* describeInternetGateway(internetGatewayId);
500 const attachment = igw.Attachments?.find((candidate) => candidate.VpcId === vpcId);
501 if (attachment?.State === "available") {
502 return igw;
503 }
504 return yield* new InternetGatewayAttachmentPending({
505 internetGatewayId,
506 vpcId,
507 state: attachment?.State ?? "missing",
508 });
509 }).pipe(
510 Effect.retry({
511 while: (error) => error instanceof InternetGatewayAttachmentPending,
512 schedule: Schedule.max([Schedule.fixed(1000), Schedule.recurs(30)]).pipe(
513 Schedule.tap(({ attempt }) =>
514 session.note(
515 `Waiting for internet gateway attachment to become available... (${attempt}s)`,
516 ),
517 ),
518 ),
519 }),
520 );
521
522 /**
523 * Wait for internet gateway to be deleted
524 */
525 const waitForInternetGatewayDeleted = (
526 internetGatewayId: string,
527 session: ScopedPlanStatusSession,
528 ) =>
529 Effect.retry(
530 Effect.gen(function* () {
531 const result = yield* ec2
532 .describeInternetGateways({ InternetGatewayIds: [internetGatewayId] })
533 .pipe(
534 Effect.tapError(Effect.logDebug),
535 Effect.catchTag("InvalidInternetGatewayID.NotFound", () =>
536 Effect.succeed({ InternetGateways: [] }),
537 ),
538 );
539
540 if (!result.InternetGateways || result.InternetGateways.length === 0) {
541 return; // Successfully deleted
542 }
543
544 // Still listed: EC2 is eventually consistent after a delete.
545 return yield* new InternetGatewayStillListed({ internetGatewayId });
546 }),
547 {
548 while: (error) => error._tag === "InternetGatewayStillListed",
549 // EC2 can keep listing a deleted gateway for minutes, so bound the
550 // wait like NatGateway: 5s x 60 = ~5 min.
551 schedule: Schedule.max([Schedule.fixed(5000), Schedule.recurs(60)]).pipe(
552 Schedule.tap(({ attempt }) =>
553 session.note(`Waiting for internet gateway deletion... (${attempt * 5}s)`),
554 ),
555 ),
556 },
557 );