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

main
ts 549 lines 16.8 KB
Raw
1 import * as Hetzner from "@distilled.cloud/hetzner";
2 import type {
3 CreateZoneRrsetRequestRecordsItem,
4 GetZoneRrsetResponseRrset,
5 ListZoneRrsetsResponseRrsetsItem,
6 } from "@distilled.cloud/hetzner/zone_rrsets";
7 import { Unowned } from "alchemy/AdoptPolicy";
8 import { deepEqual, isResolved } from "alchemy/Diff";
9 import { createPhysicalName } from "alchemy/PhysicalName";
10 import * as Provider from "alchemy/Provider";
11 import { Resource } from "alchemy/Resource";
12 import { tagRecord } from "alchemy/Tags";
13 import { recordsEqual as labelsEqual } from "alchemy/Util/equal";
14 import * as Data from "effect/Data";
15 import * as Duration from "effect/Duration";
16 import * as Effect from "effect/Effect";
17 import * as Schedule from "effect/Schedule";
18 import * as Stream from "effect/Stream";
19 import { waitForZoneAction } from "./actions.ts";
20 import {
21 alchemyStackSelector,
22 createInternalLabels,
23 hasAlchemyLabels,
24 labelSelector,
25 stripInternalLabels,
26 toLabels,
27 } from "./Labels.ts";
28 import type { Providers } from "./Providers.ts";
29
30 /**
31 * A resource-valued prop: the resource itself, or an Effect that produces
32 * it (so `yield* Zone(...)` and `Zone(...)` both type-check).
33 */
34 type Ref<T> = T | Effect.Effect<T, never, Providers>;
35
36 /**
37 * Zone identity an RRSet belongs to. A `Hetzner.Zone` resource satisfies
38 * this via `zoneId`.
39 */
40 export type RecordSetZone = { readonly zoneId: number };
41
42 export type RecordSetType =
43 | "A"
44 | "AAAA"
45 | "CAA"
46 | "CNAME"
47 | "DS"
48 | "HINFO"
49 | "HTTPS"
50 | "MX"
51 | "NS"
52 | "PTR"
53 | "RP"
54 | "SOA"
55 | "SRV"
56 | "SVCB"
57 | "TLSA"
58 | "TXT"
59 | (string & {});
60
61 export interface RecordSetRecord {
62 /**
63 * Record value. Interpretation depends on `type` — an A record is an
64 * IPv4 address, AAAA an IPv6 address, CNAME a hostname, etc. Must be
65 * unique within the RRSet. Accepts a primitive Output (e.g. a Primary
66 * IP's `ip`).
67 */
68 value: string;
69 /**
70 * Optional comment shown in the Hetzner Cloud Console. Does not affect
71 * DNS responses.
72 */
73 comment?: string;
74 }
75
76 export interface RecordSetProps {
77 /**
78 * Zone this RRSet lives in. Accepts a `Hetzner.Zone` or `{ zoneId }`.
79 * Changing the zone replaces the RRSet.
80 */
81 zone: Ref<RecordSetZone>;
82 /**
83 * DNS name of the RRSet, relative to the zone. Lowercase, must not end
84 * with a dot or the zone apex. Use `@` for the zone apex. Changing this
85 * replaces the RRSet.
86 *
87 * If omitted, a unique label is generated from the stack, stage, and
88 * logical ID.
89 */
90 name?: string;
91 /**
92 * DNS record type. All `records` share this type — two A values are one
93 * RRSet, not two resources. Changing this replaces the RRSet.
94 */
95 type: RecordSetType;
96 /**
97 * Records in this RRSet. Must be non-empty and contain distinct values.
98 * Order is not significant. Mutable — updates in place.
99 */
100 records: RecordSetRecord[];
101 /**
102 * TTL in seconds (`60`–`2147483647`). Omit to use the Zone's default TTL
103 * on create and leave the live value alone on update.
104 */
105 ttl?: number;
106 /**
107 * User-defined labels. Alchemy ownership labels (`alchemy.stack`,
108 * `alchemy.stage`, `alchemy.id`) are always merged in.
109 */
110 labels?: Record<string, string>;
111 /**
112 * Prevent the RRSet from being changed or deleted via the API.
113 *
114 * @default false
115 */
116 changeProtection?: boolean;
117 }
118
119 export interface RecordSetAttributes {
120 /**
121 * RRSet id (`{name}/{type}`, e.g. `www/A`). Stable across updates.
122 */
123 id: string;
124 /**
125 * Numeric Cloud API id of the parent Zone.
126 */
127 zoneId: number;
128 /**
129 * DNS name of the RRSet (`@` for the apex).
130 */
131 name: string;
132 /**
133 * DNS record type.
134 */
135 type: RecordSetType;
136 /**
137 * TTL in seconds, or `undefined` when the Zone default applies.
138 */
139 ttl: number | undefined;
140 /**
141 * Records currently published. Order is not significant.
142 */
143 records: RecordSetRecord[];
144 /**
145 * User-defined labels (Alchemy ownership labels stripped).
146 */
147 labels: Record<string, string>;
148 /**
149 * Whether change protection is enabled.
150 */
151 changeProtection: boolean;
152 }
153
154 export type RecordSet = Resource<
155 "Hetzner.RecordSet",
156 RecordSetProps,
157 RecordSetAttributes,
158 never,
159 Providers
160 >;
161
162 /**
163 * A Hetzner Cloud DNS resource record set (RRSet) — one `(name, type)`
164 * with one or more records. Two A values are a single resource, not two.
165 *
166 * Identity is `(zone, name, type)`: changing any of those replaces the
167 * RRSet. Records, TTL, labels, and change protection update in place.
168 * Only primary Zones accept RRSet edits.
169 *
170 * @see https://docs.hetzner.cloud/reference/cloud#zone-rrsets
171 *
172 * ### Creating an RRSet
173 * **Example:** A records on a subdomain
174 * ```typescript
175 * const zone = yield* Hetzner.Zone("example", {
176 * name: "example.com",
177 * });
178 * const www = yield* Hetzner.RecordSet("www", {
179 * zone,
180 * name: "www",
181 * type: "A",
182 * records: [
183 * { value: "192.0.2.1" },
184 * { value: "192.0.2.2" },
185 * ],
186 * ttl: 300,
187 * });
188 * ```
189 *
190 * **Example:** Apex A record from a Primary IP
191 * ```typescript
192 * const ip = yield* Hetzner.PrimaryIp("web-ip", {
193 * type: "ipv4",
194 * location: "nbg1",
195 * });
196 * const apex = yield* Hetzner.RecordSet("apex", {
197 * zone,
198 * name: "@",
199 * type: "A",
200 * records: [{ value: ip.ip }],
201 * });
202 * ```
203 *
204 * ### Updating records
205 * **Example:** Replace the record set and TTL
206 * ```typescript
207 * const www = yield* Hetzner.RecordSet("www", {
208 * zone,
209 * name: "www",
210 * type: "A",
211 * records: [{ value: "192.0.2.10" }],
212 * ttl: 600,
213 * });
214 * ```
215 *
216 * @resource
217 * @product DNS
218 */
219 export const RecordSet = Resource<RecordSet>("Hetzner.RecordSet");
220
221 export class RecordSetZoneMissing extends Data.TaggedError("Hetzner.RecordSetZoneMissing")<{
222 recordName: string;
223 type: string;
224 }> {}
225
226 class RecordSetStillExists extends Data.TaggedError("RecordSetStillExists")<{
227 zoneId: number;
228 recordName: string;
229 type: string;
230 }> {}
231
232 type CloudRrset = GetZoneRrsetResponseRrset | ListZoneRrsetsResponseRrsetsItem;
233
234 const NAME_MAX_LENGTH = 63;
235
236 const normalizeName = (name: string): string => name.toLowerCase().replace(/\.$/, "");
237
238 const normalizeType = (type: string): RecordSetType => type.toUpperCase() as RecordSetType;
239
240 const compactRecord = (record: { value: string; comment?: string | null }): RecordSetRecord => {
241 const comment = record.comment ?? undefined;
242 return comment !== undefined && comment.length > 0
243 ? { value: record.value, comment }
244 : { value: record.value };
245 };
246
247 const sortRecords = (records: ReadonlyArray<RecordSetRecord>): RecordSetRecord[] =>
248 [...records].map(compactRecord).sort((a, b) => a.value.localeCompare(b.value));
249
250 const recordsEqual = (
251 a: ReadonlyArray<RecordSetRecord>,
252 b: ReadonlyArray<RecordSetRecord>,
253 ): boolean => deepEqual(sortRecords(a), sortRecords(b), { stripNullish: true });
254
255 const toWireRecords = (
256 records: ReadonlyArray<RecordSetRecord>,
257 ): CreateZoneRrsetRequestRecordsItem[] =>
258 records.map((record) =>
259 record.comment !== undefined
260 ? { value: record.value, comment: record.comment }
261 : { value: record.value },
262 );
263
264 const zoneIdOf = (value: unknown): number | undefined => {
265 if (value === null || typeof value !== "object") return undefined;
266 const rec = value as { zoneId?: unknown; id?: unknown };
267 if (typeof rec.zoneId === "number") return rec.zoneId;
268 if (typeof rec.id === "number") return rec.id;
269 return undefined;
270 };
271
272 const resolveName = (
273 id: string,
274 news: Pick<RecordSetProps, "name">,
275 output: Pick<RecordSetAttributes, "name"> | undefined,
276 ) =>
277 Effect.gen(function* () {
278 if (news.name !== undefined) {
279 return normalizeName(news.name);
280 }
281 if (output?.name !== undefined) {
282 return output.name;
283 }
284 return yield* createPhysicalName({ id, lowercase: true, maxLength: NAME_MAX_LENGTH });
285 });
286
287 const desiredLabels = Effect.fn(function* (id: string, user: Record<string, string> | undefined) {
288 return { ...toLabels(user), ...(yield* createInternalLabels(id)) };
289 });
290
291 const toAttrs = (rrset: CloudRrset): RecordSetAttributes => ({
292 id: rrset.id,
293 zoneId: rrset.zone,
294 name: rrset.name,
295 type: rrset.type,
296 ttl: rrset.ttl ?? undefined,
297 records: sortRecords(rrset.records.map(compactRecord)),
298 labels: stripInternalLabels(tagRecord(rrset.labels)),
299 changeProtection: rrset.protection.change,
300 });
301
302 const backoff = Schedule.min([
303 Schedule.exponential(Duration.millis(500), 1.5),
304 Schedule.spaced(Duration.seconds(5)),
305 ]);
306
307 const retryLocked = <A, E extends { readonly _tag: string }, R>(effect: Effect.Effect<A, E, R>) =>
308 effect.pipe(Effect.retry({ while: (e) => e._tag === "Locked", times: 8, schedule: backoff }));
309
310 const getRrset = (zoneId: number, name: string, type: string) =>
311 Hetzner.zoneRrsets
312 .getZoneRrset({ id_or_name: String(zoneId), rr_name: name, rr_type: type })
313 .pipe(
314 Effect.map(({ rrset }) => rrset),
315 Effect.catchTag("NotFound", () => Effect.undefined),
316 );
317
318 const findByLabels = (zoneId: number, id: string) =>
319 Effect.gen(function* () {
320 const selector = labelSelector(yield* createInternalLabels(id));
321 if (selector.length === 0) return undefined;
322 return yield* Hetzner.zoneRrsets.listZoneRrsets
323 .items({ id_or_name: String(zoneId), label_selector: selector, per_page: 100 })
324 .pipe(
325 Stream.take(1),
326 Stream.runHead,
327 Effect.map((option) => (option._tag === "Some" ? option.value : undefined)),
328 );
329 });
330
331 export const RecordSetProvider = () =>
332 Provider.succeed(RecordSet, {
333 stables: ["id", "zoneId", "name", "type"],
334 nuke: { dependsOn: ["Hetzner.Zone"] },
335 list: Effect.fn(function* () {
336 const zones = yield* Hetzner.zones.listZones.items({ per_page: 50 }).pipe(Stream.runCollect);
337 const rows = yield* Effect.forEach(
338 [...zones],
339 (zone) =>
340 Hetzner.zoneRrsets.listZoneRrsets
341 .items({
342 id_or_name: String(zone.id),
343 label_selector: alchemyStackSelector,
344 per_page: 100,
345 })
346 .pipe(
347 Stream.runCollect,
348 Effect.map((chunk) => [...chunk].map(toAttrs)),
349 Effect.catchTag(["NotFound", "BadRequest", "UnprocessableEntity"], () =>
350 Effect.succeed([] as RecordSetAttributes[]),
351 ),
352 ),
353 { concurrency: 5 },
354 );
355 return rows.flat();
356 }),
357 diff: Effect.fn(function* ({ news, output }) {
358 if (!isResolved(news)) return undefined;
359 if (!output) return undefined;
360 const zoneId = zoneIdOf(news.zone);
361 if (zoneId !== undefined && zoneId !== output.zoneId) {
362 return { action: "replace" } as const;
363 }
364 if (news.name !== undefined && normalizeName(news.name) !== output.name) {
365 return { action: "replace" } as const;
366 }
367 if (normalizeType(news.type) !== output.type) {
368 return { action: "replace" } as const;
369 }
370 return undefined;
371 }),
372 read: Effect.fn(function* ({ id, olds, output }) {
373 const zoneId = output?.zoneId ?? zoneIdOf(olds?.zone);
374 const name =
375 output?.name ?? (olds?.name !== undefined ? normalizeName(olds.name) : undefined);
376 const type =
377 output?.type ?? (olds?.type !== undefined ? normalizeType(olds.type) : undefined);
378
379 let current: CloudRrset | undefined;
380 if (zoneId !== undefined && name !== undefined && type !== undefined) {
381 current = yield* getRrset(zoneId, name, type);
382 }
383 if (current === undefined && zoneId !== undefined) {
384 current = yield* findByLabels(zoneId, id);
385 }
386 if (current === undefined) return undefined;
387 const attrs = toAttrs(current);
388 return (yield* hasAlchemyLabels(id, tagRecord(current.labels))) ? attrs : Unowned(attrs);
389 }),
390 reconcile: Effect.fn(function* ({ id, news, output }) {
391 const zoneId = zoneIdOf(news.zone) ?? output?.zoneId;
392 const name = yield* resolveName(id, news, output);
393 const type = normalizeType(news.type);
394 if (zoneId === undefined) {
395 return yield* new RecordSetZoneMissing({ recordName: name, type });
396 }
397
398 const desiredRecords = sortRecords(news.records);
399 const labels = yield* desiredLabels(id, news.labels);
400 const desiredProtection = news.changeProtection ?? false;
401
402 // 1. Observe
403 let current =
404 output !== undefined &&
405 output.zoneId === zoneId &&
406 output.name === name &&
407 output.type === type
408 ? yield* getRrset(output.zoneId, output.name, output.type)
409 : yield* getRrset(zoneId, name, type);
410
411 // 2. Ensure
412 if (current === undefined) {
413 const created = yield* retryLocked(
414 Hetzner.zoneRrsets
415 .createZoneRrset({
416 id_or_name: String(zoneId),
417 name,
418 type,
419 records: toWireRecords(desiredRecords),
420 labels,
421 ...(news.ttl !== undefined ? { ttl: news.ttl } : {}),
422 })
423 .pipe(
424 Effect.catchTag("Conflict", () =>
425 getRrset(zoneId, name, type).pipe(
426 Effect.map((rrset) =>
427 rrset !== undefined ? { rrset, action: undefined } : undefined,
428 ),
429 ),
430 ),
431 ),
432 );
433 if (created === undefined) {
434 current = yield* getRrset(zoneId, name, type);
435 } else {
436 if (created.action !== undefined) {
437 yield* waitForZoneAction(created.action.id);
438 }
439 current = (yield* getRrset(zoneId, name, type)) ?? created.rrset;
440 }
441 }
442
443 if (current === undefined) {
444 return yield* new RecordSetZoneMissing({ recordName: name, type });
445 }
446
447 const zoneRef = String(zoneId);
448
449 // 3. Sync — labels (PUT overwrites the full set)
450 const observedLabels = tagRecord(current.labels);
451 if (!labelsEqual(observedLabels, labels)) {
452 const updated = yield* retryLocked(
453 Hetzner.zoneRrsets.updateZoneRrset({
454 id_or_name: zoneRef,
455 rr_name: name,
456 rr_type: type,
457 labels,
458 }),
459 );
460 current = updated.rrset;
461 }
462
463 // Sync — TTL
464 if (news.ttl !== undefined && news.ttl !== (current.ttl ?? undefined)) {
465 const { action } = yield* retryLocked(
466 Hetzner.zoneRrsetActions.changeZoneRrsetTtl({
467 id_or_name: zoneRef,
468 rr_name: name,
469 rr_type: type,
470 ttl: news.ttl,
471 }),
472 );
473 yield* waitForZoneAction(action.id);
474 current = (yield* getRrset(zoneId, name, type)) ?? current;
475 }
476
477 // Sync — records (order-insensitive; value identifies a record)
478 if (!recordsEqual(current.records.map(compactRecord), desiredRecords)) {
479 const { action } = yield* retryLocked(
480 Hetzner.zoneRrsetActions.setZoneRrsetRecords({
481 id_or_name: zoneRef,
482 rr_name: name,
483 rr_type: type,
484 records: toWireRecords(desiredRecords),
485 }),
486 );
487 yield* waitForZoneAction(action.id);
488 current = (yield* getRrset(zoneId, name, type)) ?? current;
489 }
490
491 // Sync — change protection
492 if (current.protection.change !== desiredProtection) {
493 const { action } = yield* retryLocked(
494 Hetzner.zoneRrsetActions.changeZoneRrsetProtection({
495 id_or_name: zoneRef,
496 rr_name: name,
497 rr_type: type,
498 change: desiredProtection,
499 }),
500 );
501 yield* waitForZoneAction(action.id);
502 current = (yield* getRrset(zoneId, name, type)) ?? current;
503 }
504
505 return toAttrs(current);
506 }),
507 delete: Effect.fn(function* ({ output }) {
508 const zoneId = output.zoneId;
509 const name = output.name;
510 const type = output.type;
511 const current = yield* getRrset(zoneId, name, type);
512 if (current === undefined) return;
513
514 if (current.protection.change) {
515 const { action } = yield* retryLocked(
516 Hetzner.zoneRrsetActions.changeZoneRrsetProtection({
517 id_or_name: String(zoneId),
518 rr_name: name,
519 rr_type: type,
520 change: false,
521 }),
522 );
523 yield* waitForZoneAction(action.id);
524 }
525
526 const deleted = yield* retryLocked(
527 Hetzner.zoneRrsets
528 .deleteZoneRrset({ id_or_name: String(zoneId), rr_name: name, rr_type: type })
529 .pipe(Effect.catchTag("NotFound", () => Effect.undefined)),
530 );
531 if (deleted !== undefined) {
532 yield* waitForZoneAction(deleted.action.id);
533 }
534
535 yield* getRrset(zoneId, name, type).pipe(
536 Effect.flatMap((rrset) =>
537 rrset === undefined
538 ? Effect.void
539 : new RecordSetStillExists({ zoneId, recordName: name, type }),
540 ),
541 Effect.retry({
542 while: (e) => e._tag === "RecordSetStillExists",
543 times: 8,
544 schedule: backoff,
545 }),
546 Effect.catchTag("RecordSetStillExists", () => Effect.void),
547 );
548 }),
549 });