@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 320 lines 9.99 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 { VolumeId } from "./Volume.ts";
16
17 export class SnapshotUnexpectedResponse extends Data.TaggedError("SnapshotUnexpectedResponse")<{
18 readonly message: string;
19 readonly cause?: unknown;
20 }> {}
21
22 export class SnapshotOperationFailed extends Data.TaggedError("SnapshotOperationFailed")<{
23 readonly message: string;
24 readonly cause?: unknown;
25 }> {}
26
27 export type SnapshotId<ID extends string = string> = `snap-${ID}`;
28 export const SnapshotId = <ID extends string>(id: ID): ID & SnapshotId<ID> =>
29 `snap-${id}` as ID & SnapshotId<ID>;
30
31 export type SnapshotArn = `arn:aws:ec2:${RegionID}:${AccountID}:snapshot/${SnapshotId}`;
32
33 export interface SnapshotProps {
34 /**
35 * The ID of the EBS volume to snapshot. Required. A snapshot is an immutable
36 * point-in-time copy, so changing the source volume replaces the snapshot.
37 */
38 volumeId: VolumeId;
39
40 /**
41 * A description for the snapshot. Set at creation time only.
42 */
43 description?: string;
44
45 /**
46 * Tags to assign to the snapshot. Merged with alchemy auto-tags
47 * (alchemy::stack, alchemy::stage, alchemy::id).
48 */
49 tags?: Record<string, string>;
50 }
51
52 export interface Snapshot extends Resource<
53 "AWS.EC2.Snapshot",
54 SnapshotProps,
55 {
56 /**
57 * The ID of the snapshot.
58 */
59 snapshotId: SnapshotId;
60
61 /**
62 * The Amazon Resource Name (ARN) of the snapshot.
63 */
64 snapshotArn: SnapshotArn;
65
66 /**
67 * The ID of the volume the snapshot was created from.
68 */
69 volumeId: VolumeId;
70
71 /**
72 * The size of the volume, in GiB.
73 */
74 volumeSize: number;
75
76 /**
77 * The current state of the snapshot.
78 */
79 state: ec2.SnapshotState;
80
81 /**
82 * The progress of the snapshot, as a percentage (e.g. `"100%"`).
83 */
84 progress?: string;
85
86 /**
87 * Whether the snapshot is encrypted.
88 */
89 encrypted: boolean;
90
91 /**
92 * The KMS key used to protect the snapshot, if encrypted.
93 */
94 kmsKeyId?: string;
95
96 /**
97 * The ID of the AWS account that owns the snapshot.
98 */
99 ownerId?: string;
100 },
101 never,
102 Providers
103 > {}
104 /**
105 * A point-in-time backup of an EBS {@link Volume}, stored in S3. Snapshots are
106 * incremental and immutable — you create new {@link Volume}s from them via
107 * `snapshotId`.
108 *
109 * A snapshot is immutable once created; changing the source `volumeId` replaces
110 * it. Creation is asynchronous — the resource waits for the snapshot to reach
111 * the `completed` state before returning.
112 *
113 * ### Creating a Snapshot
114 * **Example:** Snapshot a Volume
115 * ```typescript
116 * const snapshot = yield* AWS.EC2.Snapshot("DailyBackup", {
117 * volumeId: volume.volumeId,
118 * description: "nightly backup of the data volume",
119 * });
120 * ```
121 *
122 * The snapshot captures the volume's state at creation time. Because snapshots
123 * are incremental, only blocks changed since the previous snapshot of the same
124 * volume are stored.
125 *
126 * ### Restoring from a Snapshot
127 * **Example:** Create a Volume from a Snapshot
128 * ```typescript
129 * const restored = yield* AWS.EC2.Volume("Restored", {
130 * availabilityZone: "us-east-1a",
131 * snapshotId: snapshot.snapshotId,
132 * });
133 * ```
134 *
135 * Pass a snapshot's `snapshotId` to {@link Volume} to provision a new volume
136 * pre-populated with the snapshot's data — the standard backup/restore and
137 * clone-across-AZ pattern.
138 *
139 * @resource
140 */
141 export const Snapshot = Resource<Snapshot>("AWS.EC2.Snapshot");
142
143 export const SnapshotProvider = () =>
144 Provider.effect(
145 Snapshot,
146 Effect.gen(function* () {
147 return {
148 stables: [
149 "snapshotId",
150 "snapshotArn",
151 "volumeId",
152 "volumeSize",
153 "encrypted",
154 "kmsKeyId",
155 "ownerId",
156 ],
157
158 diff: Effect.fn(function* ({ news, olds }) {
159 if (!isResolved(news)) return;
160 // A snapshot is an immutable copy of one volume — changing the source
161 // volume requires a fresh snapshot.
162 if (olds.volumeId !== news.volumeId) {
163 return { action: "replace" };
164 }
165 }),
166
167 reconcile: Effect.fn(function* ({ id, news, output, session }) {
168 const { accountId, region } = yield* AWSEnvironment.current;
169 const alchemyTags = yield* createInternalTags(id);
170 const desiredTags = { ...alchemyTags, ...news.tags };
171
172 // 1. OBSERVE — output is only an id cache.
173 let snapshot: ec2.Snapshot | undefined;
174 if (output?.snapshotId) {
175 const lookup = yield* ec2
176 .describeSnapshots({ SnapshotIds: [output.snapshotId] })
177 .pipe(
178 Effect.catchTag("InvalidSnapshot.NotFound", () =>
179 Effect.succeed({ Snapshots: [] }),
180 ),
181 );
182 snapshot = lookup.Snapshots?.[0];
183 }
184
185 // 2. ENSURE — create the snapshot when missing, then wait until it is
186 // completed.
187 if (snapshot === undefined) {
188 const created = yield* ec2.createSnapshot({
189 VolumeId: news.volumeId,
190 Description: news.description,
191 TagSpecifications: [
192 {
193 ResourceType: "snapshot",
194 Tags: createTagsList(desiredTags),
195 },
196 ],
197 DryRun: false,
198 });
199 const snapshotId = created.SnapshotId! as SnapshotId;
200 yield* session.note(`Snapshot created: ${snapshotId}`);
201 snapshot = yield* waitForSnapshotCompleted(snapshotId, session);
202 }
203
204 const snapshotId = snapshot.SnapshotId! as SnapshotId;
205
206 // 3. SYNC TAGS — diff against observed cloud tags.
207 const currentTags = Object.fromEntries(
208 (snapshot.Tags ?? []).map((t) => [t.Key!, t.Value!]),
209 ) as Record<string, string>;
210 const { removed, upsert } = diffTags(currentTags, desiredTags);
211 if (removed.length > 0) {
212 yield* ec2.deleteTags({
213 Resources: [snapshotId],
214 Tags: removed.map((key) => ({ Key: key })),
215 DryRun: false,
216 });
217 }
218 if (upsert.length > 0) {
219 yield* ec2.createTags({
220 Resources: [snapshotId],
221 Tags: upsert,
222 DryRun: false,
223 });
224 }
225
226 return toSnapshotAttributes(snapshot, region, accountId);
227 }),
228
229 // Enumerate every snapshot owned by this account (never public/shared
230 // snapshots — scope to "self").
231 list: () =>
232 Effect.gen(function* () {
233 const { accountId, region } = yield* AWSEnvironment.current;
234 const chunk = yield* ec2.describeSnapshots
235 .pages({ OwnerIds: ["self"] })
236 .pipe(Stream.runCollect);
237 return Array.from(chunk).flatMap((page) =>
238 (page.Snapshots ?? []).map((s) => toSnapshotAttributes(s, region, accountId)),
239 );
240 }),
241
242 delete: Effect.fn(function* ({ output, session }) {
243 const snapshotId = output.snapshotId;
244 yield* session.note(`Deleting snapshot: ${snapshotId}`);
245 yield* ec2.deleteSnapshot({ SnapshotId: snapshotId, DryRun: false }).pipe(
246 Effect.tapError(Effect.logDebug),
247 Effect.catchTag("InvalidSnapshot.NotFound", () => Effect.void),
248 );
249 yield* session.note(`Snapshot ${snapshotId} deleted successfully`);
250 }),
251 };
252 }),
253 );
254
255 const toSnapshotAttributes = (
256 snapshot: ec2.Snapshot,
257 region: RegionID,
258 accountId: AccountID,
259 ): Snapshot["Attributes"] => {
260 const snapshotId = snapshot.SnapshotId! as SnapshotId;
261 return {
262 snapshotId,
263 snapshotArn: `arn:aws:ec2:${region}:${accountId}:snapshot/${snapshotId}` as SnapshotArn,
264 volumeId: snapshot.VolumeId! as VolumeId,
265 volumeSize: snapshot.VolumeSize ?? 0,
266 state: snapshot.State ?? "pending",
267 progress: snapshot.Progress,
268 encrypted: snapshot.Encrypted ?? false,
269 kmsKeyId: snapshot.KmsKeyId,
270 ownerId: snapshot.OwnerId,
271 };
272 };
273
274 class SnapshotPending extends Data.TaggedError("SnapshotPending")<{
275 snapshotId: string;
276 state: string;
277 progress?: string;
278 }> {}
279
280 /**
281 * Wait for the snapshot to reach the `completed` state. Bounded so a slow
282 * snapshot fails fast rather than hanging the deploy.
283 */
284 const waitForSnapshotCompleted = (snapshotId: string, session?: ScopedPlanStatusSession) =>
285 Effect.gen(function* () {
286 const result = yield* ec2.describeSnapshots({
287 SnapshotIds: [snapshotId],
288 });
289 const snapshot = result.Snapshots?.[0];
290 if (!snapshot) {
291 return yield* new SnapshotUnexpectedResponse({ message: `Snapshot ${snapshotId} not found` });
292 }
293 if (snapshot.State === "completed") {
294 return snapshot;
295 }
296 if (snapshot.State === "error") {
297 return yield* new SnapshotOperationFailed({
298 message: `Snapshot ${snapshotId} entered error state: ${snapshot.StateMessage}`,
299 });
300 }
301 return yield* new SnapshotPending({
302 snapshotId,
303 state: snapshot.State!,
304 progress: snapshot.Progress,
305 });
306 }).pipe(
307 Effect.retry({
308 while: (e) => e instanceof SnapshotPending,
309 schedule: Schedule.max([
310 Schedule.fixed(3000),
311 Schedule.recurs(30), // max ~90s
312 ]).pipe(
313 Schedule.tap(({ attempt }) =>
314 session
315 ? session.note(`Waiting for snapshot to complete... (${(attempt + 1) * 3}s)`)
316 : Effect.void,
317 ),
318 ),
319 }),
320 );