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

main
ts 556 lines 19.5 KB
Raw
1 import type * as EC2 from "@distilled.cloud/aws/ec2";
2 import * as ec2 from "@distilled.cloud/aws/ec2";
3 import { isResolved, somePropsAreDifferent } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Effect from "effect/Effect";
7 import * as Schedule from "effect/Schedule";
8 import * as Stream from "effect/Stream";
9 import type { Providers } from "../Providers.ts";
10 import { getDefaultVpcScope } from "./defaultVpcScope.ts";
11 import type { RouteTableId } from "./RouteTable.ts";
12
13 export interface RouteProps {
14 /**
15 * The ID of the route table where the route will be added.
16 * Required.
17 */
18 routeTableId: RouteTableId;
19
20 /**
21 * The IPv4 CIDR block used for the destination match.
22 * Either destinationCidrBlock, destinationIpv6CidrBlock, or destinationPrefixListId is required.
23 * @example "0.0.0.0/0"
24 */
25 destinationCidrBlock?: string;
26
27 /**
28 * The IPv6 CIDR block used for the destination match.
29 * Either destinationCidrBlock, destinationIpv6CidrBlock, or destinationPrefixListId is required.
30 * @example "::/0"
31 */
32 destinationIpv6CidrBlock?: string;
33
34 /**
35 * The ID of a prefix list used for the destination match.
36 * Either destinationCidrBlock, destinationIpv6CidrBlock, or destinationPrefixListId is required.
37 */
38 destinationPrefixListId?: string;
39
40 // ---- Target properties (exactly one required) ----
41
42 /**
43 * The ID of an internet gateway or virtual private gateway.
44 */
45 gatewayId?: string;
46
47 /**
48 * The ID of a NAT gateway.
49 */
50 natGatewayId?: string;
51
52 /**
53 * The ID of a NAT instance in your VPC.
54 * This operation fails unless exactly one network interface is attached.
55 */
56 instanceId?: string;
57
58 /**
59 * The ID of a network interface.
60 */
61 networkInterfaceId?: string;
62
63 /**
64 * The ID of a VPC peering connection.
65 */
66 vpcPeeringConnectionId?: string;
67
68 /**
69 * The ID of a transit gateway.
70 */
71 transitGatewayId?: string;
72
73 /**
74 * The ID of a local gateway.
75 */
76 localGatewayId?: string;
77
78 /**
79 * The ID of a carrier gateway.
80 * Use for Wavelength Zones only.
81 */
82 carrierGatewayId?: string;
83
84 /**
85 * The ID of an egress-only internet gateway.
86 * IPv6 traffic only.
87 */
88 egressOnlyInternetGatewayId?: string;
89
90 /**
91 * The Amazon Resource Name (ARN) of the core network.
92 */
93 coreNetworkArn?: string;
94
95 /**
96 * The ID of a VPC endpoint for Gateway Load Balancer.
97 */
98 vpcEndpointId?: string;
99 }
100
101 export interface Route extends Resource<
102 "AWS.EC2.Route",
103 RouteProps,
104 {
105 /**
106 * The ID of the route table that contains this route.
107 */
108 routeTableId: RouteTableId;
109 /**
110 * The IPv4 CIDR block used for the destination match.
111 */
112 destinationCidrBlock?: string | undefined;
113 /**
114 * The IPv6 CIDR block used for the destination match.
115 */
116 destinationIpv6CidrBlock?: string | undefined;
117 /**
118 * The ID of the prefix list used for the destination match.
119 */
120 destinationPrefixListId?: string | undefined;
121 /**
122 * Describes how the route was created (e.g. `CreateRoute`).
123 */
124 origin: EC2.RouteOrigin;
125 /**
126 * The state of the route (e.g. `active` or `blackhole`).
127 */
128 state: EC2.RouteState;
129 /**
130 * The ID of the internet gateway or virtual private gateway the route targets.
131 */
132 gatewayId?: string;
133 /**
134 * The ID of the NAT gateway the route targets.
135 */
136 natGatewayId?: string;
137 /**
138 * The ID of the NAT instance the route targets.
139 */
140 instanceId?: string;
141 /**
142 * The ID of the network interface the route targets.
143 */
144 networkInterfaceId?: string;
145 /**
146 * The ID of the VPC peering connection the route targets.
147 */
148 vpcPeeringConnectionId?: string;
149 /**
150 * The ID of the transit gateway the route targets.
151 */
152 transitGatewayId?: string;
153 /**
154 * The ID of the local gateway the route targets.
155 */
156 localGatewayId?: string;
157 /**
158 * The ID of the carrier gateway the route targets.
159 */
160 carrierGatewayId?: string;
161 /**
162 * The ID of the egress-only internet gateway the route targets (IPv6 only).
163 */
164 egressOnlyInternetGatewayId?: string;
165 /**
166 * The Amazon Resource Name (ARN) of the core network the route targets.
167 */
168 coreNetworkArn?: string;
169 },
170 never,
171 Providers
172 > {}
173 /**
174 * A single route entry inside a {@link RouteTable}. A route maps a destination
175 * to exactly one target, telling the VPC where to send packets whose address
176 * falls within the destination range.
177 *
178 * Every route has two halves:
179 * - **Destination** — exactly one of `destinationCidrBlock` (IPv4),
180 * `destinationIpv6CidrBlock` (IPv6), or `destinationPrefixListId` (a managed
181 * prefix list, e.g. for an AWS service).
182 * - **Target** — exactly one of `gatewayId` (internet/virtual private
183 * gateway), `natGatewayId`, `instanceId` (NAT instance), `networkInterfaceId`,
184 * `vpcPeeringConnectionId`, `transitGatewayId`, `localGatewayId` (Outposts),
185 * `carrierGatewayId` (Wavelength), `egressOnlyInternetGatewayId` (IPv6),
186 * `coreNetworkArn` (Cloud WAN), or `vpcEndpointId` (Gateway Load Balancer).
187 *
188 * Changing the `routeTableId` or the destination replaces the route, whereas
189 * changing only the target is applied in place via `ReplaceRoute`.
190 *
191 * ### IPv4 Routing
192 * Use an IPv4 `destinationCidrBlock` — most commonly `0.0.0.0/0` for the
193 * default route, or a narrower CIDR to route specific traffic.
194 *
195 * **Example:** Default Route to an Internet Gateway
196 * ```typescript
197 * const internetRoute = yield* AWS.EC2.Route("InternetRoute", {
198 * routeTableId: publicRouteTable.routeTableId,
199 * destinationCidrBlock: "0.0.0.0/0",
200 * gatewayId: internetGateway.internetGatewayId,
201 * });
202 * ```
203 * Sends all outbound IPv4 traffic to the internet gateway, which is what makes
204 * a subnet "public". Attach this route table to any subnet that needs inbound
205 * and outbound internet connectivity.
206 *
207 * **Example:** Default Route to a NAT Gateway
208 * ```typescript
209 * const natRoute = yield* AWS.EC2.Route("NatRoute", {
210 * routeTableId: privateRouteTable.routeTableId,
211 * destinationCidrBlock: "0.0.0.0/0",
212 * natGatewayId: natGateway.natGatewayId,
213 * });
214 * ```
215 * Lets private subnets reach the internet for outbound traffic (package
216 * updates, API calls) while blocking unsolicited inbound connections. The NAT
217 * gateway itself lives in a public subnet.
218 *
219 * **Example:** Route to a VPC Peering Connection
220 * ```typescript
221 * const peeringRoute = yield* AWS.EC2.Route("PeeringRoute", {
222 * routeTableId: routeTable.routeTableId,
223 * destinationCidrBlock: "10.1.0.0/16",
224 * vpcPeeringConnectionId: "pcx-0abc1234",
225 * });
226 * ```
227 * Routes traffic destined for the peer VPC's CIDR across a VPC peering
228 * connection. Use a narrow destination matching the remote VPC rather than
229 * `0.0.0.0/0` so only cross-VPC traffic is affected.
230 *
231 * **Example:** Route to a Transit Gateway
232 * ```typescript
233 * const transitRoute = yield* AWS.EC2.Route("TransitRoute", {
234 * routeTableId: routeTable.routeTableId,
235 * destinationCidrBlock: "172.16.0.0/12",
236 * transitGatewayId: "tgw-0abc1234",
237 * });
238 * ```
239 * Hands traffic to a transit gateway, the hub used to connect many VPCs and
240 * on-premises networks. The destination CIDR should cover the address space
241 * reachable through the transit gateway.
242 *
243 * **Example:** Route to a Network Interface or NAT Instance
244 * ```typescript
245 * const applianceRoute = yield* AWS.EC2.Route("ApplianceRoute", {
246 * routeTableId: routeTable.routeTableId,
247 * destinationCidrBlock: "0.0.0.0/0",
248 * networkInterfaceId: "eni-0abc1234",
249 * });
250 * ```
251 * Forwards traffic to a specific elastic network interface — for example a
252 * firewall or NAT instance appliance. Use `instanceId` instead when targeting
253 * a NAT instance that has exactly one network interface attached.
254 *
255 * ### IPv6 Routing
256 * IPv6 routes use `destinationIpv6CidrBlock` (e.g. `::/0` for the IPv6 default
257 * route). For outbound-only IPv6 access from private subnets, target an
258 * {@link EgressOnlyInternetGateway}.
259 *
260 * **Example:** IPv6 Egress Route to an Egress-Only Internet Gateway
261 * ```typescript
262 * const ipv6EgressRoute = yield* AWS.EC2.Route("Ipv6EgressRoute", {
263 * routeTableId: privateRouteTable.routeTableId,
264 * destinationIpv6CidrBlock: "::/0",
265 * egressOnlyInternetGatewayId: egressOnlyIgw.egressOnlyInternetGatewayId,
266 * });
267 * ```
268 * Gives IPv6-addressed instances outbound internet access while blocking
269 * inbound connections — the IPv6 equivalent of routing IPv4 through a NAT
270 * gateway.
271 *
272 * **Example:** IPv6 Internet Route to an Internet Gateway
273 * ```typescript
274 * const ipv6InternetRoute = yield* AWS.EC2.Route("Ipv6InternetRoute", {
275 * routeTableId: publicRouteTable.routeTableId,
276 * destinationIpv6CidrBlock: "::/0",
277 * gatewayId: internetGateway.internetGatewayId,
278 * });
279 * ```
280 * Provides full bidirectional IPv6 connectivity for a public subnet, since an
281 * internet gateway (unlike an egress-only gateway) allows inbound IPv6 traffic.
282 *
283 * ### Routing to AWS Services via Prefix Lists
284 * Instead of a raw CIDR, a route can match a managed prefix list — useful for
285 * AWS service ranges (e.g. an S3 gateway endpoint) where the underlying CIDRs
286 * change over time.
287 *
288 * **Example:** Prefix List Route to a Gateway VPC Endpoint
289 * ```typescript
290 * const prefixListRoute = yield* AWS.EC2.Route("S3PrefixRoute", {
291 * routeTableId: privateRouteTable.routeTableId,
292 * destinationPrefixListId: "pl-0abc1234",
293 * vpcEndpointId: "vpce-0abc1234",
294 * });
295 * ```
296 * Routes traffic for every CIDR in the prefix list to a Gateway Load Balancer
297 * VPC endpoint. AWS keeps the prefix list current, so you don't have to update
298 * the route when the service's address ranges change.
299 *
300 * @resource
301 */
302 export const Route = Resource<Route>("AWS.EC2.Route");
303
304 export const RouteProvider = () =>
305 Provider.effect(
306 Route,
307 Effect.gen(function* () {
308 return {
309 diff: Effect.fn(function* ({ news, olds }) {
310 if (!isResolved(news)) return;
311 // Route table change requires replacement
312 if (olds.routeTableId !== news.routeTableId) {
313 return { action: "replace" };
314 }
315
316 // Destination change requires replacement
317 if (
318 somePropsAreDifferent(olds, news, [
319 "destinationCidrBlock",
320 "destinationIpv6CidrBlock",
321 "destinationPrefixListId",
322 ])
323 ) {
324 return { action: "replace" };
325 }
326
327 // Target change can be done via ReplaceRoute (update)
328 }),
329
330 // Routes have no id or tags: the identity is (route table,
331 // destination), and the target and state are what drift compares.
332 read: Effect.fn(function* ({ olds, output }) {
333 const identity = output ?? olds;
334 if (identity?.routeTableId === undefined) return undefined;
335 const route = yield* describeRoute(identity.routeTableId, identity);
336 if (route === undefined) return undefined;
337 return toRouteAttributes(identity.routeTableId, identity, route);
338 }),
339
340 reconcile: Effect.fn(function* ({ news, session }) {
341 const dest =
342 news.destinationCidrBlock ||
343 news.destinationIpv6CidrBlock ||
344 news.destinationPrefixListId ||
345 "unknown";
346
347 const targetParams = {
348 RouteTableId: news.routeTableId,
349 DestinationCidrBlock: news.destinationCidrBlock,
350 DestinationIpv6CidrBlock: news.destinationIpv6CidrBlock,
351 DestinationPrefixListId: news.destinationPrefixListId,
352 GatewayId: news.gatewayId,
353 NatGatewayId: news.natGatewayId,
354 InstanceId: news.instanceId,
355 NetworkInterfaceId: news.networkInterfaceId,
356 VpcPeeringConnectionId: news.vpcPeeringConnectionId,
357 TransitGatewayId: news.transitGatewayId,
358 LocalGatewayId: news.localGatewayId,
359 CarrierGatewayId: news.carrierGatewayId,
360 EgressOnlyInternetGatewayId: news.egressOnlyInternetGatewayId,
361 CoreNetworkArn: news.coreNetworkArn,
362 DryRun: false,
363 } as const;
364
365 // Observe — Routes are identified by (routeTableId, destination).
366 // Look the route up in the route table to decide between create
367 // (missing) and replaceRoute (target drift).
368 const observed = yield* describeRoute(news.routeTableId, news);
369
370 // Ensure / Sync — CreateRoute when missing, ReplaceRoute swaps the
371 // target on an existing route in-place.
372 if (observed === undefined) {
373 yield* ec2
374 .createRoute({
375 ...targetParams,
376 VpcEndpointId: news.vpcEndpointId,
377 })
378 .pipe(
379 Effect.retry({
380 while: (e) => e._tag === "InvalidRouteTableID.NotFound",
381 schedule: Schedule.exponential(100),
382 }),
383 );
384 yield* session.note(`Route created: ${dest}`);
385 } else {
386 yield* ec2.replaceRoute(targetParams).pipe(
387 Effect.tapError(Effect.log),
388 Effect.retry({
389 while: (e) => e._tag === "InvalidRouteTableID.NotFound",
390 schedule: Schedule.exponential(100),
391 }),
392 );
393 yield* session.note(`Route target updated: ${dest}`);
394 }
395
396 // Re-read final state.
397 const route = yield* describeRoute(news.routeTableId, news);
398 return toRouteAttributes(news.routeTableId, news, route);
399 }),
400
401 // Routes are entries embedded inside RouteTables. Enumerate by
402 // flattening describeRouteTables -> RouteTables[].Routes[], pairing each
403 // route with its parent routeTableId. Skip the implicit local route
404 // (GatewayId === "local", Origin "CreateRouteTable") that AWS creates
405 // automatically and that this provider does not manage.
406 list: () =>
407 Effect.gen(function* () {
408 // Routes in the default VPC's main route table (the 0.0.0.0/0 IGW
409 // route AWS provisions) are default-VPC furniture; never
410 // census/nuke them. Routes in user-created route tables inside the
411 // default VPC are still listed.
412 const defaultVpc = yield* getDefaultVpcScope;
413 return yield* ec2.describeRouteTables.pages({}).pipe(
414 Stream.runCollect,
415 Effect.map((chunk) =>
416 Array.from(chunk).flatMap((page) =>
417 (page.RouteTables ?? []).flatMap((rt) => {
418 const routeTableId = rt.RouteTableId;
419 if (routeTableId === undefined) return [];
420 if (
421 defaultVpc.vpcId !== undefined &&
422 rt.VpcId === defaultVpc.vpcId &&
423 rt.Associations?.some((a) => a.Main)
424 ) {
425 return [];
426 }
427 return (rt.Routes ?? [])
428 .filter(
429 (r) =>
430 r.GatewayId !== "local" &&
431 // VPC Lattice injects service-managed routes while
432 // a VPC association is active. They cannot be
433 // deleted through EC2 and drain with the association.
434 r.GatewayId !== "VpcLattice",
435 )
436 .map((r) => ({
437 routeTableId: routeTableId as RouteTableId,
438 destinationCidrBlock: r.DestinationCidrBlock,
439 destinationIpv6CidrBlock: r.DestinationIpv6CidrBlock,
440 destinationPrefixListId: r.DestinationPrefixListId,
441 origin: r.Origin ?? "CreateRoute",
442 state: r.State ?? "active",
443 gatewayId: r.GatewayId,
444 natGatewayId: r.NatGatewayId,
445 instanceId: r.InstanceId,
446 networkInterfaceId: r.NetworkInterfaceId,
447 vpcPeeringConnectionId: r.VpcPeeringConnectionId,
448 transitGatewayId: r.TransitGatewayId,
449 localGatewayId: r.LocalGatewayId,
450 carrierGatewayId: r.CarrierGatewayId,
451 egressOnlyInternetGatewayId: r.EgressOnlyInternetGatewayId,
452 coreNetworkArn: r.CoreNetworkArn,
453 }));
454 }),
455 ),
456 ),
457 );
458 }),
459
460 delete: Effect.fn(function* ({ output, session }) {
461 const dest =
462 output.destinationCidrBlock ||
463 output.destinationIpv6CidrBlock ||
464 output.destinationPrefixListId ||
465 "unknown";
466
467 yield* session.note(`Deleting route: ${dest}`);
468
469 // Delete the route
470 yield* ec2
471 .deleteRoute({
472 RouteTableId: output.routeTableId,
473 DestinationCidrBlock: output.destinationCidrBlock,
474 DestinationIpv6CidrBlock: output.destinationIpv6CidrBlock,
475 DestinationPrefixListId: output.destinationPrefixListId,
476 DryRun: false,
477 })
478 .pipe(
479 Effect.tapError(Effect.logDebug),
480 Effect.catchTags({
481 "InvalidRoute.NotFound": () => Effect.void,
482 "InvalidRouteTableID.NotFound": () => Effect.void,
483 }),
484 );
485
486 yield* session.note(`Route ${dest} deleted successfully`);
487 }),
488 };
489 }),
490 );
491
492 /**
493 * Find a specific route in a route table
494 */
495 /** The attributes `read` and `reconcile` both report for a route. */
496 const toRouteAttributes = (
497 routeTableId: RouteTableId,
498 destination: Pick<
499 RouteProps,
500 "destinationCidrBlock" | "destinationIpv6CidrBlock" | "destinationPrefixListId"
501 >,
502 route: EC2.Route | undefined,
503 ): Route["Attributes"] => ({
504 routeTableId,
505 destinationCidrBlock: destination.destinationCidrBlock,
506 destinationIpv6CidrBlock: destination.destinationIpv6CidrBlock,
507 destinationPrefixListId: destination.destinationPrefixListId,
508 origin: route?.Origin ?? "CreateRoute",
509 state: route?.State ?? "active",
510 gatewayId: route?.GatewayId,
511 natGatewayId: route?.NatGatewayId,
512 instanceId: route?.InstanceId,
513 networkInterfaceId: route?.NetworkInterfaceId,
514 vpcPeeringConnectionId: route?.VpcPeeringConnectionId,
515 transitGatewayId: route?.TransitGatewayId,
516 localGatewayId: route?.LocalGatewayId,
517 carrierGatewayId: route?.CarrierGatewayId,
518 egressOnlyInternetGatewayId: route?.EgressOnlyInternetGatewayId,
519 coreNetworkArn: route?.CoreNetworkArn,
520 });
521
522 const describeRoute = (
523 routeTableId: string,
524 props: Pick<
525 RouteProps,
526 "destinationCidrBlock" | "destinationIpv6CidrBlock" | "destinationPrefixListId"
527 >,
528 ) =>
529 Effect.gen(function* () {
530 const result = yield* ec2
531 .describeRouteTables({ RouteTableIds: [routeTableId] })
532 .pipe(
533 Effect.catchTag("InvalidRouteTableID.NotFound", () => Effect.succeed({ RouteTables: [] })),
534 );
535
536 const routeTable = result.RouteTables?.[0];
537 if (!routeTable) {
538 return undefined;
539 }
540
541 // Find the matching route
542 const route = routeTable.Routes?.find((r) => {
543 if (props.destinationCidrBlock) {
544 return r.DestinationCidrBlock === props.destinationCidrBlock;
545 }
546 if (props.destinationIpv6CidrBlock) {
547 return r.DestinationIpv6CidrBlock === props.destinationIpv6CidrBlock;
548 }
549 if (props.destinationPrefixListId) {
550 return r.DestinationPrefixListId === props.destinationPrefixListId;
551 }
552 return false;
553 });
554
555 return route;
556 });