@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 374 lines 13.5 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 Effect from "effect/Effect";
7 import * as Schedule from "effect/Schedule";
8 import * as Stream from "effect/Stream";
9 import { AWSEnvironment } from "../Environment.ts";
10 import type { Providers } from "../Providers.ts";
11 import type { VpcId } from "./Vpc.ts";
12
13 export type VpcPeeringConnectionId<ID extends string = string> = `pcx-${ID}`;
14 export const VpcPeeringConnectionId = <ID extends string>(
15 id: ID,
16 ): ID & VpcPeeringConnectionId<ID> => `pcx-${id}` as ID & VpcPeeringConnectionId<ID>;
17
18 export type VpcPeeringConnectionStatus =
19 | "initiating-request"
20 | "pending-acceptance"
21 | "active"
22 | "deleted"
23 | "rejected"
24 | "failed"
25 | "expired"
26 | "provisioning"
27 | "deleting";
28
29 // Terminal states from which a peering connection cannot recover — observing
30 // one of these means the cached connection is dead and must be recreated.
31 const DEAD_STATES = new Set<string>(["deleted", "deleting", "rejected", "failed", "expired"]);
32
33 export interface VpcPeeringConnectionProps {
34 /**
35 * The ID of the requester VPC (the VPC you own that initiates the peering).
36 * Immutable — changing it replaces the connection.
37 */
38 vpcId: VpcId;
39
40 /**
41 * The ID of the accepter VPC with which to create the connection. May belong
42 * to another account (`peerOwnerId`) or Region (`peerRegion`). Immutable.
43 */
44 peerVpcId: VpcId;
45
46 /**
47 * The Region of the accepter VPC for an inter-Region peering. Defaults to the
48 * requester's Region (same-Region peering). Immutable.
49 */
50 peerRegion?: string;
51
52 /**
53 * The AWS account ID of the accepter VPC owner. Defaults to the requester's
54 * account (same-account peering). Immutable.
55 */
56 peerOwnerId?: string;
57
58 /**
59 * Whether to automatically accept the peering request. Only possible for
60 * same-account, same-Region peering (the accepter side must be reachable
61 * with the same credentials). Defaults to `true` when the peer is in the same
62 * account and Region, `false` otherwise (a cross-account/Region request stays
63 * in `pending-acceptance` until the peer accepts it out of band).
64 */
65 autoAccept?: boolean;
66
67 /**
68 * Tags to assign to the peering connection.
69 */
70 tags?: Record<string, string>;
71 }
72
73 export interface VpcPeeringConnection extends Resource<
74 "AWS.EC2.VpcPeeringConnection",
75 VpcPeeringConnectionProps,
76 {
77 /**
78 * The ID of the VPC peering connection (prefixed `pcx-`).
79 */
80 vpcPeeringConnectionId: VpcPeeringConnectionId;
81
82 /**
83 * The current status code of the peering connection.
84 */
85 status: VpcPeeringConnectionStatus;
86
87 /**
88 * The ID of the requester VPC.
89 */
90 requesterVpcId: VpcId;
91
92 /**
93 * The ID of the accepter VPC.
94 */
95 accepterVpcId: VpcId;
96
97 /**
98 * The AWS account ID of the accepter VPC owner.
99 */
100 accepterOwnerId: string;
101 },
102 never,
103 Providers
104 > {}
105
106 /**
107 * A VPC peering connection links two VPCs so resources in each can communicate
108 * using private IP addresses, as if they were on the same network. The two VPCs
109 * can be in the same account or different accounts, and the same Region or
110 * different Regions. Their CIDR blocks must not overlap.
111 *
112 * A peering connection is a two-sided handshake: a *requester* VPC creates the
113 * request and an *accepter* VPC accepts it. For same-account, same-Region
114 * peering alchemy accepts the request for you automatically (`autoAccept`
115 * defaults to `true`); for cross-account or cross-Region peering the connection
116 * is left in `pending-acceptance` for the peer to accept out of band. Once
117 * `active`, add {@link Route}s on both sides pointing the peer CIDR at the
118 * connection to actually carry traffic.
119 *
120 * ### Creating a Peering Connection
121 * **Example:** Same-Account Peering (auto-accepted)
122 * ```typescript
123 * const vpcA = yield* AWS.EC2.Vpc("VpcA", { cidrBlock: "10.0.0.0/16" });
124 * const vpcB = yield* AWS.EC2.Vpc("VpcB", { cidrBlock: "10.1.0.0/16" });
125 *
126 * const peering = yield* AWS.EC2.VpcPeeringConnection("Peering", {
127 * vpcId: vpcA.vpcId,
128 * peerVpcId: vpcB.vpcId,
129 * });
130 * ```
131 * Because both VPCs are in the same account and Region, the request is accepted
132 * automatically and the connection reaches the `active` state.
133 *
134 * **Example:** Cross-Account Peering (accepted out of band)
135 * ```typescript
136 * const peering = yield* AWS.EC2.VpcPeeringConnection("Peering", {
137 * vpcId: myVpc.vpcId,
138 * peerVpcId: "vpc-0abc123",
139 * peerOwnerId: "123456789012",
140 * });
141 * ```
142 * With a different `peerOwnerId` the connection stays in `pending-acceptance`
143 * until the peer account accepts it.
144 *
145 * ### Routing Traffic Across the Peering
146 * **Example:** Route the Peer CIDR at the Connection
147 * ```typescript
148 * const peering = yield* AWS.EC2.VpcPeeringConnection("Peering", {
149 * vpcId: vpcA.vpcId,
150 * peerVpcId: vpcB.vpcId,
151 * });
152 *
153 * const routeAtoB = yield* AWS.EC2.Route("RouteAtoB", {
154 * routeTableId: vpcARouteTable.routeTableId,
155 * destinationCidrBlock: "10.1.0.0/16",
156 * vpcPeeringConnectionId: peering.vpcPeeringConnectionId,
157 * });
158 * ```
159 * Each side needs a route pointing the other VPC's CIDR at the peering
160 * connection; only then can instances reach each other over private IPs.
161 *
162 * @resource
163 */
164 export const VpcPeeringConnection = Resource<VpcPeeringConnection>("AWS.EC2.VpcPeeringConnection");
165
166 class PeeringNotSettled {
167 readonly _tag = "PeeringNotSettled";
168 }
169
170 export const VpcPeeringConnectionProvider = () =>
171 Provider.effect(
172 VpcPeeringConnection,
173 Effect.gen(function* () {
174 const createTags = Effect.fn(function* (id: string, tags?: Record<string, string>) {
175 return {
176 Name: id,
177 ...(yield* createInternalTags(id)),
178 ...tags,
179 };
180 });
181
182 const describePeering = (pcxId: string) =>
183 ec2.describeVpcPeeringConnections({ VpcPeeringConnectionIds: [pcxId] }).pipe(
184 Effect.map((r) => r.VpcPeeringConnections?.[0]),
185 Effect.catchTags({
186 "InvalidVpcPeeringConnectionID.NotFound": () => Effect.undefined,
187 "InvalidVpcPeeringConnectionId.NotFound": () => Effect.undefined,
188 }),
189 );
190
191 // Poll until the connection reaches a settled state (out of the transient
192 // "initiating-request"/"provisioning" states) or becomes `target`.
193 const waitFor = (pcxId: string, target: VpcPeeringConnectionStatus) =>
194 describePeering(pcxId).pipe(
195 Effect.flatMap((pcx) => {
196 const code = pcx?.Status?.Code;
197 if (code === target || (code && DEAD_STATES.has(code))) {
198 return Effect.succeed(pcx);
199 }
200 return Effect.fail(new PeeringNotSettled());
201 }),
202 Effect.retry({
203 while: (e) => e instanceof PeeringNotSettled,
204 schedule: Schedule.max([Schedule.fixed(2000), Schedule.recurs(30)]),
205 }),
206 );
207
208 const toAttrs = (pcx: ec2.VpcPeeringConnection) => ({
209 vpcPeeringConnectionId: pcx.VpcPeeringConnectionId as VpcPeeringConnectionId,
210 status: (pcx.Status?.Code ?? "initiating-request") as VpcPeeringConnectionStatus,
211 requesterVpcId: pcx.RequesterVpcInfo?.VpcId as VpcId,
212 accepterVpcId: pcx.AccepterVpcInfo?.VpcId as VpcId,
213 accepterOwnerId: pcx.AccepterVpcInfo?.OwnerId ?? "",
214 });
215
216 return {
217 stables: ["vpcPeeringConnectionId"],
218
219 list: () =>
220 Effect.gen(function* () {
221 const items = yield* ec2.describeVpcPeeringConnections.pages({}).pipe(
222 Stream.runCollect,
223 Effect.map((chunk) =>
224 Array.from(chunk).flatMap((page) =>
225 (page.VpcPeeringConnections ?? [])
226 .filter(
227 (
228 pcx,
229 ): pcx is ec2.VpcPeeringConnection & {
230 VpcPeeringConnectionId: string;
231 } =>
232 pcx.VpcPeeringConnectionId != null &&
233 !DEAD_STATES.has(pcx.Status?.Code ?? ""),
234 )
235 .map(toAttrs),
236 ),
237 ),
238 );
239 return items satisfies VpcPeeringConnection["Attributes"][];
240 }),
241
242 read: Effect.fn(function* ({ output }) {
243 if (!output) return undefined;
244 const pcx = yield* describePeering(output.vpcPeeringConnectionId);
245 if (!pcx || DEAD_STATES.has(pcx.Status?.Code ?? "")) return undefined;
246 return toAttrs(pcx);
247 }),
248
249 diff: Effect.fn(function* ({ news, olds }) {
250 if (!isResolved(news)) return;
251 if (
252 news.vpcId !== olds.vpcId ||
253 news.peerVpcId !== olds.peerVpcId ||
254 news.peerRegion !== olds.peerRegion ||
255 news.peerOwnerId !== olds.peerOwnerId
256 ) {
257 return { action: "replace" };
258 }
259 // Only tags are mutable in place.
260 }),
261
262 reconcile: Effect.fn(function* ({ id, news, output, session }) {
263 const { accountId, region } = yield* AWSEnvironment.current;
264 const desiredTags = yield* createTags(id, news.tags);
265
266 const sameAccount = news.peerOwnerId === undefined || news.peerOwnerId === accountId;
267 const sameRegion = news.peerRegion === undefined || news.peerRegion === region;
268 const autoAccept = news.autoAccept ?? (sameAccount && sameRegion);
269
270 // Observe — the cached connection may have been deleted or moved to a
271 // terminal state, in which case we recreate.
272 let pcx: ec2.VpcPeeringConnection | undefined;
273 if (output?.vpcPeeringConnectionId) {
274 pcx = yield* describePeering(output.vpcPeeringConnectionId);
275 if (pcx && DEAD_STATES.has(pcx.Status?.Code ?? "")) {
276 pcx = undefined;
277 }
278 }
279
280 // Ensure — create the connection if missing.
281 if (pcx === undefined) {
282 yield* session.note("Creating VPC peering connection...");
283 const result = yield* ec2.createVpcPeeringConnection({
284 VpcId: news.vpcId as string,
285 PeerVpcId: news.peerVpcId as string,
286 PeerRegion: news.peerRegion,
287 PeerOwnerId: news.peerOwnerId,
288 TagSpecifications: [
289 {
290 ResourceType: "vpc-peering-connection",
291 Tags: createTagsList(desiredTags),
292 },
293 ],
294 });
295 pcx = result.VpcPeeringConnection!;
296 yield* session.note(`VPC peering connection created: ${pcx.VpcPeeringConnectionId}`);
297 }
298
299 const pcxId = pcx.VpcPeeringConnectionId!;
300
301 // Accept — for same-account/same-Region peering, wait for the request
302 // to settle into pending-acceptance, then accept it.
303 if (autoAccept) {
304 const settled = yield* waitFor(pcxId, "pending-acceptance");
305 if (settled?.Status?.Code === "pending-acceptance") {
306 yield* session.note("Accepting VPC peering connection...");
307 yield* ec2.acceptVpcPeeringConnection({ VpcPeeringConnectionId: pcxId }).pipe(
308 // A concurrent reconcile may have accepted it already.
309 Effect.catchTags({
310 "InvalidVpcPeeringConnectionID.NotFound": () => Effect.undefined,
311 "InvalidVpcPeeringConnectionId.NotFound": () => Effect.undefined,
312 }),
313 );
314 yield* waitFor(pcxId, "active");
315 }
316 }
317
318 // Sync tags — observed cloud tags vs desired.
319 const currentTags =
320 (yield* ec2
321 .describeTags({
322 Filters: [
323 { Name: "resource-id", Values: [pcxId] },
324 {
325 Name: "resource-type",
326 Values: ["vpc-peering-connection"],
327 },
328 ],
329 })
330 .pipe(
331 Effect.map(
332 (r) =>
333 Object.fromEntries(r.Tags?.map((t) => [t.Key!, t.Value!]) ?? []) as Record<
334 string,
335 string
336 >,
337 ),
338 )) ?? {};
339 const { removed, upsert } = diffTags(currentTags, desiredTags);
340 if (removed.length > 0) {
341 yield* ec2.deleteTags({
342 Resources: [pcxId],
343 Tags: removed.map((key) => ({ Key: key })),
344 });
345 }
346 if (upsert.length > 0) {
347 yield* ec2.createTags({ Resources: [pcxId], Tags: upsert });
348 }
349
350 const final = yield* describePeering(pcxId);
351 return toAttrs(final ?? pcx);
352 }),
353
354 delete: Effect.fn(function* ({ output, session }) {
355 const pcxId = output.vpcPeeringConnectionId;
356
357 // A connection already in a terminal state cannot (and need not) be
358 // deleted — AWS rejects deleting failed/rejected connections.
359 const observed = yield* describePeering(pcxId);
360 if (!observed || DEAD_STATES.has(observed.Status?.Code ?? "")) {
361 return;
362 }
363
364 yield* session.note(`Deleting VPC peering connection: ${pcxId}`);
365 yield* ec2.deleteVpcPeeringConnection({ VpcPeeringConnectionId: pcxId }).pipe(
366 Effect.catchTags({
367 "InvalidVpcPeeringConnectionID.NotFound": () => Effect.void,
368 "InvalidVpcPeeringConnectionId.NotFound": () => Effect.void,
369 }),
370 );
371 }),
372 };
373 }),
374 );