@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 349 lines 11.3 KB
Raw
1 import type { Credentials } from "@distilled.cloud/aws/Credentials";
2 import * as ec2 from "@distilled.cloud/aws/ec2";
3 import type { Region } from "@distilled.cloud/aws/Region";
4 import * as Data from "effect/Data";
5 import * as Effect from "effect/Effect";
6 import type { HttpClient } from "effect/http/HttpClient";
7 import * as Schedule from "effect/Schedule";
8
9 // Explicitly-typed pipeable retry helpers. Inlining `Effect.retry` in a
10 // provider lifecycle op leaks `Retry.Return`'s conditional into declaration
11 // emit and widens the provider layer to `unknown` R for every consumer of
12 // `AWS.providers()`.
13 const retryWhileVolumeInUse = <A, E extends { readonly _tag: string }, R>(
14 self: Effect.Effect<A, E, R>,
15 ): Effect.Effect<A, E, R> =>
16 Effect.retry(self, {
17 while: (e) => e._tag === "VolumeInUse",
18 schedule: Schedule.max([Schedule.fixed(2000), Schedule.recurs(15)]),
19 });
20
21 const retryWhileIncorrectState = <A, E extends { readonly _tag: string }, R>(
22 self: Effect.Effect<A, E, R>,
23 ): Effect.Effect<A, E, R> =>
24 Effect.retry(self, {
25 while: (e) => e._tag === "IncorrectState",
26 schedule: Schedule.max([Schedule.fixed(2000), Schedule.recurs(10)]),
27 });
28
29 import { isResolved } from "alchemy/Diff";
30 import * as Provider from "alchemy/Provider";
31 import type { ScopedPlanStatusSession } from "alchemy/Report";
32 import { Resource } from "alchemy/Resource";
33 import type { Providers } from "../Providers.ts";
34 import type { InstanceId } from "./Instance.ts";
35 import type { VolumeId } from "./Volume.ts";
36
37 export interface VolumeAttachmentProps {
38 /**
39 * The ID of the EBS volume to attach. Required. Changing it replaces the
40 * attachment.
41 */
42 volumeId: VolumeId;
43
44 /**
45 * The ID of the instance to attach the volume to. Required. Changing it
46 * replaces the attachment.
47 */
48 instanceId: InstanceId;
49
50 /**
51 * The device name to expose to the instance, e.g. `/dev/sdf` (Linux) or
52 * `xvdf`. Required. Changing it replaces the attachment.
53 */
54 device: string;
55
56 /**
57 * Whether to force-detach the volume on delete if a normal detach does not
58 * complete. Forcing can corrupt data if the volume is still mounted — use
59 * only when the instance is unresponsive.
60 * @default true
61 */
62 forceDetach?: boolean;
63 }
64
65 export interface VolumeAttachment extends Resource<
66 "AWS.EC2.VolumeAttachment",
67 VolumeAttachmentProps,
68 {
69 /**
70 * The ID of the attached volume.
71 */
72 volumeId: VolumeId;
73
74 /**
75 * The ID of the instance the volume is attached to.
76 */
77 instanceId: InstanceId;
78
79 /**
80 * The device name exposed to the instance.
81 */
82 device: string;
83
84 /**
85 * The attachment state.
86 */
87 state: ec2.VolumeAttachmentState;
88 },
89 never,
90 Providers
91 > {}
92 /**
93 * Attaches an EBS {@link Volume} to an EC2 {@link Instance} at a device name.
94 * The volume and instance must be in the same Availability Zone. On delete the
95 * volume is detached (and force-detached as a fallback) before the resource is
96 * removed.
97 *
98 * This is an existence-style resource — its identity is the
99 * `volumeId`/`instanceId`/`device` triple. Changing any of them replaces the
100 * attachment.
101 *
102 * ### Attaching a Volume
103 * **Example:** Attach a Volume to an Instance
104 * ```typescript
105 * const attachment = yield* AWS.EC2.VolumeAttachment("DataAttachment", {
106 * volumeId: volume.volumeId,
107 * instanceId: instance.instanceId,
108 * device: "/dev/sdf",
109 * });
110 * ```
111 *
112 * The volume appears to the instance as a block device at `device`. On modern
113 * Linux AMIs the kernel may rename `/dev/sdf` to `/dev/xvdf` — check
114 * `lsblk` inside the instance. The volume and instance must share an AZ.
115 *
116 * @resource
117 */
118 export const VolumeAttachment = Resource<VolumeAttachment>("AWS.EC2.VolumeAttachment");
119
120 export const VolumeAttachmentProvider = () =>
121 Provider.effect(
122 VolumeAttachment,
123 Effect.gen(function* () {
124 return {
125 stables: ["volumeId", "instanceId", "device"],
126
127 diff: Effect.fn(function* ({ news, olds }) {
128 if (!isResolved(news)) return;
129 if (
130 olds.volumeId !== news.volumeId ||
131 olds.instanceId !== news.instanceId ||
132 olds.device !== news.device
133 ) {
134 return { action: "replace" };
135 }
136 }),
137
138 reconcile: Effect.fn(function* ({ news, session }) {
139 // 1. OBSERVE — attachments are embedded in the volume; find one for
140 // this instance.
141 const lookup = yield* ec2
142 .describeVolumes({ VolumeIds: [news.volumeId] })
143 .pipe(Effect.catchTag("InvalidVolume.NotFound", () => Effect.succeed({ Volumes: [] })));
144 const volume = lookup.Volumes?.[0];
145 let attachment = volume?.Attachments?.find(
146 (a) =>
147 a.InstanceId === news.instanceId && a.State !== "detaching" && a.State !== "detached",
148 );
149
150 // 2. ENSURE — attach the volume when it is not already attached to
151 // this instance.
152 if (attachment === undefined) {
153 const result = yield* ec2
154 .attachVolume({
155 VolumeId: news.volumeId,
156 InstanceId: news.instanceId,
157 Device: news.device,
158 DryRun: false,
159 })
160 .pipe(
161 // The volume can briefly report VolumeInUse while a prior
162 // detach settles — retry until it frees up.
163 retryWhileVolumeInUse,
164 );
165 yield* session.note(
166 `Volume ${news.volumeId} attaching to ${news.instanceId} at ${news.device}`,
167 );
168 attachment = {
169 VolumeId: result.VolumeId,
170 InstanceId: result.InstanceId,
171 Device: result.Device,
172 State: result.State,
173 };
174 }
175
176 // 3. WAIT — until the attachment is fully attached.
177 const state = yield* waitForAttachmentState(
178 news.volumeId,
179 news.instanceId,
180 "attached",
181 session,
182 );
183
184 return {
185 volumeId: news.volumeId,
186 instanceId: news.instanceId,
187 device: attachment.Device ?? news.device,
188 state,
189 };
190 }),
191
192 // Attachments are embedded in volumes; there is no standalone
193 // enumeration keyed to this resource's identity.
194 list: () => Effect.succeed([]),
195
196 delete: Effect.fn(function* ({ output, olds, session }) {
197 const { volumeId, instanceId, device } = output;
198 const force = olds?.forceDetach ?? true;
199 yield* session.note(`Detaching volume ${volumeId} from ${instanceId}`);
200
201 // If the volume is already gone, nothing to detach.
202 const lookup = yield* ec2
203 .describeVolumes({ VolumeIds: [volumeId] })
204 .pipe(Effect.catchTag("InvalidVolume.NotFound", () => Effect.succeed({ Volumes: [] })));
205 const volume = lookup.Volumes?.[0];
206 if (!volume) {
207 return;
208 }
209 const attached = volume.Attachments?.some(
210 (a) => a.InstanceId === instanceId && a.State !== "detached",
211 );
212 if (!attached) {
213 return;
214 }
215
216 // Normal detach, retrying while the volume is still in a transient
217 // state (attaching / busy → IncorrectState).
218 yield* ec2
219 .detachVolume({
220 VolumeId: volumeId,
221 InstanceId: instanceId,
222 Device: device,
223 DryRun: false,
224 })
225 .pipe(
226 Effect.catchTag("InvalidVolume.NotFound", () => Effect.void),
227 retryWhileIncorrectState,
228 // Fall back to a forced detach if it still won't release.
229 // Explicit return type: the ternary's branches are two
230 // structurally different Effects and TS cannot unify them on
231 // its own.
232 Effect.catchTag(
233 "IncorrectState",
234 (
235 e,
236 ): Effect.Effect<
237 ec2.VolumeAttachment | void,
238 ec2.DetachVolumeError,
239 Credentials | Region | HttpClient
240 > =>
241 force
242 ? ec2
243 .detachVolume({
244 VolumeId: volumeId,
245 InstanceId: instanceId,
246 Device: device,
247 Force: true,
248 DryRun: false,
249 })
250 .pipe(
251 Effect.catchTags({
252 "InvalidVolume.NotFound": () => Effect.void,
253 IncorrectState: () => Effect.void,
254 }),
255 )
256 : Effect.fail(e),
257 ),
258 );
259
260 // Wait for the volume to return to 'available'.
261 yield* waitForVolumeDetached(volumeId, session);
262 yield* session.note(`Volume ${volumeId} detached from ${instanceId}`);
263 }),
264 };
265 }),
266 );
267
268 class AttachmentNotReady extends Data.TaggedError("AttachmentNotReady")<{
269 volumeId: string;
270 state: string;
271 }> {}
272
273 class VolumeStillAttached extends Data.TaggedError("VolumeStillAttached")<{
274 volumeId: string;
275 state: string;
276 }> {}
277
278 /**
279 * Wait for the attachment of `volumeId` to `instanceId` to reach a target
280 * state.
281 */
282 const waitForAttachmentState = (
283 volumeId: string,
284 instanceId: string,
285 target: ec2.VolumeAttachmentState,
286 session?: ScopedPlanStatusSession,
287 ): Effect.Effect<
288 ec2.VolumeAttachmentState,
289 ec2.DescribeVolumesError | AttachmentNotReady,
290 Credentials | Region | HttpClient
291 > =>
292 Effect.gen(function* () {
293 const result = yield* ec2.describeVolumes({ VolumeIds: [volumeId] });
294 const attachment = result.Volumes?.[0]?.Attachments?.find((a) => a.InstanceId === instanceId);
295 const state = attachment?.State;
296 if (state === target) {
297 return state;
298 }
299 return yield* new AttachmentNotReady({
300 volumeId,
301 state: state ?? "unknown",
302 });
303 }).pipe(
304 Effect.retry({
305 while: (e) => e instanceof AttachmentNotReady,
306 schedule: Schedule.max([
307 Schedule.fixed(2000),
308 Schedule.recurs(20), // max ~40s
309 ]).pipe(
310 Schedule.tap(({ attempt }) =>
311 session
312 ? session.note(`Waiting for volume attachment... (${(attempt + 1) * 2}s)`)
313 : Effect.void,
314 ),
315 ),
316 }),
317 );
318
319 /**
320 * Wait for the volume to return to `available` after a detach.
321 */
322 const waitForVolumeDetached = (volumeId: string, session?: ScopedPlanStatusSession) =>
323 Effect.gen(function* () {
324 const result = yield* ec2
325 .describeVolumes({ VolumeIds: [volumeId] })
326 .pipe(Effect.catchTag("InvalidVolume.NotFound", () => Effect.succeed({ Volumes: [] })));
327 const volume = result.Volumes?.[0];
328 if (!volume || volume.State === "available") {
329 return;
330 }
331 return yield* new VolumeStillAttached({
332 volumeId,
333 state: volume.State ?? "unknown",
334 });
335 }).pipe(
336 Effect.retry({
337 while: (e) => e instanceof VolumeStillAttached,
338 schedule: Schedule.max([
339 Schedule.fixed(2000),
340 Schedule.recurs(20), // max ~40s
341 ]).pipe(
342 Schedule.tap(({ attempt }) =>
343 session
344 ? session.note(`Waiting for volume to detach... (${(attempt + 1) * 2}s)`)
345 : Effect.void,
346 ),
347 ),
348 }),
349 );