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

main
ts 469 lines 15.5 KB
Raw
1 import * as certificatemanager from "@distilled.cloud/gcp/certificatemanager_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 * as Schedule from "effect/Schedule";
11 import * as Stream from "effect/Stream";
12 import { GcpEnvironment } from "../Environment.ts";
13 import {
14 createInternalLabels,
15 diffLabels,
16 hasAlchemyLabels,
17 stripInternalLabels,
18 toLabels,
19 } from "../Labels.ts";
20 import type { Providers } from "../Providers.ts";
21 import { waitForOperation } from "./operations.ts";
22
23 const DEFAULT_LOCATION = "global";
24 const MAX_NAME_LENGTH = 63;
25
26 export type DnsAuthorizationType = "FIXED_RECORD" | "PER_PROJECT_RECORD";
27
28 export type DnsAuthorizationProps = {
29 /**
30 * DnsAuthorization id (the `{dnsAuthorization}` segment of
31 * `projects/{project}/locations/{location}/dnsAuthorizations/{dnsAuthorization}`).
32 * If omitted, a unique name is generated from the stack, stage, and
33 * logical id. Must be 1-63 characters, start with a letter, and match
34 * `[a-zA-Z][a-zA-Z0-9_-]*`. Immutable — changing it replaces the
35 * authorization.
36 */
37 dnsAuthorizationId?: string;
38 /**
39 * Certificate Manager location (`global`, `us-central1`, …). Immutable —
40 * changing it replaces the authorization. `US-CENTRAL1` is accepted and
41 * normalized to `us-central1`. `FIXED_RECORD` authorizations live in
42 * `global`; regional locations default to `PER_PROJECT_RECORD`.
43 * @default "global"
44 */
45 location?: string;
46 /**
47 * Domain being authorized. Covers this domain and its wildcard
48 * (`example.com` also covers `*.example.com`). Immutable — changing it
49 * replaces the authorization.
50 */
51 domain: string;
52 /**
53 * Authorization type. Immutable — changing it replaces the
54 * authorization. Defaults to `FIXED_RECORD` in `global` and
55 * `PER_PROJECT_RECORD` in regional locations.
56 */
57 type?: DnsAuthorizationType | (string & {});
58 /**
59 * Human-readable description.
60 */
61 description?: string;
62 /**
63 * User labels. Alchemy ownership labels are merged in automatically.
64 */
65 labels?: Record<string, string>;
66 };
67
68 export type DnsAuthorization = Resource<
69 "GCP.CertificateManager.DnsAuthorization",
70 DnsAuthorizationProps,
71 {
72 /** Full resource name `projects/{project}/locations/{location}/dnsAuthorizations/{dnsAuthorization}`. */
73 name: string;
74 /** DnsAuthorization id (last path segment). */
75 dnsAuthorizationId: string;
76 /** Project id. */
77 project: string;
78 /** Location id (`global`, `us-central1`, …). */
79 location: string;
80 /** Authorized domain. */
81 domain: string;
82 /** `FIXED_RECORD` or `PER_PROJECT_RECORD`. */
83 type: string;
84 /** User-provided description. */
85 description: string | undefined;
86 /** User labels (Alchemy ownership labels stripped). */
87 labels: Record<string, string>;
88 /** FQDN of the CNAME record to add (`_acme-challenge.example.com`). */
89 dnsResourceRecordName: string | undefined;
90 /** DNS record type. Currently always `CNAME`. */
91 dnsResourceRecordType: string | undefined;
92 /** CNAME target to publish for domain validation. */
93 dnsResourceRecordData: string | undefined;
94 /** RFC3339 creation timestamp. */
95 createTime: string | undefined;
96 /** RFC3339 last-update timestamp. */
97 updateTime: string | undefined;
98 },
99 never,
100 Providers
101 >;
102
103 /**
104 * A Certificate Manager DNS authorization proving ownership of a domain
105 * for Google-managed certificates.
106 *
107 * Changing `dnsAuthorizationId`, `location`, `domain`, or `type` replaces
108 * the resource. Description and labels update in place.
109 *
110 * ### Creating a DNS Authorization
111 * **Example:** Generated name
112 * ```typescript
113 * const authorization = yield* GCP.CertificateManager.DnsAuthorization(
114 * "WwwAuth",
115 * { domain: "www.example.com" },
116 * );
117 * ```
118 *
119 * **Example:** Named authorization with labels
120 * ```typescript
121 * const authorization = yield* GCP.CertificateManager.DnsAuthorization(
122 * "WwwAuth",
123 * {
124 * dnsAuthorizationId: "www-example-auth",
125 * description: "prod www",
126 * domain: "www.example.com",
127 * labels: { env: "prod" },
128 * },
129 * );
130 * ```
131 *
132 * ### Regional Per-Project Records
133 * **Example:** PER_PROJECT_RECORD in us-central1
134 * ```typescript
135 * const authorization = yield* GCP.CertificateManager.DnsAuthorization(
136 * "WwwAuth",
137 * {
138 * location: "us-central1",
139 * type: "PER_PROJECT_RECORD",
140 * domain: "www.example.com",
141 * },
142 * );
143 * ```
144 *
145 * ### Google-Managed Certificates
146 * **Example:** Authorize a domain then issue a managed certificate
147 * ```typescript
148 * const authorization = yield* GCP.CertificateManager.DnsAuthorization(
149 * "WwwAuth",
150 * { domain: "www.example.com" },
151 * );
152 * const cert = yield* GCP.CertificateManager.Certificate("FrontendTls", {
153 * type: "MANAGED",
154 * managed: {
155 * domains: ["www.example.com"],
156 * dnsAuthorizations: [authorization.name],
157 * },
158 * });
159 * ```
160 *
161 * @resource
162 * @category CertificateManager
163 */
164 export const DnsAuthorization = Resource<DnsAuthorization>(
165 "GCP.CertificateManager.DnsAuthorization",
166 );
167
168 export class DnsAuthorizationNotResolved extends Data.TaggedError(
169 "GCP.CertificateManager.DnsAuthorizationNotResolved",
170 )<{
171 resourceName: string;
172 }> {}
173
174 export class DnsAuthorizationStillExists extends Data.TaggedError(
175 "GCP.CertificateManager.DnsAuthorizationStillExists",
176 )<{
177 resourceName: string;
178 }> {}
179
180 const lastSegment = (value: string) => {
181 const trimmed = value.replace(/\/+$/, "");
182 const parts = trimmed.split("/");
183 return parts[parts.length - 1] || trimmed;
184 };
185
186 const rfc1035 = (name: string): string => {
187 let next = name
188 .toLowerCase()
189 .replace(/[^a-z0-9-]/g, "-")
190 .replace(/-+/g, "-")
191 .replace(/^-+/, "")
192 .replace(/-+$/, "");
193 if (!/^[a-z]/.test(next)) {
194 next = `d${next}`;
195 }
196 next = next.slice(0, MAX_NAME_LENGTH).replace(/-+$/, "");
197 return next.length > 0 ? next : "dns-authorization";
198 };
199
200 const normalizeLocation = (location: string | undefined) =>
201 lastSegment(location ?? DEFAULT_LOCATION).toLowerCase();
202
203 const defaultType = (location: string): DnsAuthorizationType =>
204 location === DEFAULT_LOCATION ? "FIXED_RECORD" : "PER_PROJECT_RECORD";
205
206 const normalizeType = (type: string | undefined, location: string) => {
207 const value = (type ?? "").toUpperCase();
208 return value === "" || value === "TYPE_UNSPECIFIED" ? defaultType(location) : value;
209 };
210
211 const resourceName = (project: string, location: string, dnsAuthorizationId: string) =>
212 `projects/${project}/locations/${location}/dnsAuthorizations/${dnsAuthorizationId}`;
213
214 const parseName = (name: string) => {
215 const parts = name.split("/").filter((part) => part.length > 0);
216 const authsAt = parts.lastIndexOf("dnsAuthorizations");
217 const locationsAt = parts.lastIndexOf("locations");
218 const projectsAt = parts.lastIndexOf("projects");
219 return {
220 project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "",
221 location:
222 locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : DEFAULT_LOCATION,
223 dnsAuthorizationId:
224 authsAt >= 0 && parts[authsAt + 1] ? parts[authsAt + 1]! : lastSegment(name),
225 };
226 };
227
228 const userLabels = (
229 labels: Record<string, string | undefined> | null | undefined,
230 ): Record<string, string> => stripInternalLabels(tagRecord(labels));
231
232 const toId = (id: string, dnsAuthorizationId: string | undefined, existing?: string) =>
233 Effect.gen(function* () {
234 if (dnsAuthorizationId !== undefined) return dnsAuthorizationId;
235 if (existing !== undefined) return existing;
236 return rfc1035(
237 yield* createPhysicalName({
238 id,
239 maxLength: MAX_NAME_LENGTH,
240 lowercase: true,
241 }),
242 );
243 });
244
245 const toAttrs = (auth: certificatemanager.DnsAuthorization, project: string) => {
246 const name = auth.name ?? "";
247 const parsed = parseName(name);
248 const location = parsed.location;
249 return {
250 name,
251 dnsAuthorizationId: parsed.dnsAuthorizationId,
252 project: parsed.project || project,
253 location,
254 domain: auth.domain ?? "",
255 type: normalizeType(auth.type, location),
256 description: auth.description,
257 labels: userLabels(auth.labels),
258 dnsResourceRecordName: auth.dnsResourceRecord?.name,
259 dnsResourceRecordType: auth.dnsResourceRecord?.type,
260 dnsResourceRecordData: auth.dnsResourceRecord?.data,
261 createTime: auth.createTime,
262 updateTime: auth.updateTime,
263 };
264 };
265
266 const getByName = (name: string) =>
267 certificatemanager
268 .getProjectsLocationsDnsAuthorizations({ name })
269 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
270
271 const waitUntilExists = (name: string) =>
272 getByName(name).pipe(
273 Effect.flatMap((auth) =>
274 auth
275 ? Effect.succeed(auth)
276 : Effect.fail(new DnsAuthorizationNotResolved({ resourceName: name })),
277 ),
278 Effect.retry({
279 while: (error) => error._tag === "GCP.CertificateManager.DnsAuthorizationNotResolved",
280 times: 8,
281 schedule: Schedule.spaced("1 second"),
282 }),
283 );
284
285 const waitUntilGone = (name: string) =>
286 getByName(name).pipe(
287 Effect.flatMap((auth) =>
288 auth === undefined
289 ? Effect.void
290 : Effect.fail(new DnsAuthorizationStillExists({ resourceName: name })),
291 ),
292 Effect.retry({
293 while: (error) => error._tag === "GCP.CertificateManager.DnsAuthorizationStillExists",
294 times: 10,
295 schedule: Schedule.spaced("1 second"),
296 }),
297 );
298
299 const listOwnedDnsAuthorizations = (project: string) =>
300 certificatemanager.listProjectsLocationsDnsAuthorizations
301 .pages({
302 parent: `projects/${project}/locations/-`,
303 pageSize: 1000,
304 })
305 .pipe(
306 Stream.flatMap((page) => Stream.fromIterable(page.dnsAuthorizations ?? [])),
307 Stream.filter((auth) =>
308 Object.keys(auth.labels ?? {}).some((key) => key.startsWith("alchemy-")),
309 ),
310 Stream.map((auth) => toAttrs(auth, project)),
311 Stream.runCollect,
312 Effect.map((chunk) => Array.from(chunk)),
313 Effect.catchTag("NotFound", () => Effect.succeed([])),
314 );
315
316 export const DnsAuthorizationProvider = () =>
317 Provider.succeed(DnsAuthorization, {
318 stables: [
319 "name",
320 "dnsAuthorizationId",
321 "project",
322 "location",
323 "domain",
324 "type",
325 "dnsResourceRecordName",
326 "dnsResourceRecordType",
327 "dnsResourceRecordData",
328 "createTime",
329 ],
330
331 diff: Effect.fn(function* ({ news, olds, output }) {
332 if (!isResolved(news)) return undefined;
333
334 const previousId = olds?.dnsAuthorizationId ?? output?.dnsAuthorizationId;
335 const nextId = news.dnsAuthorizationId ?? previousId;
336 const previousLocation = normalizeLocation(olds?.location ?? output?.location);
337 const nextLocation = normalizeLocation(news.location ?? olds?.location ?? output?.location);
338 const previousDomain = olds?.domain ?? output?.domain;
339 const previousType = normalizeType(olds?.type ?? output?.type, previousLocation);
340 const nextType = normalizeType(news.type ?? olds?.type ?? output?.type, nextLocation);
341
342 const replace =
343 (previousId !== undefined && nextId !== undefined && nextId !== previousId) ||
344 previousLocation !== nextLocation ||
345 (previousDomain !== undefined && news.domain !== previousDomain) ||
346 previousType !== nextType;
347
348 if (!replace) return undefined;
349 return {
350 action: "replace" as const,
351 deleteFirst:
352 previousLocation === nextLocation && previousId !== undefined && nextId === previousId,
353 };
354 }),
355
356 read: Effect.fn(function* ({ id, olds, output }) {
357 const env = yield* GcpEnvironment.current;
358 const dnsAuthorizationId = yield* toId(
359 id,
360 olds?.dnsAuthorizationId,
361 output?.dnsAuthorizationId,
362 );
363 const location = normalizeLocation(olds?.location ?? output?.location);
364 const name = output?.name ?? resourceName(env.project, location, dnsAuthorizationId);
365 const existing = yield* getByName(name);
366 if (existing === undefined) return undefined;
367 const attrs = toAttrs(existing, env.project);
368 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
369 }),
370
371 list: () =>
372 Effect.gen(function* () {
373 const env = yield* GcpEnvironment.current;
374 return yield* listOwnedDnsAuthorizations(env.project);
375 }),
376
377 reconcile: Effect.fn(function* ({ id, news, output }) {
378 const env = yield* GcpEnvironment.current;
379 const dnsAuthorizationId = yield* toId(
380 id,
381 news.dnsAuthorizationId,
382 output?.dnsAuthorizationId,
383 );
384 const location = normalizeLocation(news.location ?? output?.location);
385 const name = resourceName(env.project, location, dnsAuthorizationId);
386 const desiredLabels = {
387 ...toLabels(news.labels),
388 ...(yield* createInternalLabels(id)),
389 };
390
391 let current = yield* getByName(name);
392
393 if (current === undefined) {
394 const body: certificatemanager.DnsAuthorization = {
395 domain: news.domain,
396 description: news.description,
397 labels: desiredLabels,
398 };
399 if (news.type !== undefined) {
400 body.type = news.type;
401 }
402 const created = yield* certificatemanager
403 .createProjectsLocationsDnsAuthorizations({
404 parent: `projects/${env.project}/locations/${location}`,
405 dnsAuthorizationId,
406 body,
407 })
408 .pipe(
409 Effect.retry({
410 while: (error) => error._tag === "Conflict",
411 times: 5,
412 schedule: Schedule.spaced("2 seconds"),
413 }),
414 Effect.catchTag("Conflict", () => Effect.undefined),
415 );
416 if (created !== undefined) {
417 yield* waitForOperation(created);
418 }
419 current = yield* waitUntilExists(name);
420 }
421
422 if (current === undefined) {
423 return yield* new DnsAuthorizationNotResolved({ resourceName: name });
424 }
425
426 const observedLabels = tagRecord(current.labels);
427 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
428 const labelsChanged = upsert.length > 0 || removed.length > 0;
429 const descriptionChanged = (current.description ?? "") !== (news.description ?? "");
430
431 if (labelsChanged || descriptionChanged) {
432 const updateMask = [
433 labelsChanged ? "labels" : undefined,
434 descriptionChanged ? "description" : undefined,
435 ].filter((field): field is string => field !== undefined);
436
437 const operation = yield* certificatemanager.patchProjectsLocationsDnsAuthorizations({
438 name,
439 updateMask: updateMask.join(","),
440 body: {
441 name,
442 labels: desiredLabels,
443 description: news.description,
444 },
445 });
446 yield* waitForOperation(operation);
447 current = yield* waitUntilExists(name);
448 }
449
450 return toAttrs(current, env.project);
451 }),
452
453 delete: Effect.fn(function* ({ output }) {
454 const operation = yield* certificatemanager
455 .deleteProjectsLocationsDnsAuthorizations({ name: output.name })
456 .pipe(
457 Effect.retry({
458 while: (error) => error._tag === "Conflict",
459 times: 8,
460 schedule: Schedule.spaced("2 seconds"),
461 }),
462 Effect.catchTag("NotFound", () => Effect.undefined),
463 );
464 if (operation !== undefined) {
465 yield* waitForOperation(operation, { notFoundOk: true });
466 }
467 yield* waitUntilGone(output.name);
468 }),
469 });