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

main
ts 369 lines 12.7 KB
Raw
1 import * as dns from "@distilled.cloud/cloudflare/dns";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource, type ResourceBinding } from "alchemy/Resource";
6 import * as Effect from "effect/Effect";
7 import * as Stream from "effect/Stream";
8 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
9 import type { Providers } from "../Providers.ts";
10 import { resolveZoneId, type Reference as ZoneReference } from "../Zone/lookup.ts";
11
12 /** Record types a {@link Records} set can manage. */
13 export type RecordsType = "A" | "AAAA" | "CNAME";
14
15 /**
16 * Binding contract of {@link Records}: composites (e.g. an
17 * `AWS.Website.StaticSite` attached to an `AWS.Website.Router`) contribute
18 * additional record names without a circular input prop.
19 */
20 export type RecordsBinding = {
21 /**
22 * Additional record names to manage alongside {@link RecordsProps.names}.
23 */
24 names?: string[];
25 };
26
27 export interface RecordsProps {
28 /**
29 * Zone that owns the records — a zone id, zone name, or `Zone`
30 * resource. When omitted, the
31 * zone containing the set's first name is inferred by walking its parent
32 * domains; the deploy fails actionably when no zone matches. Every name in
33 * the set lives in the one zone either way.
34 */
35 zone?: ZoneReference;
36 /**
37 * Record type shared by every record in the set. Stable — changing it
38 * replaces the set.
39 */
40 type: RecordsType;
41 /**
42 * Record value shared by every record in the set (e.g. the target
43 * hostname of a CNAME).
44 */
45 content: string;
46 /**
47 * Record names managed by this set. Names contributed through the binding
48 * contract (see {@link RecordsBinding}) are merged in at reconcile time.
49 */
50 names?: string[];
51 /**
52 * Whether to send the records through Cloudflare's proxy.
53 * @default false
54 */
55 proxied?: boolean;
56 /**
57 * TTL in seconds (`60`–`86400`), or `1` for Cloudflare's "automatic"
58 * setting. Must be `1` when `proxied` is `true`.
59 * @default 1
60 */
61 ttl?: number;
62 }
63
64 export interface RecordsAttributes {
65 /**
66 * Zone that owns the records. `undefined` only while the set is empty
67 * with no explicit zone — resolved on the first reconcile that has a
68 * name.
69 */
70 zoneId: string | undefined;
71 /** Record type shared by every record in the set. */
72 type: RecordsType;
73 /** Record value shared by every record in the set. */
74 content: string;
75 /** Whether the records are proxied. */
76 proxied: boolean;
77 /** TTL of the records (`1` = automatic). */
78 ttl: number;
79 /**
80 * Fully qualified names of every record currently managed by this set
81 * (declared `names` plus bound names, as of the last reconcile).
82 */
83 names: string[];
84 }
85
86 export type Records = Resource<
87 "Cloudflare.DNS.Records",
88 RecordsProps,
89 RecordsAttributes,
90 RecordsBinding,
91 Providers
92 >;
93
94 /**
95 * A dynamic set of identically-configured Cloudflare DNS records that differ
96 * only by name — the Cloudflare counterpart of `AWS.Route53.Records`.
97 *
98 * Unlike `Cloudflare.DNS.Record` (one resource per record), `Records`
99 * reconciles a whole name set against the zone: names added to the set are
100 * created or overwritten, names removed from the set are deleted. The set is
101 * the union of the declared `names` prop and names contributed through the
102 * {@link RecordsBinding} binding contract, which is how composites (e.g. a
103 * site attached to an `AWS.Website.Router`) register hostnames on a
104 * distribution's DNS without a circular input prop.
105 *
106 * Ownership: when the set is first created, records that already exist at
107 * its names are reported as not owned, so the deploy refuses to overwrite
108 * them unless `--adopt` (or `adopt(true)`) is set. Names added later are
109 * overwritten like a Route 53 `UPSERT`, and removed again when the name
110 * leaves the set or the set is destroyed. Cloudflare
111 * rejects a `CNAME` at a name that already has `A`/`AAAA` records; remove
112 * those first.
113 * ### Managing Record Sets
114 * **Example:** CNAMEs For Several Hostnames
115 * ```typescript
116 * const records = yield* Cloudflare.DNS.Records("AliasRecords", {
117 * type: "CNAME",
118 * content: distribution.domainName,
119 * names: ["www.example.com", "docs.example.com"],
120 * });
121 * ```
122 *
123 * **Example:** Binding Target For Composite-Contributed Names
124 * ```typescript
125 * // An empty set that attached sites bind their hostnames onto:
126 * const records = yield* Cloudflare.DNS.Records("SiteAliasRecords", {
127 * zone: "example.com",
128 * type: "CNAME",
129 * content: distribution.domainName,
130 * });
131 * // elsewhere:
132 * yield* records.bind`MySite`({ names: ["docs.example.com"] });
133 * ```
134 *
135 * @resource
136 * @product DNS
137 * @category Domains & DNS
138 */
139 export const Records = Resource<Records>("Cloudflare.DNS.Records");
140
141 const normalizeName = (name: string) => name.replace(/\.$/, "").toLowerCase();
142
143 /**
144 * Union of declared and bound record names, normalized (lowercase, no
145 * trailing dot), deduped and sorted for stable comparisons. Tolerates both
146 * `{ sid, data }` rows (provider lifecycle) and bare binding payloads.
147 * @internal
148 */
149 const resolveDesiredNames = (
150 declared: string[] | undefined,
151 bindings: ReadonlyArray<RecordsBinding | ResourceBinding<RecordsBinding>>,
152 ): string[] => {
153 const bound = bindings.flatMap((binding) =>
154 "data" in binding && binding.data !== undefined
155 ? ((binding as ResourceBinding<RecordsBinding>).data.names ?? [])
156 : ((binding as RecordsBinding).names ?? []),
157 );
158 return [...new Set([...(declared ?? []), ...bound].map(normalizeName))].sort((a, b) =>
159 a.localeCompare(b),
160 );
161 };
162
163 const listAtName = (zoneId: string, name: string, type: RecordsType) =>
164 dns.listRecords.items({ zoneId, name: { exact: name }, type }).pipe(
165 Stream.filter((record) => normalizeName(record.name) === name && record.type === type),
166 Stream.runCollect,
167 Effect.map((chunk) => Array.from(chunk)),
168 );
169
170 /** Cloudflare may echo a CNAME target with different casing. */
171 const sameContent = (a: string | null | undefined, b: string) =>
172 normalizeName(a ?? "") === normalizeName(b);
173
174 /**
175 * Converge `(name, type)` to exactly one record with `body`'s value: create
176 * it when missing, overwrite a record that differs (Route 53 `UPSERT`
177 * semantics), and remove extra records sharing the name. A concurrent
178 * create (`DnsRecordAlreadyExists`) is a race — re-observe and converge.
179 */
180 const upsertRecordAt = (
181 zoneId: string,
182 body: {
183 type: RecordsType;
184 name: string;
185 content: string;
186 ttl: number;
187 proxied: boolean;
188 },
189 ) =>
190 Effect.gen(function* () {
191 const name = normalizeName(body.name);
192 const sync = Effect.gen(function* () {
193 const [current, ...extra] = yield* listAtName(zoneId, name, body.type);
194 if (current === undefined) {
195 yield* dns.createRecord({ zoneId, ...body, name });
196 } else if (
197 !sameContent(current.content, body.content) ||
198 current.ttl !== body.ttl ||
199 (current.proxied ?? false) !== body.proxied
200 ) {
201 yield* dns.updateRecord({
202 zoneId,
203 dnsRecordId: current.id,
204 ...body,
205 name,
206 });
207 }
208 yield* Effect.forEach(
209 extra,
210 (record) => dns.deleteRecord({ zoneId, dnsRecordId: record.id }),
211 { discard: true },
212 );
213 });
214 yield* sync.pipe(Effect.catchTag("DnsRecordAlreadyExists", () => sync));
215 });
216
217 const deleteAtNames = (zoneId: string, type: RecordsType, names: string[]) =>
218 Effect.forEach(
219 names,
220 (name) =>
221 listAtName(zoneId, normalizeName(name), type).pipe(
222 Effect.flatMap((found) =>
223 Effect.forEach(found, (record) => dns.deleteRecord({ zoneId, dnsRecordId: record.id }), {
224 discard: true,
225 }),
226 ),
227 ),
228 { discard: true },
229 );
230
231 export const RecordsProvider = () =>
232 Provider.succeed(Records, {
233 stables: ["type"],
234
235 diff: Effect.fn(function* ({ olds, news }) {
236 if (!isResolved(news)) return undefined;
237 // Only the record type is identity. Names, content, ttl, proxied and
238 // even the zone are converged in place by reconcile (a zone move
239 // removes the old zone's records). Delete first: Cloudflare rejects a
240 // CNAME and an A/AAAA record on the same name.
241 if (olds.type !== news.type) {
242 return { action: "replace", deleteFirst: true } as const;
243 }
244 }),
245
246 read: Effect.fn(function* ({ output, olds, previous }) {
247 if (output === undefined) {
248 // No state of our own: records already at the declared names were
249 // not created by this set (DNS records carry no ownership markers),
250 // so brand them `Unowned` — the engine refuses to overwrite them
251 // unless `adopt` is set.
252 const names = resolveDesiredNames(olds?.names, []);
253 if (olds === undefined || names.length === 0) return undefined;
254 const { accountId } = yield* yield* CloudflareEnvironment;
255 const zoneId = yield* resolveZoneId({
256 accountId,
257 zone: olds.zone,
258 hostname: names[0],
259 }).pipe(Effect.orElseSucceed(() => undefined));
260 if (zoneId === undefined) return undefined;
261 const found = (yield* Effect.forEach(names, (name) =>
262 listAtName(zoneId, name, olds.type).pipe(
263 Effect.map((records) =>
264 records[0] === undefined ? [] : [{ name, record: records[0] }],
265 ),
266 ),
267 )).flat();
268 const sample = found[0]?.record;
269 if (sample === undefined) return undefined;
270 const attrs = {
271 zoneId,
272 type: olds.type,
273 content: sample.content ?? olds.content,
274 proxied: sample.proxied ?? false,
275 ttl: sample.ttl ?? 1,
276 names: found.map(({ name }) => name),
277 };
278 // The record set a replacement is replacing is ours.
279 const isPrevious =
280 previous?.zoneId === zoneId &&
281 previous.type === olds.type &&
282 attrs.names.every((name) => previous.names?.includes(name));
283 return isPrevious ? attrs : Unowned(attrs);
284 }
285 if (output.zoneId === undefined) return output;
286 const zoneId = output.zoneId;
287 const observed = yield* Effect.forEach(output.names, (name) =>
288 listAtName(zoneId, name, output.type).pipe(
289 Effect.map((records) => (records[0] === undefined ? [] : [{ name, record: records[0] }])),
290 ),
291 );
292 const found = observed.flat();
293 const sample = found[0]?.record;
294 return {
295 ...output,
296 names: found.map(({ name }) => name),
297 content: sample?.content ?? output.content,
298 ttl: sample?.ttl ?? output.ttl,
299 proxied: sample?.proxied ?? output.proxied,
300 };
301 }),
302
303 reconcile: Effect.fn(function* ({ news, output, session, bindings }) {
304 const desired = resolveDesiredNames(news.names, bindings);
305 const ttl = news.ttl ?? 1;
306 const proxied = news.proxied ?? false;
307 const zone = news.zone ?? output?.zoneId;
308 if (zone === undefined && desired.length === 0) {
309 yield* session.note(`${news.type} × 0 record(s)`);
310 return {
311 zoneId: undefined,
312 type: news.type,
313 content: news.content,
314 proxied,
315 ttl,
316 names: [],
317 };
318 }
319 const { accountId } = yield* yield* CloudflareEnvironment;
320 const zoneId = yield* resolveZoneId({
321 accountId,
322 zone,
323 hostname: desired[0] ?? "",
324 });
325
326 // `output.names` is the cache of which records this resource managed
327 // before — the only way to know what to garbage-collect. A zone move
328 // leaves every previously managed name stale in the old zone.
329 const movedZone = output?.zoneId !== undefined && output.zoneId !== zoneId;
330 const desiredSet = new Set(desired);
331 const stale = (output?.names ?? []).filter(
332 (name) => movedZone || !desiredSet.has(normalizeName(name)),
333 );
334
335 // Sync — observe each desired name and write only the delta.
336 for (const name of desired) {
337 yield* upsertRecordAt(zoneId, {
338 type: news.type,
339 name,
340 content: news.content,
341 ttl,
342 proxied,
343 });
344 }
345
346 // Garbage-collect names that left the set.
347 yield* deleteAtNames(output?.zoneId ?? zoneId, news.type, stale);
348
349 yield* session.note(
350 `${news.type} × ${desired.length} record(s)` +
351 (stale.length > 0 ? ` (-${stale.length})` : ""),
352 );
353
354 return {
355 zoneId,
356 type: news.type,
357 content: news.content,
358 proxied,
359 ttl,
360 names: desired,
361 };
362 }),
363
364 delete: Effect.fn(function* ({ output }) {
365 // The set never resolved a zone — it never created records.
366 if (output.zoneId === undefined) return;
367 yield* deleteAtNames(output.zoneId, output.type, output.names);
368 }),
369 });