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

main
ts 256 lines 8.43 KB
Raw
1 import * as Hetzner from "@distilled.cloud/hetzner";
2 import type { GetFloatingIpResponseFloatingIp } from "@distilled.cloud/hetzner/floating_ips";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Data from "effect/Data";
7 import * as Duration from "effect/Duration";
8 import * as Effect from "effect/Effect";
9 import * as Schedule from "effect/Schedule";
10 import * as Stream from "effect/Stream";
11 import { waitForAction } from "./actions.ts";
12 import { alchemyStackSelector } from "./Labels.ts";
13 import type { Providers } from "./Providers.ts";
14
15 export class FloatingIpAssignmentError extends Data.TaggedError("FloatingIpAssignmentError")<{
16 message: string;
17 }> {}
18
19 /**
20 * A resource-valued prop: the resource itself, or an Effect that produces
21 * it (so `yield* FloatingIp(...)` and `FloatingIp(...)` both type-check).
22 */
23 type Ref<T> = T | Effect.Effect<T, never, Providers>;
24
25 /**
26 * Floating IP identity this assignment binds. Accepts a
27 * `Hetzner.FloatingIp` resource or an `{ id }` stub.
28 */
29 export type FloatingIpAssignmentIp = {
30 readonly id: number;
31 };
32
33 /**
34 * Server identity a Floating IP can be assigned to. Accepts a
35 * `Hetzner.Server` resource or a `{ serverId }` stub.
36 */
37 export type FloatingIpAssignmentServer = {
38 readonly serverId: number;
39 };
40
41 export interface FloatingIpAssignmentProps {
42 /**
43 * Floating IP to assign. Accepts a `Hetzner.FloatingIp` or `{ id }`.
44 * Changing it updates the assignment in place (previous IP is
45 * unassigned).
46 */
47 floatingIp: Ref<FloatingIpAssignmentIp>;
48 /**
49 * Server to assign the Floating IP to. Accepts a `Hetzner.Server` or
50 * `{ serverId }`. Changing it updates the assignment in place.
51 */
52 server: Ref<FloatingIpAssignmentServer>;
53 }
54
55 export type FloatingIpAssignment = Resource<
56 "Hetzner.FloatingIpAssignment",
57 FloatingIpAssignmentProps,
58 {
59 /**
60 * Numeric Hetzner ID of the assigned Floating IP.
61 */
62 floatingIpId: number;
63 /**
64 * Numeric Hetzner ID of the Server the Floating IP is assigned to.
65 */
66 serverId: number;
67 },
68 never,
69 Providers
70 >;
71
72 /**
73 * Assigns a Hetzner Cloud {@link FloatingIp} to a Server. The assignment
74 * is existence-only: observe the Floating IP and ensure it is bound to
75 * the Server. Changing either reference updates in place (the previous
76 * IP is unassigned, then the new pair is assigned).
77 *
78 * A Floating IP can be assigned to at most one Server at a time. A Server
79 * may hold many Floating IPs. Destroying the assignment unassigns the IP
80 * but leaves both the Floating IP and the Server in place.
81 *
82 * @see https://docs.hetzner.cloud/reference/cloud#floating-ip-actions-assign-a-floating-ip-to-a-server
83 *
84 * ### Assigning a Floating IP
85 * **Example:** Assign an IPv4 to a Server
86 * ```typescript
87 * const server = yield* Hetzner.Server("web", {
88 * image: "ubuntu-24.04",
89 * serverType: "cx23",
90 * location: "nbg1",
91 * });
92 * const ip = yield* Hetzner.FloatingIp("public-ip", {
93 * type: "ipv4",
94 * homeLocation: "nbg1",
95 * });
96 * const assignment = yield* Hetzner.FloatingIpAssignment("public-ip-web", {
97 * floatingIp: ip,
98 * server,
99 * });
100 * ```
101 *
102 * **Example:** Assign with stub identities
103 * ```typescript
104 * const assignment = yield* Hetzner.FloatingIpAssignment("public-ip-web", {
105 * floatingIp: { id: 123 },
106 * server: { serverId: 42 },
107 * });
108 * ```
109 *
110 * @resource
111 * @product IP Address
112 */
113 export const FloatingIpAssignment = Resource<FloatingIpAssignment>("Hetzner.FloatingIpAssignment");
114
115 type CloudFloatingIp = GetFloatingIpResponseFloatingIp;
116
117 const floatingIpIdOf = (value: unknown): number | undefined => {
118 if (value === null || typeof value !== "object") return undefined;
119 const rec = value as { id?: unknown; floatingIpId?: unknown };
120 if (typeof rec.id === "number") return rec.id;
121 if (typeof rec.floatingIpId === "number") return rec.floatingIpId;
122 return undefined;
123 };
124
125 const serverIdOf = (value: unknown): number | undefined => {
126 if (value === null || typeof value !== "object") return undefined;
127 const rec = value as { serverId?: unknown; id?: unknown };
128 if (typeof rec.serverId === "number") return rec.serverId;
129 if (typeof rec.id === "number") return rec.id;
130 return undefined;
131 };
132
133 const toAttrs = (ip: CloudFloatingIp): FloatingIpAssignment["Attributes"] | undefined => {
134 if (ip.server === null) return undefined;
135 return {
136 floatingIpId: ip.id,
137 serverId: ip.server,
138 };
139 };
140
141 const getById = (id: number) =>
142 Hetzner.floatingIps.getFloatingIp({ id }).pipe(
143 Effect.map(({ floating_ip }) => floating_ip),
144 Effect.catchTag("NotFound", () => Effect.undefined),
145 );
146
147 const refresh = (id: number) =>
148 Hetzner.floatingIps.getFloatingIp({ id }).pipe(
149 Effect.map(({ floating_ip }) => floating_ip),
150 Effect.retry({
151 while: (e) => e._tag === "NotFound",
152 times: 5,
153 schedule: Schedule.min([
154 Schedule.exponential(Duration.millis(200), 1.5),
155 Schedule.spaced(Duration.seconds(2)),
156 ]),
157 }),
158 );
159
160 const observeAssignment = (floatingIpId: number, serverId: number) =>
161 Effect.gen(function* () {
162 const ip = yield* getById(floatingIpId);
163 if (ip === undefined) return undefined;
164 if (ip.server !== serverId) return undefined;
165 return ip;
166 });
167
168 const unassignIfNeeded = (ip: CloudFloatingIp) =>
169 Effect.gen(function* () {
170 if (ip.server === null) return ip;
171 const { action } = yield* Hetzner.floatingIpActions.unassignFloatingIp({
172 id: ip.id,
173 });
174 yield* waitForAction(action);
175 return yield* refresh(ip.id);
176 });
177
178 const assignTo = (ip: CloudFloatingIp, serverId: number) =>
179 Effect.gen(function* () {
180 if (ip.server === serverId) return ip;
181 const { action } = yield* Hetzner.floatingIpActions.assignFloatingIp({
182 id: ip.id,
183 server: serverId,
184 });
185 yield* waitForAction(action);
186 return yield* refresh(ip.id);
187 });
188
189 export const FloatingIpAssignmentProvider = () =>
190 Provider.succeed(FloatingIpAssignment, {
191 stables: ["floatingIpId", "serverId"],
192 nuke: { dependsOn: ["Hetzner.FloatingIp", "Hetzner.Server"] },
193 list: Effect.fn(function* () {
194 const items = yield* Hetzner.floatingIps.listFloatingIps
195 .items({ label_selector: alchemyStackSelector, per_page: 50 })
196 .pipe(
197 Stream.runCollect,
198 Effect.map((chunk) => Array.from(chunk)),
199 );
200 return items.flatMap((ip) => {
201 const attrs = toAttrs(ip);
202 return attrs === undefined ? [] : [attrs];
203 });
204 }),
205 diff: Effect.fn(function* ({ news }) {
206 if (!isResolved(news)) return undefined;
207 return undefined;
208 }),
209 read: Effect.fn(function* ({ output }) {
210 if (output === undefined) return undefined;
211 const found = yield* observeAssignment(output.floatingIpId, output.serverId);
212 return found === undefined ? undefined : toAttrs(found);
213 }),
214 reconcile: Effect.fn(function* ({ news, output }) {
215 const floatingIpId = floatingIpIdOf(news.floatingIp);
216 const serverId = serverIdOf(news.server);
217 if (floatingIpId === undefined || serverId === undefined) {
218 return yield* new FloatingIpAssignmentError({
219 message: "FloatingIpAssignment requires a resolved floatingIp and server",
220 });
221 }
222
223 // Observe — cloud assignment on the Floating IP is authoritative.
224 let current = yield* getById(floatingIpId);
225 if (current === undefined) {
226 current = yield* refresh(floatingIpId);
227 }
228
229 // Ensure — the pair exists. Release a previously owned IP first so
230 // an in-place retarget does not leave the old address assigned.
231 if (output !== undefined && output.floatingIpId !== floatingIpId) {
232 const previous = yield* getById(output.floatingIpId);
233 if (previous !== undefined && previous.server === output.serverId) {
234 yield* unassignIfNeeded(previous);
235 }
236 }
237 if (current.server !== serverId) {
238 current = yield* unassignIfNeeded(current);
239 current = yield* assignTo(current, serverId);
240 }
241
242 const attrs = toAttrs(current);
243 if (attrs === undefined) {
244 return yield* new FloatingIpAssignmentError({
245 message: "FloatingIpAssignment reconcile finished without an assignment",
246 });
247 }
248 return attrs;
249 }),
250 delete: Effect.fn(function* ({ output }) {
251 const current = yield* getById(output.floatingIpId);
252 if (current === undefined) return;
253 if (current.server !== output.serverId) return;
254 yield* unassignIfNeeded(current);
255 }),
256 });