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

main
ts 466 lines 16.2 KB
Raw
1 import * as dns from "@distilled.cloud/gcp/dns_v1";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import { tagRecord } from "alchemy/Tags";
8 import * as Data from "effect/Data";
9 import * as Effect from "effect/Effect";
10 import { GcpEnvironment } from "../Environment.ts";
11 import {
12 createInternalLabels,
13 diffLabels,
14 hasAlchemyLabels,
15 stripInternalLabels,
16 toLabels,
17 } from "../Labels.ts";
18 import { type LongRunningOperation, waitForOperation as waitForLongRunning } from "../Operation.ts";
19 import type { Providers } from "../Providers.ts";
20
21 const MAX_NAME_LENGTH = 63;
22 const DEFAULT_VISIBILITY = "public";
23 const GENERATED_DNS_SUFFIX = ".alchemy-gcp-test.";
24
25 export type ManagedZoneVisibility = "public" | "private";
26
27 export type ManagedZoneProps = {
28 /**
29 * User-assigned zone name, unique within the project. If omitted, a
30 * unique RFC1035 name is generated from the stack, stage, and logical
31 * id. Must be 1-63 characters, begin with a letter, end with a letter
32 * or digit, and contain only lowercase letters, digits, or dashes.
33 * Immutable — changing it replaces the zone.
34 */
35 zoneName?: string;
36 /**
37 * DNS name of the zone, for instance `"example.com."`. A trailing dot
38 * is added if omitted. If the prop is omitted entirely, a unique name
39 * is derived from `zoneName` (`{zoneName}.alchemy-gcp-test.`).
40 * Immutable — changing it replaces the zone.
41 */
42 dnsName?: string;
43 /**
44 * Human-readable description (max 1024 characters).
45 */
46 description?: string;
47 /**
48 * Zone visibility. Public zones are exposed to the Internet; private
49 * zones are visible only to VPC resources listed in `networks`.
50 * Immutable — changing it replaces the zone.
51 * @default "public"
52 */
53 visibility?: ManagedZoneVisibility;
54 /**
55 * VPC networks that can query a private zone. Each value may be a
56 * network name, a `projects/.../global/networks/...` path, or a full
57 * compute URL. Ignored for public zones. Updates in place.
58 */
59 networks?: string[];
60 /**
61 * Enable Cloud DNS query logging. Public zones only.
62 * @default false
63 */
64 enableLogging?: boolean;
65 /**
66 * User labels. Alchemy ownership labels are merged in automatically.
67 */
68 labels?: Record<string, string>;
69 /**
70 * Delete all non-SOA/NS record sets before destroying the zone.
71 * @default false
72 */
73 forceDestroy?: boolean;
74 };
75
76 export type ManagedZone = Resource<
77 "GCP.DNS.ManagedZone",
78 ManagedZoneProps,
79 {
80 /** User-assigned zone name. */
81 zoneName: string;
82 /** DNS name, including the trailing dot. */
83 dnsName: string;
84 /** Project id. */
85 project: string;
86 /** Server-assigned numeric id. */
87 id: string | undefined;
88 /** `public` or `private`. */
89 visibility: string;
90 /** User description. */
91 description: string | undefined;
92 /** User labels (Alchemy ownership labels stripped). */
93 labels: Record<string, string>;
94 /** Whether query logging is enabled. */
95 enableLogging: boolean;
96 /** VPC network URLs for a private zone. */
97 networks: ReadonlyArray<string>;
98 /** Authoritative name servers (output only). */
99 nameServers: ReadonlyArray<string>;
100 /** RFC3339 creation timestamp. */
101 creationTime: string | undefined;
102 },
103 never,
104 Providers
105 >;
106
107 /**
108 * A Cloud DNS managed zone.
109 *
110 * Name, DNS name, and visibility are identity — changing them replaces
111 * the zone. Description, labels, query logging, and the private-zone
112 * network list update in place.
113 *
114 * ### Creating a Zone
115 * **Example:** Generated name (public)
116 * ```typescript
117 * const zone = yield* GCP.DNS.ManagedZone("Public", {
118 * forceDestroy: true,
119 * });
120 * ```
121 *
122 * **Example:** Explicit name, DNS name, and labels
123 * ```typescript
124 * const zone = yield* GCP.DNS.ManagedZone("Public", {
125 * zoneName: "app-public",
126 * dnsName: "app.example.com.",
127 * description: "application public zone",
128 * labels: { env: "prod" },
129 * enableLogging: true,
130 * forceDestroy: true,
131 * });
132 * ```
133 *
134 * ### Private Zone
135 * **Example:** Private zone visible from one VPC
136 * ```typescript
137 * const zone = yield* GCP.DNS.ManagedZone("Internal", {
138 * dnsName: "internal.example.com.",
139 * visibility: "private",
140 * networks: ["app-vpc"],
141 * forceDestroy: true,
142 * });
143 * ```
144 *
145 * @resource
146 * @category DNS
147 */
148 export const ManagedZone = Resource<ManagedZone>("GCP.DNS.ManagedZone");
149
150 export class ManagedZoneNotResolved extends Data.TaggedError("GCP.DNS.ManagedZoneNotResolved")<{
151 zoneName: string;
152 }> {}
153
154 const userLabels = (
155 labels: Record<string, string | undefined> | null | undefined,
156 ): Record<string, string> => stripInternalLabels(tagRecord(labels));
157
158 const lastSegment = (value: string) => {
159 const trimmed = value.replace(/\/+$/, "");
160 const parts = trimmed.split("/");
161 return parts[parts.length - 1] || trimmed;
162 };
163
164 const isDone = (status: string | undefined) => (status ?? "").toLowerCase() === "done";
165
166 const normalizeDnsName = (value: string) => (value.endsWith(".") ? value : `${value}.`);
167
168 const normalizeVisibility = (value: string | undefined) =>
169 (value ?? DEFAULT_VISIBILITY).toLowerCase();
170
171 const toZoneName = (id: string, name: string | undefined, existing?: string) =>
172 Effect.gen(function* () {
173 if (name !== undefined) return name;
174 if (existing !== undefined) return existing;
175 const generated = yield* createPhysicalName({
176 id,
177 maxLength: MAX_NAME_LENGTH,
178 lowercase: true,
179 });
180 return /^[a-z]/.test(generated) ? generated : `a${generated}`.slice(0, MAX_NAME_LENGTH);
181 });
182
183 const toDnsName = (zoneName: string, dnsName: string | undefined, existing?: string) =>
184 dnsName !== undefined
185 ? normalizeDnsName(dnsName)
186 : existing !== undefined
187 ? normalizeDnsName(existing)
188 : `${zoneName}${GENERATED_DNS_SUFFIX}`;
189
190 const toNetworkUrl = (project: string, network: string) => {
191 if (network.startsWith("https://") || network.startsWith("http://")) {
192 return network;
193 }
194 if (network.includes("/")) {
195 const path = network.replace(/^\//, "");
196 return path.startsWith("compute/")
197 ? `https://www.googleapis.com/${path}`
198 : `https://www.googleapis.com/compute/v1/${path}`;
199 }
200 return `https://www.googleapis.com/compute/v1/projects/${project}/global/networks/${network}`;
201 };
202
203 const desiredNetworks = (project: string, networks: string[] | undefined) =>
204 [...new Set((networks ?? []).map((network) => toNetworkUrl(project, network)))].sort(
205 (left, right) => lastSegment(left).localeCompare(lastSegment(right)),
206 );
207
208 const observedNetworks = (zone: dns.ManagedZone) =>
209 (zone.privateVisibilityConfig?.networks ?? [])
210 .map((network) => network.networkUrl ?? "")
211 .filter((url) => url.length > 0)
212 .sort((left, right) => lastSegment(left).localeCompare(lastSegment(right)));
213
214 const sameNetworks = (left: string[], right: string[]) =>
215 left.length === right.length &&
216 left.every((url, index) => lastSegment(url) === lastSegment(right[index] ?? ""));
217
218 const toAttrs = (zone: dns.ManagedZone, project: string) => ({
219 zoneName: zone.name ?? "",
220 dnsName: zone.dnsName ?? "",
221 project,
222 id: zone.id,
223 visibility: zone.visibility ?? DEFAULT_VISIBILITY,
224 description: zone.description && zone.description.length > 0 ? zone.description : undefined,
225 labels: userLabels(zone.labels),
226 enableLogging: zone.cloudLoggingConfig?.enableLogging === true,
227 networks: observedNetworks(zone),
228 nameServers: zone.nameServers ?? [],
229 creationTime: zone.creationTime,
230 });
231
232 const getByName = (project: string, zoneName: string) =>
233 dns
234 .getManagedZones({ project, managedZone: zoneName })
235 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
236
237 /** Cloud DNS operations and changes report `status: "pending" | "done"`. */
238 const asLongRunning = (value: { id?: string; status?: string }): LongRunningOperation => ({
239 name: value.id,
240 done: isDone(value.status),
241 });
242
243 /** Zone updates and record changes propagate within a few minutes. */
244 const DNS_BUDGET = "5 minutes";
245
246 const waitForOperation = (project: string, zoneName: string, operation: dns.Operation) =>
247 waitForLongRunning(
248 asLongRunning(operation),
249 (operationId) =>
250 dns
251 .getManagedZoneOperations({
252 project,
253 managedZone: zoneName,
254 operation: operationId,
255 })
256 .pipe(Effect.map(asLongRunning)),
257 { budget: DNS_BUDGET, interval: "1 second" },
258 );
259
260 const waitForChange = (project: string, zoneName: string, change: dns.Change) =>
261 waitForLongRunning(
262 asLongRunning(change),
263 (changeId) =>
264 dns.getChanges({ project, managedZone: zoneName, changeId }).pipe(Effect.map(asLongRunning)),
265 { budget: DNS_BUDGET, interval: "1 second" },
266 );
267
268 const listRrsets = (project: string, zoneName: string) =>
269 Effect.gen(function* () {
270 const found: dns.ResourceRecordSet[] = [];
271 let pageToken: string | undefined;
272 for (let page = 0; page < 10; page++) {
273 const response = yield* dns.listResourceRecordSets({
274 project,
275 managedZone: zoneName,
276 maxResults: 1000,
277 pageToken,
278 });
279 found.push(...(response.rrsets ?? []));
280 pageToken = response.nextPageToken;
281 if (pageToken === undefined || pageToken === "") break;
282 }
283 return found;
284 }).pipe(Effect.catchTag("NotFound", () => Effect.succeed([] as dns.ResourceRecordSet[])));
285
286 const emptyZone = (project: string, zoneName: string, dnsName: string | undefined) =>
287 Effect.gen(function* () {
288 const apex = dnsName ? normalizeDnsName(dnsName) : undefined;
289 const extra = (yield* listRrsets(project, zoneName)).filter((rrset) => {
290 const type = rrset.type ?? "";
291 const name = rrset.name ?? "";
292 if (apex !== undefined && name === apex && (type === "NS" || type === "SOA")) {
293 return false;
294 }
295 return true;
296 });
297 if (extra.length === 0) return;
298 const change = yield* dns.createChanges({
299 project,
300 managedZone: zoneName,
301 body: { deletions: extra },
302 });
303 yield* waitForChange(project, zoneName, change);
304 });
305
306 const privateVisibilityConfig = (networks: string[]) =>
307 networks.length === 0
308 ? undefined
309 : {
310 networks: networks.map((networkUrl) => ({ networkUrl })),
311 };
312
313 export const ManagedZoneProvider = () =>
314 Provider.succeed(ManagedZone, {
315 stables: ["zoneName", "dnsName", "project", "id", "visibility", "nameServers", "creationTime"],
316
317 diff: Effect.fn(function* ({ news, olds, output }) {
318 if (!isResolved(news)) return undefined;
319
320 const previousName = olds?.zoneName ?? output?.zoneName;
321 const nextName = news.zoneName ?? previousName;
322 const nameChanged =
323 previousName !== undefined && nextName !== undefined && nextName !== previousName;
324
325 const previousDns = olds?.dnsName ?? output?.dnsName;
326 const nextDns =
327 news.dnsName !== undefined
328 ? normalizeDnsName(news.dnsName)
329 : previousDns !== undefined
330 ? normalizeDnsName(previousDns)
331 : undefined;
332 const dnsChanged =
333 previousDns !== undefined &&
334 nextDns !== undefined &&
335 normalizeDnsName(previousDns) !== nextDns;
336
337 const previousVisibility = normalizeVisibility(olds?.visibility ?? output?.visibility);
338 const nextVisibility = normalizeVisibility(news.visibility ?? previousVisibility);
339 const visibilityChanged = previousVisibility !== nextVisibility;
340
341 if (!nameChanged && !dnsChanged && !visibilityChanged) {
342 return undefined;
343 }
344 return {
345 action: "replace" as const,
346 deleteFirst:
347 previousName !== undefined && nextName !== undefined && nextName === previousName,
348 };
349 }),
350
351 read: Effect.fn(function* ({ id, olds, output }) {
352 const env = yield* GcpEnvironment.current;
353 const zoneName = yield* toZoneName(id, olds?.zoneName, output?.zoneName);
354 const existing = yield* getByName(env.project, zoneName);
355 if (existing === undefined) return undefined;
356 const attrs = toAttrs(existing, env.project);
357 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
358 }),
359
360 list: () =>
361 Effect.gen(function* () {
362 const env = yield* GcpEnvironment.current;
363 const found: ReturnType<typeof toAttrs>[] = [];
364 let pageToken: string | undefined;
365 for (let page = 0; page < 10; page++) {
366 const response = yield* dns.listManagedZones({
367 project: env.project,
368 maxResults: 1000,
369 pageToken,
370 });
371 for (const zone of response.managedZones ?? []) {
372 if (Object.keys(zone.labels ?? {}).some((key) => key.startsWith("alchemy-"))) {
373 found.push(toAttrs(zone, env.project));
374 }
375 }
376 pageToken = response.nextPageToken;
377 if (pageToken === undefined || pageToken === "") break;
378 }
379 return found;
380 }),
381
382 reconcile: Effect.fn(function* ({ id, news, output }) {
383 const env = yield* GcpEnvironment.current;
384 const zoneName = yield* toZoneName(id, news.zoneName, output?.zoneName);
385 const dnsName = toDnsName(zoneName, news.dnsName, output?.dnsName);
386 const visibility = normalizeVisibility(news.visibility ?? output?.visibility);
387 const description = news.description ?? "";
388 const enableLogging = news.enableLogging === true;
389 const networks = visibility === "private" ? desiredNetworks(env.project, news.networks) : [];
390 const desiredLabels = {
391 ...toLabels(news.labels),
392 ...(yield* createInternalLabels(id)),
393 };
394
395 let current = yield* getByName(env.project, zoneName);
396
397 if (current === undefined) {
398 const created = yield* dns
399 .createManagedZones({
400 project: env.project,
401 body: {
402 name: zoneName,
403 dnsName,
404 description,
405 visibility,
406 labels: desiredLabels,
407 cloudLoggingConfig: { enableLogging },
408 privateVisibilityConfig: privateVisibilityConfig(networks),
409 },
410 })
411 .pipe(Effect.catchTag("Conflict", () => getByName(env.project, zoneName)));
412 current = created ?? undefined;
413 }
414
415 if (current === undefined) {
416 return yield* new ManagedZoneNotResolved({ zoneName });
417 }
418
419 const observedLabels = tagRecord(current.labels);
420 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
421 const labelsChanged = upsert.length > 0 || removed.length > 0;
422 const descriptionChanged = (current.description ?? "") !== description;
423 const loggingChanged = (current.cloudLoggingConfig?.enableLogging === true) !== enableLogging;
424 const networksChanged =
425 visibility === "private" && !sameNetworks(observedNetworks(current), networks);
426
427 if (labelsChanged || descriptionChanged || loggingChanged || networksChanged) {
428 const body: dns.ManagedZone = {};
429 if (labelsChanged) body.labels = desiredLabels;
430 if (descriptionChanged) body.description = description;
431 if (loggingChanged) {
432 body.cloudLoggingConfig = { enableLogging };
433 }
434 if (networksChanged) {
435 body.privateVisibilityConfig = privateVisibilityConfig(networks);
436 }
437 const operation = yield* dns.patchManagedZones({
438 project: env.project,
439 managedZone: zoneName,
440 body,
441 });
442 yield* waitForOperation(env.project, zoneName, operation);
443 current = (yield* getByName(env.project, zoneName)) ?? current;
444 }
445
446 return toAttrs(current, env.project);
447 }),
448
449 delete: Effect.fn(function* ({ olds, output, force }) {
450 const mayEmpty = olds.forceDestroy === true || force === true;
451 const project = output.project;
452 const zoneName = output.zoneName;
453 if (mayEmpty) {
454 yield* emptyZone(project, zoneName, output.dnsName);
455 }
456 const attempt = dns
457 .deleteManagedZones({ project, managedZone: zoneName })
458 .pipe(Effect.catchTag("NotFound", () => Effect.void));
459 yield* attempt.pipe(
460 Effect.catchIf(
461 (error) => mayEmpty && (error._tag === "Conflict" || error._tag === "BadRequest"),
462 () => emptyZone(project, zoneName, output.dnsName).pipe(Effect.andThen(attempt)),
463 ),
464 );
465 }),
466 });