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

main
ts 409 lines 13.6 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 CertificateMapIpConfig = {
27 /** External IP address where this map is serving. */
28 ipAddress: string | undefined;
29 /** Ports on `ipAddress` where this map is serving. */
30 ports: number[];
31 };
32
33 export type CertificateMapGclbTarget = {
34 /**
35 * Target HTTPS proxy using this map
36 * (`//compute.googleapis.com/projects/{project}/global/targetHttpsProxies/{proxy}`).
37 */
38 targetHttpsProxy: string | undefined;
39 /**
40 * Target SSL proxy using this map
41 * (`//compute.googleapis.com/projects/{project}/global/targetSslProxies/{proxy}`).
42 */
43 targetSslProxy: string | undefined;
44 /** IP configurations where this map is serving. */
45 ipConfigs: CertificateMapIpConfig[];
46 };
47
48 export type CertificateMapProps = {
49 /**
50 * Certificate map id (the `{certificateMap}` segment of
51 * `projects/{project}/locations/{location}/certificateMaps/{certificateMap}`).
52 * If omitted, a unique name is generated from the stack, stage, and
53 * logical id. Must be 1-63 characters, start with a letter, and match
54 * `[a-z]([-a-z0-9]*[a-z0-9])?`. Immutable — changing it replaces the
55 * certificate map.
56 */
57 certificateMapId?: string;
58 /**
59 * Certificate Manager location. Certificate maps are global resources;
60 * omit or set `"global"`. Immutable — changing it replaces the map.
61 * `GLOBAL` is accepted and normalized to `global`.
62 * @default "global"
63 */
64 location?: string;
65 /**
66 * Human-readable description.
67 */
68 description?: string;
69 /**
70 * User labels. Alchemy ownership labels are merged in automatically.
71 */
72 labels?: Record<string, string>;
73 };
74
75 export type CertificateMap = Resource<
76 "GCP.CertificateManager.CertificateMap",
77 CertificateMapProps,
78 {
79 /** Full resource name `projects/{project}/locations/{location}/certificateMaps/{certificateMap}`. */
80 name: string;
81 /** Certificate map id (last path segment). */
82 certificateMapId: string;
83 /** Project id. */
84 project: string;
85 /** Location id (`global`). */
86 location: string;
87 /** User-provided description. */
88 description: string | undefined;
89 /** User labels (Alchemy ownership labels stripped). */
90 labels: Record<string, string>;
91 /** GCLB targets currently using this map (output-only). */
92 gclbTargets: CertificateMapGclbTarget[];
93 /** RFC3339 creation timestamp. */
94 createTime: string | undefined;
95 /** RFC3339 last-update timestamp. */
96 updateTime: string | undefined;
97 },
98 never,
99 Providers
100 >;
101
102 /**
103 * A Certificate Manager certificate map — a collection of certificate
104 * configurations selected by SNI for global external Application and
105 * proxy Network Load Balancers.
106 *
107 * Changing `certificateMapId` or `location` replaces the resource.
108 * Description and labels update in place. Certificate maps cannot be
109 * deleted while they still contain certificate map entries.
110 *
111 * ### Creating a Certificate Map
112 * **Example:** Generated name
113 * ```typescript
114 * const map = yield* GCP.CertificateManager.CertificateMap("FrontendMap", {});
115 * ```
116 *
117 * **Example:** Named map with labels
118 * ```typescript
119 * const map = yield* GCP.CertificateManager.CertificateMap("FrontendMap", {
120 * certificateMapId: "app-frontend",
121 * description: "prod frontend",
122 * labels: { env: "prod" },
123 * });
124 * ```
125 *
126 * ### Updating a Certificate Map
127 * **Example:** Description and labels
128 * ```typescript
129 * const map = yield* GCP.CertificateManager.CertificateMap("FrontendMap", {
130 * certificateMapId: "app-frontend",
131 * description: "prod frontend v2",
132 * labels: { env: "prod", role: "tls" },
133 * });
134 * ```
135 *
136 * @resource
137 * @category CertificateManager
138 */
139 export const CertificateMap = Resource<CertificateMap>("GCP.CertificateManager.CertificateMap");
140
141 export class CertificateMapNotResolved extends Data.TaggedError(
142 "GCP.CertificateManager.CertificateMapNotResolved",
143 )<{
144 resourceName: string;
145 }> {}
146
147 export class CertificateMapStillExists extends Data.TaggedError(
148 "GCP.CertificateManager.CertificateMapStillExists",
149 )<{
150 resourceName: string;
151 }> {}
152
153 const lastSegment = (value: string) => {
154 const trimmed = value.replace(/\/+$/, "");
155 const parts = trimmed.split("/");
156 return parts[parts.length - 1] || trimmed;
157 };
158
159 const rfc1035 = (name: string): string => {
160 let next = name
161 .toLowerCase()
162 .replace(/[^a-z0-9-]/g, "-")
163 .replace(/-+/g, "-")
164 .replace(/^-+/, "")
165 .replace(/-+$/, "");
166 if (!/^[a-z]/.test(next)) {
167 next = `c${next}`;
168 }
169 next = next.slice(0, MAX_NAME_LENGTH).replace(/-+$/, "");
170 return next.length > 0 ? next : "certificatemap";
171 };
172
173 const normalizeLocation = (location: string | undefined) =>
174 lastSegment(location ?? DEFAULT_LOCATION).toLowerCase();
175
176 const resourceName = (project: string, location: string, certificateMapId: string) =>
177 `projects/${project}/locations/${location}/certificateMaps/${certificateMapId}`;
178
179 const parseName = (name: string) => {
180 const parts = name.split("/").filter((part) => part.length > 0);
181 const mapsAt = parts.lastIndexOf("certificateMaps");
182 const locationsAt = parts.lastIndexOf("locations");
183 const projectsAt = parts.lastIndexOf("projects");
184 return {
185 project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "",
186 location:
187 locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : DEFAULT_LOCATION,
188 certificateMapId: mapsAt >= 0 && parts[mapsAt + 1] ? parts[mapsAt + 1]! : lastSegment(name),
189 };
190 };
191
192 const userLabels = (
193 labels: Record<string, string | undefined> | null | undefined,
194 ): Record<string, string> => stripInternalLabels(tagRecord(labels));
195
196 const toId = (id: string, certificateMapId: string | undefined, existing?: string) =>
197 Effect.gen(function* () {
198 if (certificateMapId !== undefined) return certificateMapId;
199 if (existing !== undefined) return existing;
200 return rfc1035(
201 yield* createPhysicalName({
202 id,
203 maxLength: MAX_NAME_LENGTH,
204 lowercase: true,
205 }),
206 );
207 });
208
209 const toGclbTargets = (
210 targets: certificatemanager.GclbTargetList | undefined,
211 ): CertificateMapGclbTarget[] =>
212 (targets ?? []).map((target) => ({
213 targetHttpsProxy: target.targetHttpsProxy,
214 targetSslProxy: target.targetSslProxy,
215 ipConfigs: (target.ipConfigs ?? []).map((config) => ({
216 ipAddress: config.ipAddress,
217 ports: config.ports ?? [],
218 })),
219 }));
220
221 const toAttrs = (map: certificatemanager.CertificateMap, project: string) => {
222 const name = map.name ?? "";
223 const parsed = parseName(name);
224 return {
225 name,
226 certificateMapId: parsed.certificateMapId,
227 project: parsed.project || project,
228 location: parsed.location,
229 description: map.description,
230 labels: userLabels(map.labels),
231 gclbTargets: toGclbTargets(map.gclbTargets),
232 createTime: map.createTime,
233 updateTime: map.updateTime,
234 };
235 };
236
237 const getByName = (name: string) =>
238 certificatemanager
239 .getProjectsLocationsCertificateMaps({ name })
240 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
241
242 const waitUntilExists = (name: string) =>
243 getByName(name).pipe(
244 Effect.flatMap((map) =>
245 map
246 ? Effect.succeed(map)
247 : Effect.fail(new CertificateMapNotResolved({ resourceName: name })),
248 ),
249 Effect.retry({
250 while: (error) => error._tag === "GCP.CertificateManager.CertificateMapNotResolved",
251 times: 8,
252 schedule: Schedule.spaced("1 second"),
253 }),
254 );
255
256 const waitUntilGone = (name: string) =>
257 getByName(name).pipe(
258 Effect.flatMap((map) =>
259 map === undefined
260 ? Effect.void
261 : Effect.fail(new CertificateMapStillExists({ resourceName: name })),
262 ),
263 Effect.retry({
264 while: (error) => error._tag === "GCP.CertificateManager.CertificateMapStillExists",
265 times: 10,
266 schedule: Schedule.spaced("1 second"),
267 }),
268 );
269
270 const listOwnedMaps = (project: string) =>
271 certificatemanager.listProjectsLocationsCertificateMaps
272 .pages({
273 parent: `projects/${project}/locations/-`,
274 pageSize: 1000,
275 })
276 .pipe(
277 Stream.flatMap((page) => Stream.fromIterable(page.certificateMaps ?? [])),
278 Stream.filter((map) =>
279 Object.keys(map.labels ?? {}).some((key) => key.startsWith("alchemy-")),
280 ),
281 Stream.map((map) => toAttrs(map, project)),
282 Stream.runCollect,
283 Effect.map((chunk) => Array.from(chunk)),
284 Effect.catchTag("NotFound", () => Effect.succeed([])),
285 );
286
287 export const CertificateMapProvider = () =>
288 Provider.succeed(CertificateMap, {
289 stables: ["name", "certificateMapId", "project", "location", "createTime"],
290
291 diff: Effect.fn(function* ({ news, olds, output }) {
292 if (!isResolved(news)) return undefined;
293
294 const previousId = olds?.certificateMapId ?? output?.certificateMapId;
295 const nextId = news.certificateMapId ?? previousId;
296 const previousLocation = normalizeLocation(olds?.location ?? output?.location);
297 const nextLocation = normalizeLocation(news.location ?? olds?.location ?? output?.location);
298
299 const replace =
300 (previousId !== undefined && nextId !== undefined && nextId !== previousId) ||
301 previousLocation !== nextLocation;
302
303 if (!replace) return undefined;
304 return {
305 action: "replace" as const,
306 };
307 }),
308
309 read: Effect.fn(function* ({ id, olds, output }) {
310 const env = yield* GcpEnvironment.current;
311 const certificateMapId = yield* toId(id, olds?.certificateMapId, output?.certificateMapId);
312 const location = normalizeLocation(olds?.location ?? output?.location);
313 const name = output?.name ?? resourceName(env.project, location, certificateMapId);
314 const existing = yield* getByName(name);
315 if (existing === undefined) return undefined;
316 const attrs = toAttrs(existing, env.project);
317 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
318 }),
319
320 list: () =>
321 Effect.gen(function* () {
322 const env = yield* GcpEnvironment.current;
323 return yield* listOwnedMaps(env.project);
324 }),
325
326 reconcile: Effect.fn(function* ({ id, news, output }) {
327 const env = yield* GcpEnvironment.current;
328 const certificateMapId = yield* toId(id, news.certificateMapId, output?.certificateMapId);
329 const location = normalizeLocation(news.location ?? output?.location);
330 const name = resourceName(env.project, location, certificateMapId);
331 const desiredLabels = {
332 ...toLabels(news.labels),
333 ...(yield* createInternalLabels(id)),
334 };
335
336 let current = yield* getByName(name);
337
338 if (current === undefined) {
339 const created = yield* certificatemanager
340 .createProjectsLocationsCertificateMaps({
341 parent: `projects/${env.project}/locations/${location}`,
342 certificateMapId,
343 body: {
344 description: news.description,
345 labels: desiredLabels,
346 },
347 })
348 .pipe(
349 Effect.retry({
350 while: (error) => error._tag === "Conflict",
351 times: 5,
352 schedule: Schedule.spaced("2 seconds"),
353 }),
354 Effect.catchTag("Conflict", () => Effect.undefined),
355 );
356 if (created !== undefined) {
357 yield* waitForOperation(created);
358 }
359 current = yield* waitUntilExists(name);
360 }
361
362 if (current === undefined) {
363 return yield* new CertificateMapNotResolved({ resourceName: name });
364 }
365
366 const observedLabels = tagRecord(current.labels);
367 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
368 const labelsChanged = upsert.length > 0 || removed.length > 0;
369 const descriptionChanged = (current.description ?? "") !== (news.description ?? "");
370
371 if (labelsChanged || descriptionChanged) {
372 const updateMask = [
373 labelsChanged ? "labels" : undefined,
374 descriptionChanged ? "description" : undefined,
375 ].filter((field): field is string => field !== undefined);
376
377 const operation = yield* certificatemanager.patchProjectsLocationsCertificateMaps({
378 name,
379 updateMask: updateMask.join(","),
380 body: {
381 name,
382 labels: desiredLabels,
383 description: news.description,
384 },
385 });
386 yield* waitForOperation(operation);
387 current = yield* waitUntilExists(name);
388 }
389
390 return toAttrs(current, env.project);
391 }),
392
393 delete: Effect.fn(function* ({ output }) {
394 const operation = yield* certificatemanager
395 .deleteProjectsLocationsCertificateMaps({ name: output.name })
396 .pipe(
397 Effect.retry({
398 while: (error) => error._tag === "Conflict",
399 times: 8,
400 schedule: Schedule.spaced("2 seconds"),
401 }),
402 Effect.catchTag("NotFound", () => Effect.undefined),
403 );
404 if (operation !== undefined) {
405 yield* waitForOperation(operation, { notFoundOk: true });
406 }
407 yield* waitUntilGone(output.name);
408 }),
409 });