The best way to control Claude Code, Codex and more from any computer or phone

main
ts 506 lines 15.6 KB
Raw
1 import * as Hetzner from "@distilled.cloud/hetzner";
2 import type {
3 GetImageResponseImage,
4 ListImagesResponseImagesItem,
5 UpdateImageResponseImage,
6 } from "@distilled.cloud/hetzner/images";
7 import type { CreateServerImageResponseImage } from "@distilled.cloud/hetzner/server_actions";
8 import { Unowned } from "alchemy/AdoptPolicy";
9 import { isResolved } from "alchemy/Diff";
10 import { createPhysicalName } from "alchemy/PhysicalName";
11 import * as Provider from "alchemy/Provider";
12 import { Resource } from "alchemy/Resource";
13 import { tagRecord } from "alchemy/Tags";
14 import * as Data from "effect/Data";
15 import * as Duration from "effect/Duration";
16 import * as Effect from "effect/Effect";
17 import * as Schedule from "effect/Schedule";
18 import * as Stream from "effect/Stream";
19 import { waitForAction } from "./actions.ts";
20 import {
21 alchemyStackSelector,
22 createInternalLabels,
23 diffLabels,
24 hasAlchemyLabels,
25 labelSelector,
26 stripInternalLabels,
27 toLabels,
28 } from "./Labels.ts";
29 import type { Providers } from "./Providers.ts";
30
31 const MAX_DESCRIPTION_LENGTH = 64;
32
33 export type ImageType = "snapshot" | "backup";
34
35 export type ImageStatus = "available" | "creating" | "unavailable";
36
37 export type ImageArchitecture = "x86" | "arm";
38
39 export type ImageOsFlavor =
40 | "ubuntu"
41 | "centos"
42 | "debian"
43 | "fedora"
44 | "rocky"
45 | "alma"
46 | "opensuse"
47 | "unknown";
48
49 /**
50 * A resource-valued prop: the resource itself, or an Effect that produces
51 * it (so `yield* Server(...)` and `Server(...)` both type-check).
52 */
53 type Ref<T> = T | Effect.Effect<T, never, Providers>;
54
55 /**
56 * Server identity an Image is snapshotted from. Accepts a `Hetzner.Server`
57 * resource or a `{ serverId }` stub. Stock (system/app) Images are not
58 * managed here — look those up with `Hetzner.findImage`.
59 */
60 export type ImageServer = {
61 readonly serverId: number;
62 };
63
64 export interface ImageProps {
65 /**
66 * Server to snapshot. Required on create. Changing the source Server
67 * replaces the Image (Hetzner cannot re-snapshot onto an existing Image).
68 * Accepts a `Hetzner.Server` or `{ serverId }`.
69 */
70 server: Ref<ImageServer>;
71 /**
72 * Human-readable description. Snapshots have no unique `name` (that
73 * field is only set on system Images). If omitted, a unique description
74 * is generated from the stack, stage and logical ID.
75 */
76 description?: string;
77 /**
78 * Image type. Snapshots are independent of the source Server and billed
79 * per GB. Backups are bound to the Server (and deleted with it) and
80 * require backups to be enabled. Convert a backup to a snapshot in
81 * place; snapshot → backup replaces.
82 *
83 * @default "snapshot"
84 */
85 type?: ImageType;
86 /**
87 * User-defined labels. Alchemy ownership labels (`alchemy.stack` /
88 * `alchemy.stage` / `alchemy.id`) are always merged in.
89 */
90 labels?: Record<string, string>;
91 /**
92 * Prevent the Image from being deleted via the API. Only valid on
93 * snapshots.
94 *
95 * @default false
96 */
97 deleteProtection?: boolean;
98 }
99
100 export type Image = Resource<
101 "Hetzner.Image",
102 ImageProps,
103 {
104 /** Numeric Hetzner Image ID. */
105 id: number;
106 /** Image type (`snapshot` or `backup`). */
107 type: ImageType;
108 /** Image status. */
109 status: ImageStatus;
110 /**
111 * Unique identifier. Only set for system Images — snapshots and
112 * backups are `null`.
113 */
114 name: string | null;
115 /** Human-readable description. */
116 description: string;
117 /**
118 * Size of the Image file in Hetzner storage in GB. Relevant for
119 * snapshot billing. `null` while the Image is still creating.
120 */
121 imageSize: number | null;
122 /** Size of the disk contained in the Image in GB. */
123 diskSize: number;
124 /** RFC3339 creation timestamp. */
125 created: string;
126 /** ID of the Server this Image was created from, or `null`. */
127 createdFromId: number | null;
128 /** Server name at snapshot time, or `null`. */
129 createdFromName: string | null;
130 /**
131 * Server ID this Image is bound to. Only set for `backup` Images.
132 */
133 boundTo: number | null;
134 /** Flavor of operating system contained in the Image. */
135 osFlavor: ImageOsFlavor;
136 /** Operating system version, or `null`. */
137 osVersion: string | null;
138 /** Whether rapid deploy of the Image is available. */
139 rapidDeploy: boolean | undefined;
140 /** Whether delete protection is enabled. */
141 deleteProtection: boolean;
142 /** RFC3339 deprecation timestamp, or `null`. */
143 deprecated: string | null;
144 /** CPU architecture compatible with the Image. */
145 architecture: ImageArchitecture;
146 /** User-defined labels (Alchemy ownership labels stripped). */
147 labels: Record<string, string>;
148 },
149 never,
150 Providers
151 >;
152
153 /**
154 * A Hetzner Cloud custom Image — a snapshot (or backup) of a Server's
155 * disk. Stock system/app Images (`ubuntu-24.04`, …) are Catalog lookups
156 * via `Hetzner.findImage`, not this resource.
157 *
158 * Snapshots are created with `POST /servers/{id}/actions/create_image`
159 * and billed per GB. Description, labels, delete protection, and
160 * backup→snapshot conversion update in place. Changing the source Server
161 * replaces the Image.
162 *
163 * @see https://docs.hetzner.cloud/reference/cloud#images
164 *
165 * ### Creating a Snapshot
166 * **Example:** Snapshot from a Server
167 * ```typescript
168 * const server = yield* Hetzner.Server("web", {
169 * serverType: "cx22",
170 * image: "ubuntu-24.04",
171 * location: "nbg1",
172 * });
173 * const image = yield* Hetzner.Image("golden", {
174 * server,
175 * description: "golden-web",
176 * labels: { role: "golden" },
177 * });
178 * ```
179 *
180 * **Example:** Snapshot with generated description
181 * ```typescript
182 * const image = yield* Hetzner.Image("backup", {
183 * server: { serverId: 42 },
184 * });
185 * ```
186 *
187 * ### Updating a Snapshot
188 * **Example:** Description, labels, and protection
189 * ```typescript
190 * const image = yield* Hetzner.Image("golden", {
191 * server,
192 * description: "golden-web-v2",
193 * labels: { role: "golden", env: "prod" },
194 * deleteProtection: true,
195 * });
196 * ```
197 *
198 * @resource
199 * @product Server
200 */
201 export const Image = Resource<Image>("Hetzner.Image");
202
203 type CloudImage =
204 | GetImageResponseImage
205 | ListImagesResponseImagesItem
206 | CreateServerImageResponseImage
207 | UpdateImageResponseImage;
208
209 class ImagePending extends Data.TaggedError("ImagePending")<{
210 imageId: number;
211 status: string;
212 }> {}
213
214 class ImageTimeout extends Data.TaggedError("ImageTimeout")<{
215 imageId: number;
216 status: string;
217 }> {}
218
219 class ImageNotResolved extends Data.TaggedError("Hetzner.ImageNotResolved")<{
220 serverId: number;
221 description: string;
222 }> {}
223
224 class ImageServerRequired extends Data.TaggedError("Hetzner.ImageServerRequired")<{
225 description: string;
226 }> {}
227
228 const DEFAULT_TYPE: ImageType = "snapshot";
229
230 const asType = (type: string): ImageType => (type === "backup" ? "backup" : "snapshot");
231
232 const asStatus = (status: string): ImageStatus =>
233 status === "creating" || status === "unavailable" ? status : "available";
234
235 const asArchitecture = (architecture: string): ImageArchitecture =>
236 architecture === "arm" ? "arm" : "x86";
237
238 const asOsFlavor = (flavor: string): ImageOsFlavor => {
239 switch (flavor) {
240 case "ubuntu":
241 case "centos":
242 case "debian":
243 case "fedora":
244 case "rocky":
245 case "alma":
246 case "opensuse":
247 case "unknown":
248 return flavor;
249 default:
250 return "unknown";
251 }
252 };
253
254 const userLabels = (
255 labels: Record<string, string | undefined> | null | undefined,
256 ): Record<string, string> => stripInternalLabels(tagRecord(labels));
257
258 const toAttrs = (image: CloudImage): Image["Attributes"] => ({
259 id: image.id,
260 type: asType(image.type),
261 status: asStatus(image.status),
262 name: image.name,
263 description: image.description,
264 imageSize: image.image_size,
265 diskSize: image.disk_size,
266 created: image.created,
267 createdFromId: image.created_from?.id ?? null,
268 createdFromName: image.created_from?.name ?? null,
269 boundTo: image.bound_to,
270 osFlavor: asOsFlavor(image.os_flavor),
271 osVersion: image.os_version,
272 rapidDeploy: image.rapid_deploy,
273 deleteProtection: image.protection.delete,
274 deprecated: image.deprecated,
275 architecture: asArchitecture(image.architecture),
276 labels: userLabels(image.labels),
277 });
278
279 const retryable = (e: { readonly _tag: string }): boolean =>
280 e._tag === "ImagePending" ||
281 e._tag === "TooManyRequests" ||
282 e._tag === "ServiceUnavailable" ||
283 e._tag === "InternalServerError" ||
284 e._tag === "BadGateway" ||
285 e._tag === "GatewayTimeout" ||
286 e._tag === "Locked";
287
288 const backoff = Schedule.min([
289 Schedule.exponential(Duration.millis(500), 1.5),
290 Schedule.spaced(Duration.seconds(5)),
291 ]);
292
293 const toDescription = (id: string, description: string | undefined, existing?: string) =>
294 Effect.gen(function* () {
295 return (
296 description ??
297 existing ??
298 (yield* createPhysicalName({ id, maxLength: MAX_DESCRIPTION_LENGTH }))
299 );
300 });
301
302 const getById = (id: number) =>
303 Hetzner.images.getImage({ id }).pipe(
304 Effect.map(({ image }) => image),
305 Effect.catchTag("NotFound", () => Effect.undefined),
306 );
307
308 const getByLabels = (labels: Record<string, string>) =>
309 Hetzner.images
310 .listImages({
311 type: ["snapshot", "backup"],
312 label_selector: labelSelector(labels),
313 per_page: 50,
314 })
315 .pipe(Effect.map(({ images }) => images[0]));
316
317 const observe = Effect.fn(function* ({ id, outputId }: { id: string; outputId?: number }) {
318 if (outputId !== undefined) {
319 const byId = yield* getById(outputId);
320 if (byId !== undefined) return byId;
321 }
322 const internal = yield* createInternalLabels(id);
323 return yield* getByLabels(internal);
324 });
325
326 const waitUntilAvailable = (imageId: number) =>
327 getById(imageId).pipe(
328 Effect.flatMap((image) =>
329 image !== undefined && image.status === "available"
330 ? Effect.succeed(image)
331 : Effect.fail(
332 new ImagePending({
333 imageId,
334 status: image?.status ?? "missing",
335 }),
336 ),
337 ),
338 Effect.retry({
339 while: retryable,
340 times: 10,
341 schedule: Schedule.spaced(Duration.seconds(5)),
342 }),
343 Effect.catchTag(
344 "ImagePending",
345 (e) =>
346 new ImageTimeout({
347 imageId: e.imageId,
348 status: e.status,
349 }),
350 ),
351 );
352
353 const waitUntilGone = (imageId: number) =>
354 Hetzner.images.getImage({ id: imageId }).pipe(
355 Effect.map(() => false),
356 Effect.catchTag("NotFound", () => Effect.succeed(true)),
357 Effect.repeat({
358 schedule: Schedule.spaced(Duration.seconds(1)),
359 until: (gone) => gone,
360 times: 10,
361 }),
362 );
363
364 const serverIdOf = (value: unknown): number | undefined => {
365 if (value == null || typeof value !== "object") return undefined;
366 const id = (value as { serverId?: unknown }).serverId;
367 return typeof id === "number" ? id : undefined;
368 };
369
370 const disableProtection = (id: number) =>
371 Hetzner.imageActions
372 .changeImageProtection({ id, delete: false })
373 .pipe(Effect.flatMap(({ action }) => waitForAction(action)));
374
375 export const ImageProvider = () =>
376 Provider.succeed(Image, {
377 stables: ["id", "created", "createdFromId", "architecture", "diskSize", "osFlavor"],
378 list: Effect.fn(function* () {
379 const items = yield* Hetzner.images.listImages
380 .items({
381 type: ["snapshot", "backup"],
382 label_selector: alchemyStackSelector,
383 per_page: 50,
384 })
385 .pipe(
386 Stream.runCollect,
387 Effect.map((chunk) => Array.from(chunk)),
388 );
389 return items.map(toAttrs);
390 }),
391 diff: Effect.fn(function* ({ news, output }) {
392 if (!isResolved(news)) return undefined;
393 if (output !== undefined) {
394 const nextServerId = serverIdOf(news.server);
395 if (
396 nextServerId !== undefined &&
397 output.createdFromId !== null &&
398 nextServerId !== output.createdFromId
399 ) {
400 return { action: "replace" } as const;
401 }
402 const nextType = news.type ?? DEFAULT_TYPE;
403 if (nextType === "backup" && output.type === "snapshot") {
404 return { action: "replace" } as const;
405 }
406 }
407 return undefined;
408 }),
409 read: Effect.fn(function* ({ id, output }) {
410 const found = yield* observe({
411 id,
412 outputId: output?.id,
413 });
414 if (found === undefined) return undefined;
415 const attrs = toAttrs(found);
416 const owned = yield* hasAlchemyLabels(id, tagRecord(found.labels));
417 return owned ? attrs : Unowned(attrs);
418 }),
419 reconcile: Effect.fn(function* ({ id, news, output }) {
420 const description = yield* toDescription(id, news.description, output?.description);
421 const internalLabels = yield* createInternalLabels(id);
422 const desiredLabels = {
423 ...toLabels(news.labels),
424 ...internalLabels,
425 };
426 const desiredType = news.type ?? DEFAULT_TYPE;
427 const desiredProtection = news.deleteProtection ?? false;
428 const desiredServerId = serverIdOf(news.server);
429
430 // Observe by id only. Do not fall back to ownership labels — a
431 // create-first replacement still has the old generation live under
432 // the same logical id, and snapshots are not uniquely named.
433 let current = output?.id !== undefined ? yield* getById(output.id) : undefined;
434
435 if (current === undefined) {
436 if (desiredServerId === undefined) {
437 return yield* new ImageServerRequired({ description });
438 }
439 const created = yield* Hetzner.serverActions.createServerImage({
440 id: desiredServerId,
441 description,
442 type: desiredType,
443 labels: desiredLabels,
444 });
445 const imageId =
446 created.image?.id ??
447 created.action?.resources.find((resource) => resource.type === "image")?.id;
448 if (imageId === undefined) {
449 return yield* new ImageNotResolved({
450 serverId: desiredServerId,
451 description,
452 });
453 }
454 if (created.action) {
455 yield* waitForAction(created.action).pipe(
456 Effect.catchTag("ActionTimeout", () => Effect.void),
457 );
458 }
459 current = yield* waitUntilAvailable(imageId);
460 }
461
462 const observedLabels = tagRecord(current.labels);
463 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
464 const labelsChanged = upsert.length > 0 || removed.length > 0;
465 const convertToSnapshot = current.type === "backup" && desiredType === "snapshot";
466 const descriptionChanged = current.description !== description;
467 if (descriptionChanged || labelsChanged || convertToSnapshot) {
468 const updated = yield* Hetzner.images.updateImage({
469 id: current.id,
470 description: descriptionChanged ? description : undefined,
471 type: convertToSnapshot ? "snapshot" : undefined,
472 labels: labelsChanged ? desiredLabels : undefined,
473 });
474 current = updated.image ?? (yield* waitUntilAvailable(current.id));
475 }
476
477 if (current.protection.delete !== desiredProtection) {
478 const { action } = yield* Hetzner.imageActions.changeImageProtection({
479 id: current.id,
480 delete: desiredProtection,
481 });
482 yield* waitForAction(action);
483 current = (yield* getById(current.id)) ?? current;
484 }
485
486 return toAttrs(current);
487 }),
488 delete: Effect.fn(function* ({ output }) {
489 const current = yield* getById(output.id);
490 if (current === undefined) return;
491
492 if (current.protection.delete) {
493 yield* disableProtection(current.id);
494 }
495
496 yield* Hetzner.images.deleteImage({ id: current.id }).pipe(
497 Effect.catchTag("NotFound", () => Effect.void),
498 Effect.retry({
499 while: retryable,
500 times: 8,
501 schedule: backoff,
502 }),
503 );
504 yield* waitUntilGone(current.id);
505 }),
506 });