@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 356 lines 12 KB
Raw
1 import * as Hetzner from "@distilled.cloud/hetzner";
2 import type { ZonePrimary, ZoneSecondary } from "@distilled.cloud/hetzner/zones";
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 { recordsEqual } from "alchemy/Util/equal";
10 import * as Data from "effect/Data";
11 import * as Duration from "effect/Duration";
12 import * as Effect from "effect/Effect";
13 import * as Schedule from "effect/Schedule";
14 import * as Stream from "effect/Stream";
15 import { waitForZoneAction } from "./actions.ts";
16 import {
17 alchemyStackSelector,
18 createInternalLabels,
19 hasAlchemyLabels,
20 labelSelector,
21 stripInternalLabels,
22 toLabels,
23 } from "./Labels.ts";
24 import type { Providers } from "./Providers.ts";
25
26 export type ZoneMode = "primary" | "secondary";
27 export type ZoneStatus = "ok" | "updating" | "error";
28 export type ZoneRegistrar = "hetzner" | "other" | "unknown";
29 export type ZoneDelegationStatus =
30 | "valid"
31 | "partially-valid"
32 | "invalid"
33 | "lame"
34 | "unregistered"
35 | "unknown"
36 | (string & {});
37
38 export interface ZoneProps {
39 /**
40 * Apex domain of the zone (e.g. `example.com`). Must be lowercase, must
41 * not end with a dot, and must use a well-known public suffix. Subdomains
42 * are not supported. Changing this replaces the zone.
43 *
44 * If omitted, a unique `*.com` name is generated from the stack, stage,
45 * and logical ID.
46 */
47 name?: string;
48 /**
49 * Zone mode. Primary zones are edited via the Cloud API (RRSets);
50 * secondary zones are transferred from primary nameservers via AXFR.
51 * Cannot be changed after creation — triggers a replacement.
52 *
53 * @default "primary"
54 */
55 mode?: ZoneMode;
56 /**
57 * Default TTL in seconds for RRSets that do not set their own TTL.
58 * Must be between 60 and 2147483647. Omit to keep Hetzner's default on
59 * create and leave the live value alone on update.
60 */
61 ttl?: number;
62 /**
63 * User-defined labels. Alchemy ownership labels (`alchemy.stack`,
64 * `alchemy.stage`, `alchemy.id`) are always merged in.
65 */
66 labels?: Record<string, string>;
67 /**
68 * Prevent the zone from being deleted via the API.
69 *
70 * @default false
71 */
72 deleteProtection?: boolean;
73 }
74
75 export interface ZoneAttributes {
76 /** Numeric Cloud API id of the zone. Stable across updates. */
77 zoneId: number;
78 /** Apex domain name. */
79 name: string;
80 /** Zone mode (`primary` or `secondary`). */
81 mode: ZoneMode;
82 /** Default TTL in seconds. */
83 ttl: number;
84 /** User-defined labels (Alchemy ownership labels stripped). */
85 labels: Record<string, string>;
86 /** Whether delete protection is enabled. */
87 deleteProtection: boolean;
88 /** Live zone status. */
89 status: ZoneStatus;
90 /** Number of resource records in the zone. */
91 recordCount: number;
92 /** Domain registrar as reported by Hetzner. */
93 registrar: ZoneRegistrar;
94 /** RFC3339 creation timestamp. */
95 created: string;
96 /** Authoritative Hetzner nameservers assigned to this zone. */
97 assignedNameservers: string[];
98 /** Nameservers currently delegated by the parent DNS zone. */
99 delegatedNameservers: string[];
100 /** Delegation check status, when Hetzner has reported one. */
101 delegationStatus: ZoneDelegationStatus | undefined;
102 }
103
104 export type Zone = Resource<"Hetzner.Zone", ZoneProps, ZoneAttributes, never, Providers>;
105
106 /**
107 * A Hetzner Cloud DNS zone — an apex domain hosted on Hetzner's
108 * authoritative nameservers.
109 *
110 * The zone `name` is the identity: changing it replaces the zone. Default
111 * TTL, labels, and delete protection update in place. Resource record sets
112 * are a separate resource (`RecordSet`).
113 * @see https://docs.hetzner.cloud/reference/cloud#zones
114 *
115 * ### Creating a Zone
116 * **Example:** Primary zone with a default TTL
117 * ```typescript
118 * const zone = yield* Hetzner.Zone("example", {
119 * name: "example.com",
120 * ttl: 3600,
121 * });
122 * ```
123 *
124 * **Example:** Zone with labels and delete protection
125 * ```typescript
126 * const zone = yield* Hetzner.Zone("example", {
127 * name: "example.com",
128 * labels: { env: "prod" },
129 * deleteProtection: true,
130 * });
131 * ```
132 *
133 * @resource
134 * @product DNS
135 */
136 export const Zone = Resource<Zone>("Hetzner.Zone");
137
138 type CloudZone = ZonePrimary | ZoneSecondary;
139
140 const DEFAULT_MODE: ZoneMode = "primary";
141
142 const normalizeName = (name: string): string => name.toLowerCase().replace(/\.$/, "");
143
144 const generateZoneName = (id: string) =>
145 createPhysicalName({ id, lowercase: true, maxLength: 63 }).pipe(
146 Effect.map((physical) => `${physical}.com`),
147 );
148
149 const resolveZoneName = (
150 id: string,
151 news: Pick<ZoneProps, "name">,
152 output: Pick<ZoneAttributes, "name"> | undefined,
153 ) =>
154 Effect.gen(function* () {
155 if (news.name !== undefined) {
156 return normalizeName(news.name);
157 }
158 if (output?.name !== undefined) {
159 return output.name;
160 }
161 return yield* generateZoneName(id);
162 });
163
164 const desiredLabels = Effect.fn(function* (id: string, user: Record<string, string> | undefined) {
165 return { ...toLabels(user), ...(yield* createInternalLabels(id)) };
166 });
167
168 const toAttrs = (zone: CloudZone): ZoneAttributes => ({
169 zoneId: zone.id,
170 name: zone.name,
171 mode: zone.mode,
172 ttl: zone.ttl,
173 labels: stripInternalLabels(tagRecord(zone.labels)),
174 deleteProtection: zone.protection.delete,
175 status: zone.status,
176 recordCount: zone.record_count,
177 registrar: zone.registrar,
178 created: zone.created,
179 assignedNameservers: zone.authoritative_nameservers.assigned,
180 delegatedNameservers: zone.authoritative_nameservers.delegated,
181 delegationStatus: zone.authoritative_nameservers.delegation_status,
182 });
183
184 const getZoneBy = (idOrName: string) =>
185 Hetzner.zones.getZone({ id_or_name: idOrName }).pipe(
186 Effect.map(({ zone }) => zone),
187 Effect.catchTag("NotFound", () => Effect.undefined),
188 );
189
190 class ZoneStillExists extends Data.TaggedError("ZoneStillExists")<{ idOrName: string }> {}
191
192 const backoff = Schedule.min([
193 Schedule.exponential(Duration.millis(500), 1.5),
194 Schedule.spaced(Duration.seconds(5)),
195 ]);
196
197 const retryLocked = <A, E extends { readonly _tag: string }, R>(effect: Effect.Effect<A, E, R>) =>
198 effect.pipe(Effect.retry({ while: (e) => e._tag === "Locked", times: 8, schedule: backoff }));
199
200 export const ZoneProvider = () =>
201 Provider.succeed(Zone, {
202 stables: ["zoneId", "name", "mode"],
203 list: Effect.fn(function* () {
204 const zones = yield* Hetzner.zones.listZones
205 .items({ label_selector: alchemyStackSelector, per_page: 50 })
206 .pipe(Stream.runCollect);
207 return [...zones].map(toAttrs);
208 }),
209 diff: Effect.fn(function* ({ news, output }) {
210 if (!isResolved(news)) return undefined;
211 if (!output) return undefined;
212 if (news.name !== undefined && normalizeName(news.name) !== output.name) {
213 return { action: "replace" } as const;
214 }
215 if ((news.mode ?? DEFAULT_MODE) !== output.mode) {
216 return { action: "replace" } as const;
217 }
218 const desiredProtection = news.deleteProtection ?? false;
219 const labelsChanged = !recordsEqual(news.labels ?? {}, output.labels);
220 const ttlChanged = news.ttl !== undefined && news.ttl !== output.ttl;
221 if (ttlChanged || labelsChanged || desiredProtection !== output.deleteProtection) {
222 return { action: "update" } as const;
223 }
224 return undefined;
225 }),
226 read: Effect.fn(function* ({ id, olds, output }) {
227 let zone: CloudZone | undefined;
228 if (output?.zoneId !== undefined) {
229 zone = yield* getZoneBy(String(output.zoneId));
230 }
231 if (zone === undefined) {
232 const name = output?.name ?? olds?.name;
233 if (name !== undefined) {
234 zone = yield* getZoneBy(normalizeName(name));
235 }
236 }
237 if (zone === undefined) {
238 const expected = yield* createInternalLabels(id);
239 const selector = labelSelector(expected);
240 if (selector.length > 0) {
241 zone = yield* Hetzner.zones.listZones
242 .items({ label_selector: selector, per_page: 50 })
243 .pipe(
244 Stream.take(1),
245 Stream.runHead,
246 Effect.map((option) => (option._tag === "Some" ? option.value : undefined)),
247 );
248 }
249 }
250 if (zone === undefined) return undefined;
251 const attrs = toAttrs(zone);
252 return (yield* hasAlchemyLabels(id, tagRecord(zone.labels))) ? attrs : Unowned(attrs);
253 }),
254 reconcile: Effect.fn(function* ({ id, news, output }) {
255 const name = yield* resolveZoneName(id, news, output);
256 const mode = news.mode ?? output?.mode ?? DEFAULT_MODE;
257 const idOrName = output?.zoneId !== undefined ? String(output.zoneId) : name;
258
259 // 1. Observe
260 let current = yield* getZoneBy(idOrName);
261 if (current === undefined && output?.zoneId !== undefined) {
262 current = yield* getZoneBy(name);
263 }
264
265 // 2. Ensure
266 if (current === undefined) {
267 const labels = yield* desiredLabels(id, news.labels);
268 const created = yield* retryLocked(
269 Hetzner.zones
270 .createZone({
271 name,
272 mode,
273 ...(news.ttl !== undefined ? { ttl: news.ttl } : {}),
274 labels,
275 })
276 .pipe(
277 Effect.catchTag("Conflict", () =>
278 Hetzner.zones
279 .getZone({ id_or_name: name })
280 .pipe(Effect.map(({ zone }) => ({ zone, action: undefined }))),
281 ),
282 ),
283 );
284 if (created.action !== undefined) {
285 yield* waitForZoneAction(created.action);
286 }
287 current =
288 created.action === undefined ? created.zone : ((yield* getZoneBy(name)) ?? created.zone);
289 }
290
291 const zoneRef = String(current.id);
292
293 // 3. Sync — labels (PUT overwrites the full set)
294 const labels = yield* desiredLabels(id, news.labels);
295 const observedLabels = tagRecord(current.labels);
296 if (!recordsEqual(observedLabels, labels)) {
297 const updated = yield* retryLocked(
298 Hetzner.zones.updateZone({ id_or_name: zoneRef, labels }),
299 );
300 current = updated.zone;
301 }
302
303 // Sync — default TTL (primary zones only; secondary ignores it)
304 if (news.ttl !== undefined && news.ttl !== current.ttl && current.mode === "primary") {
305 const { action } = yield* retryLocked(
306 Hetzner.zoneActions.changeZoneTtl({ id_or_name: zoneRef, ttl: news.ttl }),
307 );
308 yield* waitForZoneAction(action);
309 current = (yield* getZoneBy(zoneRef)) ?? current;
310 }
311
312 // Sync — delete protection
313 const desiredProtection = news.deleteProtection ?? false;
314 if (current.protection.delete !== desiredProtection) {
315 const { action } = yield* retryLocked(
316 Hetzner.zoneActions.changeZoneProtection({
317 id_or_name: zoneRef,
318 delete: desiredProtection,
319 }),
320 );
321 yield* waitForZoneAction(action);
322 current = (yield* getZoneBy(zoneRef)) ?? current;
323 }
324
325 return toAttrs(current);
326 }),
327 delete: Effect.fn(function* ({ output }) {
328 const idOrName = String(output.zoneId);
329 const current = yield* getZoneBy(idOrName);
330 if (current === undefined) return;
331
332 if (current.protection.delete) {
333 const { action } = yield* retryLocked(
334 Hetzner.zoneActions.changeZoneProtection({ id_or_name: idOrName, delete: false }),
335 );
336 yield* waitForZoneAction(action);
337 }
338
339 const deleted = yield* retryLocked(
340 Hetzner.zones
341 .deleteZone({ id_or_name: idOrName })
342 .pipe(Effect.catchTag("NotFound", () => Effect.undefined)),
343 );
344 if (deleted !== undefined) {
345 yield* waitForZoneAction(deleted.action);
346 }
347
348 yield* getZoneBy(idOrName).pipe(
349 Effect.flatMap((zone) =>
350 zone === undefined ? Effect.void : new ZoneStillExists({ idOrName }),
351 ),
352 Effect.retry({ while: (e) => e._tag === "ZoneStillExists", times: 8, schedule: backoff }),
353 Effect.catchTag("ZoneStillExists", () => Effect.void),
354 );
355 }),
356 });