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

main
ts 464 lines 15.1 KB
Raw
1 import * as Hetzner from "@distilled.cloud/hetzner";
2 import type {
3 GetVolumeResponseVolume,
4 ListVolumesResponseVolumesItem,
5 } from "@distilled.cloud/hetzner/volumes";
6 import { Unowned } from "alchemy/AdoptPolicy";
7 import { isResolved } from "alchemy/Diff";
8 import { createPhysicalName } from "alchemy/PhysicalName";
9 import * as Provider from "alchemy/Provider";
10 import { Resource } from "alchemy/Resource";
11 import { tagRecord } from "alchemy/Tags";
12 import * as Data from "effect/Data";
13 import * as Duration from "effect/Duration";
14 import * as Effect from "effect/Effect";
15 import * as Schedule from "effect/Schedule";
16 import * as Stream from "effect/Stream";
17 import { waitForAction, waitForActions } from "./actions.ts";
18 import {
19 alchemyStackSelector,
20 createInternalLabels,
21 diffLabels,
22 hasAlchemyLabels,
23 labelSelector,
24 stripInternalLabels,
25 toLabels,
26 } from "./Labels.ts";
27 import type { Providers } from "./Providers.ts";
28
29 const DEFAULT_LOCATION = "nbg1";
30 const MIN_SIZE_GB = 10;
31 const MAX_NAME_LENGTH = 64;
32
33 export type VolumeFormat = "ext4" | "xfs";
34
35 export type VolumeStatus = "available" | "creating";
36
37 /**
38 * A resource-valued prop: the resource itself, or an Effect that produces
39 * it (so `yield* Server(...)` and `Server(...)` both type-check).
40 */
41 type Ref<T> = T | Effect.Effect<T, never, Providers>;
42
43 /**
44 * Server identity a Volume can attach to at create time. Accepts a
45 * `Hetzner.Server` resource or a `{ serverId }` stub.
46 */
47 export type VolumeServer = { readonly serverId: number };
48
49 export interface VolumeProps {
50 /**
51 * Size of the Volume in GB. Minimum 10, maximum 10240. Increasing size
52 * updates in place (Hetzner cannot shrink a Volume — decreasing it
53 * replaces).
54 */
55 size: number;
56 /**
57 * Filesystem to format on create. One of `ext4` or `xfs`. Cannot be
58 * changed after creation — changing it replaces the Volume.
59 */
60 format?: VolumeFormat;
61 /**
62 * Location to create the Volume in (`nbg1`, `fsn1`, `hel1`, …). Required
63 * unless `server` is set (the Volume is then created in the Server's
64 * location). Cannot be changed after creation.
65 *
66 * @default "nbg1"
67 */
68 location?: string;
69 /**
70 * Volume name. Must be unique per project, 1–64 characters, alphanumeric
71 * with dashes/underscores/dots, starting and ending alphanumeric. If
72 * omitted, a unique name is generated from the stack, stage and logical
73 * ID.
74 */
75 name?: string;
76 /**
77 * User-defined labels. Alchemy ownership labels (`alchemy.stack` /
78 * `alchemy.stage` / `alchemy.id`) are always merged in.
79 */
80 labels?: Record<string, string>;
81 /**
82 * Server to attach the Volume to at create time. Accepts a
83 * `Hetzner.Server` or `{ serverId }`. Location may be omitted when this
84 * is set. Subsequent attach/detach is reconciled from the observed
85 * server.
86 */
87 server?: Ref<VolumeServer>;
88 /**
89 * Auto-mount the Volume after attach. Only used when `server` is set.
90 *
91 * @default false
92 */
93 automount?: boolean;
94 }
95
96 export type Volume = Resource<
97 "Hetzner.Volume",
98 VolumeProps,
99 {
100 /** Numeric Hetzner Volume ID. */
101 id: number;
102 /** Volume name (unique per project). */
103 name: string;
104 /** Size in GB. */
105 size: number;
106 /** Filesystem if formatted on creation. */
107 format: VolumeFormat | undefined;
108 /** Location name (`nbg1`, `fsn1`, …). */
109 location: string;
110 /** Numeric location ID. */
111 locationId: number;
112 /** Device path on the file system (e.g. `/dev/disk/by-id/scsi-…`). */
113 linuxDevice: string;
114 /** Volume status. */
115 status: VolumeStatus;
116 /** Attached Server ID, or `null` if unattached. */
117 serverId: number | null;
118 /** RFC3339 creation timestamp. */
119 created: string;
120 /** User-defined labels (Alchemy ownership labels stripped). */
121 labels: Record<string, string>;
122 },
123 never,
124 Providers
125 >;
126
127 /**
128 * A Hetzner Cloud Volume — a network block device that can be attached to
129 * a Server in the same Location. Unattached Volumes are valid; pass
130 * `server` to attach at create time.
131 *
132 * Size can grow in place (min 10 GB). Format and location are immutable
133 * (changing either replaces the Volume). Hetzner cannot shrink a Volume.
134 *
135 * @see https://docs.hetzner.cloud/reference/cloud#volumes
136 *
137 * ### Creating a Volume
138 * **Example:** Unattached Volume
139 * ```typescript
140 * const volume = yield* Hetzner.Volume("data", {
141 * size: 10,
142 * format: "ext4",
143 * location: "nbg1",
144 * });
145 * ```
146 *
147 * **Example:** Named Volume with labels
148 * ```typescript
149 * const volume = yield* Hetzner.Volume("data", {
150 * name: "app-data",
151 * size: 20,
152 * format: "xfs",
153 * location: "nbg1",
154 * labels: { role: "db" },
155 * });
156 * ```
157 *
158 * ### Attaching to a Server
159 * **Example:** Create-time attach
160 * ```typescript
161 * const server = yield* Hetzner.Server("web", {
162 * serverType: "cx22",
163 * image: "ubuntu-24.04",
164 * location: "nbg1",
165 * });
166 * const volume = yield* Hetzner.Volume("data", {
167 * size: 10,
168 * format: "ext4",
169 * server,
170 * automount: true,
171 * });
172 * ```
173 *
174 * @resource
175 * @product Volume
176 */
177 export const Volume = Resource<Volume>("Hetzner.Volume");
178
179 type CloudVolume = GetVolumeResponseVolume | ListVolumesResponseVolumesItem;
180
181 class VolumePending extends Data.TaggedError("VolumePending")<{
182 volumeId: number;
183 status: string;
184 }> {}
185
186 class VolumeTimeout extends Data.TaggedError("VolumeTimeout")<{
187 volumeId: number;
188 status: string;
189 }> {}
190
191 class VolumeNotCreated extends Data.TaggedError("Hetzner.VolumeNotCreated")<{
192 resourceName: string;
193 }> {}
194
195 const asFormat = (format: string | null | undefined): VolumeFormat | undefined =>
196 format === "ext4" || format === "xfs" ? format : undefined;
197
198 const userLabels = (
199 labels: Record<string, string | undefined> | null | undefined,
200 ): Record<string, string> => stripInternalLabels(tagRecord(labels));
201
202 const toAttrs = (volume: CloudVolume): Volume["Attributes"] => ({
203 id: volume.id,
204 name: volume.name,
205 size: volume.size,
206 format: asFormat(volume.format),
207 location: volume.location.name,
208 locationId: volume.location.id,
209 linuxDevice: volume.linux_device,
210 status: volume.status,
211 serverId: volume.server,
212 created: volume.created,
213 labels: userLabels(volume.labels),
214 });
215
216 const retryable = (e: { readonly _tag: string }): boolean =>
217 e._tag === "VolumePending" ||
218 e._tag === "TooManyRequests" ||
219 e._tag === "ServiceUnavailable" ||
220 e._tag === "InternalServerError" ||
221 e._tag === "BadGateway" ||
222 e._tag === "GatewayTimeout" ||
223 e._tag === "Locked";
224
225 const backoff = Schedule.min([
226 Schedule.exponential(Duration.millis(500), 1.5),
227 Schedule.spaced(Duration.seconds(5)),
228 ]);
229
230 const createVolumeName = (id: string, name: string | undefined, existing?: string) =>
231 Effect.gen(function* () {
232 return name ?? existing ?? (yield* createPhysicalName({ id, maxLength: MAX_NAME_LENGTH }));
233 });
234
235 const getById = (id: number) =>
236 Hetzner.volumes.getVolume({ id }).pipe(
237 Effect.map(({ volume }) => volume),
238 Effect.catchTag("NotFound", () => Effect.undefined),
239 );
240
241 const getByName = (name: string) =>
242 Hetzner.volumes
243 .listVolumes({ name, per_page: 50 })
244 .pipe(Effect.map(({ volumes }) => volumes.find((item) => item.name === name)));
245
246 const getByLabels = (labels: Record<string, string>) =>
247 Hetzner.volumes
248 .listVolumes({ label_selector: labelSelector(labels), per_page: 50 })
249 .pipe(Effect.map(({ volumes }) => volumes[0]));
250
251 const observe = Effect.fn(function* ({
252 id,
253 name,
254 outputId,
255 }: {
256 id: string;
257 name?: string;
258 outputId?: number;
259 }) {
260 if (outputId !== undefined) {
261 const byId = yield* getById(outputId);
262 if (byId !== undefined) return byId;
263 }
264 if (name !== undefined) {
265 const byName = yield* getByName(name);
266 if (byName !== undefined) return byName;
267 }
268 const internal = yield* createInternalLabels(id);
269 return yield* getByLabels(internal);
270 });
271
272 const waitUntilAvailable = (volumeId: number) =>
273 Hetzner.volumes.getVolume({ id: volumeId }).pipe(
274 Effect.flatMap(({ volume }) =>
275 volume.status === "available"
276 ? Effect.succeed(volume)
277 : Effect.fail(new VolumePending({ volumeId: volume.id, status: volume.status })),
278 ),
279 Effect.retry({ while: retryable, times: 10, schedule: backoff }),
280 Effect.catchTag(
281 "VolumePending",
282 (e) => new VolumeTimeout({ volumeId: e.volumeId, status: e.status }),
283 ),
284 );
285
286 const settleAction = (action: Parameters<typeof waitForAction>[0]) =>
287 waitForAction(action).pipe(Effect.catchTag("ActionTimeout", () => Effect.void));
288
289 const settleActions = (actions: Parameters<typeof waitForActions>[0]) =>
290 waitForActions(actions).pipe(Effect.catchTag("ActionTimeout", () => Effect.void));
291
292 const waitUntilGone = (volumeId: number) =>
293 Hetzner.volumes.getVolume({ id: volumeId }).pipe(
294 Effect.map(() => false),
295 Effect.catchTag("NotFound", () => Effect.succeed(true)),
296 Effect.repeat({
297 schedule: Schedule.spaced(Duration.seconds(1)),
298 until: (gone) => gone,
299 times: 10,
300 }),
301 );
302
303 const serverIdOf = (value: unknown): number | undefined => {
304 if (value == null || typeof value !== "object") return undefined;
305 const id = (value as { serverId?: unknown }).serverId;
306 return typeof id === "number" ? id : undefined;
307 };
308
309 export const VolumeProvider = () =>
310 Provider.succeed(Volume, {
311 stables: ["id", "linuxDevice", "location", "locationId", "created"],
312 list: Effect.fn(function* () {
313 const items = yield* Hetzner.volumes.listVolumes
314 .items({ label_selector: alchemyStackSelector, per_page: 50 })
315 .pipe(
316 Stream.runCollect,
317 Effect.map((chunk) => Array.from(chunk)),
318 );
319 return items.map(toAttrs);
320 }),
321 diff: Effect.fn(function* ({ news, output }) {
322 if (!isResolved(news)) return undefined;
323 if (output !== undefined) {
324 if (news.location !== undefined && news.location !== output.location) {
325 return { action: "replace" } as const;
326 }
327 if (news.format !== undefined && news.format !== output.format) {
328 return { action: "replace" } as const;
329 }
330 if (news.size < output.size) {
331 return { action: "replace" } as const;
332 }
333 }
334 return undefined;
335 }),
336 read: Effect.fn(function* ({ id, olds, output }) {
337 const found = yield* observe({ id, name: olds?.name ?? output?.name, outputId: output?.id });
338 if (found === undefined) return undefined;
339 const attrs = toAttrs(found);
340 const owned = yield* hasAlchemyLabels(id, tagRecord(found.labels));
341 return owned ? attrs : Unowned(attrs);
342 }),
343 reconcile: Effect.fn(function* ({ id, news, output }) {
344 const name = yield* createVolumeName(id, news.name, output?.name);
345 const internalLabels = yield* createInternalLabels(id);
346 const desiredLabels = { ...toLabels(news.labels), ...internalLabels };
347 const desiredServerId = serverIdOf(news.server);
348 const location =
349 news.location ?? (desiredServerId === undefined ? DEFAULT_LOCATION : undefined);
350
351 // Observe by id then desired name only. Do not fall back to
352 // ownership labels — a create-first replacement still has the old
353 // generation live under the same logical id.
354 let current = output?.id !== undefined ? yield* getById(output.id) : undefined;
355 if (current === undefined) {
356 current = yield* getByName(name);
357 }
358
359 // Ensure — create only when missing. A Conflict is a race with a
360 // peer reconciler or a name that just became visible; re-observe.
361 if (current === undefined) {
362 const created = yield* Hetzner.volumes
363 .createVolume({
364 name,
365 size: Math.max(news.size, MIN_SIZE_GB),
366 format: news.format,
367 location,
368 labels: desiredLabels,
369 server: desiredServerId,
370 automount: desiredServerId !== undefined ? news.automount : undefined,
371 })
372 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
373 if (created !== undefined) {
374 if (created.action) {
375 yield* settleActions([created.action, ...created.next_actions]);
376 }
377 current = yield* waitUntilAvailable(created.volume.id);
378 } else {
379 const hit = yield* getByName(name);
380 if (hit === undefined) {
381 return yield* new VolumeNotCreated({ resourceName: name });
382 }
383 current = yield* waitUntilAvailable(hit.id);
384 }
385 }
386
387 // Sync name + labels against observed cloud labels, not olds.
388 // updateVolume overwrites the full label set.
389 const observedLabels = tagRecord(current.labels);
390 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
391 const needsMeta = current.name !== name || upsert.length > 0 || removed.length > 0;
392 if (needsMeta) {
393 const updated = yield* Hetzner.volumes.updateVolume({
394 id: current.id,
395 name,
396 labels: desiredLabels,
397 });
398 current = updated.volume;
399 }
400
401 // Sync size — grow only. Shrink is a replacement (handled in diff).
402 if (news.size > current.size) {
403 const { action } = yield* Hetzner.volumeActions.resizeVolume({
404 id: current.id,
405 size: news.size,
406 });
407 yield* settleAction(action);
408 current = yield* waitUntilAvailable(current.id);
409 }
410
411 // Sync attach — create-time sugar also applies on later updates.
412 const observedServerId = current.server ?? undefined;
413 if (desiredServerId !== observedServerId) {
414 if (observedServerId !== undefined) {
415 const { action } = yield* Hetzner.volumeActions.detachVolume({ id: current.id });
416 yield* settleAction(action);
417 current = yield* waitUntilAvailable(current.id);
418 }
419 if (desiredServerId !== undefined) {
420 const { action } = yield* Hetzner.volumeActions.attachVolume({
421 id: current.id,
422 server: desiredServerId,
423 automount: news.automount,
424 });
425 yield* settleAction(action);
426 current = yield* waitUntilAvailable(current.id);
427 }
428 }
429
430 return toAttrs(current);
431 }),
432 delete: Effect.fn(function* ({ output }) {
433 const current = yield* getById(output.id);
434 if (current === undefined) return;
435
436 if (current.protection.delete) {
437 const { action } = yield* Hetzner.volumeActions.changeVolumeProtection({
438 id: current.id,
439 delete: false,
440 });
441 yield* settleAction(action);
442 }
443
444 const attached = current.server;
445 if (attached !== null) {
446 yield* Hetzner.volumeActions.detachVolume({ id: current.id }).pipe(
447 Effect.flatMap(({ action }) => settleAction(action)),
448 // Server delete detaches the Volume first; treat that race as
449 // already-detached.
450 Effect.catchTag(["NotFound", "UnprocessableEntity"], () => Effect.void),
451 );
452 }
453
454 yield* Hetzner.volumes.deleteVolume({ id: current.id }).pipe(
455 Effect.catchTag("NotFound", () => Effect.void),
456 Effect.retry({
457 while: (e) => retryable(e) || e._tag === "UnprocessableEntity",
458 times: 8,
459 schedule: backoff,
460 }),
461 );
462 yield* waitUntilGone(current.id);
463 }),
464 });