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

main
ts 830 lines 29.3 KB
Raw
1 import * as ec2 from "@distilled.cloud/aws/ec2";
2 import { isResolved } from "alchemy/Diff";
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 } from "alchemy/Tags";
12 import * as Data from "effect/Data";
13 import * as Effect from "effect/Effect";
14 import * as Option from "effect/Option";
15 import * as Schedule from "effect/Schedule";
16 import * as Stream from "effect/Stream";
17 import type { AccountID } from "../Environment.ts";
18 import { AWSEnvironment } from "../Environment.ts";
19 import type { Providers } from "../Providers.ts";
20 import type { RegionID } from "../Region.ts";
21 import type { AllocationId } from "./EIP.ts";
22 import type { SubnetId } from "./Subnet.ts";
23 import type { VpcId } from "./Vpc.ts";
24
25 export class NatGatewayUnexpectedResponse extends Data.TaggedError("NatGatewayUnexpectedResponse")<{
26 readonly message: string;
27 readonly cause?: unknown;
28 }> {}
29
30 export type NatGatewayId<ID extends string = string> = `nat-${ID}`;
31 export const NatGatewayId = <ID extends string>(id: ID): ID & NatGatewayId<ID> =>
32 `nat-${id}` as ID & NatGatewayId<ID>;
33
34 export type NatGatewayArn = `arn:aws:ec2:${RegionID}:${AccountID}:natgateway/${NatGatewayId}`;
35
36 export interface NatGatewayAvailabilityZoneAddress {
37 /**
38 * The Availability Zone (e.g. `us-east-1a`) the addresses serve.
39 * Specify either this or `availabilityZoneId`.
40 */
41 availabilityZone?: string;
42
43 /**
44 * The Availability Zone ID (e.g. `use1-az1`) the addresses serve.
45 * Specify either this or `availabilityZone`.
46 */
47 availabilityZoneId?: string;
48
49 /**
50 * The allocation IDs of the Elastic IP addresses the gateway uses in this
51 * Availability Zone.
52 */
53 allocationIds: AllocationId[];
54 }
55
56 export interface NatGatewayProps {
57 /**
58 * Whether the NAT gateway lives in a single Availability Zone (`"zonal"`) or
59 * spans every Availability Zone of a VPC (`"regional"`).
60 *
61 * A zonal gateway needs `subnetId`; a regional gateway needs `vpcId` and only
62 * supports public connectivity. Changing the mode replaces the gateway.
63 * @default "zonal"
64 */
65 availabilityMode?: ec2.AvailabilityMode;
66
67 /**
68 * The subnet in which to create the NAT gateway.
69 * Required for zonal NAT gateways. For public NAT gateways, this must be a
70 * public subnet.
71 */
72 subnetId?: SubnetId;
73
74 /**
75 * The VPC in which to create a regional NAT gateway.
76 * Required when `availabilityMode` is `"regional"`. The VPC must have an
77 * internet gateway attached.
78 */
79 vpcId?: VpcId;
80
81 /**
82 * Elastic IP addresses to use per Availability Zone for a regional NAT
83 * gateway (manual mode).
84 *
85 * When omitted, a regional gateway runs in automatic mode: AWS allocates its
86 * addresses and expands it to every Availability Zone with workloads. When
87 * set, the gateway runs in manual mode and only serves the listed zones;
88 * addresses are associated and disassociated in place as this list changes.
89 * Switching between automatic and manual mode replaces the gateway.
90 */
91 availabilityZoneAddresses?: NatGatewayAvailabilityZoneAddress[];
92
93 /**
94 * How long (in seconds) to let in-flight connections drain before an Elastic
95 * IP removed from `availabilityZoneAddresses` is forcibly released.
96 * Between 1 and 4000. Changing it never replaces the gateway.
97 * @default 350
98 */
99 maxDrainDurationSeconds?: number;
100
101 /**
102 * The allocation ID of the Elastic IP address for the gateway.
103 * Required for public NAT gateways.
104 */
105 allocationId?: AllocationId;
106
107 /**
108 * Indicates whether the NAT gateway supports public or private connectivity.
109 * @default "public"
110 */
111 connectivityType?: ec2.ConnectivityType;
112
113 /**
114 * The private IPv4 address to assign to the NAT gateway.
115 * If you don't provide an address, a private IPv4 address will be automatically assigned.
116 */
117 privateIpAddress?: string;
118
119 /**
120 * Secondary allocation IDs for additional private IP addresses.
121 * Only valid for private NAT gateways.
122 */
123 secondaryAllocationIds?: AllocationId[];
124
125 /**
126 * Secondary private IPv4 addresses.
127 * Only valid for private NAT gateways.
128 */
129 secondaryPrivateIpAddresses?: string[];
130
131 /**
132 * The number of secondary private IPv4 addresses to assign.
133 * Only valid for private NAT gateways.
134 */
135 secondaryPrivateIpAddressCount?: number;
136
137 /**
138 * Tags to assign to the NAT gateway.
139 */
140 tags?: Record<string, string>;
141 }
142
143 export interface NatGateway extends Resource<
144 "AWS.EC2.NatGateway",
145 NatGatewayProps,
146 {
147 /**
148 * The ID of the NAT gateway.
149 */
150 natGatewayId: NatGatewayId;
151
152 /**
153 * The Amazon Resource Name (ARN) of the NAT gateway.
154 */
155 natGatewayArn: `arn:aws:ec2:${RegionID}:${AccountID}:natgateway/${string}`;
156
157 /**
158 * The ID of the subnet in which the NAT gateway is located.
159 * Undefined for regional NAT gateways.
160 */
161 subnetId: SubnetId | undefined;
162
163 /**
164 * Whether the NAT gateway is zonal or regional.
165 */
166 availabilityMode: ec2.AvailabilityMode;
167
168 /**
169 * Whether a regional NAT gateway automatically expands to Availability
170 * Zones with workloads (`"enabled"` in automatic mode, `"disabled"` in
171 * manual mode).
172 */
173 autoProvisionZones?: ec2.AutoProvisionZonesState;
174
175 /**
176 * Whether a regional NAT gateway automatically scales its IP addresses.
177 */
178 autoScalingIps?: ec2.AutoScalingIpsState;
179
180 /**
181 * The ID of the route table AWS creates for a regional NAT gateway.
182 */
183 routeTableId?: string;
184
185 /**
186 * The ID of the VPC in which the NAT gateway is located.
187 */
188 vpcId: string;
189
190 /**
191 * The current state of the NAT gateway.
192 */
193 state: ec2.NatGatewayState;
194
195 /**
196 * The connectivity type of the NAT gateway.
197 */
198 connectivityType: ec2.ConnectivityType;
199
200 /**
201 * The Elastic IP address associated with the NAT gateway (for public NAT gateways).
202 */
203 publicIp?: string;
204
205 /**
206 * The private IP address associated with the NAT gateway.
207 */
208 privateIp?: string;
209
210 /**
211 * Information about the IP addresses and network interface associated with the NAT gateway.
212 */
213 natGatewayAddresses?: Array<{
214 allocationId?: string;
215 networkInterfaceId?: string;
216 privateIp?: string;
217 publicIp?: string;
218 associationId?: string;
219 isPrimary?: boolean;
220 failureMessage?: string;
221 status?: ec2.NatGatewayAddressStatus;
222 availabilityZone?: string;
223 availabilityZoneId?: string;
224 }>;
225
226 /**
227 * If the NAT gateway could not be created, specifies the error code for the failure.
228 */
229 failureCode?: string;
230
231 /**
232 * If the NAT gateway could not be created, specifies the error message for the failure.
233 */
234 failureMessage?: string;
235
236 /**
237 * The date and time the NAT gateway was created.
238 */
239 createTime?: string;
240
241 /**
242 * The date and time the NAT gateway was deleted, if applicable.
243 */
244 deleteTime?: string;
245 },
246 never,
247 Providers
248 > {}
249 /**
250 * A NAT gateway that lets instances in a private subnet reach the internet
251 * (and other AWS services) while preventing unsolicited inbound connections.
252 *
253 * The gateway lives in the subnet given by `subnetId`, and its
254 * `connectivityType` decides how it connects: a `"public"` gateway must sit in a
255 * *public* subnet and requires an Elastic IP via `allocationId`, while a
256 * `"private"` gateway has no public address and is used for VPC-to-VPC routing.
257 * A NAT gateway only carries traffic once a `Route` sends `0.0.0.0/0` from the
258 * private subnet's route table to it. Core properties (`availabilityMode`,
259 * `subnetId`, `vpcId`, `connectivityType`, `allocationId`) are immutable, so
260 * changing them replaces the gateway.
261 *
262 * ### Public NAT Gateways
263 * Public gateways translate private addresses to a stable public IP, so they
264 * must be placed in a public subnet (one with a route to an internet gateway)
265 * and given an Elastic IP allocation.
266 * **Example:** Public NAT Gateway with an Elastic IP
267 * ```typescript
268 * const eip = yield* AWS.EC2.EIP("NatEip", {});
269 *
270 * const natGateway = yield* AWS.EC2.NatGateway("NatGateway", {
271 * subnetId: publicSubnet.subnetId,
272 * allocationId: eip.allocationId,
273 * connectivityType: "public",
274 * tags: { Name: "production-nat" },
275 * });
276 * ```
277 * Allocating the EIP first and passing its `allocationId` gives the gateway a
278 * fixed public IP. `connectivityType` defaults to `"public"`, so it can be
279 * omitted; this is the standard way to give private instances outbound internet
280 * access.
281 *
282 * ### Private NAT Gateways
283 * Private gateways have no public IP and route traffic between VPCs or to
284 * on-premises networks without exposing it to the internet.
285 * **Example:** Private NAT Gateway with a Fixed Private IP
286 * ```typescript
287 * const natGateway = yield* AWS.EC2.NatGateway("PrivateNat", {
288 * subnetId: privateSubnet.subnetId,
289 * connectivityType: "private",
290 * privateIpAddress: "10.0.10.10",
291 * });
292 * ```
293 * Omitting `allocationId` and setting `connectivityType: "private"` creates a
294 * gateway with no public address; `privateIpAddress` pins it to a specific
295 * address in the subnet instead of letting AWS choose one automatically.
296 *
297 * **Example:** Private NAT Gateway with Secondary Addresses
298 * ```typescript
299 * const natGateway = yield* AWS.EC2.NatGateway("ScaledNat", {
300 * subnetId: privateSubnet.subnetId,
301 * connectivityType: "private",
302 * secondaryPrivateIpAddressCount: 3,
303 * });
304 * ```
305 * Secondary private addresses — via `secondaryPrivateIpAddressCount`,
306 * `secondaryPrivateIpAddresses`, or `secondaryAllocationIds` — raise the number
307 * of simultaneous connections a private gateway can sustain to busy
308 * destinations, which is only valid for private gateways.
309 *
310 * ### Regional NAT Gateways
311 * A regional NAT gateway spans every Availability Zone of a VPC under one ID,
312 * so it needs a `vpcId` instead of a public subnet. The VPC must have an
313 * internet gateway attached.
314 * **Example:** Regional NAT Gateway in Automatic Mode
315 * ```typescript
316 * const natGateway = yield* AWS.EC2.NatGateway("RegionalNat", {
317 * availabilityMode: "regional",
318 * vpcId: vpc.vpcId,
319 * });
320 * ```
321 * In automatic mode AWS allocates the public addresses and expands the gateway
322 * to each Availability Zone where your workloads run.
323 *
324 * **Example:** Regional NAT Gateway with Your Own Elastic IPs
325 * ```typescript
326 * const natGateway = yield* AWS.EC2.NatGateway("RegionalNat", {
327 * availabilityMode: "regional",
328 * vpcId: vpc.vpcId,
329 * availabilityZoneAddresses: [
330 * { availabilityZone: "us-east-1a", allocationIds: [eipA.allocationId] },
331 * { availabilityZone: "us-east-1b", allocationIds: [eipB.allocationId] },
332 * ],
333 * });
334 * ```
335 * Listing `availabilityZoneAddresses` switches the gateway to manual mode: it
336 * serves only the listed zones with the given Elastic IPs, and adding or
337 * removing entries associates or disassociates addresses without replacing the
338 * gateway.
339 *
340 * ### Routing Private Traffic
341 * **Example:** Default Route Through the NAT Gateway
342 * ```typescript
343 * const natRoute = yield* AWS.EC2.Route("NatRoute", {
344 * routeTableId: privateRouteTable.routeTableId,
345 * destinationCidrBlock: "0.0.0.0/0",
346 * natGatewayId: natGateway.natGatewayId,
347 * });
348 * ```
349 * Without a route the gateway is inert; this entry sends all outbound traffic
350 * from the private subnet's route table through the gateway so private instances
351 * can reach the internet.
352 *
353 * @resource
354 */
355 export const NatGateway = Resource<NatGateway>("AWS.EC2.NatGateway");
356
357 export const NatGatewayProvider = () =>
358 Provider.effect(
359 NatGateway,
360 Effect.gen(function* () {
361 const createTags = Effect.fn(function* (id: string, tags?: Record<string, string>) {
362 return {
363 Name: id,
364 ...(yield* createInternalTags(id)),
365 ...tags,
366 };
367 });
368
369 const describeNatGateway = (natGatewayId: string) =>
370 ec2.describeNatGateways({ NatGatewayIds: [natGatewayId] }).pipe(
371 Effect.map((r) => r.NatGateways?.[0]),
372 Effect.flatMap((gw) =>
373 gw
374 ? Effect.succeed(gw)
375 : Effect.fail(
376 new NatGatewayUnexpectedResponse({
377 message: `NAT Gateway ${natGatewayId} not found`,
378 }),
379 ),
380 ),
381 );
382
383 const toAttrs = Effect.fn(function* (gw: ec2.NatGateway) {
384 const { accountId, region } = yield* AWSEnvironment.current;
385 const primaryAddress =
386 gw.NatGatewayAddresses?.find((a) => a.IsPrimary) ?? gw.NatGatewayAddresses?.[0];
387 return {
388 natGatewayId: gw.NatGatewayId as NatGatewayId,
389 natGatewayArn:
390 `arn:aws:ec2:${region}:${accountId}:natgateway/${gw.NatGatewayId}` as NatGatewayArn,
391 subnetId: gw.SubnetId as SubnetId | undefined,
392 vpcId: gw.VpcId!,
393 state: gw.State!,
394 connectivityType: gw.ConnectivityType!,
395 availabilityMode: gw.AvailabilityMode ?? "zonal",
396 autoProvisionZones: gw.AutoProvisionZones,
397 autoScalingIps: gw.AutoScalingIps,
398 routeTableId: gw.RouteTableId,
399 publicIp: primaryAddress?.PublicIp,
400 privateIp: primaryAddress?.PrivateIp,
401 natGatewayAddresses: gw.NatGatewayAddresses?.map((a) => ({
402 allocationId: a.AllocationId,
403 networkInterfaceId: a.NetworkInterfaceId,
404 privateIp: a.PrivateIp,
405 publicIp: a.PublicIp,
406 associationId: a.AssociationId,
407 isPrimary: a.IsPrimary,
408 failureMessage: a.FailureMessage,
409 status: a.Status,
410 availabilityZone: a.AvailabilityZone,
411 availabilityZoneId: a.AvailabilityZoneId,
412 })),
413 failureCode: gw.FailureCode,
414 failureMessage: gw.FailureMessage,
415 createTime:
416 gw.CreateTime instanceof Date
417 ? gw.CreateTime.toISOString()
418 : (gw.CreateTime as string | undefined),
419 deleteTime:
420 gw.DeleteTime instanceof Date
421 ? gw.DeleteTime.toISOString()
422 : (gw.DeleteTime as string | undefined),
423 } satisfies NatGateway["Attributes"];
424 });
425
426 // Find NAT Gateway by alchemy tags when we don't have the ID
427 const findNatGatewayByTags = Effect.fn(function* (id: string) {
428 const filters = yield* createAlchemyTagFilters(id);
429 // Find a NAT Gateway that's not deleted and has matching tags
430 return yield* ec2.describeNatGateways
431 .items({ Filter: filters })
432 .pipe(Stream.runHead, Effect.map(Option.getOrUndefined));
433 });
434
435 return {
436 stables: ["natGatewayId", "natGatewayArn", "vpcId"],
437
438 read: Effect.fn(function* ({ id, output }) {
439 if (output) {
440 // We have the NAT Gateway ID, use it directly
441 return yield* toAttrs(yield* describeNatGateway(output.natGatewayId));
442 }
443
444 // No output - try to find by tags (recovery from incomplete create)
445 const gw = yield* findNatGatewayByTags(id);
446 if (gw) {
447 return yield* toAttrs(gw);
448 }
449
450 // Not found
451 return undefined;
452 }),
453
454 list: () =>
455 Effect.gen(function* () {
456 // describeNatGateways enumerates every NAT gateway in the
457 // account/region; paginate exhaustively and drop deleted ones.
458 const pages = yield* ec2.describeNatGateways.pages({}).pipe(Stream.runCollect);
459 const gateways = Array.from(pages).flatMap((page) =>
460 (page.NatGateways ?? []).filter(
461 (gw): gw is ec2.NatGateway & { NatGatewayId: string } =>
462 gw.NatGatewayId != null && gw.State !== "deleted",
463 ),
464 );
465 return yield* Effect.forEach(gateways, (gw) => toAttrs(gw));
466 }),
467
468 diff: Effect.fn(function* ({ news, olds }) {
469 if (!isResolved(news)) return;
470 // NAT Gateway is mostly immutable - any change to core properties requires replacement
471 if (
472 (news.availabilityMode ?? "zonal") !== (olds.availabilityMode ?? "zonal") ||
473 news.subnetId !== olds.subnetId ||
474 news.vpcId !== olds.vpcId ||
475 news.connectivityType !== olds.connectivityType ||
476 news.allocationId !== olds.allocationId ||
477 // automatic <-> manual mode cannot be switched in place
478 (news.availabilityZoneAddresses === undefined) !==
479 (olds.availabilityZoneAddresses === undefined)
480 ) {
481 return { action: "replace" };
482 }
483 // Tags and manual-mode zone addresses can be updated in-place
484 }),
485
486 reconcile: Effect.fn(function* ({ id, news, output, session }) {
487 const desiredTags = yield* createTags(id, news.tags);
488
489 // Observe — try the cached id first; if missing, search by alchemy
490 // tags so an interrupted create can recover before re-running the
491 // API. We treat a non-deleted match as ours because diff/replace
492 // already covers immutable property changes upstream.
493 let gw: ec2.NatGateway | undefined;
494 if (output?.natGatewayId) {
495 const lookup = yield* ec2
496 .describeNatGateways({ NatGatewayIds: [output.natGatewayId] })
497 .pipe(
498 Effect.catchTag("NatGatewayNotFound", () => Effect.succeed({ NatGateways: [] })),
499 );
500 gw = lookup.NatGateways?.[0];
501 } else {
502 gw = yield* findNatGatewayByTags(id);
503 }
504
505 // Treat a deleted/deleting NAT as if it doesn't exist so we recreate.
506 if (gw && (gw.State === "deleted" || gw.State === "deleting" || gw.State === "failed")) {
507 gw = undefined;
508 }
509
510 // Ensure — create the NAT gateway when missing.
511 if (gw === undefined) {
512 yield* session.note("Creating NAT Gateway...");
513 const result = yield* ec2.createNatGateway({
514 AvailabilityMode: news.availabilityMode,
515 SubnetId: news.subnetId,
516 VpcId: news.vpcId,
517 AvailabilityZoneAddresses: news.availabilityZoneAddresses?.map((a) => ({
518 AvailabilityZone: a.availabilityZone,
519 AvailabilityZoneId: a.availabilityZoneId,
520 AllocationIds: a.allocationIds,
521 })),
522 AllocationId: news.allocationId as string | undefined,
523 ConnectivityType:
524 news.connectivityType ??
525 (news.availabilityMode === "regional" ? undefined : "public"),
526 PrivateIpAddress: news.privateIpAddress,
527 SecondaryAllocationIds: news.secondaryAllocationIds as string[] | undefined,
528 SecondaryPrivateIpAddresses: news.secondaryPrivateIpAddresses,
529 SecondaryPrivateIpAddressCount: news.secondaryPrivateIpAddressCount,
530 TagSpecifications: [
531 {
532 ResourceType: "natgateway",
533 Tags: createTagsList(desiredTags),
534 },
535 ],
536 DryRun: false,
537 });
538 const natGatewayId = result.NatGateway!.NatGatewayId!;
539 yield* session.note(`NAT Gateway created: ${natGatewayId}`);
540 gw = yield* waitForNatGatewayAvailable(natGatewayId, session);
541 }
542
543 const natGatewayId = gw.NatGatewayId!;
544
545 // Sync manual-mode zone addresses — observed associations vs desired.
546 if (news.availabilityZoneAddresses) {
547 // An in-flight association has no AssociationId yet, so it can be
548 // neither diffed nor disassociated — let it settle first.
549 const settled = yield* waitForNatGatewayAddresses(
550 natGatewayId,
551 (a) => a.Status === "associating",
552 session,
553 );
554 const observed = (settled.NatGatewayAddresses ?? []).filter(
555 (a) =>
556 a.AllocationId !== undefined &&
557 a.Status !== "disassociating" &&
558 a.Status !== "failed",
559 );
560 const desired = news.availabilityZoneAddresses.flatMap((zone) =>
561 zone.allocationIds.map((allocationId) => ({ zone, allocationId })),
562 );
563 const sameZone = (a: ec2.NatGatewayAddress, zone: NatGatewayAvailabilityZoneAddress) =>
564 zone.availabilityZoneId !== undefined
565 ? a.AvailabilityZoneId === zone.availabilityZoneId
566 : a.AvailabilityZone === zone.availabilityZone;
567 const stale = observed.filter(
568 (a) =>
569 a.AssociationId !== undefined &&
570 !desired.some((d) => d.allocationId === a.AllocationId && sameZone(a, d.zone)),
571 );
572 if (stale.length > 0) {
573 yield* session.note(`Disassociating ${stale.length} NAT Gateway address(es)...`);
574 yield* ec2.disassociateNatGatewayAddress({
575 NatGatewayId: natGatewayId,
576 AssociationIds: stale.map((a) => a.AssociationId!),
577 MaxDrainDurationSeconds: news.maxDrainDurationSeconds,
578 });
579 // An EIP moving between zones must be released before it can
580 // be associated again.
581 const moving = stale
582 .map((a) => a.AllocationId!)
583 .filter((allocationId) => desired.some((d) => d.allocationId === allocationId));
584 if (moving.length > 0) {
585 yield* waitForNatGatewayAddresses(
586 natGatewayId,
587 (a) => a.AllocationId !== undefined && moving.includes(a.AllocationId),
588 session,
589 );
590 }
591 }
592 for (const zone of news.availabilityZoneAddresses) {
593 const missing = zone.allocationIds.filter(
594 (allocationId) =>
595 !observed.some((a) => a.AllocationId === allocationId && sameZone(a, zone)),
596 );
597 if (missing.length > 0) {
598 yield* session.note(
599 `Associating ${missing.length} address(es) in ${zone.availabilityZoneId ?? zone.availabilityZone}...`,
600 );
601 yield* ec2.associateNatGatewayAddress({
602 NatGatewayId: natGatewayId,
603 AvailabilityZone: zone.availabilityZone,
604 AvailabilityZoneId: zone.availabilityZoneId,
605 AllocationIds: missing,
606 });
607 }
608 }
609 const associated = yield* waitForNatGatewayAddresses(
610 natGatewayId,
611 (a) => a.Status === "associating",
612 session,
613 );
614 const failed = (associated.NatGatewayAddresses ?? []).find(
615 (a) =>
616 a.Status === "failed" &&
617 desired.some((d) => d.allocationId === a.AllocationId && sameZone(a, d.zone)),
618 );
619 if (failed) {
620 return yield* new NatGatewayAddressFailed({
621 natGatewayId,
622 allocationId: failed.AllocationId!,
623 failureMessage: failed.FailureMessage,
624 });
625 }
626 }
627
628 // Sync tags — observed cloud tags vs desired.
629 const currentTags =
630 (yield* ec2
631 .describeTags({
632 Filters: [
633 { Name: "resource-id", Values: [natGatewayId] },
634 { Name: "resource-type", Values: ["natgateway"] },
635 ],
636 })
637 .pipe(
638 Effect.map(
639 (r) =>
640 Object.fromEntries(r.Tags?.map((t) => [t.Key!, t.Value!]) ?? []) as Record<
641 string,
642 string
643 >,
644 ),
645 )) ?? {};
646 const { removed, upsert } = diffTags(currentTags, desiredTags);
647 if (removed.length > 0) {
648 yield* ec2.deleteTags({
649 Resources: [natGatewayId],
650 Tags: removed.map((key) => ({ Key: key })),
651 DryRun: false,
652 });
653 }
654 if (upsert.length > 0) {
655 yield* ec2.createTags({
656 Resources: [natGatewayId],
657 Tags: upsert,
658 DryRun: false,
659 });
660 }
661
662 // Re-read final state.
663 const final = yield* describeNatGateway(natGatewayId);
664 return yield* toAttrs(final);
665 }),
666
667 delete: Effect.fn(function* ({ output, session }) {
668 const natGatewayId = output.natGatewayId;
669
670 yield* session.note(`Deleting NAT Gateway: ${natGatewayId}`);
671
672 yield* ec2
673 .deleteNatGateway({
674 NatGatewayId: natGatewayId,
675 DryRun: false,
676 })
677 .pipe(Effect.catchTag("NatGatewayNotFound", () => Effect.void));
678
679 // Wait for NAT Gateway to be deleted
680 yield* waitForNatGatewayDeleted(natGatewayId, session);
681
682 yield* session.note(`NAT Gateway ${natGatewayId} deleted`);
683 }),
684 };
685 }),
686 );
687
688 // Retryable error: NAT Gateway is still pending
689 class NatGatewayPending extends Data.TaggedError("NatGatewayPending")<{
690 natGatewayId: string;
691 state: string;
692 }> {}
693
694 // Terminal error: NAT Gateway creation failed
695 class NatGatewayFailed extends Data.TaggedError("NatGatewayFailed")<{
696 natGatewayId: string;
697 failureCode?: string;
698 failureMessage?: string;
699 }> {}
700
701 // Terminal error: NAT Gateway not found
702 class NatGatewayNotFound extends Data.TaggedError("NatGatewayNotFound")<{
703 natGatewayId: string;
704 }> {}
705
706 /**
707 * Wait for NAT Gateway to be in available state
708 */
709 const waitForNatGatewayAvailable = (natGatewayId: string, session: ScopedPlanStatusSession) =>
710 Effect.gen(function* () {
711 const result = yield* ec2.describeNatGateways({
712 NatGatewayIds: [natGatewayId],
713 });
714 const gw = result.NatGateways?.[0];
715
716 if (!gw) {
717 return yield* new NatGatewayNotFound({ natGatewayId });
718 }
719
720 if (gw.State === "available") {
721 return gw;
722 }
723
724 if (gw.State === "failed") {
725 return yield* new NatGatewayFailed({
726 natGatewayId,
727 failureCode: gw.FailureCode,
728 failureMessage: gw.FailureMessage,
729 });
730 }
731
732 // Still pending - this is the only retryable case
733 return yield* new NatGatewayPending({ natGatewayId, state: gw.State! });
734 }).pipe(
735 Effect.tapError(Effect.logDebug),
736 Effect.retry({
737 while: (e) => e._tag === "NatGatewayPending",
738 schedule: Schedule.max([Schedule.fixed(5000), Schedule.recurs(60)]).pipe(
739 Schedule.tap(({ attempt }) =>
740 session.note(`Waiting for NAT Gateway to be available... (${attempt * 5}s)`),
741 ),
742 ),
743 }),
744 );
745
746 // Retryable error: NAT Gateway is still deleting
747 class NatGatewayDeleting extends Data.TaggedError("NatGatewayDeleting")<{
748 natGatewayId: string;
749 state: string;
750 }> {}
751
752 /**
753 * Wait for NAT Gateway to be deleted
754 */
755 const waitForNatGatewayDeleted = (natGatewayId: string, session: ScopedPlanStatusSession) =>
756 Effect.gen(function* () {
757 const result = yield* ec2
758 .describeNatGateways({ NatGatewayIds: [natGatewayId] })
759 .pipe(Effect.catchTag("NatGatewayNotFound", () => Effect.succeed({ NatGateways: [] })));
760
761 const gw = result.NatGateways?.[0];
762
763 if (!gw || gw.State === "deleted") {
764 return; // Successfully deleted
765 }
766
767 yield* Effect.logDebug(gw);
768
769 // Still deleting - this is the only retryable case
770 return yield* new NatGatewayDeleting({ natGatewayId, state: gw.State! });
771 }).pipe(
772 Effect.tapError(Effect.logDebug),
773 Effect.retry({
774 while: (e) => e._tag === "NatGatewayDeleting",
775 schedule: Schedule.max([Schedule.fixed(5000), Schedule.recurs(60)]).pipe(
776 Schedule.tap(({ attempt }) =>
777 session.note(`Waiting for NAT Gateway deletion... (${attempt * 5}s)`),
778 ),
779 ),
780 }),
781 );
782
783 // Terminal error: an Elastic IP could not be associated with the NAT Gateway
784 class NatGatewayAddressFailed extends Data.TaggedError("NatGatewayAddressFailed")<{
785 natGatewayId: string;
786 allocationId: string;
787 failureMessage?: string;
788 }> {}
789
790 // Retryable error: NAT Gateway addresses are still transitioning
791 class NatGatewayAddressesPending extends Data.TaggedError("NatGatewayAddressesPending")<{
792 natGatewayId: string;
793 allocationIds: string[];
794 }> {}
795
796 /**
797 * Wait until no NAT Gateway address matches `pending`, returning the settled gateway
798 */
799 const waitForNatGatewayAddresses = Effect.fn(
800 function* (
801 natGatewayId: string,
802 pending: (address: ec2.NatGatewayAddress) => boolean,
803 _session: ScopedPlanStatusSession,
804 ) {
805 const result = yield* ec2.describeNatGateways({ NatGatewayIds: [natGatewayId] });
806 const gw = result.NatGateways?.[0];
807 if (!gw) {
808 return yield* new NatGatewayNotFound({ natGatewayId });
809 }
810 const transitioning = (gw.NatGatewayAddresses ?? []).filter(pending);
811 if (transitioning.length > 0) {
812 return yield* new NatGatewayAddressesPending({
813 natGatewayId,
814 allocationIds: transitioning.map((a) => a.AllocationId ?? "unknown"),
815 });
816 }
817 return gw;
818 },
819 (effect, _natGatewayId, _pending, session) =>
820 effect.pipe(
821 Effect.retry({
822 while: (e) => e._tag === "NatGatewayAddressesPending",
823 schedule: Schedule.max([Schedule.fixed(5000), Schedule.recurs(90)]).pipe(
824 Schedule.tap(({ attempt }) =>
825 session.note(`Waiting for NAT Gateway addresses to settle... (${attempt * 5}s)`),
826 ),
827 ),
828 }),
829 ),
830 );