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

main
ts 430 lines 13.5 KB
Raw
1 import * as Hetzner from "@distilled.cloud/hetzner";
2 import type { GetPrimaryIpResponsePrimaryIp } from "@distilled.cloud/hetzner/primary_ips";
3 import { Unowned } from "alchemy/AdoptPolicy";
4 import { isResolved } from "alchemy/Diff";
5 import { createPhysicalName } from "alchemy/PhysicalName";
6 import * as Provider from "alchemy/Provider";
7 import { Resource } from "alchemy/Resource";
8 import { tagRecord } from "alchemy/Tags";
9 import * as Data from "effect/Data";
10 import * as Duration from "effect/Duration";
11 import * as Effect from "effect/Effect";
12 import * as Schedule from "effect/Schedule";
13 import * as Stream from "effect/Stream";
14 import { waitForAction } from "./actions.ts";
15 import { findLocation } from "./Catalog.ts";
16 import {
17 alchemyStackSelector,
18 createInternalLabels,
19 diffLabels,
20 hasAlchemyLabels,
21 stripInternalLabels,
22 toLabels,
23 } from "./Labels.ts";
24 import type { Providers } from "./Providers.ts";
25
26 export type PrimaryIpType = "ipv4" | "ipv6";
27
28 export interface PrimaryIpProps {
29 /**
30 * Address family. Cannot be changed after creation — changing it
31 * triggers a replacement.
32 */
33 type: PrimaryIpType;
34 /**
35 * Location name (`nbg1`, `fsn1`, `hel1`, …) or numeric Location ID.
36 * Required unless `datacenter` is set. Cannot be changed after
37 * creation — changing it triggers a replacement.
38 */
39 location?: string | number;
40 /**
41 * Datacenter name (`nbg1-dc3`, `fsn1-dc14`, …) or numeric Datacenter
42 * ID. Alternative to `location`; a name is mapped onto the parent
43 * Location (`nbg1-dc3` → `nbg1`). Cannot be changed after creation —
44 * changing it triggers a replacement.
45 */
46 datacenter?: string | number;
47 /**
48 * Name of the Primary IP. Must be unique per Hetzner project. If
49 * omitted, a unique name is generated from the stack, stage, and
50 * logical ID.
51 */
52 name?: string;
53 /**
54 * If enabled, Hetzner deletes this Primary IP when its assigned
55 * resource is deleted.
56 * @default false
57 */
58 autoDelete?: boolean;
59 /**
60 * User-defined labels (`key`/`value` pairs) applied to the Primary IP.
61 * Alchemy ownership labels are added automatically.
62 */
63 labels?: Record<string, string>;
64 /**
65 * Prevent the Primary IP from being deleted via the API.
66 * @default false
67 */
68 deleteProtection?: boolean;
69 }
70
71 export type PrimaryIp = Resource<
72 "Hetzner.PrimaryIp",
73 PrimaryIpProps,
74 {
75 /**
76 * Numeric Hetzner ID of the Primary IP.
77 */
78 id: number;
79 /**
80 * Name of the Primary IP.
81 */
82 name: string;
83 /**
84 * Address family of the Primary IP.
85 */
86 type: PrimaryIpType;
87 /**
88 * Assigned address. For `ipv6` this is the `/64` network.
89 */
90 ip: string;
91 /**
92 * Location name the IP is bound to (`nbg1`, `fsn1`, …).
93 */
94 location: string;
95 /**
96 * Numeric Location id.
97 */
98 locationId: number;
99 /**
100 * Datacenter name or id from props, when the resource was placed via
101 * `datacenter`. Not returned by the API.
102 */
103 datacenter: string | undefined;
104 /**
105 * Whether Hetzner has blocked the Primary IP.
106 */
107 blocked: boolean;
108 /**
109 * Auto-delete flag.
110 */
111 autoDelete: boolean;
112 /**
113 * Assigned resource id, or `null` if unassigned.
114 */
115 assigneeId: number | null;
116 /**
117 * Assigned resource type (`server`), when assigned.
118 */
119 assigneeType: string | undefined;
120 /**
121 * RFC3339 timestamp when the Primary IP was created.
122 */
123 created: string;
124 /**
125 * User-defined labels (Alchemy ownership labels are stripped).
126 */
127 labels: Record<string, string>;
128 /**
129 * Whether delete protection is enabled.
130 */
131 deleteProtection: boolean;
132 },
133 never,
134 Providers
135 >;
136
137 /**
138 * An unassigned Hetzner Cloud Primary IP. Provide `type` and either a
139 * `location` or a `datacenter`; Alchemy generates a unique name unless
140 * you set `name`. Assignee wiring is a later resource.
141 *
142 * `type`, `location`, and `datacenter` are immutable — changing any of
143 * them replaces the Primary IP (new address). `name`, `autoDelete`,
144 * `labels`, and `deleteProtection` update in place.
145 *
146 * @see https://docs.hetzner.cloud/reference/cloud#primary-ips
147 *
148 * ### Creating a Primary IP
149 * **Example:** IPv6 in Nuremberg
150 * ```typescript
151 * const ip = yield* Hetzner.PrimaryIp("web-ipv6", {
152 * type: "ipv6",
153 * location: "nbg1",
154 * });
155 * ```
156 *
157 * **Example:** IPv4 placed by datacenter
158 * ```typescript
159 * const ip = yield* Hetzner.PrimaryIp("web-ipv4", {
160 * type: "ipv4",
161 * datacenter: "nbg1-dc3",
162 * });
163 * ```
164 *
165 * ### Labels and auto-delete
166 * **Example:** Named IP with labels
167 * ```typescript
168 * const ip = yield* Hetzner.PrimaryIp("mail", {
169 * name: "mail-ipv4",
170 * type: "ipv4",
171 * location: "fsn1",
172 * autoDelete: false,
173 * labels: { role: "mail" },
174 * });
175 * ```
176 *
177 * @resource
178 * @product IP Address
179 */
180 export const PrimaryIp = Resource<PrimaryIp>("Hetzner.PrimaryIp");
181
182 export class PrimaryIpPlacementRequired extends Data.TaggedError(
183 "Hetzner.PrimaryIpPlacementRequired",
184 )<{ message: string }> {}
185
186 type CloudPrimaryIp = GetPrimaryIpResponsePrimaryIp;
187
188 const asType = (type: string): PrimaryIpType => (type === "ipv6" ? "ipv6" : "ipv4");
189
190 const userLabels = (
191 labels: Record<string, string | undefined> | null | undefined,
192 ): Record<string, string> => stripInternalLabels(tagRecord(labels));
193
194 /**
195 * Hetzner datacenter names are `{location}-dc{n}` (e.g. `nbg1-dc3`).
196 * Numeric ids are passed through — Locations use a different id space.
197 */
198 export const locationFromDatacenter = (datacenter: string | number): string | number => {
199 if (typeof datacenter === "number") return datacenter;
200 const match = /^([a-z0-9]+)-dc\d+$/i.exec(datacenter);
201 return match ? match[1]!.toLowerCase() : datacenter;
202 };
203
204 const resolvePlacement = (
205 props: Pick<PrimaryIpProps, "location" | "datacenter">,
206 ): string | number | undefined => {
207 if (props.location !== undefined) return props.location;
208 if (props.datacenter !== undefined) {
209 return locationFromDatacenter(props.datacenter);
210 }
211 return undefined;
212 };
213
214 const samePlacement = (
215 news: Pick<PrimaryIpProps, "location" | "datacenter">,
216 attrs: PrimaryIp["Attributes"],
217 ): boolean => {
218 const desired = resolvePlacement(news);
219 if (desired === undefined) return true;
220 return (
221 desired === attrs.location ||
222 desired === attrs.locationId ||
223 String(desired) === String(attrs.locationId)
224 );
225 };
226
227 const toAttrs = (
228 ip: CloudPrimaryIp,
229 extras?: { datacenter?: string | number },
230 ): PrimaryIp["Attributes"] => ({
231 id: ip.id,
232 name: ip.name,
233 type: asType(ip.type),
234 ip: ip.ip,
235 location: ip.location.name,
236 locationId: ip.location.id,
237 datacenter: extras?.datacenter !== undefined ? String(extras.datacenter) : undefined,
238 blocked: ip.blocked,
239 autoDelete: ip.auto_delete,
240 assigneeId: ip.assignee_id,
241 assigneeType: ip.assignee_type,
242 created: ip.created,
243 labels: userLabels(ip.labels),
244 deleteProtection: ip.protection.delete,
245 });
246
247 const createPrimaryIpName = (id: string, name: string | undefined, existing?: string) =>
248 Effect.gen(function* () {
249 return name ?? existing ?? (yield* createPhysicalName({ id, maxLength: 63 }));
250 });
251
252 const getById = (id: number) =>
253 Hetzner.primaryIps.getPrimaryIp({ id }).pipe(
254 Effect.map(({ primary_ip }) => primary_ip),
255 Effect.catchTag("NotFound", () => Effect.undefined),
256 );
257
258 const getByName = (name: string) =>
259 Hetzner.primaryIps
260 .listPrimaryIps({ name, per_page: 50 })
261 .pipe(Effect.map(({ primary_ips }) => primary_ips[0]));
262
263 const observe = Effect.fn(function* ({
264 name,
265 outputId,
266 }: {
267 id: string;
268 name?: string;
269 outputId?: number;
270 }) {
271 // Identity is the numeric id (cached on `output`) or the unique
272 // project-scoped name. Do NOT fall back to alchemy.* labels: a
273 // replacement shares the logical id with the old generation, so a
274 // label lookup would adopt the IP we are replacing.
275 if (outputId !== undefined) {
276 const byId = yield* getById(outputId);
277 if (byId !== undefined) return byId;
278 }
279 if (name !== undefined) {
280 return yield* getByName(name);
281 }
282 return undefined;
283 });
284
285 const refresh = (id: number) =>
286 Hetzner.primaryIps.getPrimaryIp({ id }).pipe(
287 Effect.map(({ primary_ip }) => primary_ip),
288 Effect.retry({
289 while: (e) => e._tag === "NotFound",
290 times: 5,
291 schedule: Schedule.min([
292 Schedule.exponential(Duration.millis(200), 1.5),
293 Schedule.spaced(Duration.seconds(2)),
294 ]),
295 }),
296 );
297
298 const disableProtection = (id: number) =>
299 Hetzner.primaryIpActions
300 .changePrimaryIpProtection({ id, delete: false })
301 .pipe(Effect.flatMap(({ action }) => waitForAction(action)));
302
303 export const PrimaryIpProvider = () =>
304 Provider.succeed(PrimaryIp, {
305 stables: ["id", "ip", "type", "location", "locationId", "created"],
306 nuke: { dependsOn: ["Hetzner.Server"] },
307 list: Effect.fn(function* () {
308 const items = yield* Hetzner.primaryIps.listPrimaryIps
309 .items({ label_selector: alchemyStackSelector, per_page: 50 })
310 .pipe(
311 Stream.runCollect,
312 Effect.map((chunk) => Array.from(chunk)),
313 );
314 return items.map((ip) => toAttrs(ip));
315 }),
316 diff: Effect.fn(function* ({ news, output }) {
317 if (!isResolved(news)) return undefined;
318 if (output !== undefined) {
319 if (news.type !== output.type) {
320 return { action: "replace" } as const;
321 }
322 if (!samePlacement(news, output)) {
323 return { action: "replace" } as const;
324 }
325 }
326 return undefined;
327 }),
328 read: Effect.fn(function* ({ id, olds, output }) {
329 const found = yield* observe({ id, name: olds?.name ?? output?.name, outputId: output?.id });
330 if (found === undefined) return undefined;
331 const attrs = toAttrs(found, { datacenter: olds?.datacenter ?? output?.datacenter });
332 const owned = yield* hasAlchemyLabels(id, tagRecord(found.labels));
333 return owned ? attrs : Unowned(attrs);
334 }),
335 reconcile: Effect.fn(function* ({ id, news, output }) {
336 const name = yield* createPrimaryIpName(id, news.name, output?.name);
337 const internalLabels = yield* createInternalLabels(id);
338 const desiredLabels = { ...toLabels(news.labels), ...internalLabels };
339 const desiredAutoDelete = news.autoDelete ?? false;
340 const desiredProtection = news.deleteProtection ?? false;
341
342 // Observe — cloud state is authoritative. `output.id` is a cache
343 // for the stable identifier; if the IP is gone, we recreate.
344 let current = yield* observe({ id, name, outputId: output?.id });
345
346 // Ensure — create only when missing. A Conflict is a race with a
347 // peer reconciler or a name that just became visible; re-observe.
348 if (current === undefined) {
349 const placement = resolvePlacement(news);
350 if (placement === undefined) {
351 return yield* new PrimaryIpPlacementRequired({
352 message: "PrimaryIp requires `location` or `datacenter` when creating",
353 });
354 }
355 const location = yield* findLocation(placement);
356 const created = yield* Hetzner.primaryIps
357 .createPrimaryIp({
358 name,
359 type: news.type,
360 location: location.name,
361 labels: desiredLabels,
362 auto_delete: desiredAutoDelete,
363 })
364 .pipe(
365 Effect.catchTag("Conflict", () =>
366 observe({ id, name }).pipe(
367 Effect.flatMap((hit) =>
368 hit !== undefined
369 ? Effect.succeed({ primary_ip: hit, action: undefined })
370 : Hetzner.primaryIps.createPrimaryIp({
371 name,
372 type: news.type,
373 location: location.name,
374 labels: desiredLabels,
375 auto_delete: desiredAutoDelete,
376 }),
377 ),
378 ),
379 ),
380 );
381 if (created.action) {
382 yield* waitForAction(created.action);
383 }
384 current = created.primary_ip;
385 }
386
387 // Sync — name / auto_delete / labels via PUT (labels overwrite the
388 // full set). Protection is a separate Action.
389 const observedLabels = tagRecord(current.labels);
390 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
391 const needsUpdate =
392 current.name !== name ||
393 current.auto_delete !== desiredAutoDelete ||
394 upsert.length > 0 ||
395 removed.length > 0;
396 if (needsUpdate) {
397 const updated = yield* Hetzner.primaryIps.updatePrimaryIp({
398 id: current.id,
399 name,
400 auto_delete: desiredAutoDelete,
401 labels: desiredLabels,
402 });
403 current = updated.primary_ip;
404 }
405
406 if (current.protection.delete !== desiredProtection) {
407 const { action } = yield* Hetzner.primaryIpActions.changePrimaryIpProtection({
408 id: current.id,
409 delete: desiredProtection,
410 });
411 yield* waitForAction(action);
412 }
413
414 return toAttrs(yield* refresh(current.id), { datacenter: news.datacenter });
415 }),
416 delete: Effect.fn(function* ({ output }) {
417 const current = yield* getById(output.id);
418 if (current === undefined) return;
419 if (current.protection.delete) {
420 yield* disableProtection(current.id);
421 }
422 if (current.assignee_id !== null) {
423 const { action } = yield* Hetzner.primaryIpActions.unassignPrimaryIp({ id: current.id });
424 yield* waitForAction(action);
425 }
426 yield* Hetzner.primaryIps
427 .deletePrimaryIp({ id: current.id })
428 .pipe(Effect.catchTag("NotFound", () => Effect.void));
429 }),
430 });