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

main
ts 398 lines 13.8 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 { tagRecord } from "alchemy/Tags";
8 import * as Data from "effect/Data";
9 import * as Effect from "effect/Effect";
10 import * as Schedule from "effect/Schedule";
11 import { GcpEnvironment } from "../Environment.ts";
12 import {
13 ALCHEMY_LABEL_PREFIX,
14 createInternalLabels,
15 diffLabels,
16 hasAlchemyLabels,
17 stripInternalLabels,
18 toLabels,
19 } from "../Labels.ts";
20 import type { Providers } from "../Providers.ts";
21
22 const MAX_NAME_LENGTH = 63;
23
24 export type ResponsePolicyProps = {
25 /**
26 * User-assigned response policy name, unique within the project. If
27 * omitted, a unique RFC1035 name is generated from the stack, stage,
28 * and logical id. Must be 1-63 characters, begin with a letter, end
29 * with a letter or digit, and contain only lowercase letters, digits,
30 * or dashes. Immutable — changing it replaces the response policy.
31 */
32 responsePolicyName?: string;
33 /**
34 * Human-readable description.
35 */
36 description?: string;
37 /**
38 * User labels. Alchemy ownership labels are merged in automatically.
39 */
40 labels?: Record<string, string>;
41 /**
42 * VPC networks this response policy applies to. Each value may be a
43 * network name, a `projects/.../global/networks/...` path, or a full
44 * compute URL. A network may belong to at most one response policy.
45 * Updates in place.
46 */
47 networks?: string[];
48 /**
49 * GKE clusters this response policy applies to, as
50 * `projects/{project}/locations/{location}/clusters/{cluster}`.
51 * Updates in place.
52 */
53 gkeClusters?: string[];
54 };
55
56 export type ResponsePolicy = Resource<
57 "GCP.DNS.ResponsePolicy",
58 ResponsePolicyProps,
59 {
60 /** User-assigned response policy name. */
61 responsePolicyName: string;
62 /** Project id. */
63 project: string;
64 /** Server-assigned numeric id. */
65 id: string | undefined;
66 /** User description. */
67 description: string | undefined;
68 /** User labels (Alchemy ownership labels stripped). */
69 labels: Record<string, string>;
70 /** VPC network URLs bound to this response policy. */
71 networks: ReadonlyArray<string>;
72 /** GKE cluster resource names bound to this response policy. */
73 gkeClusters: ReadonlyArray<string>;
74 /** Server-reported kind (`dns#responsePolicy`). */
75 kind: string | undefined;
76 },
77 never,
78 Providers
79 >;
80
81 /**
82 * A Cloud DNS response policy applied to one or more VPC networks.
83 *
84 * Response policies override DNS answers for selected names (via
85 * response policy rules) for VMs in bound networks. Name is identity —
86 * changing it replaces the policy. Description, labels, and the
87 * network / GKE cluster lists update in place.
88 *
89 * ### Creating a Response Policy
90 * **Example:** Generated name bound to a VPC
91 * ```typescript
92 * const vpc = yield* GCP.Compute.Network("Vpc", {
93 * autoCreateSubnetworks: false,
94 * });
95 * const policy = yield* GCP.DNS.ResponsePolicy("Overrides", {
96 * networks: [vpc.networkName],
97 * });
98 * ```
99 *
100 * **Example:** Explicit name, description, and labels
101 * ```typescript
102 * const policy = yield* GCP.DNS.ResponsePolicy("Overrides", {
103 * responsePolicyName: "app-overrides",
104 * description: "split-horizon answers",
105 * labels: { env: "prod" },
106 * networks: ["app-vpc"],
107 * });
108 * ```
109 *
110 * @resource
111 * @category DNS
112 */
113 export const ResponsePolicy = Resource<ResponsePolicy>("GCP.DNS.ResponsePolicy");
114
115 export class ResponsePolicyNotResolved extends Data.TaggedError(
116 "GCP.DNS.ResponsePolicyNotResolved",
117 )<{
118 responsePolicyName: string;
119 }> {}
120
121 const userLabels = (
122 labels: Record<string, string | undefined> | null | undefined,
123 ): Record<string, string> => stripInternalLabels(tagRecord(labels));
124
125 const lastSegment = (value: string) => {
126 const trimmed = value.replace(/\/+$/, "");
127 const parts = trimmed.split("/");
128 return parts[parts.length - 1] || trimmed;
129 };
130
131 const toNetworkUrl = (project: string, network: string) => {
132 if (network.startsWith("https://") || network.startsWith("http://")) {
133 return network;
134 }
135 if (network.includes("/")) {
136 const path = network.replace(/^\//, "");
137 return path.startsWith("compute/")
138 ? `https://www.googleapis.com/${path}`
139 : `https://www.googleapis.com/compute/v1/${path}`;
140 }
141 return `https://www.googleapis.com/compute/v1/projects/${project}/global/networks/${network}`;
142 };
143
144 const desiredNetworks = (project: string, networks: string[] | undefined) =>
145 [...new Set((networks ?? []).map((network) => toNetworkUrl(project, network)))].sort(
146 (left, right) => lastSegment(left).localeCompare(lastSegment(right)),
147 );
148
149 const observedNetworks = (policy: dns.ResponsePolicy) =>
150 (policy.networks ?? [])
151 .map((network) => network.networkUrl ?? "")
152 .filter((url) => url.length > 0)
153 .sort((left, right) => lastSegment(left).localeCompare(lastSegment(right)));
154
155 const sameNetworks = (left: string[], right: string[]) =>
156 left.length === right.length &&
157 left.every((url, index) => lastSegment(url) === lastSegment(right[index] ?? ""));
158
159 const desiredClusters = (clusters: string[] | undefined) => [...new Set(clusters ?? [])].sort();
160
161 const observedClusters = (policy: dns.ResponsePolicy) =>
162 (policy.gkeClusters ?? [])
163 .map((cluster) => cluster.gkeClusterName ?? "")
164 .filter((name) => name.length > 0)
165 .sort();
166
167 const sameList = (left: string[], right: string[]) =>
168 left.length === right.length && left.every((value, index) => value === right[index]);
169
170 const toResponsePolicyName = (id: string, name: string | undefined, existing?: string) =>
171 Effect.gen(function* () {
172 if (name !== undefined) return name;
173 if (existing !== undefined) return existing;
174 const generated = yield* createPhysicalName({
175 id,
176 maxLength: MAX_NAME_LENGTH,
177 lowercase: true,
178 });
179 const rfc = generated
180 .replace(/[^a-z0-9-]/g, "-")
181 .replace(/^[^a-z]+/, "r")
182 .slice(0, MAX_NAME_LENGTH)
183 .replace(/-+$/g, "");
184 return rfc.length > 0 ? rfc : "r";
185 });
186
187 const toAttrs = (policy: dns.ResponsePolicy, project: string) => ({
188 responsePolicyName: policy.responsePolicyName ?? "",
189 project,
190 id: policy.id,
191 description: policy.description && policy.description.length > 0 ? policy.description : undefined,
192 labels: userLabels(policy.labels),
193 networks: observedNetworks(policy),
194 gkeClusters: observedClusters(policy),
195 kind: policy.kind,
196 });
197
198 const getByName = (project: string, responsePolicyName: string) =>
199 dns
200 .getResponsePolicies({ project, responsePolicy: responsePolicyName })
201 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
202
203 const listRules = (project: string, responsePolicyName: string) =>
204 Effect.gen(function* () {
205 const found: dns.ResponsePolicyRule[] = [];
206 let pageToken: string | undefined;
207 for (let page = 0; page < 10; page++) {
208 const response = yield* dns.listResponsePolicyRules({
209 project,
210 responsePolicy: responsePolicyName,
211 maxResults: 1000,
212 pageToken,
213 });
214 found.push(...(response.responsePolicyRules ?? []));
215 pageToken = response.nextPageToken;
216 if (pageToken === undefined || pageToken === "") break;
217 }
218 return found;
219 }).pipe(Effect.catchTag("NotFound", () => Effect.succeed([] as dns.ResponsePolicyRule[])));
220
221 const emptyRules = (project: string, responsePolicyName: string) =>
222 Effect.gen(function* () {
223 const rules = yield* listRules(project, responsePolicyName);
224 yield* Effect.forEach(
225 rules,
226 (rule) =>
227 rule.ruleName
228 ? dns
229 .deleteResponsePolicyRules({
230 project,
231 responsePolicy: responsePolicyName,
232 responsePolicyRule: rule.ruleName,
233 })
234 .pipe(Effect.catchTag("NotFound", () => Effect.void))
235 : Effect.void,
236 { concurrency: 4 },
237 );
238 });
239
240 export const ResponsePolicyProvider = () =>
241 Provider.succeed(ResponsePolicy, {
242 stables: ["responsePolicyName", "project", "id"],
243
244 diff: Effect.fn(function* ({ news, olds, output }) {
245 if (!isResolved(news)) return undefined;
246 const previousName = olds?.responsePolicyName ?? output?.responsePolicyName;
247 const nextName = news.responsePolicyName ?? previousName;
248 if (previousName === undefined || nextName === undefined || nextName === previousName) {
249 return undefined;
250 }
251 // A VPC may belong to only one response policy, so the old policy
252 // must be deleted before the new one can attach to the same
253 // network.
254 return { action: "replace" as const, deleteFirst: true };
255 }),
256
257 read: Effect.fn(function* ({ id, olds, output, previous }) {
258 const env = yield* GcpEnvironment.current;
259 const responsePolicyName = yield* toResponsePolicyName(
260 id,
261 olds?.responsePolicyName,
262 output?.responsePolicyName,
263 );
264 const existing = yield* getByName(env.project, responsePolicyName);
265 if (existing === undefined) return undefined;
266 const attrs = toAttrs(existing, env.project);
267 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels)))
268 ? attrs
269 : unownedUnlessPrevious(attrs, previous, "responsePolicyName");
270 }),
271
272 list: () =>
273 Effect.gen(function* () {
274 const env = yield* GcpEnvironment.current;
275 const found: ReturnType<typeof toAttrs>[] = [];
276 let pageToken: string | undefined;
277 for (let page = 0; page < 10; page++) {
278 const response = yield* dns.listResponsePolicies({
279 project: env.project,
280 maxResults: 1000,
281 pageToken,
282 });
283 for (const policy of response.responsePolicies ?? []) {
284 if (
285 Object.keys(policy.labels ?? {}).some((key) => key.startsWith(ALCHEMY_LABEL_PREFIX))
286 ) {
287 found.push(toAttrs(policy, env.project));
288 }
289 }
290 pageToken = response.nextPageToken;
291 if (pageToken === undefined || pageToken === "") break;
292 }
293 return found;
294 }),
295
296 reconcile: Effect.fn(function* ({ id, news, output }) {
297 const env = yield* GcpEnvironment.current;
298 const responsePolicyName = yield* toResponsePolicyName(
299 id,
300 news.responsePolicyName,
301 output?.responsePolicyName,
302 );
303 const description = news.description ?? "";
304 const networks = desiredNetworks(env.project, news.networks);
305 const gkeClusters = desiredClusters(news.gkeClusters);
306 const desiredLabels = {
307 ...toLabels(news.labels),
308 ...(yield* createInternalLabels(id)),
309 };
310
311 let current = yield* getByName(env.project, responsePolicyName);
312
313 if (current === undefined) {
314 const created = yield* dns
315 .createResponsePolicies({
316 project: env.project,
317 body: {
318 responsePolicyName,
319 description,
320 labels: desiredLabels,
321 networks: networks.map((networkUrl) => ({ networkUrl })),
322 gkeClusters: gkeClusters.map((gkeClusterName) => ({
323 gkeClusterName,
324 })),
325 },
326 })
327 .pipe(Effect.catchTag("Conflict", () => getByName(env.project, responsePolicyName)));
328 current = created ?? undefined;
329 }
330
331 if (current === undefined) {
332 return yield* new ResponsePolicyNotResolved({ responsePolicyName });
333 }
334
335 const observedLabels = tagRecord(current.labels);
336 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
337 const labelsChanged = upsert.length > 0 || removed.length > 0;
338 const descriptionChanged = (current.description ?? "") !== description;
339 const networksChanged = !sameNetworks(observedNetworks(current), networks);
340 const clustersChanged = !sameList(observedClusters(current), gkeClusters);
341
342 if (labelsChanged || descriptionChanged || networksChanged || clustersChanged) {
343 const body: dns.ResponsePolicy = {};
344 if (labelsChanged) body.labels = desiredLabels;
345 if (descriptionChanged) body.description = description;
346 if (networksChanged) {
347 body.networks = networks.map((networkUrl) => ({ networkUrl }));
348 }
349 if (clustersChanged) {
350 body.gkeClusters = gkeClusters.map((gkeClusterName) => ({
351 gkeClusterName,
352 }));
353 }
354 const patched = yield* dns.patchResponsePolicies({
355 project: env.project,
356 responsePolicy: responsePolicyName,
357 body,
358 });
359 current =
360 patched.responsePolicy ?? (yield* getByName(env.project, responsePolicyName)) ?? current;
361 }
362
363 return toAttrs(current, env.project);
364 }),
365
366 delete: Effect.fn(function* ({ output }) {
367 const project = output.project;
368 const responsePolicyName = output.responsePolicyName;
369 const detach = Effect.gen(function* () {
370 yield* emptyRules(project, responsePolicyName);
371 yield* dns
372 .patchResponsePolicies({
373 project,
374 responsePolicy: responsePolicyName,
375 body: { networks: [], gkeClusters: [] },
376 })
377 .pipe(Effect.catchTag("NotFound", () => Effect.void));
378 });
379 const attempt = dns
380 .deleteResponsePolicies({
381 project,
382 responsePolicy: responsePolicyName,
383 })
384 .pipe(Effect.catchTag("NotFound", () => Effect.void));
385 yield* detach.pipe(
386 Effect.andThen(attempt),
387 Effect.catchIf(
388 (error) => error._tag === "Conflict" || error._tag === "BadRequest",
389 () => detach.pipe(Effect.andThen(attempt)),
390 ),
391 Effect.retry({
392 while: (error) => error._tag === "Conflict" || error._tag === "BadRequest",
393 times: 8,
394 schedule: Schedule.spaced("2 seconds"),
395 }),
396 );
397 }),
398 });