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

main
ts 601 lines 19 KB
Raw
1 import * as Hetzner from "@distilled.cloud/hetzner";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import { tagRecord } from "alchemy/Tags";
8 import * as Data from "effect/Data";
9 import * as Duration from "effect/Duration";
10 import * as Effect from "effect/Effect";
11 import * as Schedule from "effect/Schedule";
12 import * as Stream from "effect/Stream";
13 import { waitForAction } from "./actions.ts";
14 import {
15 alchemyStackSelector,
16 createInternalLabels,
17 diffLabels,
18 hasAlchemyLabels,
19 labelSelector,
20 stripInternalLabels,
21 toLabels,
22 } from "./Labels.ts";
23 import type { Providers } from "./Providers.ts";
24
25 export class NetworkNotCreated extends Data.TaggedError("Hetzner.NetworkNotCreated")<{
26 resourceName: string;
27 }> {}
28
29 export type NetworkSubnetType = "cloud" | "server" | "vswitch";
30
31 export interface NetworkSubnet {
32 /**
33 * Subnet type. `cloud` is the usual choice for Cloud Servers and Load
34 * Balancers. `vswitch` attaches a Robot vSwitch and requires `vswitchId`.
35 */
36 type: NetworkSubnetType;
37 /**
38 * IPv4 range of the subnet in CIDR notation. Must be a subnet of the
39 * parent network `ipRange` and must not overlap other subnets or route
40 * destinations. Minimum size is `/30`. If omitted on create, Hetzner
41 * allocates the first free `/24`.
42 */
43 ipRange?: string;
44 /**
45 * Network zone this subnet lives in (`eu-central`, `us-east`, `us-west`,
46 * `ap-southeast`). `nbg1` / `fsn1` / `hel1` are in `eu-central`.
47 */
48 networkZone: string;
49 /**
50 * Robot vSwitch id. Required when `type` is `vswitch`.
51 */
52 vswitchId?: number;
53 }
54
55 export interface NetworkRoute {
56 /**
57 * Destination prefix. Must be an RFC1918 IPv4 range or `0.0.0.0/0`, and
58 * must not overlap any subnet or other route destination.
59 */
60 destination: string;
61 /**
62 * Next-hop IP inside the network. Cannot be the first IP of the
63 * network's `ipRange` or `172.31.1.1`.
64 */
65 gateway: string;
66 }
67
68 export interface NetworkProps {
69 /**
70 * Name of the Network. Must be unique per project. If omitted, a unique
71 * name is generated from the app, stage, and logical ID.
72 */
73 name?: string;
74 /**
75 * IPv4 range of the whole Network in CIDR notation. Must be RFC1918 and
76 * at least `/24`. Can only be **extended** later (`change_ip_range`);
77 * shrinking or moving to a non-superset range replaces the Network.
78 */
79 ipRange: string;
80 /**
81 * Subnets allocated in this Network. Synced via `add_subnet` /
82 * `delete_subnet` — they are not their own resources.
83 */
84 subnets?: NetworkSubnet[];
85 /**
86 * Static routes in this Network. Synced via `add_route` / `delete_route`.
87 */
88 routes?: NetworkRoute[];
89 /**
90 * Expose this Network's routes to a connected Robot vSwitch.
91 * @default false
92 */
93 exposeRoutesToVswitch?: boolean;
94 /**
95 * Prevent the Network from being deleted in the Cloud Console / API
96 * until this is cleared. The provider disables protection before delete.
97 * @default false
98 */
99 deleteProtection?: boolean;
100 /**
101 * User-defined labels. Alchemy ownership labels (`alchemy.stack` /
102 * `alchemy.stage` / `alchemy.id`) are merged in automatically.
103 */
104 labels?: Record<string, string>;
105 }
106
107 export interface NetworkSubnetAttr extends NetworkSubnet {
108 /** Gateway Hetzner assigned to this subnet. */
109 gateway: string;
110 }
111
112 export type Network = Resource<
113 "Hetzner.Network",
114 NetworkProps,
115 {
116 /** Numeric Hetzner Network id. */
117 networkId: number;
118 /** Observed Network name. */
119 name: string;
120 /** Observed IPv4 range (CIDR). */
121 ipRange: string;
122 /** Observed subnets, including the assigned gateway. */
123 subnets: NetworkSubnetAttr[];
124 /** Observed static routes. */
125 routes: NetworkRoute[];
126 /** Server ids currently attached to this Network. */
127 servers: number[];
128 /** Load Balancer ids currently attached to this Network. */
129 loadBalancers: number[];
130 /** Whether delete protection is enabled. */
131 deleteProtection: boolean;
132 /** Whether routes are exposed to a connected vSwitch. */
133 exposeRoutesToVswitch: boolean;
134 /** User-facing labels (Alchemy ownership labels stripped). */
135 labels: Record<string, string>;
136 /** RFC3339 creation timestamp. */
137 created: string;
138 },
139 never,
140 Providers
141 >;
142
143 /**
144 * A Hetzner Cloud private Network — an isolated IPv4 range that Cloud
145 * Servers and Load Balancers attach to. Subnets, routes, delete protection,
146 * and labels are synced on the Network itself; `network_actions` are not
147 * modeled as their own resources.
148 *
149 * @see https://docs.hetzner.cloud/reference/cloud#networks
150 *
151 * ### Creating a Network
152 * **Example:** Basic Network
153 * ```typescript
154 * const network = yield* Hetzner.Network("vpc", {
155 * ipRange: "10.0.0.0/16",
156 * });
157 * ```
158 *
159 * **Example:** Network with a cloud subnet
160 * ```typescript
161 * const network = yield* Hetzner.Network("vpc", {
162 * ipRange: "10.0.0.0/16",
163 * subnets: [
164 * { type: "cloud", ipRange: "10.0.1.0/24", networkZone: "eu-central" },
165 * ],
166 * });
167 * ```
168 *
169 * ### Routes and protection
170 * **Example:** Static route and delete protection
171 * ```typescript
172 * const network = yield* Hetzner.Network("vpc", {
173 * ipRange: "10.0.0.0/16",
174 * subnets: [
175 * { type: "cloud", ipRange: "10.0.1.0/24", networkZone: "eu-central" },
176 * ],
177 * routes: [{ destination: "10.10.0.0/24", gateway: "10.0.1.2" }],
178 * deleteProtection: true,
179 * });
180 * ```
181 *
182 * ### Labels
183 * **Example:** User labels
184 * ```typescript
185 * const network = yield* Hetzner.Network("vpc", {
186 * ipRange: "10.0.0.0/16",
187 * labels: { env: "prod", role: "vpc" },
188 * });
189 * ```
190 *
191 * @resource
192 * @product Network
193 */
194 export const Network = Resource<Network>("Hetzner.Network");
195
196 type ObservedNetwork = {
197 id: number;
198 name: string;
199 ip_range: string;
200 subnets: ReadonlyArray<{
201 type: string;
202 ip_range?: string;
203 network_zone: string;
204 gateway: string;
205 vswitch_id?: number | null;
206 }>;
207 routes: ReadonlyArray<{ destination: string; gateway: string }>;
208 servers: ReadonlyArray<number>;
209 load_balancers?: ReadonlyArray<number>;
210 protection: { delete: boolean };
211 labels: Record<string, string | undefined>;
212 created: string;
213 expose_routes_to_vswitch: boolean;
214 };
215
216 const busy = (e: { readonly _tag: string }): boolean =>
217 e._tag === "Locked" || e._tag === "Conflict";
218
219 const busyRetry = {
220 while: busy,
221 times: 8,
222 schedule: Schedule.min([
223 Schedule.exponential(Duration.millis(500), 1.5),
224 Schedule.spaced(Duration.seconds(5)),
225 ]),
226 } as const;
227
228 const alreadyThere = (e: { readonly _tag: string }): boolean =>
229 e._tag === "Conflict" || e._tag === "UnprocessableEntity";
230
231 const alreadyGone = (e: { readonly _tag: string }): boolean =>
232 e._tag === "NotFound" || e._tag === "UnprocessableEntity";
233
234 const createNetworkName = (id: string, name: string | undefined) =>
235 Effect.gen(function* () {
236 return (
237 name ??
238 (yield* createPhysicalName({
239 id,
240 maxLength: 63,
241 lowercase: true,
242 }))
243 );
244 });
245
246 const desiredLabelsOf = Effect.fn(function* (
247 id: string,
248 labels: Record<string, string> | undefined,
249 ) {
250 return {
251 ...toLabels(labels),
252 ...(yield* createInternalLabels(id)),
253 };
254 });
255
256 const subnetKey = (subnet: {
257 type: string;
258 ipRange?: string;
259 networkZone: string;
260 vswitchId?: number | null;
261 }): string =>
262 `${subnet.type}|${subnet.ipRange ?? ""}|${subnet.networkZone}|${subnet.vswitchId ?? ""}`;
263
264 const routeKey = (route: { destination: string; gateway: string }): string =>
265 `${route.destination}|${route.gateway}`;
266
267 const toSubnetAttr = (subnet: ObservedNetwork["subnets"][number]): NetworkSubnetAttr => ({
268 type: subnet.type as NetworkSubnetType,
269 ipRange: subnet.ip_range,
270 networkZone: subnet.network_zone,
271 gateway: subnet.gateway,
272 vswitchId: subnet.vswitch_id ?? undefined,
273 });
274
275 const toAttrs = (network: ObservedNetwork): Network["Attributes"] => ({
276 networkId: network.id,
277 name: network.name,
278 ipRange: network.ip_range,
279 subnets: network.subnets.map(toSubnetAttr),
280 routes: network.routes.map((route) => ({
281 destination: route.destination,
282 gateway: route.gateway,
283 })),
284 servers: [...network.servers],
285 loadBalancers: [...(network.load_balancers ?? [])],
286 deleteProtection: network.protection.delete,
287 exposeRoutesToVswitch: network.expose_routes_to_vswitch,
288 labels: stripInternalLabels(tagRecord(network.labels)),
289 created: network.created,
290 });
291
292 const parseCidr = (cidr: string): { ip: number; prefix: number } | undefined => {
293 const [addr, prefixRaw] = cidr.split("/");
294 if (addr === undefined || prefixRaw === undefined) return undefined;
295 const parts = addr.split(".").map(Number);
296 if (
297 parts.length !== 4 ||
298 parts.some((part) => !Number.isInteger(part) || part < 0 || part > 255)
299 ) {
300 return undefined;
301 }
302 const prefix = Number(prefixRaw);
303 if (!Number.isInteger(prefix) || prefix < 0 || prefix > 32) return undefined;
304 const ip = ((parts[0]! << 24) | (parts[1]! << 16) | (parts[2]! << 8) | parts[3]!) >>> 0;
305 return { ip, prefix };
306 };
307
308 /** True when `outer` is equal to or a supernet of `inner`. */
309 const cidrContains = (outer: string, inner: string): boolean => {
310 const a = parseCidr(outer);
311 const b = parseCidr(inner);
312 if (a === undefined || b === undefined) return false;
313 if (a.prefix > b.prefix) return false;
314 const mask = a.prefix === 0 ? 0 : (0xffffffff << (32 - a.prefix)) >>> 0;
315 return (a.ip & mask) === (b.ip & mask);
316 };
317
318 const getById = (id: number) =>
319 Hetzner.networks.getNetwork({ id }).pipe(
320 Effect.map(({ network }) => network),
321 Effect.catchTag("NotFound", () => Effect.undefined),
322 );
323
324 const findByName = (name: string) =>
325 Hetzner.networks
326 .listNetworks({ name, per_page: 50 })
327 .pipe(Effect.map(({ networks }) => networks.find((item) => item.name === name)));
328
329 const findByLabels = (labels: Record<string, string>) =>
330 Hetzner.networks
331 .listNetworks({
332 label_selector: labelSelector(labels),
333 per_page: 50,
334 })
335 .pipe(Effect.map(({ networks }) => networks[0]));
336
337 const observe = (networkId: number | undefined, name: string, id: string) =>
338 Effect.gen(function* () {
339 if (networkId !== undefined) {
340 const byId = yield* getById(networkId);
341 if (byId) return byId;
342 }
343 const byLabels = yield* findByLabels(yield* createInternalLabels(id));
344 if (byLabels) return byLabels;
345 return yield* findByName(name);
346 });
347
348 const runAction = <E extends { readonly _tag: string }, R>(
349 effect: Effect.Effect<{ action: { id: number } }, E, R>,
350 ) =>
351 effect.pipe(
352 Effect.retry(busyRetry),
353 Effect.flatMap(({ action }) => waitForAction(action)),
354 );
355
356 const syncIpRange = (networkId: number, observed: string, desired: string) =>
357 Effect.gen(function* () {
358 if (observed === desired) return;
359 yield* runAction(
360 Hetzner.networkActions.changeNetworkIpRange({
361 id: networkId,
362 ip_range: desired,
363 }),
364 );
365 });
366
367 const syncMetadata = (args: {
368 networkId: number;
369 observed: ObservedNetwork;
370 name: string;
371 exposeRoutesToVswitch: boolean;
372 labels: Record<string, string>;
373 }) =>
374 Effect.gen(function* () {
375 const observedLabels = tagRecord(args.observed.labels);
376 const { removed, upsert } = diffLabels(observedLabels, args.labels);
377 const labelsChanged = removed.length > 0 || upsert.length > 0;
378 const nameChanged = args.observed.name !== args.name;
379 const exposeChanged = args.observed.expose_routes_to_vswitch !== args.exposeRoutesToVswitch;
380 if (!labelsChanged && !nameChanged && !exposeChanged) return;
381 yield* Hetzner.networks
382 .updateNetwork({
383 id: args.networkId,
384 name: nameChanged ? args.name : undefined,
385 expose_routes_to_vswitch: exposeChanged ? args.exposeRoutesToVswitch : undefined,
386 labels: labelsChanged ? args.labels : undefined,
387 })
388 .pipe(Effect.retry(busyRetry));
389 });
390
391 const syncSubnets = (
392 networkId: number,
393 observed: ObservedNetwork["subnets"],
394 desired: readonly NetworkSubnet[],
395 ) =>
396 Effect.gen(function* () {
397 const observedMapped = observed.map((subnet) => ({
398 type: subnet.type,
399 ipRange: subnet.ip_range,
400 networkZone: subnet.network_zone,
401 vswitchId: subnet.vswitch_id ?? undefined,
402 }));
403 const observedKeys = new Set(observedMapped.map(subnetKey));
404 const desiredKeys = new Set(desired.map(subnetKey));
405
406 for (const subnet of observedMapped) {
407 if (desiredKeys.has(subnetKey(subnet))) continue;
408 if (subnet.ipRange === undefined) continue;
409 yield* runAction(
410 Hetzner.networkActions.deleteNetworkSubnet({
411 id: networkId,
412 ip_range: subnet.ipRange,
413 }),
414 ).pipe(Effect.catchIf(alreadyGone, () => Effect.void));
415 }
416
417 for (const subnet of desired) {
418 if (observedKeys.has(subnetKey(subnet))) continue;
419 yield* runAction(
420 Hetzner.networkActions.addNetworkSubnet({
421 id: networkId,
422 type: subnet.type,
423 ip_range: subnet.ipRange,
424 network_zone: subnet.networkZone,
425 vswitch_id: subnet.vswitchId,
426 }),
427 ).pipe(Effect.catchIf(alreadyThere, () => Effect.void));
428 }
429 });
430
431 const syncRoutes = (
432 networkId: number,
433 observed: ObservedNetwork["routes"],
434 desired: readonly NetworkRoute[],
435 ) =>
436 Effect.gen(function* () {
437 const observedKeys = new Set(observed.map(routeKey));
438 const desiredKeys = new Set(desired.map(routeKey));
439
440 for (const route of observed) {
441 if (desiredKeys.has(routeKey(route))) continue;
442 yield* runAction(
443 Hetzner.networkActions.deleteNetworkRoute({
444 id: networkId,
445 destination: route.destination,
446 gateway: route.gateway,
447 }),
448 ).pipe(Effect.catchIf(alreadyGone, () => Effect.void));
449 }
450
451 for (const route of desired) {
452 if (observedKeys.has(routeKey(route))) continue;
453 yield* runAction(
454 Hetzner.networkActions.addNetworkRoute({
455 id: networkId,
456 destination: route.destination,
457 gateway: route.gateway,
458 }),
459 ).pipe(Effect.catchIf(alreadyThere, () => Effect.void));
460 }
461 });
462
463 const syncProtection = (networkId: number, observed: boolean, desired: boolean) =>
464 Effect.gen(function* () {
465 if (observed === desired) return;
466 yield* runAction(
467 Hetzner.networkActions.changeNetworkProtection({
468 id: networkId,
469 delete: desired,
470 }),
471 );
472 });
473
474 export const NetworkProvider = () =>
475 Provider.succeed(Network, {
476 stables: ["networkId", "created"],
477
478 list: Effect.fn(function* () {
479 return yield* Hetzner.networks.listNetworks
480 .items({ label_selector: alchemyStackSelector, per_page: 50 })
481 .pipe(
482 Stream.runCollect,
483 Effect.map((chunk) => Array.from(chunk, toAttrs)),
484 );
485 }),
486
487 diff: Effect.fn(function* ({ news, output }) {
488 if (!isResolved(news)) return undefined;
489 if (
490 output !== undefined &&
491 news.ipRange !== output.ipRange &&
492 !cidrContains(news.ipRange, output.ipRange)
493 ) {
494 return { action: "replace" } as const;
495 }
496 return undefined;
497 }),
498
499 read: Effect.fn(function* ({ id, olds, output }) {
500 const name = yield* createNetworkName(id, olds?.name ?? output?.name);
501 const observed = yield* observe(output?.networkId, name, id);
502 if (observed === undefined) return undefined;
503 const attrs = toAttrs(observed);
504 return (yield* hasAlchemyLabels(id, tagRecord(observed.labels))) ? attrs : Unowned(attrs);
505 }),
506
507 reconcile: Effect.fn(function* ({ id, news, output }) {
508 const name = yield* createNetworkName(
509 id,
510 news.name ?? (output === undefined ? undefined : output.name),
511 );
512 const desiredLabels = yield* desiredLabelsOf(id, news.labels);
513 const desiredSubnets = news.subnets ?? [];
514 const desiredRoutes = news.routes ?? [];
515 const exposeRoutesToVswitch = news.exposeRoutesToVswitch ?? false;
516 const deleteProtection = news.deleteProtection ?? false;
517
518 // Observe — cached `output.networkId` is a hint. Fall back to
519 // ownership labels, then the deterministic name.
520 let current = yield* observe(output?.networkId, name, id);
521
522 // A replacement create shares the logical id (and thus ownership
523 // labels) with the outgoing generation. If the observed row cannot
524 // accept the desired `ipRange` (Hetzner can only extend a range),
525 // do not reuse it — create a new Network and let the engine delete
526 // the old generation.
527 if (
528 current !== undefined &&
529 current.ip_range !== news.ipRange &&
530 !cidrContains(news.ipRange, current.ip_range)
531 ) {
532 current = undefined;
533 }
534
535 // Ensure — create when missing. A name-collision race is treated as
536 // the peer winning; we pick that row up and continue into sync.
537 if (current === undefined) {
538 const created = yield* Hetzner.networks
539 .createNetwork({
540 name,
541 ip_range: news.ipRange,
542 labels: desiredLabels,
543 subnets: desiredSubnets.map((subnet) => ({
544 type: subnet.type,
545 ip_range: subnet.ipRange,
546 network_zone: subnet.networkZone,
547 vswitch_id: subnet.vswitchId,
548 })),
549 routes: desiredRoutes.map((route) => ({
550 destination: route.destination,
551 gateway: route.gateway,
552 })),
553 expose_routes_to_vswitch: exposeRoutesToVswitch,
554 })
555 .pipe(
556 Effect.retry(busyRetry),
557 Effect.map((response) => response.network),
558 Effect.catchIf(alreadyThere, () => findByName(name)),
559 );
560 current = created;
561 }
562
563 if (current === undefined) {
564 return yield* new NetworkNotCreated({ resourceName: name });
565 }
566
567 // Sync each mutable aspect from observed cloud state, not `olds`.
568 yield* syncIpRange(current.id, current.ip_range, news.ipRange);
569 yield* syncMetadata({
570 networkId: current.id,
571 observed: current,
572 name,
573 exposeRoutesToVswitch,
574 labels: desiredLabels,
575 });
576 const afterMeta = (yield* getById(current.id)) ?? current;
577 yield* syncSubnets(current.id, afterMeta.subnets, desiredSubnets);
578 const afterSubnets = (yield* getById(current.id)) ?? afterMeta;
579 yield* syncRoutes(current.id, afterSubnets.routes, desiredRoutes);
580 const afterRoutes = (yield* getById(current.id)) ?? afterSubnets;
581 yield* syncProtection(current.id, afterRoutes.protection.delete, deleteProtection);
582
583 const fresh = yield* getById(current.id);
584 return toAttrs(fresh ?? afterRoutes);
585 }),
586
587 delete: Effect.fn(function* ({ output }) {
588 if (output.deleteProtection) {
589 yield* runAction(
590 Hetzner.networkActions.changeNetworkProtection({
591 id: output.networkId,
592 delete: false,
593 }),
594 ).pipe(Effect.catchIf(alreadyGone, () => Effect.void));
595 }
596 yield* Hetzner.networks.deleteNetwork({ id: output.networkId }).pipe(
597 Effect.retry(busyRetry),
598 Effect.catchTag("NotFound", () => Effect.void),
599 );
600 }),
601 });