@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 290 lines 9.13 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 * as Data from "effect/Data";
7 import * as Effect from "effect/Effect";
8 import * as Schedule from "effect/Schedule";
9 import type { Providers } from "../Providers.ts";
10 import type { InstanceId } from "./Instance.ts";
11 import type { NetworkInterfaceId } from "./NetworkInterface.ts";
12
13 export type NetworkInterfaceAttachmentId<ID extends string = string> = `eni-attach-${ID}`;
14
15 export interface NetworkInterfaceAttachmentProps {
16 /**
17 * The ID of the network interface to attach. Required. Changing it replaces
18 * the attachment.
19 */
20 networkInterfaceId: NetworkInterfaceId;
21
22 /**
23 * The ID of the instance to attach the interface to. Required. Changing it
24 * replaces the attachment.
25 */
26 instanceId: InstanceId;
27
28 /**
29 * The device index for the interface on the instance (0 is the primary
30 * interface). Required. Changing it replaces the attachment.
31 */
32 deviceIndex: number;
33
34 /**
35 * Whether to force-detach the interface on delete if a normal detach does
36 * not complete.
37 * @default true
38 */
39 forceDetach?: boolean;
40 }
41
42 export interface NetworkInterfaceAttachment extends Resource<
43 "AWS.EC2.NetworkInterfaceAttachment",
44 NetworkInterfaceAttachmentProps,
45 {
46 /**
47 * The ID of the attachment.
48 */
49 attachmentId: NetworkInterfaceAttachmentId;
50
51 /**
52 * The ID of the attached network interface.
53 */
54 networkInterfaceId: NetworkInterfaceId;
55
56 /**
57 * The ID of the instance the interface is attached to.
58 */
59 instanceId: InstanceId;
60
61 /**
62 * The device index of the interface on the instance.
63 */
64 deviceIndex: number;
65
66 /**
67 * The attachment status.
68 */
69 status: ec2.AttachmentStatus;
70 },
71 never,
72 Providers
73 > {}
74 /**
75 * Attaches an {@link NetworkInterface} (ENI) to an EC2 {@link Instance} at a
76 * device index. The interface and instance must be in the same Availability
77 * Zone. On delete the interface is detached (force-detached as a fallback)
78 * before the resource is removed.
79 *
80 * This is an existence-style resource — its identity is the
81 * `networkInterfaceId`/`instanceId`/`deviceIndex` triple. Changing any of them
82 * replaces the attachment.
83 *
84 * ### Attaching a Network Interface
85 * **Example:** Attach a Secondary ENI to an Instance
86 * ```typescript
87 * const attachment = yield* AWS.EC2.NetworkInterfaceAttachment("SecondaryEni", {
88 * networkInterfaceId: eni.networkInterfaceId,
89 * instanceId: instance.instanceId,
90 * deviceIndex: 1,
91 * });
92 * ```
93 *
94 * Device index 0 is the instance's primary interface, so secondary interfaces
95 * use index 1 and up. The ENI's IPs and security groups now apply to the
96 * instance on that interface.
97 *
98 * @resource
99 */
100 export const NetworkInterfaceAttachment = Resource<NetworkInterfaceAttachment>(
101 "AWS.EC2.NetworkInterfaceAttachment",
102 );
103
104 export const NetworkInterfaceAttachmentProvider = () =>
105 Provider.effect(
106 NetworkInterfaceAttachment,
107 Effect.gen(function* () {
108 return {
109 stables: ["attachmentId", "networkInterfaceId", "instanceId", "deviceIndex"],
110
111 diff: Effect.fn(function* ({ news, olds }) {
112 if (!isResolved(news)) return;
113 if (
114 olds.networkInterfaceId !== news.networkInterfaceId ||
115 olds.instanceId !== news.instanceId ||
116 olds.deviceIndex !== news.deviceIndex
117 ) {
118 return { action: "replace" };
119 }
120 }),
121
122 reconcile: Effect.fn(function* ({ news, output, session }) {
123 // 1. OBSERVE — the attachment lives on the interface.
124 const lookup = yield* ec2
125 .describeNetworkInterfaces({
126 NetworkInterfaceIds: [news.networkInterfaceId],
127 })
128 .pipe(
129 Effect.catchTag("InvalidNetworkInterfaceID.NotFound", () =>
130 Effect.succeed({ NetworkInterfaces: [] }),
131 ),
132 );
133 const eni = lookup.NetworkInterfaces?.[0];
134 const existing = eni?.Attachment;
135 const attachedToInstance =
136 existing?.InstanceId === news.instanceId &&
137 existing?.Status !== "detaching" &&
138 existing?.Status !== "detached";
139
140 // 2. ENSURE — attach when not already attached to this instance.
141 let attachmentId =
142 attachedToInstance && existing?.AttachmentId
143 ? (existing.AttachmentId as NetworkInterfaceAttachmentId)
144 : output?.attachmentId;
145 if (!attachedToInstance) {
146 const result = yield* ec2.attachNetworkInterface({
147 NetworkInterfaceId: news.networkInterfaceId,
148 InstanceId: news.instanceId,
149 DeviceIndex: news.deviceIndex,
150 DryRun: false,
151 });
152 attachmentId = result.AttachmentId! as NetworkInterfaceAttachmentId;
153 yield* session.note(
154 `Network interface ${news.networkInterfaceId} attaching to ${news.instanceId}`,
155 );
156 }
157
158 // 3. WAIT — until attached.
159 const status = yield* waitForEniAttachmentState(
160 news.networkInterfaceId,
161 "attached",
162 session,
163 );
164
165 return {
166 attachmentId: attachmentId!,
167 networkInterfaceId: news.networkInterfaceId,
168 instanceId: news.instanceId,
169 deviceIndex: news.deviceIndex,
170 status,
171 };
172 }),
173
174 // Attachments are embedded in interfaces; there is no standalone
175 // enumeration keyed to this resource's identity.
176 list: () => Effect.succeed([]),
177
178 delete: Effect.fn(function* ({ output, olds, session }) {
179 const { attachmentId, networkInterfaceId } = output;
180 const force = olds?.forceDetach ?? true;
181 yield* session.note(
182 `Detaching network interface ${networkInterfaceId} (${attachmentId})`,
183 );
184
185 yield* ec2
186 .detachNetworkInterface({
187 AttachmentId: attachmentId,
188 Force: force,
189 DryRun: false,
190 })
191 .pipe(
192 Effect.catchTag("InvalidAttachmentID.NotFound", () => Effect.void),
193 // The interface can still be in-use momentarily — retry.
194 Effect.retry({
195 while: (e) => e._tag === "DependencyViolation",
196 schedule: Schedule.max([Schedule.fixed(3000), Schedule.recurs(15)]),
197 }),
198 );
199
200 // Wait for the interface to return to 'available'.
201 yield* waitForEniDetached(networkInterfaceId, session);
202 yield* session.note(`Network interface ${networkInterfaceId} detached`);
203 }),
204 };
205 }),
206 );
207
208 class EniAttachmentPending extends Data.TaggedError("EniAttachmentPending")<{
209 networkInterfaceId: string;
210 status: string;
211 }> {}
212
213 class EniStillAttached extends Data.TaggedError("EniStillAttached")<{
214 networkInterfaceId: string;
215 status: string;
216 }> {}
217
218 /**
219 * Wait for the interface's attachment to reach a target status.
220 */
221 const waitForEniAttachmentState = (
222 networkInterfaceId: string,
223 target: ec2.AttachmentStatus,
224 session?: ScopedPlanStatusSession,
225 ) =>
226 Effect.gen(function* () {
227 const result = yield* ec2.describeNetworkInterfaces({
228 NetworkInterfaceIds: [networkInterfaceId],
229 });
230 const status = result.NetworkInterfaces?.[0]?.Attachment?.Status;
231 if (status === target) {
232 return status;
233 }
234 return yield* new EniAttachmentPending({
235 networkInterfaceId,
236 status: status ?? "unknown",
237 });
238 }).pipe(
239 Effect.retry({
240 while: (e) => e instanceof EniAttachmentPending,
241 schedule: Schedule.max([
242 Schedule.fixed(2000),
243 Schedule.recurs(20), // max ~40s
244 ]).pipe(
245 Schedule.tap(({ attempt }) =>
246 session
247 ? session.note(`Waiting for interface attachment... (${(attempt + 1) * 2}s)`)
248 : Effect.void,
249 ),
250 ),
251 }),
252 );
253
254 /**
255 * Wait for the interface to return to `available` after a detach.
256 */
257 const waitForEniDetached = (networkInterfaceId: string, session?: ScopedPlanStatusSession) =>
258 Effect.gen(function* () {
259 const result = yield* ec2
260 .describeNetworkInterfaces({
261 NetworkInterfaceIds: [networkInterfaceId],
262 })
263 .pipe(
264 Effect.catchTag("InvalidNetworkInterfaceID.NotFound", () =>
265 Effect.succeed({ NetworkInterfaces: [] }),
266 ),
267 );
268 const eni = result.NetworkInterfaces?.[0];
269 if (!eni || eni.Status === "available" || eni.Attachment === undefined) {
270 return;
271 }
272 return yield* new EniStillAttached({
273 networkInterfaceId,
274 status: eni.Status ?? "unknown",
275 });
276 }).pipe(
277 Effect.retry({
278 while: (e) => e instanceof EniStillAttached,
279 schedule: Schedule.max([
280 Schedule.fixed(2000),
281 Schedule.recurs(20), // max ~40s
282 ]).pipe(
283 Schedule.tap(({ attempt }) =>
284 session
285 ? session.note(`Waiting for interface to detach... (${(attempt + 1) * 2}s)`)
286 : Effect.void,
287 ),
288 ),
289 }),
290 );