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

main
ts 400 lines 12.5 KB
Raw
1 import * as Hetzner from "@distilled.cloud/hetzner";
2 import type { GetFloatingIpResponseFloatingIp } from "@distilled.cloud/hetzner/floating_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 labelSelector,
22 stripInternalLabels,
23 toLabels,
24 } from "./Labels.ts";
25 import type { Providers } from "./Providers.ts";
26
27 export type FloatingIpType = "ipv4" | "ipv6";
28
29 export interface FloatingIpProps {
30 /**
31 * Address family of the Floating IP. Cannot be changed after creation —
32 * changing it triggers a replacement.
33 */
34 type: FloatingIpType;
35 /**
36 * Home Location for the Floating IP (`nbg1`, `fsn1`, `hel1`, …) or the
37 * Location's numeric id. Routing is optimized for this Location. Cannot
38 * be changed after creation — changing it triggers a replacement.
39 */
40 homeLocation: string | number;
41 /**
42 * Name of the Floating IP. Must be unique per Hetzner project. If
43 * omitted, a unique name is generated from the stack, stage, and
44 * logical ID.
45 */
46 name?: string;
47 /**
48 * Free-form description shown in the Hetzner Cloud Console.
49 */
50 description?: string | null;
51 /**
52 * User-defined labels (`key`/`value` pairs) applied to the Floating IP.
53 * Alchemy ownership labels are added automatically.
54 */
55 labels?: Record<string, string>;
56 /**
57 * Prevent the Floating IP from being deleted via the API.
58 * @default false
59 */
60 deleteProtection?: boolean;
61 }
62
63 export type FloatingIp = Resource<
64 "Hetzner.FloatingIp",
65 FloatingIpProps,
66 {
67 /**
68 * Numeric Hetzner ID of the Floating IP.
69 */
70 id: number;
71 /**
72 * Name of the Floating IP.
73 */
74 name: string;
75 /**
76 * Address family of the Floating IP.
77 */
78 type: FloatingIpType;
79 /**
80 * Assigned address. For `ipv6` this is the `/64` network.
81 */
82 ip: string;
83 /**
84 * Home Location name (`nbg1`, `fsn1`, …).
85 */
86 homeLocation: string;
87 /**
88 * Numeric ID of the home Location.
89 */
90 homeLocationId: number;
91 /**
92 * Description of the Floating IP, or `null` if unset.
93 */
94 description: string | null;
95 /**
96 * Whether Hetzner has blocked the Floating IP.
97 */
98 blocked: boolean;
99 /**
100 * Whether delete protection is enabled.
101 */
102 deleteProtection: boolean;
103 /**
104 * User-defined labels (Alchemy ownership labels are stripped).
105 */
106 labels: Record<string, string>;
107 /**
108 * RFC3339 timestamp when the Floating IP was created.
109 */
110 created: string;
111 /**
112 * Numeric Server ID this Floating IP is assigned to, or `null` if
113 * unassigned. Assignment is managed by `FloatingIpAssignment`.
114 */
115 serverId: number | null;
116 },
117 never,
118 Providers
119 >;
120
121 /**
122 * An unassigned Hetzner Cloud Floating IP. Provide `type` and a
123 * `homeLocation`; Alchemy generates a unique name unless you set `name`.
124 * Assignment to a Server is a separate `FloatingIpAssignment` resource.
125 *
126 * `type` and `homeLocation` are immutable — changing either replaces the
127 * Floating IP (new address). `name`, `description`, `labels`, and
128 * `deleteProtection` update in place.
129 *
130 * @see https://docs.hetzner.cloud/reference/cloud#floating-ips
131 *
132 * ### Creating a Floating IP
133 * **Example:** Unassigned IPv4 in nbg1
134 * ```typescript
135 * const ip = yield* Hetzner.FloatingIp("public-ip", {
136 * type: "ipv4",
137 * homeLocation: "nbg1",
138 * });
139 * ```
140 *
141 * **Example:** IPv6 with description and labels
142 * ```typescript
143 * const ip = yield* Hetzner.FloatingIp("v6", {
144 * type: "ipv6",
145 * homeLocation: "nbg1",
146 * description: "edge anycast",
147 * labels: { role: "edge" },
148 * });
149 * ```
150 *
151 * ### Updating a Floating IP
152 * **Example:** Rename and relabel
153 * ```typescript
154 * const ip = yield* Hetzner.FloatingIp("public-ip", {
155 * type: "ipv4",
156 * homeLocation: "nbg1",
157 * name: "public-ip-prod",
158 * description: "production frontend",
159 * labels: { env: "prod" },
160 * });
161 * ```
162 *
163 * @resource
164 * @product IP Address
165 */
166 export const FloatingIp = Resource<FloatingIp>("Hetzner.FloatingIp");
167
168 type CloudFloatingIp = GetFloatingIpResponseFloatingIp;
169
170 const asType = (type: string): FloatingIpType => (type === "ipv6" ? "ipv6" : "ipv4");
171
172 const userLabels = (
173 labels: Record<string, string | undefined> | null | undefined,
174 ): Record<string, string> => stripInternalLabels(tagRecord(labels));
175
176 const toAttrs = (ip: CloudFloatingIp): FloatingIp["Attributes"] => ({
177 id: ip.id,
178 name: ip.name,
179 type: asType(ip.type),
180 ip: ip.ip,
181 homeLocation: ip.home_location.name,
182 homeLocationId: ip.home_location.id,
183 description: ip.description,
184 blocked: ip.blocked,
185 deleteProtection: ip.protection.delete,
186 labels: userLabels(ip.labels),
187 created: ip.created,
188 serverId: ip.server,
189 });
190
191 const createFloatingIpName = (id: string, name: string | undefined, existing?: string) =>
192 Effect.gen(function* () {
193 return name ?? existing ?? (yield* createPhysicalName({ id, maxLength: 63 }));
194 });
195
196 const getById = (id: number) =>
197 Hetzner.floatingIps.getFloatingIp({ id }).pipe(
198 Effect.map(({ floating_ip }) => floating_ip),
199 Effect.catchTag("NotFound", () => Effect.undefined),
200 );
201
202 const getByName = (name: string) =>
203 Hetzner.floatingIps
204 .listFloatingIps({ name, per_page: 50 })
205 .pipe(Effect.map(({ floating_ips }) => floating_ips[0]));
206
207 const getByLabels = (labels: Record<string, string>) =>
208 Hetzner.floatingIps
209 .listFloatingIps({ label_selector: labelSelector(labels), per_page: 50 })
210 .pipe(Effect.map(({ floating_ips }) => floating_ips[0]));
211
212 const observe = Effect.fn(function* ({
213 id,
214 name,
215 outputId,
216 }: {
217 id: string;
218 name?: string;
219 outputId?: number;
220 }) {
221 if (outputId !== undefined) {
222 const byId = yield* getById(outputId);
223 if (byId !== undefined) return byId;
224 }
225 if (name !== undefined) {
226 const byName = yield* getByName(name);
227 if (byName !== undefined) return byName;
228 }
229 const internal = yield* createInternalLabels(id);
230 return yield* getByLabels(internal);
231 });
232
233 const refresh = (id: number) =>
234 Hetzner.floatingIps.getFloatingIp({ id }).pipe(
235 Effect.map(({ floating_ip }) => floating_ip),
236 Effect.retry({
237 while: (e) => e._tag === "NotFound",
238 times: 5,
239 schedule: Schedule.min([
240 Schedule.exponential(Duration.millis(200), 1.5),
241 Schedule.spaced(Duration.seconds(2)),
242 ]),
243 }),
244 );
245
246 const sameHomeLocation = (
247 desired: string | number,
248 attrs: Pick<FloatingIp["Attributes"], "homeLocation" | "homeLocationId">,
249 ): boolean =>
250 desired === attrs.homeLocation ||
251 desired === attrs.homeLocationId ||
252 String(desired) === String(attrs.homeLocationId);
253
254 const matchesDesired = (
255 ip: CloudFloatingIp,
256 type: FloatingIpType,
257 location: { name: string; id: number },
258 ): boolean =>
259 asType(ip.type) === type &&
260 sameHomeLocation(location.name, {
261 homeLocation: ip.home_location.name,
262 homeLocationId: ip.home_location.id,
263 });
264
265 const disableProtection = (id: number) =>
266 Hetzner.floatingIpActions
267 .changeFloatingIpProtection({ id, delete: false })
268 .pipe(Effect.flatMap(({ action }) => waitForAction(action)));
269
270 export class FloatingIpNotCreated extends Data.TaggedError("Hetzner.FloatingIpNotCreated")<{
271 resourceName: string;
272 }> {}
273
274 export const FloatingIpProvider = () =>
275 Provider.succeed(FloatingIp, {
276 stables: ["id", "ip", "type", "homeLocation", "homeLocationId", "created"],
277 nuke: { dependsOn: ["Hetzner.Server"] },
278 list: Effect.fn(function* () {
279 const items = yield* Hetzner.floatingIps.listFloatingIps
280 .items({ label_selector: alchemyStackSelector, per_page: 50 })
281 .pipe(
282 Stream.runCollect,
283 Effect.map((chunk) => Array.from(chunk)),
284 );
285 return items.map(toAttrs);
286 }),
287 diff: Effect.fn(function* ({ news, output }) {
288 if (!isResolved(news)) return undefined;
289 if (output !== undefined) {
290 if (news.type !== output.type) {
291 return { action: "replace" } as const;
292 }
293 if (!sameHomeLocation(news.homeLocation, output)) {
294 return { action: "replace" } as const;
295 }
296 }
297 return undefined;
298 }),
299 read: Effect.fn(function* ({ id, olds, output }) {
300 const found = yield* observe({ id, name: olds?.name ?? output?.name, outputId: output?.id });
301 if (found === undefined) return undefined;
302 const attrs = toAttrs(found);
303 const owned = yield* hasAlchemyLabels(id, tagRecord(found.labels));
304 return owned ? attrs : Unowned(attrs);
305 }),
306 reconcile: Effect.fn(function* ({ id, news, output }) {
307 const location = yield* findLocation(news.homeLocation);
308 const name = yield* createFloatingIpName(id, news.name, output?.name);
309 const internalLabels = yield* createInternalLabels(id);
310 const desiredLabels = { ...toLabels(news.labels), ...internalLabels };
311 const desiredDescription = news.description ?? null;
312 const desiredProtection = news.deleteProtection ?? false;
313
314 // Observe — cloud state is authoritative. `output.id` is a cache
315 // for the stable identifier; if the IP is gone, we recreate.
316 let current: CloudFloatingIp | undefined = yield* observe({ id, name, outputId: output?.id });
317 // A previous generation found via ownership labels (same logical id,
318 // different type/location) is the resource being replaced — do not
319 // take it over; create a new Floating IP instead.
320 if (
321 current !== undefined &&
322 current.id !== output?.id &&
323 !matchesDesired(current, news.type, location)
324 ) {
325 current = undefined;
326 }
327
328 // Ensure — create only when missing. A Conflict is a race with a
329 // peer reconciler or a name that just became visible; re-observe.
330 if (current === undefined) {
331 const created = yield* Hetzner.floatingIps
332 .createFloatingIp({
333 type: news.type,
334 home_location: location.name,
335 name,
336 description: desiredDescription,
337 labels: desiredLabels,
338 })
339 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
340 if (created !== undefined) {
341 if (created.action) {
342 yield* waitForAction(created.action);
343 }
344 current = created.floating_ip;
345 } else {
346 const hit = yield* observe({ id, name });
347 if (hit !== undefined && matchesDesired(hit, news.type, location)) {
348 current = hit;
349 }
350 }
351 }
352
353 if (current === undefined) {
354 return yield* new FloatingIpNotCreated({ resourceName: name });
355 }
356
357 // Sync — name / description / labels via PUT (labels overwrite the
358 // full set). Protection is a separate Action.
359 const observedLabels = tagRecord(current.labels);
360 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
361 const needsUpdate =
362 current.name !== name ||
363 (current.description ?? null) !== desiredDescription ||
364 upsert.length > 0 ||
365 removed.length > 0;
366 if (needsUpdate) {
367 const updated = yield* Hetzner.floatingIps.updateFloatingIp({
368 id: current.id,
369 name,
370 description: desiredDescription,
371 labels: desiredLabels,
372 });
373 current = updated.floating_ip;
374 }
375
376 if (current.protection.delete !== desiredProtection) {
377 const { action } = yield* Hetzner.floatingIpActions.changeFloatingIpProtection({
378 id: current.id,
379 delete: desiredProtection,
380 });
381 yield* waitForAction(action);
382 }
383
384 return toAttrs(yield* refresh(current.id));
385 }),
386 delete: Effect.fn(function* ({ output }) {
387 const current = yield* getById(output.id);
388 if (current === undefined) return;
389 if (current.protection.delete) {
390 yield* disableProtection(current.id);
391 }
392 if (current.server !== null) {
393 const { action } = yield* Hetzner.floatingIpActions.unassignFloatingIp({ id: current.id });
394 yield* waitForAction(action);
395 }
396 yield* Hetzner.floatingIps
397 .deleteFloatingIp({ id: current.id })
398 .pipe(Effect.catchTag("NotFound", () => Effect.void));
399 }),
400 });