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

main
ts 462 lines 16.3 KB
Raw
1 import * as dns from "@distilled.cloud/gcp/dns_v1";
2 import { unownedUnlessPrevious } 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 * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import * as Schedule from "effect/Schedule";
10 import { GcpEnvironment } from "../Environment.ts";
11 import { alchemyLabelKeys, createInternalLabels, hasAlchemyLabels } from "../Labels.ts";
12 import type { Providers } from "../Providers.ts";
13
14 const MAX_NAME_LENGTH = 63;
15
16 export type PolicyAlternativeNameServer = {
17 /**
18 * IPv4 address of the target name server.
19 */
20 ipv4Address?: string;
21 /**
22 * IPv6 address of the target name server. Mutually exclusive with
23 * `ipv4Address`.
24 */
25 ipv6Address?: string;
26 /**
27 * Forwarding path. `default` uses address ranges (RFC1918 via the VPC,
28 * public via the internet). `private` always sends queries through the
29 * VPC.
30 */
31 forwardingPath?:
32 | dns.PolicyAlternativeNameServerConfigTargetNameServerForwardingPathEnum
33 | (string & {});
34 };
35
36 export type PolicyProps = {
37 /**
38 * User-assigned policy name, unique within the project. If omitted, a
39 * unique RFC1035 name is generated from the stack, stage, and logical
40 * id. Must be 1-63 characters, begin with a letter, end with a letter
41 * or digit, and contain only lowercase letters, digits, or dashes.
42 * Immutable — changing it replaces the policy.
43 */
44 policyName?: string;
45 /**
46 * Human-readable description (max 1024 characters). DNS policies have
47 * no labels field, so Alchemy ownership is stored in a `[alchemy …]`
48 * prefix and stripped from attributes.
49 */
50 description?: string;
51 /**
52 * Allow on-premises resolvers to query Cloud DNS using inbound
53 * forwarding VIPs allocated from each bound subnet.
54 * @default false
55 */
56 enableInboundForwarding?: boolean;
57 /**
58 * Enable Cloud DNS query logging for bound networks.
59 * @default false
60 */
61 enableLogging?: boolean;
62 /**
63 * VPC networks this policy applies to. Each value may be a network
64 * name, a `projects/.../global/networks/...` path, or a full compute
65 * URL. A network may belong to at most one DNS server policy. Updates
66 * in place.
67 */
68 networks?: string[];
69 /**
70 * Outbound forwarding targets. When set, all DNS queries from bound
71 * networks are forwarded to these name servers (Cloud DNS private
72 * zones such as `.internal` are not consulted).
73 */
74 alternativeNameServers?: PolicyAlternativeNameServer[];
75 /**
76 * Enable DNS64 (`dns64Config.scope.allQueries`) for bound networks.
77 * @default false
78 */
79 enableDns64?: boolean;
80 };
81
82 export type Policy = Resource<
83 "GCP.DNS.Policy",
84 PolicyProps,
85 {
86 /** User-assigned policy name. */
87 policyName: string;
88 /** Project id. */
89 project: string;
90 /** Server-assigned numeric id. */
91 id: string | undefined;
92 /** User description (Alchemy ownership marker stripped). */
93 description: string | undefined;
94 /** Whether inbound forwarding is enabled. */
95 enableInboundForwarding: boolean;
96 /** Whether query logging is enabled. */
97 enableLogging: boolean;
98 /** VPC network URLs bound to this policy. */
99 networks: ReadonlyArray<string>;
100 /** Outbound forwarding targets. */
101 alternativeNameServers: ReadonlyArray<PolicyAlternativeNameServer>;
102 /** Whether DNS64 is enabled for all queries. */
103 enableDns64: boolean;
104 /** Server-reported kind (`dns#policy`). */
105 kind: string | undefined;
106 },
107 never,
108 Providers
109 >;
110
111 /**
112 * A Cloud DNS server policy applied to one or more VPC networks.
113 *
114 * A policy controls inbound DNS forwarding, outbound forwarding to
115 * alternative name servers, query logging, and DNS64. Name is identity
116 * — changing it replaces the policy. A VPC network can belong to at
117 * most one server policy.
118 *
119 * DNS policies have no labels. Alchemy stamps
120 * `alchemy-stack` / `alchemy-stage` / `alchemy-id` into the description
121 * so `list` and `pnpm nuke:gcp` can identify owned policies.
122 *
123 * ### Creating a Policy
124 * **Example:** Generated name, logging enabled
125 * ```typescript
126 * const vpc = yield* GCP.Compute.Network("Vpc", {
127 * autoCreateSubnetworks: false,
128 * });
129 * const policy = yield* GCP.DNS.Policy("CorpDns", {
130 * enableLogging: true,
131 * networks: [vpc.networkName],
132 * });
133 * ```
134 *
135 * **Example:** Explicit name, inbound forwarding, and description
136 * ```typescript
137 * const policy = yield* GCP.DNS.Policy("CorpDns", {
138 * policyName: "corp-dns",
139 * description: "inbound resolver for on-prem",
140 * enableInboundForwarding: true,
141 * enableLogging: true,
142 * networks: ["app-vpc"],
143 * });
144 * ```
145 *
146 * ### Outbound Forwarding
147 * **Example:** Forward all queries to on-prem name servers
148 * ```typescript
149 * const policy = yield* GCP.DNS.Policy("Forward", {
150 * networks: ["app-vpc"],
151 * alternativeNameServers: [{ ipv4Address: "192.0.2.53" }],
152 * });
153 * ```
154 *
155 * @resource
156 * @category DNS
157 */
158 export const Policy = Resource<Policy>("GCP.DNS.Policy");
159
160 export class PolicyNotResolved extends Data.TaggedError("GCP.DNS.PolicyNotResolved")<{
161 policyName: string;
162 }> {}
163
164 const lastSegment = (value: string) => {
165 const trimmed = value.replace(/\/+$/, "");
166 const parts = trimmed.split("/");
167 return parts[parts.length - 1] || trimmed;
168 };
169
170 const toNetworkUrl = (project: string, network: string) => {
171 if (network.startsWith("https://") || network.startsWith("http://")) {
172 return network;
173 }
174 if (network.includes("/")) {
175 const path = network.replace(/^\//, "");
176 return path.startsWith("compute/")
177 ? `https://www.googleapis.com/${path}`
178 : `https://www.googleapis.com/compute/v1/${path}`;
179 }
180 return `https://www.googleapis.com/compute/v1/projects/${project}/global/networks/${network}`;
181 };
182
183 const desiredNetworks = (project: string, networks: string[] | undefined) =>
184 [...new Set((networks ?? []).map((network) => toNetworkUrl(project, network)))].sort(
185 (left, right) => lastSegment(left).localeCompare(lastSegment(right)),
186 );
187
188 const observedNetworks = (policy: dns.Policy) =>
189 (policy.networks ?? [])
190 .map((network) => network.networkUrl ?? "")
191 .filter((url) => url.length > 0)
192 .sort((left, right) => lastSegment(left).localeCompare(lastSegment(right)));
193
194 const sameNetworks = (left: string[], right: string[]) =>
195 left.length === right.length &&
196 left.every((url, index) => lastSegment(url) === lastSegment(right[index] ?? ""));
197
198 const desiredNameServers = (
199 servers: PolicyAlternativeNameServer[] | undefined,
200 ): PolicyAlternativeNameServer[] =>
201 (servers ?? []).map((server) => ({
202 ipv4Address: server.ipv4Address,
203 ipv6Address: server.ipv6Address,
204 forwardingPath: server.forwardingPath,
205 }));
206
207 const observedNameServers = (policy: dns.Policy): PolicyAlternativeNameServer[] =>
208 (policy.alternativeNameServerConfig?.targetNameServers ?? []).map((server) => ({
209 ipv4Address: server.ipv4Address,
210 ipv6Address: server.ipv6Address,
211 forwardingPath: server.forwardingPath,
212 }));
213
214 const sameNameServers = (
215 left: PolicyAlternativeNameServer[],
216 right: PolicyAlternativeNameServer[],
217 ) => JSON.stringify(left) === JSON.stringify(right);
218
219 const encodeDescription = (internal: Record<string, string>, user?: string): string => {
220 const marker = `[alchemy ${alchemyLabelKeys.stack}=${internal[alchemyLabelKeys.stack] ?? ""} ${alchemyLabelKeys.stage}=${internal[alchemyLabelKeys.stage] ?? ""} ${alchemyLabelKeys.id}=${internal[alchemyLabelKeys.id] ?? ""}]`;
221 return user && user.length > 0 ? `${marker}\n${user}` : marker;
222 };
223
224 const parseDescription = (description: string | undefined) => {
225 if (!description?.startsWith("[alchemy ")) {
226 return { labels: {} as Record<string, string>, description };
227 }
228 const end = description.indexOf("]");
229 if (end < 0) return { labels: {} as Record<string, string>, description };
230 const labels: Record<string, string> = {};
231 for (const part of description.slice("[alchemy ".length, end).split(/\s+/)) {
232 const eq = part.indexOf("=");
233 if (eq > 0) {
234 labels[part.slice(0, eq)] = part.slice(eq + 1);
235 }
236 }
237 const rest = description.slice(end + 1).replace(/^\n/, "");
238 return {
239 labels,
240 description: rest.length > 0 ? rest : undefined,
241 };
242 };
243
244 const hasAlchemyMarker = (description: string | undefined) =>
245 Object.keys(parseDescription(description).labels).some((key) => key.startsWith("alchemy-"));
246
247 const toPolicyName = (id: string, name: string | undefined, existing?: string) =>
248 Effect.gen(function* () {
249 if (name !== undefined) return name;
250 if (existing !== undefined) return existing;
251 const generated = yield* createPhysicalName({
252 id,
253 maxLength: MAX_NAME_LENGTH,
254 lowercase: true,
255 });
256 const rfc = generated
257 .replace(/[^a-z0-9-]/g, "-")
258 .replace(/^[^a-z]+/, "p")
259 .slice(0, MAX_NAME_LENGTH)
260 .replace(/-+$/g, "");
261 return rfc.length > 0 ? rfc : "p";
262 });
263
264 const toAttrs = (policy: dns.Policy, project: string) => ({
265 policyName: policy.name ?? "",
266 project,
267 id: policy.id,
268 description: parseDescription(policy.description).description,
269 enableInboundForwarding: policy.enableInboundForwarding === true,
270 enableLogging: policy.enableLogging === true,
271 networks: observedNetworks(policy),
272 alternativeNameServers: observedNameServers(policy),
273 enableDns64: policy.dns64Config?.scope?.allQueries === true,
274 kind: policy.kind,
275 });
276
277 const getByName = (project: string, policyName: string) =>
278 dns
279 .getPolicies({ project, policy: policyName })
280 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
281
282 const alternativeNameServerConfig = (
283 servers: PolicyAlternativeNameServer[],
284 ): dns.PolicyAlternativeNameServerConfig | undefined =>
285 servers.length === 0
286 ? undefined
287 : {
288 targetNameServers: servers.map((server) => ({
289 ipv4Address: server.ipv4Address,
290 ipv6Address: server.ipv6Address,
291 forwardingPath: server.forwardingPath,
292 })),
293 };
294
295 const dns64Config = (enable: boolean): dns.PolicyDns64Config | undefined =>
296 enable ? { scope: { allQueries: true } } : undefined;
297
298 export const PolicyProvider = () =>
299 Provider.succeed(Policy, {
300 stables: ["policyName", "project", "id"],
301
302 diff: Effect.fn(function* ({ news, olds, output }) {
303 if (!isResolved(news)) return undefined;
304 const previousName = olds?.policyName ?? output?.policyName;
305 const nextName = news.policyName ?? previousName;
306 if (previousName === undefined || nextName === undefined || nextName === previousName) {
307 return undefined;
308 }
309 // A VPC may belong to only one server policy, so the old policy
310 // must be deleted (and its networks unbound) before the new one
311 // can attach to the same network.
312 return { action: "replace" as const, deleteFirst: true };
313 }),
314
315 read: Effect.fn(function* ({ id, olds, output, previous }) {
316 const env = yield* GcpEnvironment.current;
317 const policyName = yield* toPolicyName(id, olds?.policyName, output?.policyName);
318 const existing = yield* getByName(env.project, policyName);
319 if (existing === undefined) return undefined;
320 const attrs = toAttrs(existing, env.project);
321 const parsed = parseDescription(existing.description);
322 return (yield* hasAlchemyLabels(id, parsed.labels))
323 ? attrs
324 : unownedUnlessPrevious(attrs, previous, "policyName");
325 }),
326
327 list: () =>
328 Effect.gen(function* () {
329 const env = yield* GcpEnvironment.current;
330 const found: ReturnType<typeof toAttrs>[] = [];
331 let pageToken: string | undefined;
332 for (let page = 0; page < 10; page++) {
333 const response = yield* dns.listPolicies({
334 project: env.project,
335 maxResults: 1000,
336 pageToken,
337 });
338 for (const policy of response.policies ?? []) {
339 if (hasAlchemyMarker(policy.description)) {
340 found.push(toAttrs(policy, env.project));
341 }
342 }
343 pageToken = response.nextPageToken;
344 if (pageToken === undefined || pageToken === "") break;
345 }
346 return found;
347 }),
348
349 reconcile: Effect.fn(function* ({ id, news, output }) {
350 const env = yield* GcpEnvironment.current;
351 const policyName = yield* toPolicyName(id, news.policyName, output?.policyName);
352 const enableInboundForwarding = news.enableInboundForwarding === true;
353 const enableLogging = news.enableLogging === true;
354 const enableDns64 = news.enableDns64 === true;
355 const networks = desiredNetworks(env.project, news.networks);
356 const nameServers = desiredNameServers(news.alternativeNameServers);
357 const ownership = yield* createInternalLabels(id);
358 const desiredDescription = encodeDescription(ownership, news.description);
359
360 let current = yield* getByName(env.project, policyName);
361
362 if (current === undefined) {
363 const created = yield* dns
364 .createPolicies({
365 project: env.project,
366 body: {
367 name: policyName,
368 description: desiredDescription,
369 enableInboundForwarding,
370 enableLogging,
371 networks: networks.map((networkUrl) => ({ networkUrl })),
372 alternativeNameServerConfig: alternativeNameServerConfig(nameServers),
373 dns64Config: dns64Config(enableDns64),
374 },
375 })
376 .pipe(Effect.catchTag("Conflict", () => getByName(env.project, policyName)));
377 current = created ?? undefined;
378 }
379
380 if (current === undefined) {
381 return yield* new PolicyNotResolved({ policyName });
382 }
383
384 const descriptionChanged = (current.description ?? "") !== desiredDescription;
385 const inboundChanged = (current.enableInboundForwarding === true) !== enableInboundForwarding;
386 const loggingChanged = (current.enableLogging === true) !== enableLogging;
387 const dns64Changed = (current.dns64Config?.scope?.allQueries === true) !== enableDns64;
388 const networksChanged = !sameNetworks(observedNetworks(current), networks);
389 const nameServersChanged = !sameNameServers(observedNameServers(current), nameServers);
390
391 if (
392 descriptionChanged ||
393 inboundChanged ||
394 loggingChanged ||
395 dns64Changed ||
396 networksChanged ||
397 nameServersChanged
398 ) {
399 const body: dns.Policy = {};
400 if (descriptionChanged) body.description = desiredDescription;
401 if (inboundChanged) {
402 body.enableInboundForwarding = enableInboundForwarding;
403 }
404 if (loggingChanged) body.enableLogging = enableLogging;
405 if (dns64Changed) {
406 body.dns64Config = enableDns64
407 ? { scope: { allQueries: true } }
408 : { scope: { allQueries: false } };
409 }
410 if (networksChanged) {
411 body.networks = networks.map((networkUrl) => ({ networkUrl }));
412 }
413 if (nameServersChanged) {
414 body.alternativeNameServerConfig = {
415 targetNameServers: nameServers.map((server) => ({
416 ipv4Address: server.ipv4Address,
417 ipv6Address: server.ipv6Address,
418 forwardingPath: server.forwardingPath,
419 })),
420 };
421 }
422 const patched = yield* dns.patchPolicies({
423 project: env.project,
424 policy: policyName,
425 body,
426 });
427 current = patched.policy ?? (yield* getByName(env.project, policyName)) ?? current;
428 }
429
430 return toAttrs(current, env.project);
431 }),
432
433 delete: Effect.fn(function* ({ output }) {
434 const project = output.project;
435 const policyName = output.policyName;
436 const detach = dns
437 .patchPolicies({
438 project,
439 policy: policyName,
440 body: {
441 enableInboundForwarding: false,
442 networks: [],
443 },
444 })
445 .pipe(Effect.catchTag("NotFound", () => Effect.void));
446 const attempt = dns
447 .deletePolicies({ project, policy: policyName })
448 .pipe(Effect.catchTag("NotFound", () => Effect.void));
449 yield* detach.pipe(
450 Effect.andThen(attempt),
451 Effect.catchIf(
452 (error) => error._tag === "Conflict" || error._tag === "BadRequest",
453 () => detach.pipe(Effect.andThen(attempt)),
454 ),
455 Effect.retry({
456 while: (error) => error._tag === "Conflict" || error._tag === "BadRequest",
457 times: 8,
458 schedule: Schedule.spaced("2 seconds"),
459 }),
460 );
461 }),
462 });