@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 456 lines 17 KB
Raw
1 import type * as EC2 from "@distilled.cloud/aws/ec2";
2 import * as ec2 from "@distilled.cloud/aws/ec2";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import type { ScopedPlanStatusSession } from "alchemy/Report";
6 import { Resource } from "alchemy/Resource";
7 import * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import * as Schedule from "effect/Schedule";
10 import * as Stream from "effect/Stream";
11 import type { Providers } from "../Providers.ts";
12 import type { RouteTableId } from "./RouteTable.ts";
13 import type { SubnetId } from "./Subnet.ts";
14
15 export class RouteTableAssociationUnexpectedResponse extends Data.TaggedError(
16 "RouteTableAssociationUnexpectedResponse",
17 )<{
18 readonly message: string;
19 readonly cause?: unknown;
20 }> {}
21
22 export class RouteTableAssociationOperationFailed extends Data.TaggedError(
23 "RouteTableAssociationOperationFailed",
24 )<{
25 readonly message: string;
26 readonly cause?: unknown;
27 }> {}
28
29 export class RouteTableAssociationNotReady extends Data.TaggedError(
30 "RouteTableAssociationNotReady",
31 )<{
32 readonly message: string;
33 readonly cause?: unknown;
34 }> {}
35
36 export type RouteTableAssociationId<ID extends string = string> = `rtbassoc-${ID}`;
37 export const RouteTableAssociationId = <ID extends string>(
38 id: ID,
39 ): ID & RouteTableAssociationId<ID> => `rtbassoc-${id}` as ID & RouteTableAssociationId<ID>;
40
41 export interface RouteTableAssociationProps {
42 /**
43 * The ID of the route table.
44 * Required.
45 */
46 routeTableId: RouteTableId;
47
48 /**
49 * The ID of the subnet to associate with the route table.
50 * Either subnetId or gatewayId is required, but not both.
51 */
52 subnetId?: SubnetId;
53
54 /**
55 * The ID of the gateway (internet gateway or virtual private gateway) to associate with the route table.
56 * Either subnetId or gatewayId is required, but not both.
57 */
58 gatewayId?: string;
59 }
60
61 export interface RouteTableAssociation extends Resource<
62 "AWS.EC2.RouteTableAssociation",
63 RouteTableAssociationProps,
64 {
65 /**
66 * The ID of the association.
67 */
68 associationId: RouteTableAssociationId;
69
70 /**
71 * The ID of the route table.
72 */
73 routeTableId: RouteTableId;
74
75 /**
76 * The ID of the subnet (if the association is with a subnet).
77 */
78 subnetId?: SubnetId | undefined;
79
80 /**
81 * The ID of the gateway (if the association is with a gateway).
82 */
83 gatewayId?: string | undefined;
84
85 /**
86 * The state of the association.
87 */
88 associationState: {
89 state: EC2.RouteTableAssociationStateCode;
90 statusMessage?: string;
91 };
92 },
93 never,
94 Providers
95 > {}
96 /**
97 * Associates a {@link RouteTable} with a subnet (or a gateway), making that
98 * route table govern traffic for the associated resource. A subnet can be
99 * associated with exactly one route table at a time; multiple subnets may share
100 * the same route table.
101 *
102 * Provide exactly one of `subnetId` or `gatewayId`. Changing the subnet or
103 * gateway replaces the association, whereas pointing an existing association at
104 * a different route table is applied in place via
105 * `ReplaceRouteTableAssociation`.
106 *
107 * ### Associating Subnets
108 * Associating a subnet overrides the VPC's main route table for that subnet.
109 * This is how you make a subnet "public" (associate it with a table that has an
110 * internet-gateway route) or "private" (associate it with a NAT-gateway table).
111 *
112 * **Example:** Associate a Subnet with a Route Table
113 * ```typescript
114 * const association = yield* AWS.EC2.RouteTableAssociation("PublicSubnetAssociation", {
115 * routeTableId: publicRouteTable.routeTableId,
116 * subnetId: publicSubnet.subnetId,
117 * });
118 * ```
119 * Binds a single subnet to the route table so its instances follow that
120 * table's routes. The returned `associationId` (prefixed `rtbassoc-`) can be
121 * used to track or replace the association.
122 *
123 * **Example:** Share One Route Table Across Multiple Subnets
124 * ```typescript
125 * const subnet1Association = yield* AWS.EC2.RouteTableAssociation("PublicSubnet1Association", {
126 * routeTableId: publicRouteTable.routeTableId,
127 * subnetId: publicSubnet1.subnetId,
128 * });
129 *
130 * const subnet2Association = yield* AWS.EC2.RouteTableAssociation("PublicSubnet2Association", {
131 * routeTableId: publicRouteTable.routeTableId,
132 * subnetId: publicSubnet2.subnetId,
133 * });
134 * ```
135 * Declaring multiple associations against the same `routeTableId` gives every
136 * listed subnet identical routing — a concise way to apply one public (or
137 * private) routing policy across all subnets in a tier.
138 *
139 * ### Associating Gateways (Edge Routing)
140 * Instead of a subnet, an association can target an internet gateway or
141 * virtual private gateway via `gatewayId`. This "gateway route table
142 * association" enables edge routing, where inbound traffic is inspected or
143 * redirected (e.g. to a firewall appliance) as it enters the VPC.
144 *
145 * **Example:** Associate a Route Table with an Internet Gateway
146 * ```typescript
147 * const edgeAssociation = yield* AWS.EC2.RouteTableAssociation("EdgeAssociation", {
148 * routeTableId: ingressRouteTable.routeTableId,
149 * gatewayId: internetGateway.internetGatewayId,
150 * });
151 * ```
152 * Attaches the route table at the gateway rather than at a subnet, so traffic
153 * arriving from the internet is steered by this table — typically toward an
154 * inspection appliance before reaching its destination subnet.
155 *
156 * @resource
157 */
158 export const RouteTableAssociation = Resource<RouteTableAssociation>(
159 "AWS.EC2.RouteTableAssociation",
160 );
161
162 export const RouteTableAssociationProvider = () =>
163 Provider.effect(
164 RouteTableAssociation,
165 Effect.gen(function* () {
166 return {
167 stables: ["associationId", "subnetId", "gatewayId"],
168
169 // Associations are embedded in describeRouteTables — each RouteTable
170 // carries an Associations[] of {subnet/gateway, routeTable,
171 // associationId}. Flatten every page's associations across the region.
172 // The implicit "main" association (the VPC default route-table binding)
173 // is skipped: it isn't a standalone resource we create or manage.
174 list: () =>
175 ec2.describeRouteTables.pages({}).pipe(
176 Stream.runCollect,
177 Effect.map((chunk) =>
178 Array.from(chunk).flatMap((page) =>
179 (page.RouteTables ?? []).flatMap((rt) =>
180 (rt.Associations ?? [])
181 .filter(
182 (
183 a,
184 ): a is EC2.RouteTableAssociation & {
185 RouteTableAssociationId: string;
186 RouteTableId: string;
187 } =>
188 a.Main !== true &&
189 a.RouteTableAssociationId != null &&
190 a.RouteTableId != null,
191 )
192 .map((a) => ({
193 associationId: a.RouteTableAssociationId as RouteTableAssociationId,
194 routeTableId: a.RouteTableId as RouteTableId,
195 subnetId: a.SubnetId as SubnetId | undefined,
196 gatewayId: a.GatewayId,
197 associationState: {
198 state: a.AssociationState?.State ?? "associated",
199 statusMessage: a.AssociationState?.StatusMessage,
200 },
201 })),
202 ),
203 ),
204 ),
205 ),
206
207 diff: Effect.fn(function* ({ news, olds }) {
208 if (!isResolved(news)) return;
209 // Subnet/Gateway change requires replacement (use ReplaceRouteTableAssociation internally)
210 if (olds.subnetId !== news.subnetId) {
211 return { action: "replace" };
212 }
213 if (olds.gatewayId !== news.gatewayId) {
214 return { action: "replace" };
215 }
216 // Route table change can be done via ReplaceRouteTableAssociation
217 }),
218
219 // A subnet (or gateway) has at most one route table association, so
220 // look it up by the subnet/gateway rather than the association id: a
221 // route table swapped out of band gets a new association id, which
222 // drift then reports as a changed route table (and repair swaps
223 // back) instead of a missing association.
224 read: Effect.fn(function* ({ olds, output }) {
225 const subnetId = output?.subnetId ?? olds?.subnetId;
226 const gatewayId = output?.gatewayId ?? olds?.gatewayId;
227 if (subnetId === undefined && gatewayId === undefined) return undefined;
228 const lookup = yield* ec2.describeRouteTables({
229 Filters: [
230 subnetId !== undefined
231 ? { Name: "association.subnet-id", Values: [subnetId] }
232 : { Name: "association.gateway-id", Values: [gatewayId!] },
233 ],
234 });
235 const assoc = (lookup.RouteTables ?? [])
236 .flatMap((rt) => rt.Associations ?? [])
237 .find(
238 (a) =>
239 a.Main !== true &&
240 (subnetId !== undefined ? a.SubnetId === subnetId : a.GatewayId === gatewayId) &&
241 a.AssociationState?.State !== "disassociated" &&
242 a.AssociationState?.State !== "disassociating",
243 );
244 if (!assoc?.RouteTableAssociationId || !assoc.RouteTableId) return undefined;
245 return {
246 associationId: assoc.RouteTableAssociationId as RouteTableAssociationId,
247 routeTableId: assoc.RouteTableId as RouteTableId,
248 subnetId: assoc.SubnetId as SubnetId | undefined,
249 gatewayId: assoc.GatewayId,
250 associationState: {
251 state: assoc.AssociationState?.State ?? "associated",
252 statusMessage: assoc.AssociationState?.StatusMessage,
253 },
254 };
255 }),
256
257 reconcile: Effect.fn(function* ({ news, output, session }) {
258 // Observe — try the cached associationId first; if the association
259 // was disassociated out-of-band, fall through to AssociateRouteTable.
260 let observed:
261 | {
262 associationId: string;
263 routeTableId: string;
264 subnetId?: string;
265 gatewayId?: string;
266 state?: EC2.RouteTableAssociationStateCode;
267 statusMessage?: string;
268 }
269 | undefined;
270 if (output?.associationId) {
271 const lookup = yield* ec2
272 .describeRouteTables({
273 Filters: [
274 {
275 Name: "association.route-table-association-id",
276 Values: [output.associationId],
277 },
278 ],
279 })
280 .pipe(
281 Effect.catchTag("InvalidRouteTableID.NotFound", () =>
282 Effect.succeed({ RouteTables: [] }),
283 ),
284 );
285 for (const rt of lookup.RouteTables ?? []) {
286 const assoc = rt.Associations?.find(
287 (a) => a.RouteTableAssociationId === output.associationId,
288 );
289 if (assoc) {
290 observed = {
291 associationId: assoc.RouteTableAssociationId!,
292 routeTableId: assoc.RouteTableId!,
293 subnetId: assoc.SubnetId,
294 gatewayId: assoc.GatewayId,
295 state: assoc.AssociationState?.State,
296 statusMessage: assoc.AssociationState?.StatusMessage,
297 };
298 break;
299 }
300 }
301 }
302
303 // Ensure — no existing association ⇒ AssociateRouteTable.
304 if (observed === undefined) {
305 const result = yield* ec2
306 .associateRouteTable({
307 RouteTableId: news.routeTableId,
308 SubnetId: news.subnetId,
309 GatewayId: news.gatewayId,
310 DryRun: false,
311 })
312 .pipe(
313 Effect.retry({
314 while: (e) =>
315 e._tag === "InvalidRouteTableID.NotFound" ||
316 e._tag === "InvalidSubnetID.NotFound",
317 schedule: Schedule.exponential(100),
318 }),
319 );
320 const associationId = result.AssociationId! as RouteTableAssociationId;
321 yield* session.note(`Route table association created: ${associationId}`);
322 yield* waitForAssociationState(news.routeTableId, associationId, "associated", session);
323 return {
324 associationId,
325 routeTableId: news.routeTableId as RouteTableId,
326 subnetId: news.subnetId as SubnetId | undefined,
327 gatewayId: news.gatewayId as string | undefined,
328 // Waited for above; matches what `read` observes.
329 associationState: { state: "associated" as const },
330 };
331 }
332
333 // Sync — drift in routeTableId is patched in place by
334 // ReplaceRouteTableAssociation. Subnet/gateway changes are
335 // intercepted upstream by `diff` as a replacement.
336 if (observed.routeTableId !== (news.routeTableId as string)) {
337 const result = yield* ec2.replaceRouteTableAssociation({
338 AssociationId: observed.associationId,
339 RouteTableId: news.routeTableId,
340 DryRun: false,
341 });
342 const newAssociationId = result.NewAssociationId! as RouteTableAssociationId;
343 yield* session.note(`Route table association replaced: ${newAssociationId}`);
344 yield* waitForAssociationState(
345 news.routeTableId,
346 newAssociationId,
347 "associated",
348 session,
349 );
350 return {
351 associationId: newAssociationId,
352 routeTableId: news.routeTableId as RouteTableId,
353 subnetId: news.subnetId as SubnetId | undefined,
354 gatewayId: news.gatewayId as string | undefined,
355 // Waited for above; matches what `read` observes.
356 associationState: { state: "associated" as const },
357 };
358 }
359
360 // Already in the desired state — just report it.
361 return {
362 associationId: observed.associationId as RouteTableAssociationId,
363 routeTableId: observed.routeTableId as RouteTableId,
364 subnetId: observed.subnetId as SubnetId | undefined,
365 gatewayId: observed.gatewayId,
366 associationState: {
367 state: observed.state ?? "associated",
368 statusMessage: observed.statusMessage,
369 },
370 };
371 }),
372
373 delete: Effect.fn(function* ({ output, session }) {
374 yield* session.note(`Deleting route table association: ${output.associationId}`);
375
376 // Disassociate the route table
377 yield* ec2
378 .disassociateRouteTable({
379 AssociationId: output.associationId,
380 DryRun: false,
381 })
382 .pipe(
383 Effect.tapError(Effect.log),
384 Effect.catchTag("InvalidAssociationID.NotFound", () => Effect.void),
385 );
386
387 yield* session.note(
388 `Route table association ${output.associationId} deleted successfully`,
389 );
390 }),
391 };
392 }),
393 );
394
395 /**
396 * Wait for association to reach a specific state
397 */
398 const waitForAssociationState = (
399 routeTableId: string,
400 associationId: string,
401 targetState: "associating" | "associated" | "disassociating" | "disassociated",
402 session?: ScopedPlanStatusSession,
403 ) =>
404 Effect.retry(
405 Effect.gen(function* () {
406 const result = yield* ec2.describeRouteTables({ RouteTableIds: [routeTableId] }).pipe(
407 Effect.catchTag("InvalidRouteTableID.NotFound", () =>
408 Effect.succeed({
409 RouteTables: [],
410 } as ec2.DescribeRouteTablesResult),
411 ),
412 );
413
414 const routeTable = result.RouteTables?.[0];
415 if (!routeTable) {
416 return yield* new RouteTableAssociationUnexpectedResponse({
417 message: "Route table not found",
418 });
419 }
420
421 const association = routeTable.Associations?.find(
422 (a) => a.RouteTableAssociationId === associationId,
423 );
424
425 if (!association) {
426 // Association might not exist yet, retry
427 return yield* new RouteTableAssociationUnexpectedResponse({
428 message: "Association not found",
429 });
430 }
431
432 if (association.AssociationState?.State === targetState) {
433 return;
434 }
435
436 if (association.AssociationState?.State === "failed") {
437 return yield* new RouteTableAssociationOperationFailed({
438 message: `Association failed: ${association.AssociationState.StatusMessage}`,
439 });
440 }
441
442 // Still in progress, fail to trigger retry
443 return yield* new RouteTableAssociationNotReady({
444 message: `Association state: ${association.AssociationState?.State}`,
445 });
446 }),
447 {
448 schedule: Schedule.max([Schedule.fixed(1000), Schedule.recurs(30)]).pipe(
449 Schedule.tap(({ attempt }) =>
450 session
451 ? session.note(`Waiting for association to be ${targetState}... (${attempt}s)`)
452 : Effect.void,
453 ),
454 ),
455 },
456 );