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

main
ts 560 lines 20.3 KB
Raw
1 import type * as EC2 from "@distilled.cloud/aws/ec2";
2 import * as ec2 from "@distilled.cloud/aws/ec2";
3 import { Unowned } from "alchemy/AdoptPolicy";
4 import { isResolved } from "alchemy/Diff";
5 import * as Provider from "alchemy/Provider";
6 import type { ScopedPlanStatusSession } from "alchemy/Report";
7 import { Resource } from "alchemy/Resource";
8 import { createInternalTags, createTagsList, diffTags, hasAlchemyTags } from "alchemy/Tags";
9 import * as Data from "effect/Data";
10 import * as Effect from "effect/Effect";
11 import * as Schedule from "effect/Schedule";
12 import * as Stream from "effect/Stream";
13 import type { AccountID } from "../Environment.ts";
14 import { AWSEnvironment } from "../Environment.ts";
15 import { tagListRecord } from "../internal/Observe.ts";
16 import type { Providers } from "../Providers.ts";
17 import type { RegionID } from "../Region.ts";
18 import type { VpcId } from "./Vpc.ts";
19
20 export class RouteTableNotReady extends Data.TaggedError("RouteTableNotReady")<{
21 readonly message: string;
22 readonly cause?: unknown;
23 }> {}
24
25 export type RouteTableId<ID extends string = string> = `rtb-${ID}`;
26 export const RouteTableId = <ID extends string>(id: ID): ID & RouteTableId<ID> =>
27 `rtb-${id}` as ID & RouteTableId<ID>;
28
29 export interface RouteTableProps {
30 /**
31 * The VPC to create the route table in.
32 * Required.
33 */
34 vpcId: VpcId;
35
36 /**
37 * Tags to assign to the route table.
38 * These will be merged with alchemy auto-tags (alchemy::stack, alchemy::stage, alchemy::id).
39 */
40 tags?: Record<string, string>;
41 }
42
43 export interface RouteTable extends Resource<
44 "AWS.EC2.RouteTable",
45 RouteTableProps,
46 {
47 /**
48 * The ID of the VPC the route table is in.
49 */
50 vpcId: VpcId;
51
52 /**
53 * The ID of the route table.
54 */
55 routeTableId: RouteTableId;
56
57 /**
58 * The Amazon Resource Name (ARN) of the route table.
59 */
60 routeTableArn: `arn:aws:ec2:${RegionID}:${AccountID}:route-table/${string}`;
61
62 /**
63 * The ID of the AWS account that owns the route table.
64 */
65 ownerId?: string;
66
67 /**
68 * The associations between the route table and subnets or gateways.
69 */
70 associations?: Array<{
71 /**
72 * Whether this is the main route table for the VPC.
73 */
74 main: boolean;
75 /**
76 * The ID of the association.
77 */
78 routeTableAssociationId?: string;
79 /**
80 * The ID of the route table.
81 */
82 routeTableId?: string;
83 /**
84 * The ID of the subnet (if the association is with a subnet).
85 */
86 subnetId?: string;
87 /**
88 * The ID of the gateway (if the association is with a gateway).
89 */
90 gatewayId?: string;
91 /**
92 * The state of the association.
93 */
94 associationState?: {
95 state: EC2.RouteTableAssociationStateCode;
96 statusMessage?: string;
97 };
98 }>;
99
100 /**
101 * The routes in the route table.
102 */
103 routes?: Array<{
104 /**
105 * The IPv4 CIDR block used for the destination match.
106 */
107 destinationCidrBlock?: string;
108 /**
109 * The IPv6 CIDR block used for the destination match.
110 */
111 destinationIpv6CidrBlock?: string;
112 /**
113 * The prefix of the AWS service.
114 */
115 destinationPrefixListId?: string;
116 /**
117 * The ID of the egress-only internet gateway.
118 */
119 egressOnlyInternetGatewayId?: string;
120 /**
121 * The ID of the gateway (internet gateway or virtual private gateway).
122 */
123 gatewayId?: string;
124 /**
125 * The ID of the NAT instance.
126 */
127 instanceId?: string;
128 /**
129 * The ID of AWS account that owns the NAT instance.
130 */
131 instanceOwnerId?: string;
132 /**
133 * The ID of the NAT gateway.
134 */
135 natGatewayId?: string;
136 /**
137 * The ID of the transit gateway.
138 */
139 transitGatewayId?: string;
140 /**
141 * The ID of the local gateway.
142 */
143 localGatewayId?: string;
144 /**
145 * The ID of the carrier gateway.
146 */
147 carrierGatewayId?: string;
148 /**
149 * The ID of the network interface.
150 */
151 networkInterfaceId?: string;
152 /**
153 * Describes how the route was created.
154 */
155 origin: EC2.RouteOrigin;
156 /**
157 * The state of the route.
158 */
159 state: EC2.RouteState;
160 /**
161 * The ID of the VPC peering connection.
162 */
163 vpcPeeringConnectionId?: string;
164 /**
165 * The Amazon Resource Name (ARN) of the core network.
166 */
167 coreNetworkArn?: string;
168 }>;
169
170 /**
171 * Any virtual private gateway (VGW) propagating routes.
172 */
173 propagatingVgws?: Array<{
174 gatewayId: string;
175 }>;
176
177 /**
178 * Tags on the route table, as observed. Lets `alchemy drift` detect
179 * out-of-band changes.
180 */
181 tags?: Record<string, string>;
182 },
183 never,
184 Providers
185 > {}
186 /**
187 * A VPC route table holds a set of routes that determine where network
188 * traffic from associated subnets (or gateways) is directed. Create one
189 * route table per routing domain — typically a "public" table whose default
190 * route points at an {@link InternetGateway}, and one or more "private" tables
191 * whose default route points at a NAT gateway.
192 *
193 * A route table is little more than a container: it owns a `vpcId` and tags,
194 * while the actual routing behaviour is supplied by separate {@link Route}
195 * resources and applied to subnets by {@link RouteTableAssociation} resources.
196 *
197 * ### Creating a Route Table
198 * The only required input is the `vpcId` the table belongs to. Changing
199 * `vpcId` later replaces the route table, since a table cannot move between
200 * VPCs.
201 *
202 * **Example:** Basic Route Table
203 * ```typescript
204 * const routeTable = yield* AWS.EC2.RouteTable("PublicRouteTable", {
205 * vpcId: myVpc.vpcId,
206 * });
207 * ```
208 * Creates an empty route table in the given VPC. It starts with only the
209 * implicit `local` route (managed by AWS) until you add your own
210 * {@link Route} resources.
211 *
212 * **Example:** Route Table with Tags
213 * ```typescript
214 * const routeTable = yield* AWS.EC2.RouteTable("PrivateRouteTable", {
215 * vpcId: myVpc.vpcId,
216 * tags: { Name: "private-rt", Tier: "private" },
217 * });
218 * ```
219 * The `tags` map is merged with the alchemy auto-tags (`alchemy::stack`,
220 * `alchemy::stage`, `alchemy::id`) and can be updated in place without
221 * replacing the table. Use the `Name` tag to label the table in the AWS
222 * console.
223 *
224 * ### Building a Public Routing Domain
225 * A route table only directs traffic once you attach routes to it and
226 * associate it with subnets. The pattern below wires a public subnet to the
227 * internet: an {@link InternetGateway}, a default {@link Route} pointing at it,
228 * and a {@link RouteTableAssociation} binding the subnet to the table.
229 *
230 * **Example:** Route Table, Internet Route, and Subnet Association
231 * ```typescript
232 * const internetGateway = yield* AWS.EC2.InternetGateway("InternetGateway", {
233 * vpcId: myVpc.vpcId,
234 * });
235 *
236 * const publicRouteTable = yield* AWS.EC2.RouteTable("PublicRouteTable", {
237 * vpcId: myVpc.vpcId,
238 * });
239 *
240 * const internetRoute = yield* AWS.EC2.Route("InternetRoute", {
241 * routeTableId: publicRouteTable.routeTableId,
242 * destinationCidrBlock: "0.0.0.0/0",
243 * gatewayId: internetGateway.internetGatewayId,
244 * });
245 *
246 * const association = yield* AWS.EC2.RouteTableAssociation("PublicSubnetAssociation", {
247 * routeTableId: publicRouteTable.routeTableId,
248 * subnetId: publicSubnet.subnetId,
249 * });
250 * ```
251 * Any subnet associated with this table now reaches the public internet via
252 * the `0.0.0.0/0` route. Multiple subnets can share the same route table by
253 * declaring additional associations — a common way to give every public
254 * subnet in a VPC identical routing.
255 *
256 * @resource
257 */
258 export const RouteTable = Resource<RouteTable>("AWS.EC2.RouteTable");
259
260 export const RouteTableProvider = () =>
261 Provider.effect(
262 RouteTable,
263 Effect.gen(function* () {
264 return {
265 stables: ["routeTableId", "ownerId", "routeTableArn", "vpcId"],
266
267 list: () =>
268 Effect.gen(function* () {
269 const { accountId, region } = yield* AWSEnvironment.current;
270 return yield* ec2.describeRouteTables.pages({}).pipe(
271 Stream.runCollect,
272 Effect.map((chunk) =>
273 Array.from(chunk).flatMap((page) =>
274 (page.RouteTables ?? [])
275 .filter(
276 (rt): rt is ec2.RouteTable & { RouteTableId: string } =>
277 rt.RouteTableId != null &&
278 // Every VPC has an implicit main route table. AWS does
279 // not allow deleting it directly; deleting the VPC
280 // removes it automatically.
281 !rt.Associations?.some((assoc) => assoc.Main === true),
282 )
283 .map((rt) => {
284 const routeTableId = rt.RouteTableId as RouteTableId;
285 return {
286 routeTableId,
287 routeTableArn:
288 `arn:aws:ec2:${region}:${accountId}:route-table/${routeTableId}` as `arn:aws:ec2:${RegionID}:${AccountID}:route-table/${string}`,
289 vpcId: rt.VpcId as VpcId,
290 ownerId: rt.OwnerId,
291 associations: rt.Associations?.map((assoc) => ({
292 main: assoc.Main ?? false,
293 routeTableAssociationId: assoc.RouteTableAssociationId,
294 routeTableId: assoc.RouteTableId,
295 subnetId: assoc.SubnetId,
296 gatewayId: assoc.GatewayId,
297 associationState: assoc.AssociationState
298 ? {
299 state: assoc.AssociationState.State!,
300 statusMessage: assoc.AssociationState.StatusMessage,
301 }
302 : undefined,
303 })),
304 routes: rt.Routes?.map((route) => ({
305 destinationCidrBlock: route.DestinationCidrBlock,
306 destinationIpv6CidrBlock: route.DestinationIpv6CidrBlock,
307 destinationPrefixListId: route.DestinationPrefixListId,
308 egressOnlyInternetGatewayId: route.EgressOnlyInternetGatewayId,
309 gatewayId: route.GatewayId,
310 instanceId: route.InstanceId,
311 instanceOwnerId: route.InstanceOwnerId,
312 natGatewayId: route.NatGatewayId,
313 transitGatewayId: route.TransitGatewayId,
314 localGatewayId: route.LocalGatewayId,
315 carrierGatewayId: route.CarrierGatewayId,
316 networkInterfaceId: route.NetworkInterfaceId,
317 origin: route.Origin!,
318 state: route.State!,
319 vpcPeeringConnectionId: route.VpcPeeringConnectionId,
320 coreNetworkArn: route.CoreNetworkArn,
321 })),
322 propagatingVgws: rt.PropagatingVgws?.map((vgw) => ({
323 gatewayId: vgw.GatewayId!,
324 })),
325 };
326 }),
327 ),
328 ),
329 );
330 }),
331
332 diff: Effect.fn(function* ({ news, olds }) {
333 if (!isResolved(news)) return;
334 // VpcId change requires replacement
335 if (olds.vpcId !== news.vpcId) {
336 return { action: "replace" };
337 }
338 // Tags can be updated in-place
339 }),
340
341 // The table owns only its existence and tags. Its routes and
342 // associations are managed by `Route` and `RouteTableAssociation`
343 // (which observe them), so the persisted snapshot is carried forward
344 // instead of reporting their changes as this table's drift.
345 read: Effect.fn(function* ({ id, output }) {
346 if (!output?.routeTableId) return undefined;
347 const routeTable = (yield* ec2
348 .describeRouteTables({ RouteTableIds: [output.routeTableId] })
349 .pipe(
350 Effect.catchTag("InvalidRouteTableID.NotFound", () =>
351 Effect.succeed({ RouteTables: [] }),
352 ),
353 )).RouteTables?.[0];
354 if (!routeTable?.RouteTableId) return undefined;
355 const tags = tagListRecord(routeTable.Tags);
356 const attrs = { ...output, ownerId: routeTable.OwnerId, tags };
357 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
358 }),
359
360 reconcile: Effect.fn(function* ({ id, news, output, session }) {
361 const { accountId, region } = yield* AWSEnvironment.current;
362 const alchemyTags = yield* createInternalTags(id);
363 const desiredTags = { ...alchemyTags, ...news.tags };
364
365 // Observe — find the route table via cached id, else fall through
366 // to create.
367 let routeTable: ec2.RouteTable | undefined;
368 if (output?.routeTableId) {
369 const lookup = yield* ec2
370 .describeRouteTables({ RouteTableIds: [output.routeTableId] })
371 .pipe(
372 Effect.catchTag("InvalidRouteTableID.NotFound", () =>
373 Effect.succeed({ RouteTables: [] }),
374 ),
375 );
376 routeTable = lookup.RouteTables?.[0];
377 }
378
379 // Ensure — create the route table when missing.
380 if (routeTable === undefined) {
381 const createResult = yield* ec2
382 .createRouteTable({
383 VpcId: news.vpcId,
384 TagSpecifications: [
385 {
386 ResourceType: "route-table",
387 Tags: createTagsList(desiredTags),
388 },
389 ],
390 DryRun: false,
391 })
392 .pipe(
393 Effect.retry({
394 while: (e) => e._tag === "InvalidVpcID.NotFound",
395 schedule: Schedule.max([Schedule.fixed(500), Schedule.recurs(10)]),
396 }),
397 );
398 const newId = createResult.RouteTable!.RouteTableId! as RouteTableId;
399 yield* session.note(`Route table created: ${newId}`);
400 routeTable = yield* describeRouteTable(newId, session);
401 }
402
403 const routeTableId = routeTable.RouteTableId! as RouteTableId;
404
405 // Sync tags — observed cloud tags vs desired.
406 const currentTags = Object.fromEntries(
407 (routeTable.Tags ?? []).map((t) => [t.Key!, t.Value!]),
408 ) as Record<string, string>;
409 const { removed, upsert } = diffTags(currentTags, desiredTags);
410 if (removed.length > 0) {
411 yield* ec2.deleteTags({
412 Resources: [routeTableId],
413 Tags: removed.map((key) => ({ Key: key })),
414 });
415 }
416 if (upsert.length > 0) {
417 yield* ec2.createTags({
418 Resources: [routeTableId],
419 Tags: upsert,
420 });
421 }
422
423 // Re-read final state.
424 const final = yield* describeRouteTable(routeTableId, session);
425 return {
426 routeTableId,
427 routeTableArn:
428 `arn:aws:ec2:${region}:${accountId}:route-table/${routeTableId}` as `arn:aws:ec2:${RegionID}:${AccountID}:route-table/${string}`,
429 vpcId: news.vpcId as VpcId,
430 ownerId: final.OwnerId,
431 associations: final.Associations?.map((assoc) => ({
432 main: assoc.Main ?? false,
433 routeTableAssociationId: assoc.RouteTableAssociationId,
434 routeTableId: assoc.RouteTableId,
435 subnetId: assoc.SubnetId,
436 gatewayId: assoc.GatewayId,
437 associationState: assoc.AssociationState
438 ? {
439 state: assoc.AssociationState.State!,
440 statusMessage: assoc.AssociationState.StatusMessage,
441 }
442 : undefined,
443 })),
444 routes: final.Routes?.map((route) => ({
445 destinationCidrBlock: route.DestinationCidrBlock,
446 destinationIpv6CidrBlock: route.DestinationIpv6CidrBlock,
447 destinationPrefixListId: route.DestinationPrefixListId,
448 egressOnlyInternetGatewayId: route.EgressOnlyInternetGatewayId,
449 gatewayId: route.GatewayId,
450 instanceId: route.InstanceId,
451 instanceOwnerId: route.InstanceOwnerId,
452 natGatewayId: route.NatGatewayId,
453 transitGatewayId: route.TransitGatewayId,
454 localGatewayId: route.LocalGatewayId,
455 carrierGatewayId: route.CarrierGatewayId,
456 networkInterfaceId: route.NetworkInterfaceId,
457 origin: route.Origin!,
458 state: route.State!,
459 vpcPeeringConnectionId: route.VpcPeeringConnectionId,
460 coreNetworkArn: route.CoreNetworkArn,
461 })),
462 propagatingVgws: final.PropagatingVgws?.map((vgw) => ({
463 gatewayId: vgw.GatewayId!,
464 })),
465 tags: tagListRecord(final.Tags),
466 };
467 }),
468
469 delete: Effect.fn(function* ({ output, session }) {
470 const routeTableId = output.routeTableId;
471
472 yield* session.note(`Deleting route table: ${routeTableId}`);
473
474 // 1. Attempt to delete route table
475 yield* ec2
476 .deleteRouteTable({
477 RouteTableId: routeTableId,
478 DryRun: false,
479 })
480 .pipe(
481 Effect.tapError(Effect.logDebug),
482 Effect.catchTag("InvalidRouteTableID.NotFound", () => Effect.void),
483 // Retry on dependency violations (associations still being deleted)
484 Effect.retry({
485 // DependencyViolation means there are still dependent resources
486 while: (e) => e._tag === "DependencyViolation",
487 schedule: Schedule.max([Schedule.fixed(3000), Schedule.recurs(10)]).pipe(
488 Schedule.tap(({ attempt }) =>
489 session.note(`Waiting for dependencies to clear... (attempt ${attempt})`),
490 ),
491 ),
492 }),
493 );
494
495 // 2. Wait for route table to be fully deleted
496 yield* waitForRouteTableDeleted(routeTableId, session);
497
498 yield* session.note(`Route table ${routeTableId} deleted successfully`);
499 }),
500 };
501 }),
502 );
503
504 /**
505 * Describe a route table by ID
506 */
507 const describeRouteTable = (routeTableId: string, _session?: ScopedPlanStatusSession) =>
508 Effect.gen(function* () {
509 const result = yield* ec2
510 .describeRouteTables({ RouteTableIds: [routeTableId] })
511 .pipe(
512 Effect.catchTag("InvalidRouteTableID.NotFound", () => Effect.succeed({ RouteTables: [] })),
513 );
514
515 const routeTable = result.RouteTables?.[0];
516 if (!routeTable) {
517 // createRouteTable can return before the new ID is visible to
518 // describeRouteTables. Keep the ID in this reconcile and retry the
519 // observation instead of failing after create and losing the only
520 // handle the engine has for cleanup.
521 return yield* new RouteTableNotVisible({ routeTableId });
522 }
523 return routeTable;
524 }).pipe(
525 Effect.retry({
526 while: (error) => error instanceof RouteTableNotVisible,
527 schedule: Schedule.max([Schedule.fixed(500), Schedule.recurs(10)]),
528 }),
529 );
530
531 class RouteTableNotVisible extends Data.TaggedError("RouteTableNotVisible")<{
532 routeTableId: string;
533 }> {}
534
535 /**
536 * Wait for route table to be deleted
537 */
538 const waitForRouteTableDeleted = (routeTableId: string, session: ScopedPlanStatusSession) =>
539 Effect.retry(
540 Effect.gen(function* () {
541 const result = yield* ec2.describeRouteTables({ RouteTableIds: [routeTableId] }).pipe(
542 Effect.tapError(Effect.logDebug),
543 Effect.catchTag("InvalidRouteTableID.NotFound", () => Effect.succeed({ RouteTables: [] })),
544 );
545
546 if (!result.RouteTables || result.RouteTables.length === 0) {
547 return; // Successfully deleted
548 }
549
550 // Still exists, fail to trigger retry
551 return yield* new RouteTableNotReady({ message: "Route table still exists" });
552 }),
553 {
554 schedule: Schedule.max([Schedule.fixed(2000), Schedule.recurs(10)]).pipe(
555 Schedule.tap(({ attempt }) =>
556 session.note(`Waiting for route table deletion... (${attempt * 2}s)`),
557 ),
558 ),
559 },
560 );