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

main
ts 422 lines 13.9 KB
Raw
1 import * as dns from "@distilled.cloud/gcp/dns_v1";
2 import { isResolved } from "alchemy/Diff";
3 import { createPhysicalName } from "alchemy/PhysicalName";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Data from "effect/Data";
7 import * as Effect from "effect/Effect";
8 import { GcpEnvironment } from "../Environment.ts";
9 import { ALCHEMY_LABEL_PREFIX } from "../Labels.ts";
10 import type { Providers } from "../Providers.ts";
11
12 const DEFAULT_TTL = 300;
13 const MAX_LABEL_LENGTH = 63;
14 const SYSTEM_TYPES = new Set(["SOA", "NS"]);
15
16 export type ResourceRecordSetRoutingPolicy = dns.RRSetRoutingPolicy;
17
18 export type ResourceRecordSetProps = {
19 /**
20 * Managed zone name or numeric id that owns this record set. Immutable —
21 * changing it replaces the record set.
22 */
23 managedZone: string;
24 /**
25 * Fully qualified DNS name (e.g. `"www.example.com."`). A trailing dot
26 * is added if omitted. Relative names are qualified with the zone's
27 * DNS name. If omitted entirely, a unique subdomain of the zone is
28 * generated. Immutable — changing it replaces the record set.
29 */
30 name?: string;
31 /**
32 * DNS record type (`A`, `AAAA`, `CNAME`, `MX`, `TXT`, `NS`, …).
33 * Immutable — changing it replaces the record set.
34 */
35 type: string;
36 /**
37 * TTL in seconds.
38 * @default 300
39 */
40 ttl?: number;
41 /**
42 * Resource-record data. For `A` records this is a list of IPv4
43 * addresses; for `TXT`, quoted strings. Mutually exclusive with
44 * `routingPolicy`.
45 */
46 rrdatas?: string[];
47 /**
48 * Dynamic routing policy (geo / weighted-round-robin / primary-backup).
49 * A record set has either `rrdatas` or `routingPolicy`, not both.
50 */
51 routingPolicy?: ResourceRecordSetRoutingPolicy;
52 };
53
54 export type ResourceRecordSet = Resource<
55 "GCP.DNS.ResourceRecordSet",
56 ResourceRecordSetProps,
57 {
58 /** Project id. */
59 project: string;
60 /** Managed zone name. */
61 managedZone: string;
62 /** Fully qualified DNS name, with trailing dot. */
63 name: string;
64 /** DNS record type. */
65 type: string;
66 /** TTL in seconds. */
67 ttl: number;
68 /** Resource-record data. */
69 rrdatas: string[];
70 /** Dynamic routing policy, if this is not a static record. */
71 routingPolicy: ResourceRecordSetRoutingPolicy | undefined;
72 /** DNSSEC signature records, if present. */
73 signatureRrdatas: string[] | undefined;
74 /** Server-reported kind (`dns#resourceRecordSet`). */
75 kind: string | undefined;
76 },
77 never,
78 Providers
79 >;
80
81 /**
82 * A Cloud DNS resource record set inside a managed zone.
83 *
84 * Identity is `(managedZone, name, type)`. TTL, `rrdatas`, and
85 * `routingPolicy` are mutable. Record sets have no labels; `list` / nuke
86 * discover them by enumerating managed zones stamped with `alchemy-*`
87 * labels and skipping the zone's apex `SOA`/`NS` records.
88 *
89 * ### Creating a Record Set
90 * **Example:** A record
91 * ```typescript
92 * const zone = yield* GCP.DNS.ManagedZone("Public", { forceDestroy: true });
93 * const www = yield* GCP.DNS.ResourceRecordSet("Www", {
94 * managedZone: zone.zoneName,
95 * name: "www",
96 * type: "A",
97 * ttl: 300,
98 * rrdatas: ["203.0.113.10"],
99 * });
100 * ```
101 *
102 * **Example:** TXT record
103 * ```typescript
104 * const verify = yield* GCP.DNS.ResourceRecordSet("Verify", {
105 * managedZone: zone.zoneName,
106 * name: zone.dnsName,
107 * type: "TXT",
108 * ttl: 60,
109 * rrdatas: ['"v=spf1 -all"'],
110 * });
111 * ```
112 *
113 * **Example:** Generated subdomain
114 * ```typescript
115 * const record = yield* GCP.DNS.ResourceRecordSet("Probe", {
116 * managedZone: zone.zoneName,
117 * type: "A",
118 * rrdatas: ["203.0.113.20"],
119 * });
120 * ```
121 *
122 * @resource
123 * @category DNS
124 */
125 export const ResourceRecordSet = Resource<ResourceRecordSet>("GCP.DNS.ResourceRecordSet");
126
127 export class ResourceRecordSetNotResolved extends Data.TaggedError(
128 "GCP.DNS.ResourceRecordSetNotResolved",
129 )<{
130 managedZone: string;
131 resourceName: string;
132 type: string;
133 }> {}
134
135 export class ResourceRecordSetZoneNotFound extends Data.TaggedError(
136 "GCP.DNS.ResourceRecordSetZoneNotFound",
137 )<{
138 managedZone: string;
139 }> {}
140
141 const withTrailingDot = (name: string) => (name.endsWith(".") ? name : `${name}.`);
142
143 const normalizeFqdn = (name: string) => withTrailingDot(name).toLowerCase();
144
145 const normalizeType = (type: string) => type.toUpperCase();
146
147 const isRelativeName = (name: string) => {
148 const trimmed = name.endsWith(".") ? name.slice(0, -1) : name;
149 return !trimmed.includes(".");
150 };
151
152 const qualifyName = (name: string, dnsName: string) => {
153 const zone = normalizeFqdn(dnsName);
154 if (isRelativeName(name)) {
155 return `${name.replace(/\.$/, "").toLowerCase()}.${zone}`;
156 }
157 const fqdn = normalizeFqdn(name);
158 if (fqdn === zone || fqdn.endsWith(`.${zone}`)) return fqdn;
159 return `${name.replace(/\.$/, "").toLowerCase()}.${zone}`;
160 };
161
162 const dnsLabel = (value: string) => {
163 const cleaned = value.toLowerCase().replace(/[^a-z0-9-]/g, "-");
164 const trimmed = cleaned.replace(/^-+/, "").slice(0, MAX_LABEL_LENGTH);
165 const started = /^[a-z]/.test(trimmed) ? trimmed : `r${trimmed}`;
166 return started.replace(/-+$/g, "").slice(0, MAX_LABEL_LENGTH);
167 };
168
169 const sameRrdatas = (left: string[] | undefined, right: string[] | undefined) =>
170 JSON.stringify(left ?? []) === JSON.stringify(right ?? []);
171
172 const sameRoutingPolicy = (
173 left: ResourceRecordSetRoutingPolicy | undefined,
174 right: ResourceRecordSetRoutingPolicy | undefined,
175 ) => JSON.stringify(left ?? null) === JSON.stringify(right ?? null);
176
177 const nameIdentityChanged = (newsName: string | undefined, previousName: string | undefined) => {
178 if (newsName === undefined || previousName === undefined) return false;
179 const previous = normalizeFqdn(previousName);
180 if (isRelativeName(newsName)) {
181 const label = newsName.replace(/\.$/, "").toLowerCase();
182 return previous.split(".")[0] !== label;
183 }
184 return normalizeFqdn(newsName) !== previous;
185 };
186
187 const isApexSystemRecord = (record: dns.ResourceRecordSet, dnsName: string | undefined) => {
188 const type = normalizeType(record.type ?? "");
189 if (!SYSTEM_TYPES.has(type)) return false;
190 if (dnsName === undefined || record.name === undefined) {
191 return type === "SOA";
192 }
193 return normalizeFqdn(record.name) === normalizeFqdn(dnsName);
194 };
195
196 const hasAlchemyZoneLabels = (labels: Record<string, string | undefined> | null | undefined) =>
197 Object.keys(labels ?? {}).some((key) => key.startsWith(ALCHEMY_LABEL_PREFIX));
198
199 const toBody = (props: {
200 name: string;
201 type: string;
202 ttl: number;
203 rrdatas?: string[];
204 routingPolicy?: ResourceRecordSetRoutingPolicy;
205 }): dns.ResourceRecordSet =>
206 props.routingPolicy !== undefined
207 ? {
208 name: props.name,
209 type: props.type,
210 ttl: props.ttl,
211 routingPolicy: props.routingPolicy,
212 }
213 : {
214 name: props.name,
215 type: props.type,
216 ttl: props.ttl,
217 rrdatas: props.rrdatas ?? [],
218 };
219
220 const toAttrs = (record: dns.ResourceRecordSet, project: string, managedZone: string) => ({
221 project,
222 managedZone,
223 name: record.name ? normalizeFqdn(record.name) : "",
224 type: normalizeType(record.type ?? ""),
225 ttl: record.ttl ?? DEFAULT_TTL,
226 rrdatas: record.rrdatas ?? [],
227 routingPolicy: record.routingPolicy,
228 signatureRrdatas: record.signatureRrdatas,
229 kind: record.kind,
230 });
231
232 const getZone = (project: string, managedZone: string) =>
233 dns
234 .getManagedZones({ project, managedZone })
235 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
236
237 const getByName = (project: string, managedZone: string, name: string, type: string) =>
238 dns
239 .getResourceRecordSets({ project, managedZone, name, type })
240 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
241
242 const toRecordName = (
243 id: string,
244 name: string | undefined,
245 existing: string | undefined,
246 dnsName: string,
247 ) =>
248 Effect.gen(function* () {
249 if (name !== undefined) return qualifyName(name, dnsName);
250 if (existing !== undefined) return normalizeFqdn(existing);
251 const generated = yield* createPhysicalName({
252 id,
253 maxLength: MAX_LABEL_LENGTH,
254 lowercase: true,
255 });
256 return `${dnsLabel(generated)}.${normalizeFqdn(dnsName)}`;
257 });
258
259 const listRrsets = (project: string, zoneName: string) =>
260 Effect.gen(function* () {
261 const found: dns.ResourceRecordSet[] = [];
262 let pageToken: string | undefined;
263 for (let page = 0; page < 10; page++) {
264 const response = yield* dns.listResourceRecordSets({
265 project,
266 managedZone: zoneName,
267 maxResults: 1000,
268 pageToken,
269 });
270 found.push(...(response.rrsets ?? []));
271 pageToken = response.nextPageToken;
272 if (pageToken === undefined || pageToken === "") break;
273 }
274 return found;
275 }).pipe(Effect.catchTag("NotFound", () => Effect.succeed([] as dns.ResourceRecordSet[])));
276
277 const listAlchemyZones = (project: string) =>
278 Effect.gen(function* () {
279 const found: dns.ManagedZone[] = [];
280 let pageToken: string | undefined;
281 for (let page = 0; page < 10; page++) {
282 const response = yield* dns.listManagedZones({
283 project,
284 maxResults: 1000,
285 pageToken,
286 });
287 for (const zone of response.managedZones ?? []) {
288 if (hasAlchemyZoneLabels(zone.labels)) found.push(zone);
289 }
290 pageToken = response.nextPageToken;
291 if (pageToken === undefined || pageToken === "") break;
292 }
293 return found;
294 });
295
296 export const ResourceRecordSetProvider = () =>
297 Provider.succeed(ResourceRecordSet, {
298 stables: ["project", "managedZone", "name", "type"],
299
300 diff: Effect.fn(function* ({ news, olds, output }) {
301 if (!isResolved(news)) return undefined;
302 const previousZone = olds?.managedZone ?? output?.managedZone;
303 const previousName = olds?.name ?? output?.name;
304 const previousType = olds?.type ?? output?.type;
305 const nextType = normalizeType(news.type);
306 const zoneChanged = previousZone !== undefined && news.managedZone !== previousZone;
307 const typeChanged = previousType !== undefined && nextType !== normalizeType(previousType);
308 const nameChanged = nameIdentityChanged(news.name, previousName);
309 if (zoneChanged || typeChanged || nameChanged) {
310 return { action: "replace" as const, deleteFirst: false };
311 }
312 return undefined;
313 }),
314
315 read: Effect.fn(function* ({ id, olds, output }) {
316 const env = yield* GcpEnvironment.current;
317 const managedZone = output?.managedZone ?? olds?.managedZone;
318 const typeRaw = output?.type ?? olds?.type;
319 if (managedZone === undefined || typeRaw === undefined) {
320 return undefined;
321 }
322 const type = normalizeType(typeRaw);
323 const zone = yield* getZone(env.project, managedZone);
324 if (zone === undefined || zone.name === undefined) return undefined;
325 const name = yield* toRecordName(id, olds?.name, output?.name, zone.dnsName ?? zone.name);
326 const existing = yield* getByName(env.project, zone.name, name, type);
327 if (existing === undefined) return undefined;
328 // Record sets have no labels. Identity (zone + name + type) is
329 // ownership — same as Route 53 records.
330 return toAttrs(existing, env.project, zone.name);
331 }),
332
333 list: () =>
334 Effect.gen(function* () {
335 const env = yield* GcpEnvironment.current;
336 const zones = yield* listAlchemyZones(env.project);
337 const pages = yield* Effect.forEach(
338 zones,
339 (zone) =>
340 zone.name
341 ? listRrsets(env.project, zone.name).pipe(
342 Effect.map((records) =>
343 records
344 .filter((record) => !isApexSystemRecord(record, zone.dnsName))
345 .map((record) => toAttrs(record, env.project, zone.name ?? "")),
346 ),
347 )
348 : Effect.succeed([] as ReturnType<typeof toAttrs>[]),
349 { concurrency: 4 },
350 );
351 return pages.flat();
352 }),
353
354 reconcile: Effect.fn(function* ({ id, news, output }) {
355 const env = yield* GcpEnvironment.current;
356 const zone = yield* getZone(env.project, news.managedZone);
357 if (zone === undefined || zone.name === undefined) {
358 return yield* new ResourceRecordSetZoneNotFound({
359 managedZone: news.managedZone,
360 });
361 }
362 const managedZone = zone.name;
363 const type = normalizeType(news.type);
364 const name = yield* toRecordName(id, news.name, output?.name, zone.dnsName ?? managedZone);
365 const ttl = news.ttl ?? DEFAULT_TTL;
366 const desired = toBody({
367 name,
368 type,
369 ttl,
370 rrdatas: news.rrdatas,
371 routingPolicy: news.routingPolicy,
372 });
373
374 let current = yield* getByName(env.project, managedZone, name, type);
375
376 if (current === undefined) {
377 const created = yield* dns
378 .createResourceRecordSets({
379 project: env.project,
380 managedZone,
381 body: desired,
382 })
383 .pipe(Effect.catchTag("Conflict", () => getByName(env.project, managedZone, name, type)));
384 current = created ?? undefined;
385 }
386
387 if (current === undefined) {
388 return yield* new ResourceRecordSetNotResolved({
389 managedZone,
390 resourceName: name,
391 type,
392 });
393 }
394
395 const ttlChanged = (current.ttl ?? DEFAULT_TTL) !== ttl;
396 const rrdatasChanged = !sameRrdatas(current.rrdatas, desired.rrdatas);
397 const routingChanged = !sameRoutingPolicy(current.routingPolicy, desired.routingPolicy);
398
399 if (ttlChanged || rrdatasChanged || routingChanged) {
400 current = yield* dns.patchResourceRecordSets({
401 project: env.project,
402 managedZone,
403 name,
404 type,
405 body: desired,
406 });
407 }
408
409 return toAttrs(current, env.project, managedZone);
410 }),
411
412 delete: Effect.fn(function* ({ output }) {
413 yield* dns
414 .deleteResourceRecordSets({
415 project: output.project,
416 managedZone: output.managedZone,
417 name: output.name,
418 type: output.type,
419 })
420 .pipe(Effect.catchTag("NotFound", () => Effect.void));
421 }),
422 });