@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 438 lines 14.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 type { ScopedPlanStatusSession } from "alchemy/Report";
5 import { Resource } from "alchemy/Resource";
6 import { createInternalTags, createTagsList, diffTags } from "alchemy/Tags";
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 { AccountID } from "../Environment.ts";
12 import { AWSEnvironment } from "../Environment.ts";
13 import type { Providers } from "../Providers.ts";
14 import type { RegionID } from "../Region.ts";
15 import type { SecurityGroupId } from "./SecurityGroup.ts";
16 import type { SubnetId } from "./Subnet.ts";
17 import type { VpcId } from "./Vpc.ts";
18
19 export class NetworkInterfaceUnexpectedResponse extends Data.TaggedError(
20 "NetworkInterfaceUnexpectedResponse",
21 )<{
22 readonly message: string;
23 readonly cause?: unknown;
24 }> {}
25
26 export type NetworkInterfaceId<ID extends string = string> = `eni-${ID}`;
27 export const NetworkInterfaceId = <ID extends string>(id: ID): ID & NetworkInterfaceId<ID> =>
28 `eni-${id}` as ID & NetworkInterfaceId<ID>;
29
30 export type NetworkInterfaceArn =
31 `arn:aws:ec2:${RegionID}:${AccountID}:network-interface/${NetworkInterfaceId}`;
32
33 export interface NetworkInterfaceProps {
34 /**
35 * The ID of the subnet to create the network interface in. Required.
36 * Changing it replaces the interface.
37 */
38 subnetId: SubnetId;
39
40 /**
41 * A description for the network interface. Mutable in place.
42 */
43 description?: string;
44
45 /**
46 * The primary private IPv4 address to assign. If omitted, AWS selects one
47 * from the subnet range. Changing it replaces the interface.
48 */
49 privateIpAddress?: string;
50
51 /**
52 * Additional (secondary) private IPv4 addresses to assign at creation.
53 */
54 privateIpAddresses?: string[];
55
56 /**
57 * The security groups to associate with the interface. Mutable in place.
58 */
59 securityGroupIds?: SecurityGroupId[];
60
61 /**
62 * Whether source/destination checking is enabled. Disable it for NAT
63 * instances and other appliances that forward traffic. Mutable in place.
64 * @default true
65 */
66 sourceDestCheck?: boolean;
67
68 /**
69 * The type of network interface.
70 * @default "interface"
71 */
72 interfaceType?: ec2.NetworkInterfaceCreationType;
73
74 /**
75 * Tags to assign to the network interface. Merged with alchemy auto-tags
76 * (alchemy::stack, alchemy::stage, alchemy::id).
77 */
78 tags?: Record<string, string>;
79 }
80
81 export interface NetworkInterface extends Resource<
82 "AWS.EC2.NetworkInterface",
83 NetworkInterfaceProps,
84 {
85 /**
86 * The ID of the network interface.
87 */
88 networkInterfaceId: NetworkInterfaceId;
89
90 /**
91 * The Amazon Resource Name (ARN) of the network interface.
92 */
93 networkInterfaceArn: NetworkInterfaceArn;
94
95 /**
96 * The ID of the subnet the interface is in.
97 */
98 subnetId: SubnetId;
99
100 /**
101 * The ID of the VPC the interface is in.
102 */
103 vpcId: VpcId;
104
105 /**
106 * The Availability Zone of the interface.
107 */
108 availabilityZone: string;
109
110 /**
111 * The primary private IPv4 address.
112 */
113 privateIpAddress?: string;
114
115 /**
116 * All private IPv4 addresses assigned to the interface.
117 */
118 privateIpAddresses: string[];
119
120 /**
121 * The MAC address of the interface.
122 */
123 macAddress?: string;
124
125 /**
126 * The security groups associated with the interface.
127 */
128 securityGroupIds: SecurityGroupId[];
129
130 /**
131 * Whether source/destination checking is enabled.
132 */
133 sourceDestCheck: boolean;
134
135 /**
136 * The current status of the interface.
137 */
138 status: ec2.NetworkInterfaceStatus;
139
140 /**
141 * The ID of the AWS account that owns the interface.
142 */
143 ownerId?: string;
144 },
145 never,
146 Providers
147 > {}
148 /**
149 * An Elastic Network Interface (ENI) — a virtual network card in a VPC subnet
150 * with its own private IPs, MAC address, and security groups. Attach one to an
151 * instance via a {@link NetworkInterfaceAttachment} for stable-IP and
152 * multi-homing patterns.
153 *
154 * Changing `subnetId` or the primary `privateIpAddress` replaces the interface.
155 * `description`, `securityGroupIds`, and `sourceDestCheck` are applied in place.
156 *
157 * ### Creating a Network Interface
158 * **Example:** Basic ENI
159 * ```typescript
160 * const eni = yield* AWS.EC2.NetworkInterface("AppEni", {
161 * subnetId: subnet.subnetId,
162 * description: "stable IP for the app server",
163 * securityGroupIds: [securityGroup.groupId],
164 * });
165 * ```
166 *
167 * The interface gets a private IP from the subnet's range. Its IP survives
168 * instance replacement — detach it from a failed instance and attach it to a
169 * new one to keep the same address.
170 *
171 * ### Fixed Private IP
172 * **Example:** ENI with a Fixed Private IP
173 * ```typescript
174 * const eni = yield* AWS.EC2.NetworkInterface("FixedIpEni", {
175 * subnetId: subnet.subnetId,
176 * privateIpAddress: "10.0.1.50",
177 * securityGroupIds: [securityGroup.groupId],
178 * });
179 * ```
180 *
181 * Pinning `privateIpAddress` gives the interface a predictable address —
182 * useful for appliances and services other resources reference by IP.
183 *
184 * ### Forwarding Appliances
185 * **Example:** ENI with Source/Dest Check Disabled
186 * ```typescript
187 * const eni = yield* AWS.EC2.NetworkInterface("NatEni", {
188 * subnetId: subnet.subnetId,
189 * sourceDestCheck: false,
190 * securityGroupIds: [securityGroup.groupId],
191 * });
192 * ```
193 *
194 * Disable `sourceDestCheck` when the interface belongs to a NAT instance,
195 * firewall, or router that forwards packets not addressed to itself.
196 *
197 * @resource
198 */
199 export const NetworkInterface = Resource<NetworkInterface>("AWS.EC2.NetworkInterface");
200
201 export const NetworkInterfaceProvider = () =>
202 Provider.effect(
203 NetworkInterface,
204 Effect.gen(function* () {
205 return {
206 stables: [
207 "networkInterfaceId",
208 "networkInterfaceArn",
209 "subnetId",
210 "vpcId",
211 "availabilityZone",
212 "ownerId",
213 ],
214
215 diff: Effect.fn(function* ({ news, olds }) {
216 if (!isResolved(news)) return;
217 if (olds.subnetId !== news.subnetId || olds.privateIpAddress !== news.privateIpAddress) {
218 return { action: "replace" };
219 }
220 }),
221
222 reconcile: Effect.fn(function* ({ id, news, output, session }) {
223 const { accountId, region } = yield* AWSEnvironment.current;
224 const alchemyTags = yield* createInternalTags(id);
225 const desiredTags = { ...alchemyTags, ...news.tags };
226
227 // 1. OBSERVE — output is only an id cache.
228 let eni: ec2.NetworkInterface | undefined;
229 if (output?.networkInterfaceId) {
230 const lookup = yield* ec2
231 .describeNetworkInterfaces({
232 NetworkInterfaceIds: [output.networkInterfaceId],
233 })
234 .pipe(
235 Effect.catchTag("InvalidNetworkInterfaceID.NotFound", () =>
236 Effect.succeed({ NetworkInterfaces: [] }),
237 ),
238 );
239 eni = lookup.NetworkInterfaces?.[0];
240 }
241
242 // 2. ENSURE — create the interface when missing.
243 if (eni === undefined) {
244 const secondary = (news.privateIpAddresses ?? []).map((ip) => ({
245 Primary: false,
246 PrivateIpAddress: ip,
247 }));
248 const created = yield* ec2.createNetworkInterface({
249 SubnetId: news.subnetId,
250 Description: news.description,
251 PrivateIpAddress: news.privateIpAddress,
252 PrivateIpAddresses: secondary.length > 0 ? secondary : undefined,
253 Groups: news.securityGroupIds,
254 InterfaceType: news.interfaceType,
255 TagSpecifications: [
256 {
257 ResourceType: "network-interface",
258 Tags: createTagsList(desiredTags),
259 },
260 ],
261 DryRun: false,
262 });
263 eni = created.NetworkInterface!;
264 yield* session.note(`Network interface created: ${eni.NetworkInterfaceId}`);
265 eni = yield* waitForNetworkInterface(eni.NetworkInterfaceId!, session);
266 }
267
268 const eniId = eni.NetworkInterfaceId! as NetworkInterfaceId;
269
270 // 3. SYNC — description, security groups, source/dest check.
271 if (news.description !== undefined && news.description !== (eni.Description ?? "")) {
272 yield* ec2.modifyNetworkInterfaceAttribute({
273 NetworkInterfaceId: eniId,
274 Description: { Value: news.description },
275 DryRun: false,
276 });
277 yield* session.note("Updated network interface description");
278 }
279
280 if (news.securityGroupIds !== undefined) {
281 const observed = (eni.Groups ?? []).map((g) => g.GroupId!).sort();
282 const desired = [...news.securityGroupIds].sort();
283 if (JSON.stringify(observed) !== JSON.stringify(desired)) {
284 yield* ec2.modifyNetworkInterfaceAttribute({
285 NetworkInterfaceId: eniId,
286 Groups: news.securityGroupIds,
287 DryRun: false,
288 });
289 yield* session.note("Updated network interface security groups");
290 }
291 }
292
293 const desiredSourceDestCheck = news.sourceDestCheck ?? true;
294 if ((eni.SourceDestCheck ?? true) !== desiredSourceDestCheck) {
295 yield* ec2.modifyNetworkInterfaceAttribute({
296 NetworkInterfaceId: eniId,
297 SourceDestCheck: { Value: desiredSourceDestCheck },
298 DryRun: false,
299 });
300 yield* session.note(`Updated source/dest check: ${desiredSourceDestCheck}`);
301 }
302
303 // 3b. SYNC TAGS — diff against observed cloud tags.
304 const currentTags = Object.fromEntries(
305 (eni.TagSet ?? []).map((t) => [t.Key!, t.Value!]),
306 ) as Record<string, string>;
307 const { removed, upsert } = diffTags(currentTags, desiredTags);
308 if (removed.length > 0) {
309 yield* ec2.deleteTags({
310 Resources: [eniId],
311 Tags: removed.map((key) => ({ Key: key })),
312 DryRun: false,
313 });
314 }
315 if (upsert.length > 0) {
316 yield* ec2.createTags({
317 Resources: [eniId],
318 Tags: upsert,
319 DryRun: false,
320 });
321 }
322
323 // 4. RETURN fresh attributes.
324 const finalLookup = yield* ec2.describeNetworkInterfaces({
325 NetworkInterfaceIds: [eniId],
326 });
327 const final = finalLookup.NetworkInterfaces?.[0] ?? eni;
328 return toNetworkInterfaceAttributes(final, region, accountId);
329 }),
330
331 // Enumerate every network interface in the ambient account/region.
332 list: () =>
333 Effect.gen(function* () {
334 const { accountId, region } = yield* AWSEnvironment.current;
335 const chunk = yield* ec2.describeNetworkInterfaces.pages({}).pipe(Stream.runCollect);
336 return Array.from(chunk).flatMap((page) =>
337 (page.NetworkInterfaces ?? []).map((n) =>
338 toNetworkInterfaceAttributes(n, region, accountId),
339 ),
340 );
341 }),
342
343 delete: Effect.fn(function* ({ output, session }) {
344 const eniId = output.networkInterfaceId;
345 yield* session.note(`Deleting network interface: ${eniId}`);
346 yield* ec2
347 .deleteNetworkInterface({
348 NetworkInterfaceId: eniId,
349 DryRun: false,
350 })
351 .pipe(
352 Effect.tapError(Effect.logDebug),
353 Effect.catchTag("InvalidNetworkInterfaceID.NotFound", () => Effect.void),
354 // A just-detached interface can briefly report InUse — retry
355 // until the attachment fully clears.
356 Effect.retry({
357 while: (e) => e._tag === "InvalidNetworkInterface.InUse",
358 schedule: Schedule.max([Schedule.fixed(3000), Schedule.recurs(20)]).pipe(
359 Schedule.tap(({ attempt }) =>
360 session.note(`Waiting for interface to detach... (attempt ${attempt + 1})`),
361 ),
362 ),
363 }),
364 );
365 yield* session.note(`Network interface ${eniId} deleted`);
366 }),
367 };
368 }),
369 );
370
371 const toNetworkInterfaceAttributes = (
372 eni: ec2.NetworkInterface,
373 region: RegionID,
374 accountId: AccountID,
375 ): NetworkInterface["Attributes"] => {
376 const eniId = eni.NetworkInterfaceId! as NetworkInterfaceId;
377 return {
378 networkInterfaceId: eniId,
379 networkInterfaceArn:
380 `arn:aws:ec2:${region}:${accountId}:network-interface/${eniId}` as NetworkInterfaceArn,
381 subnetId: eni.SubnetId! as SubnetId,
382 vpcId: eni.VpcId! as VpcId,
383 availabilityZone: eni.AvailabilityZone!,
384 privateIpAddress: eni.PrivateIpAddress,
385 privateIpAddresses: (eni.PrivateIpAddresses ?? [])
386 .map((p) => p.PrivateIpAddress!)
387 .filter((ip): ip is string => ip !== undefined),
388 macAddress: eni.MacAddress,
389 securityGroupIds: (eni.Groups ?? [])
390 .map((g) => g.GroupId! as SecurityGroupId)
391 .filter((g): g is SecurityGroupId => g !== undefined),
392 sourceDestCheck: eni.SourceDestCheck ?? true,
393 status: eni.Status ?? "available",
394 ownerId: eni.OwnerId,
395 };
396 };
397
398 class NetworkInterfacePending extends Data.TaggedError("NetworkInterfacePending")<{
399 networkInterfaceId: string;
400 status: string;
401 }> {}
402
403 /**
404 * Wait for the network interface to reach an `available` (or in-use) status.
405 */
406 const waitForNetworkInterface = (networkInterfaceId: string, session?: ScopedPlanStatusSession) =>
407 Effect.gen(function* () {
408 const result = yield* ec2.describeNetworkInterfaces({
409 NetworkInterfaceIds: [networkInterfaceId],
410 });
411 const eni = result.NetworkInterfaces?.[0];
412 if (!eni) {
413 return yield* new NetworkInterfaceUnexpectedResponse({
414 message: `Network interface ${networkInterfaceId} not found`,
415 });
416 }
417 if (eni.Status === "available" || eni.Status === "in-use") {
418 return eni;
419 }
420 return yield* new NetworkInterfacePending({
421 networkInterfaceId,
422 status: eni.Status!,
423 });
424 }).pipe(
425 Effect.retry({
426 while: (e) => e instanceof NetworkInterfacePending,
427 schedule: Schedule.max([
428 Schedule.fixed(2000),
429 Schedule.recurs(20), // max ~40s
430 ]).pipe(
431 Schedule.tap(({ attempt }) =>
432 session
433 ? session.note(`Waiting for network interface... (${(attempt + 1) * 2}s)`)
434 : Effect.void,
435 ),
436 ),
437 }),
438 );