@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, 06:00 UTC

main
ts 384 lines 14.6 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 { Resource } from "alchemy/Resource";
5 import { createInternalTags, createTagsList, diffTags } from "alchemy/Tags";
6 import * as Data from "effect/Data";
7 import * as Effect from "effect/Effect";
8 import * as Schedule from "effect/Schedule";
9 import * as Stream from "effect/Stream";
10 import type { AccountID } from "../Environment.ts";
11 import { AWSEnvironment } from "../Environment.ts";
12 import type { Providers } from "../Providers.ts";
13 import type { RegionID } from "../Region.ts";
14 import type { VpcId } from "./Vpc.ts";
15
16 export class EgressOnlyInternetGatewayUnexpectedResponse extends Data.TaggedError(
17 "EgressOnlyInternetGatewayUnexpectedResponse",
18 )<{
19 readonly message: string;
20 readonly cause?: unknown;
21 }> {}
22
23 export type EgressOnlyInternetGatewayId<ID extends string = string> = `eigw-${ID}`;
24 export const EgressOnlyInternetGatewayId = <ID extends string>(
25 id: ID,
26 ): ID & EgressOnlyInternetGatewayId<ID> => `eigw-${id}` as ID & EgressOnlyInternetGatewayId<ID>;
27
28 export type EgressOnlyInternetGatewayArn<
29 ID extends EgressOnlyInternetGatewayId = EgressOnlyInternetGatewayId,
30 > = `arn:aws:ec2:${RegionID}:${AccountID}:egress-only-internet-gateway/${ID}`;
31
32 export interface EgressOnlyInternetGatewayProps {
33 /**
34 * The VPC for which to create the egress-only internet gateway.
35 */
36 vpcId: VpcId;
37
38 /**
39 * Tags to assign to the egress-only internet gateway.
40 */
41 tags?: Record<string, string>;
42 }
43
44 export interface EgressOnlyInternetGateway extends Resource<
45 "AWS.EC2.EgressOnlyInternetGateway",
46 EgressOnlyInternetGatewayProps,
47 {
48 /**
49 * The ID of the egress-only internet gateway.
50 */
51 egressOnlyInternetGatewayId: EgressOnlyInternetGatewayId;
52
53 /**
54 * The Amazon Resource Name (ARN) of the egress-only internet gateway.
55 */
56 egressOnlyInternetGatewayArn: EgressOnlyInternetGatewayArn;
57
58 /**
59 * Information about the attachment of the egress-only internet gateway.
60 */
61 attachments?: Array<{
62 /**
63 * The current state of the attachment.
64 */
65 state: "attaching" | "attached" | "detaching" | "detached";
66 /**
67 * The ID of the VPC.
68 */
69 vpcId: VpcId;
70 }>;
71 },
72 never,
73 Providers
74 > {}
75 /**
76 * An egress-only internet gateway is the IPv6 counterpart to a NAT gateway: it
77 * lets instances in a VPC initiate outbound IPv6 traffic to the internet while
78 * preventing the internet from initiating inbound connections to them. Use it
79 * to give private, IPv6-addressed resources outbound-only internet access.
80 *
81 * Unlike a NAT gateway it is free, has no bandwidth charges, and does not
82 * require an Elastic IP — but it works for IPv6 only. It always belongs to a
83 * VPC (`vpcId` is required); the gateway must be paired with an IPv6
84 * {@link Route} to actually carry traffic.
85 *
86 * ### Creating an Egress-Only Internet Gateway
87 * The gateway is created and attached to `vpcId` in a single step. Because the
88 * attachment is intrinsic, changing `vpcId` replaces the gateway rather than
89 * moving it.
90 *
91 * **Example:** Basic Egress-Only Internet Gateway
92 * ```typescript
93 * const egressOnlyIgw = yield* AWS.EC2.EgressOnlyInternetGateway("EgressOnlyIgw", {
94 * vpcId: myVpc.vpcId,
95 * });
96 * ```
97 * Creates the gateway in the VPC. The resulting
98 * `egressOnlyInternetGatewayId` (prefixed `eigw-`) is referenced from a
99 * route's `egressOnlyInternetGatewayId` target.
100 *
101 * **Example:** Egress-Only Internet Gateway with Tags
102 * ```typescript
103 * const egressOnlyIgw = yield* AWS.EC2.EgressOnlyInternetGateway("EgressOnlyIgw", {
104 * vpcId: myVpc.vpcId,
105 * tags: { Name: "production-eigw" },
106 * });
107 * ```
108 * The `tags` map is merged with the alchemy auto-tags and can be updated in
109 * place without replacing the gateway.
110 *
111 * ### Routing IPv6 Egress Traffic
112 * A gateway alone does nothing until a private route table sends IPv6 traffic
113 * to it. Pair it with a `::/0` {@link Route} so private, IPv6-addressed
114 * instances can reach the internet outbound-only.
115 *
116 * **Example:** IPv6 Default Route to the Egress-Only Gateway
117 * ```typescript
118 * const egressOnlyIgw = yield* AWS.EC2.EgressOnlyInternetGateway("EgressOnlyIgw", {
119 * vpcId: myVpc.vpcId,
120 * });
121 *
122 * const ipv6EgressRoute = yield* AWS.EC2.Route("Ipv6EgressRoute", {
123 * routeTableId: privateRouteTable.routeTableId,
124 * destinationIpv6CidrBlock: "::/0",
125 * egressOnlyInternetGatewayId: egressOnlyIgw.egressOnlyInternetGatewayId,
126 * });
127 * ```
128 * Instances in subnets associated with `privateRouteTable` can now make
129 * outbound IPv6 connections (updates, API calls) while remaining unreachable
130 * from the public internet.
131 *
132 * @resource
133 */
134 export const EgressOnlyInternetGateway = Resource<EgressOnlyInternetGateway>(
135 "AWS.EC2.EgressOnlyInternetGateway",
136 );
137
138 /** `DeleteEgressOnlyInternetGateway` returned `ReturnCode: false` (no error). */
139 class EigwDeleteFailed extends Data.TaggedError("EigwDeleteFailed")<{
140 readonly eigwId: string;
141 }> {}
142
143 /** The gateway is still observable after a successful delete call. */
144 class EigwStillExists extends Data.TaggedError("EigwStillExists")<{
145 readonly eigwId: string;
146 }> {}
147
148 export const EgressOnlyInternetGatewayProvider = () =>
149 Provider.effect(
150 EgressOnlyInternetGateway,
151 Effect.gen(function* () {
152 const createTags = Effect.fn(function* (id: string, tags?: Record<string, string>) {
153 return {
154 Name: id,
155 ...(yield* createInternalTags(id)),
156 ...tags,
157 };
158 });
159
160 const describeEgressOnlyInternetGateway = (eigwId: string) =>
161 ec2
162 .describeEgressOnlyInternetGateways({
163 EgressOnlyInternetGatewayIds: [eigwId],
164 })
165 .pipe(
166 Effect.map((r) => r.EgressOnlyInternetGateways?.[0]),
167 Effect.flatMap((gw) =>
168 gw
169 ? Effect.succeed(gw)
170 : Effect.fail(
171 new EgressOnlyInternetGatewayUnexpectedResponse({
172 message: `Egress-Only Internet Gateway ${eigwId} not found`,
173 }),
174 ),
175 ),
176 );
177
178 const toAttrs = (gw: ec2.EgressOnlyInternetGateway) =>
179 AWSEnvironment.current.pipe(
180 Effect.map((env) => ({
181 egressOnlyInternetGatewayId:
182 gw.EgressOnlyInternetGatewayId as EgressOnlyInternetGatewayId,
183 egressOnlyInternetGatewayArn:
184 `arn:aws:ec2:${env.region}:${env.accountId}:egress-only-internet-gateway/${gw.EgressOnlyInternetGatewayId}` as EgressOnlyInternetGatewayArn,
185 attachments: gw.Attachments?.map((a) => ({
186 state: a.State as "attaching" | "attached" | "detaching" | "detached",
187 vpcId: a.VpcId as VpcId,
188 })),
189 })),
190 );
191
192 return {
193 stables: ["egressOnlyInternetGatewayId", "egressOnlyInternetGatewayArn"],
194
195 list: () =>
196 Effect.gen(function* () {
197 const env = yield* AWSEnvironment.current;
198 const items = yield* ec2.describeEgressOnlyInternetGateways.pages({}).pipe(
199 Stream.runCollect,
200 Effect.map((chunk) =>
201 Array.from(chunk).flatMap((page) =>
202 (page.EgressOnlyInternetGateways ?? [])
203 .filter(
204 (
205 gw,
206 ): gw is ec2.EgressOnlyInternetGateway & {
207 EgressOnlyInternetGatewayId: string;
208 } => gw.EgressOnlyInternetGatewayId != null,
209 )
210 .map((gw) => ({
211 egressOnlyInternetGatewayId:
212 gw.EgressOnlyInternetGatewayId as EgressOnlyInternetGatewayId,
213 egressOnlyInternetGatewayArn:
214 `arn:aws:ec2:${env.region}:${env.accountId}:egress-only-internet-gateway/${gw.EgressOnlyInternetGatewayId}` as EgressOnlyInternetGatewayArn,
215 attachments: gw.Attachments?.map((a) => ({
216 state: a.State as "attaching" | "attached" | "detaching" | "detached",
217 vpcId: a.VpcId as VpcId,
218 })),
219 })),
220 ),
221 ),
222 );
223 return items satisfies EgressOnlyInternetGateway["Attributes"][];
224 }),
225
226 read: Effect.fn(function* ({ output }) {
227 if (!output) return undefined;
228 const gw = yield* describeEgressOnlyInternetGateway(output.egressOnlyInternetGatewayId);
229 return yield* toAttrs(gw);
230 }),
231
232 diff: Effect.fn(function* ({ news, olds }) {
233 if (!isResolved(news)) return;
234 // VPC change requires replacement
235 if (news.vpcId !== olds.vpcId) {
236 return { action: "replace" };
237 }
238 // Tags can be updated in-place
239 }),
240
241 reconcile: Effect.fn(function* ({ id, news, output, session }) {
242 const desiredTags = yield* createTags(id, news.tags);
243
244 // Observe — find the EIGW via cached id, else fall through to create.
245 let gw: ec2.EgressOnlyInternetGateway | undefined;
246 if (output?.egressOnlyInternetGatewayId) {
247 const lookup = yield* ec2
248 .describeEgressOnlyInternetGateways({
249 EgressOnlyInternetGatewayIds: [output.egressOnlyInternetGatewayId],
250 })
251 .pipe(
252 Effect.catchTag("InvalidEgressOnlyInternetGatewayId.NotFound", () =>
253 Effect.succeed({ EgressOnlyInternetGateways: [] }),
254 ),
255 );
256 gw = lookup.EgressOnlyInternetGateways?.[0];
257 }
258
259 // Ensure — create the EIGW if it isn't there yet.
260 if (gw === undefined) {
261 yield* session.note("Creating Egress-Only Internet Gateway...");
262 const result = yield* ec2.createEgressOnlyInternetGateway({
263 VpcId: news.vpcId as string,
264 TagSpecifications: [
265 {
266 ResourceType: "egress-only-internet-gateway",
267 Tags: createTagsList(desiredTags),
268 },
269 ],
270 DryRun: false,
271 });
272 const newGwId = result.EgressOnlyInternetGateway!.EgressOnlyInternetGatewayId!;
273 yield* session.note(`Egress-Only Internet Gateway created: ${newGwId}`);
274 gw = yield* describeEgressOnlyInternetGateway(newGwId);
275 }
276
277 const eigwId = gw.EgressOnlyInternetGatewayId!;
278
279 // Sync tags — observed cloud tags vs desired.
280 const currentTags =
281 (yield* ec2
282 .describeTags({
283 Filters: [
284 { Name: "resource-id", Values: [eigwId] },
285 {
286 Name: "resource-type",
287 Values: ["egress-only-internet-gateway"],
288 },
289 ],
290 })
291 .pipe(
292 Effect.map(
293 (r) =>
294 Object.fromEntries(r.Tags?.map((t) => [t.Key!, t.Value!]) ?? []) as Record<
295 string,
296 string
297 >,
298 ),
299 )) ?? {};
300 const { removed, upsert } = diffTags(currentTags, desiredTags);
301 if (removed.length > 0) {
302 yield* ec2.deleteTags({
303 Resources: [eigwId],
304 Tags: removed.map((key) => ({ Key: key })),
305 DryRun: false,
306 });
307 }
308 if (upsert.length > 0) {
309 yield* ec2.createTags({
310 Resources: [eigwId],
311 Tags: upsert,
312 DryRun: false,
313 });
314 }
315
316 // Re-read to reflect current cloud state in the returned attributes.
317 const final = yield* describeEgressOnlyInternetGateway(eigwId);
318 return yield* toAttrs(final);
319 }),
320
321 delete: Effect.fn(function* ({ output, session }) {
322 const eigwId = output.egressOnlyInternetGatewayId;
323
324 yield* session.note(`Deleting Egress-Only Internet Gateway: ${eigwId}`);
325
326 yield* ec2
327 .deleteEgressOnlyInternetGateway({
328 EgressOnlyInternetGatewayId: eigwId,
329 DryRun: false,
330 })
331 .pipe(
332 Effect.tapError(Effect.logDebug),
333 // `DeleteEgressOnlyInternetGateway` reports failure as
334 // `ReturnCode: false` with NO error. Treating that as success
335 // orphans the gateway: the engine drops the state row while the
336 // gateway stays attached, wedging the parent VPC's delete on
337 // DependencyViolation forever. Surface it so the retry below
338 // re-drives the call (and the delete fails loudly if it never
339 // takes).
340 Effect.flatMap((result) =>
341 result.ReturnCode === false
342 ? Effect.fail(new EigwDeleteFailed({ eigwId }))
343 : Effect.void,
344 ),
345 Effect.catchTags({
346 "InvalidGatewayID.NotFound": () => Effect.void,
347 "InvalidEgressOnlyInternetGatewayId.NotFound": () => Effect.void,
348 }),
349 // Retry on dependency violations (e.g., routes still using the EIGW)
350 Effect.retry({
351 while: (e) => e._tag === "DependencyViolation" || e._tag === "EigwDeleteFailed",
352 schedule: Schedule.max([Schedule.fixed(5000), Schedule.recurs(30)]).pipe(
353 Schedule.tap(({ attempt }) =>
354 session.note(`Waiting for dependencies to clear... (attempt ${attempt})`),
355 ),
356 ),
357 }),
358 );
359
360 // Deletion is asynchronous: wait until the gateway is actually gone
361 // before reporting success, so the parent VPC's delete (which the
362 // engine runs next) never races a still-attached gateway.
363 yield* ec2
364 .describeEgressOnlyInternetGateways({
365 EgressOnlyInternetGatewayIds: [eigwId],
366 })
367 .pipe(
368 Effect.flatMap((r) =>
369 (r.EgressOnlyInternetGateways ?? []).length === 0
370 ? Effect.void
371 : Effect.fail(new EigwStillExists({ eigwId })),
372 ),
373 Effect.retry({
374 while: (e) => e._tag === "EigwStillExists",
375 schedule: Schedule.max([Schedule.fixed(2000), Schedule.recurs(15)]),
376 }),
377 Effect.catchTag("InvalidEgressOnlyInternetGatewayId.NotFound", () => Effect.void),
378 );
379
380 yield* session.note(`Egress-Only Internet Gateway ${eigwId} deleted`);
381 }),
382 };
383 }),
384 );