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

main
ts 597 lines 19.9 KB
Raw
1 import * as servicedirectory from "@distilled.cloud/gcp/servicedirectory_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 { GcpEnvironment } from "../Environment.ts";
12 import {
13 ALCHEMY_LABEL_PREFIX,
14 createInternalLabels,
15 diffLabels,
16 hasAlchemyLabels,
17 stripInternalLabels,
18 } from "../Labels.ts";
19 import type { Providers } from "../Providers.ts";
20
21 const MAX_ENDPOINT_ID_LENGTH = 63;
22 const DEFAULT_PORT = 0;
23
24 export type EndpointProps = {
25 /**
26 * Parent Service Directory service. Full name
27 * `projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}`
28 * or the service id (combined with `namespace`). Immutable — changing
29 * it replaces the endpoint.
30 */
31 service: string;
32 /**
33 * Parent namespace. Full name
34 * `projects/{project}/locations/{location}/namespaces/{namespace}` or
35 * the namespace id (combined with `location`). Used when `service` is
36 * a bare id. Immutable — changing it replaces the endpoint.
37 */
38 namespace?: string;
39 /**
40 * Location of the endpoint (e.g. `us-central1`). Used when `service`
41 * is a bare id. Immutable — changing it replaces the endpoint.
42 * `US-CENTRAL1` is accepted and normalized to `us-central1`.
43 * @default the stack's GCP region (`GCP.Region`, else the profile
44 * region, else `us-central1`)
45 */
46 location?: string;
47 /**
48 * Endpoint id (the `{endpoint}` segment of
49 * `.../services/{service}/endpoints/{endpoint}`). If omitted, a unique
50 * name is generated from the stack, stage, and logical id. Must be
51 * 1-63 characters and match `[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?`.
52 * Immutable — changing it replaces the endpoint.
53 */
54 endpointId?: string;
55 /**
56 * IPv4 or IPv6 address. Host:port, IPv6 brackets, and truncated
57 * addresses are rejected. Limited to 45 characters.
58 */
59 address?: string;
60 /**
61 * Port in `[0, 65535]`.
62 * @default 0
63 */
64 port?: number;
65 /**
66 * User annotations consumed by service clients. Alchemy ownership
67 * (`alchemy-stack` / `alchemy-stage` / `alchemy-id`) is merged in
68 * automatically. The entire annotations map may contain at most 512
69 * characters across all key-value pairs.
70 */
71 annotations?: Record<string, string>;
72 /**
73 * Google Compute Engine network of the endpoint, as
74 * `projects/{projectNumber}/locations/global/networks/{network}`. The
75 * project must be a project *number*. Immutable — changing it
76 * replaces the endpoint.
77 */
78 network?: string;
79 };
80
81 export type Endpoint = Resource<
82 "GCP.ServiceDirectory.Endpoint",
83 EndpointProps,
84 {
85 /** Full resource name `projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}/endpoints/{endpoint}`. */
86 name: string;
87 /** Endpoint id (last path segment). */
88 endpointId: string;
89 /** Parent service resource name. */
90 service: string;
91 /** Parent namespace resource name. */
92 namespace: string;
93 /** Project id. */
94 project: string;
95 /** Location id (e.g. `us-central1`). */
96 location: string;
97 /** IPv4 or IPv6 address, if set. */
98 address: string | undefined;
99 /** Port currently on the endpoint. */
100 port: number;
101 /** User annotations (Alchemy ownership annotations stripped). */
102 annotations: Record<string, string>;
103 /** VPC network resource name, if set. */
104 network: string | undefined;
105 /** Server-assigned UUID4. */
106 uid: string | undefined;
107 },
108 never,
109 Providers
110 >;
111
112 /**
113 * A Service Directory endpoint — an address/port registration on a
114 * service. The parent service must already exist.
115 *
116 * Changing `endpointId`, `service`, `namespace`, `location`, or
117 * `network` replaces the endpoint. `address`, `port`, and `annotations`
118 * update in place.
119 *
120 * Endpoints have no labels field. Alchemy stamps ownership into
121 * `annotations` so `list` / `pnpm nuke:gcp` can find owned endpoints
122 * under alchemy-labeled namespaces.
123 *
124 * ### Creating an Endpoint
125 * **Example:** Address and port on a service
126 * ```typescript
127 * const ns = yield* GCP.ServiceDirectory.Namespace("Services", {});
128 * const api = yield* GCP.ServiceDirectory.Service("Api", {
129 * namespace: ns.name,
130 * });
131 * const endpoint = yield* GCP.ServiceDirectory.Endpoint("Https", {
132 * service: api.name,
133 * address: "10.0.0.1",
134 * port: 443,
135 * });
136 * ```
137 *
138 * **Example:** Explicit id and annotations
139 * ```typescript
140 * const endpoint = yield* GCP.ServiceDirectory.Endpoint("Https", {
141 * service: api.name,
142 * endpointId: "api-https",
143 * address: "10.0.0.1",
144 * port: 443,
145 * annotations: { protocol: "https" },
146 * });
147 * ```
148 *
149 * @resource
150 * @category ServiceDirectory
151 */
152 export const Endpoint = Resource<Endpoint>("GCP.ServiceDirectory.Endpoint");
153
154 export class EndpointNotResolved extends Data.TaggedError(
155 "GCP.ServiceDirectory.EndpointNotResolved",
156 )<{
157 resourceName: string;
158 }> {}
159
160 export class EndpointParentMissing extends Data.TaggedError(
161 "GCP.ServiceDirectory.EndpointParentMissing",
162 )<{
163 service: string;
164 }> {}
165
166 const lastSegment = (value: string) => {
167 const trimmed = value.replace(/\/+$/, "");
168 const parts = trimmed.split("/");
169 return parts[parts.length - 1] || trimmed;
170 };
171
172 const normalizeLocation = (location: string | undefined, defaultLocation: string) =>
173 lastSegment(location ?? defaultLocation).toLowerCase();
174
175 const normalizeOptional = (value: string | undefined) =>
176 value === undefined || value === "" ? undefined : value;
177
178 const locationParent = (project: string, location: string) =>
179 `projects/${project}/locations/${location}`;
180
181 const parseName = (name: string, defaultLocation: string) => {
182 const parts = name.split("/").filter((part) => part.length > 0);
183 const endpointsAt = parts.lastIndexOf("endpoints");
184 const servicesAt = parts.lastIndexOf("services");
185 const namespacesAt = parts.lastIndexOf("namespaces");
186 const locationsAt = parts.lastIndexOf("locations");
187 const projectsAt = parts.lastIndexOf("projects");
188 const namespace = namespacesAt >= 0 ? parts.slice(0, namespacesAt + 2).join("/") : "";
189 const service = servicesAt >= 0 ? parts.slice(0, servicesAt + 2).join("/") : "";
190 return {
191 project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "",
192 location:
193 locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : defaultLocation,
194 namespace,
195 namespaceId: namespacesAt >= 0 && parts[namespacesAt + 1] ? parts[namespacesAt + 1]! : "",
196 service,
197 serviceId: servicesAt >= 0 && parts[servicesAt + 1] ? parts[servicesAt + 1]! : "",
198 endpointId:
199 endpointsAt >= 0 && parts[endpointsAt + 1] ? parts[endpointsAt + 1]! : lastSegment(name),
200 };
201 };
202
203 const resolveParent = (
204 project: string,
205 service: string,
206 namespace: string | undefined,
207 location: string | undefined,
208 region: string,
209 ) => {
210 if (service.includes("/")) {
211 const parsed = parseName(
212 service.includes("/endpoints/") ? service : `${service.replace(/\/+$/, "")}/endpoints/_`,
213 region,
214 );
215 return {
216 parent: parsed.service,
217 location: parsed.location,
218 project: parsed.project || project,
219 namespace: parsed.namespace,
220 };
221 }
222 const loc = normalizeLocation(location, region);
223 if (namespace === undefined || namespace === "") {
224 return undefined;
225 }
226 const namespaceName = namespace.includes("/namespaces/")
227 ? namespace.replace(/\/+$/, "")
228 : `projects/${project}/locations/${loc}/namespaces/${namespace}`;
229 const parsed = parseName(`${namespaceName}/services/_/endpoints/_`, region);
230 return {
231 parent: `${parsed.namespace}/services/${service}`,
232 location: parsed.location,
233 project: parsed.project || project,
234 namespace: parsed.namespace,
235 };
236 };
237
238 const parentKey = (
239 service: string | undefined,
240 namespace: string | undefined,
241 location: string | undefined,
242 region: string,
243 ) => {
244 if (service === undefined || service === "") return undefined;
245 const resolved = resolveParent("_", service, namespace, location, region);
246 if (resolved === undefined) return undefined;
247 return `${resolved.location}/${lastSegment(resolved.namespace)}/${lastSegment(resolved.parent)}`;
248 };
249
250 const resourceName = (parent: string, endpointId: string) => `${parent}/endpoints/${endpointId}`;
251
252 const userAnnotations = (
253 annotations: Record<string, string | undefined> | null | undefined,
254 ): Record<string, string> => stripInternalLabels(tagRecord(annotations));
255
256 const hasAlchemyAnnotation = (annotations: Record<string, string | undefined> | null | undefined) =>
257 Object.keys(annotations ?? {}).some((key) => key.startsWith(ALCHEMY_LABEL_PREFIX));
258
259 const hasAlchemyNamespaceLabels = (labels: Record<string, string | undefined> | null | undefined) =>
260 Object.keys(labels ?? {}).some((key) => key.startsWith(ALCHEMY_LABEL_PREFIX));
261
262 const toId = (id: string, endpointId: string | undefined, existing?: string) =>
263 Effect.gen(function* () {
264 if (endpointId !== undefined) return endpointId;
265 if (existing !== undefined) return existing;
266 const generated = yield* createPhysicalName({
267 id,
268 maxLength: MAX_ENDPOINT_ID_LENGTH,
269 lowercase: true,
270 forbiddenPrefixes: ["gcp"],
271 });
272 const named = /^[a-z]/.test(generated) ? generated : `e${generated}`;
273 return named.replace(/-+$/g, "").slice(0, MAX_ENDPOINT_ID_LENGTH).replace(/-+$/g, "");
274 });
275
276 const toAttrs = (endpoint: servicedirectory.Endpoint, project: string, region: string) => {
277 const name = endpoint.name ?? "";
278 const parsed = parseName(name, region);
279 return {
280 name,
281 endpointId: parsed.endpointId,
282 service: parsed.service,
283 namespace: parsed.namespace,
284 project: parsed.project || project,
285 location: parsed.location,
286 address: normalizeOptional(endpoint.address),
287 port: endpoint.port ?? DEFAULT_PORT,
288 annotations: userAnnotations(endpoint.annotations),
289 network: normalizeOptional(endpoint.network),
290 uid: endpoint.uid,
291 };
292 };
293
294 const getByName = (name: string) =>
295 servicedirectory
296 .getProjectsLocationsNamespacesServicesEndpoints({ name })
297 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
298
299 const deleteByName = (name: string) =>
300 servicedirectory.deleteProjectsLocationsNamespacesServicesEndpoints({ name }).pipe(
301 Effect.retry({
302 while: (error) => error._tag === "Conflict",
303 times: 8,
304 schedule: Schedule.spaced("1 second"),
305 }),
306 Effect.catchTag("NotFound", () => Effect.void),
307 );
308
309 const paginate = <A, E, R>(
310 fetch: (
311 pageToken: string | undefined,
312 ) => Effect.Effect<{ items: A[]; nextPageToken?: string }, E, R>,
313 ) =>
314 Effect.gen(function* () {
315 const found: A[] = [];
316 let pageToken: string | undefined;
317 do {
318 const response = yield* fetch(pageToken);
319 found.push(...response.items);
320 pageToken = response.nextPageToken;
321 } while (pageToken !== undefined && pageToken !== "");
322 return found;
323 });
324
325 const listNamespacesAt = (parent: string) =>
326 paginate((pageToken) =>
327 servicedirectory
328 .listProjectsLocationsNamespaces({
329 parent,
330 pageSize: 1000,
331 pageToken,
332 })
333 .pipe(
334 Effect.map((response) => ({
335 items: (response.namespaces ?? []).filter((namespace) =>
336 hasAlchemyNamespaceLabels(namespace.labels),
337 ),
338 nextPageToken: response.nextPageToken,
339 })),
340 Effect.catchTag("NotFound", () =>
341 Effect.succeed({
342 items: [] as servicedirectory.Namespace[],
343 nextPageToken: undefined,
344 }),
345 ),
346 ),
347 );
348
349 const listServicesAt = (parent: string) =>
350 paginate((pageToken) =>
351 servicedirectory
352 .listProjectsLocationsNamespacesServices({
353 parent,
354 pageSize: 1000,
355 pageToken,
356 })
357 .pipe(
358 Effect.map((response) => ({
359 items: response.services ?? [],
360 nextPageToken: response.nextPageToken,
361 })),
362 Effect.catchTag("NotFound", () =>
363 Effect.succeed({
364 items: [] as servicedirectory.Service[],
365 nextPageToken: undefined,
366 }),
367 ),
368 ),
369 );
370
371 const listEndpointsAt = (parent: string) =>
372 paginate((pageToken) =>
373 servicedirectory
374 .listProjectsLocationsNamespacesServicesEndpoints({
375 parent,
376 pageSize: 1000,
377 pageToken,
378 })
379 .pipe(
380 Effect.map((response) => ({
381 items: response.endpoints ?? [],
382 nextPageToken: response.nextPageToken,
383 })),
384 Effect.catchTag("NotFound", () =>
385 Effect.succeed({
386 items: [] as servicedirectory.Endpoint[],
387 nextPageToken: undefined,
388 }),
389 ),
390 ),
391 );
392
393 const listLocations = (project: string) =>
394 paginate((pageToken) =>
395 servicedirectory
396 .listProjectsLocations({
397 name: `projects/${project}`,
398 pageSize: 100,
399 pageToken,
400 })
401 .pipe(
402 Effect.map((response) => ({
403 items: (response.locations ?? [])
404 .map((location) => location.name)
405 .filter((name): name is string => !!name),
406 nextPageToken: response.nextPageToken,
407 })),
408 Effect.catchTag("NotFound", () =>
409 Effect.succeed({
410 items: [] as string[],
411 nextPageToken: undefined,
412 }),
413 ),
414 ),
415 );
416
417 export const EndpointProvider = () =>
418 Provider.succeed(Endpoint, {
419 stables: ["name", "endpointId", "service", "namespace", "project", "location", "uid"],
420
421 diff: Effect.fn(function* ({ news, olds, output }) {
422 if (!isResolved(news)) return undefined;
423 const env = yield* GcpEnvironment.current;
424 const previousId = olds?.endpointId ?? output?.endpointId;
425 const nextId = news.endpointId ?? previousId;
426 const idChanged = previousId !== undefined && nextId !== undefined && nextId !== previousId;
427
428 const previousParent = parentKey(
429 olds?.service ?? output?.service,
430 olds?.namespace ?? output?.namespace,
431 olds?.location ?? output?.location,
432 env.region,
433 );
434 const nextParent = parentKey(
435 news.service,
436 news.namespace ?? olds?.namespace ?? output?.namespace,
437 news.location ?? olds?.location ?? output?.location,
438 env.region,
439 );
440 const parentChanged =
441 previousParent !== undefined && nextParent !== undefined && previousParent !== nextParent;
442
443 const previousNetwork = normalizeOptional(olds?.network ?? output?.network);
444 const nextNetwork = normalizeOptional(news.network ?? previousNetwork);
445 const networkChanged = previousNetwork !== nextNetwork;
446
447 if (!idChanged && !parentChanged && !networkChanged) return undefined;
448 return {
449 action: "replace" as const,
450 deleteFirst:
451 networkChanged &&
452 !idChanged &&
453 !parentChanged &&
454 previousId !== undefined &&
455 nextId === previousId,
456 };
457 }),
458
459 read: Effect.fn(function* ({ id, olds, output }) {
460 const env = yield* GcpEnvironment.current;
461 const endpointId = yield* toId(id, olds?.endpointId, output?.endpointId);
462 const parent = resolveParent(
463 env.project,
464 olds?.service ?? output?.service ?? "",
465 olds?.namespace ?? output?.namespace,
466 olds?.location ?? output?.location,
467 env.region,
468 );
469 const name =
470 output?.name ??
471 (parent !== undefined ? resourceName(parent.parent, endpointId) : undefined);
472 if (name === undefined) return undefined;
473 const existing = yield* getByName(name);
474 if (existing === undefined) return undefined;
475 const attrs = toAttrs(existing, env.project, env.region);
476 return (yield* hasAlchemyLabels(id, tagRecord(existing.annotations)))
477 ? attrs
478 : Unowned(attrs);
479 }),
480
481 list: () =>
482 Effect.gen(function* () {
483 const env = yield* GcpEnvironment.current;
484 const fallback = [locationParent(env.project, env.region)];
485 const locations = yield* listLocations(env.project);
486 const parents = locations.length > 0 ? locations : fallback;
487 const namespacePages = yield* Effect.forEach(
488 parents,
489 (parent) => listNamespacesAt(parent),
490 { concurrency: 4 },
491 );
492 const namespaces = namespacePages.flat();
493 const servicePages = yield* Effect.forEach(
494 namespaces,
495 (namespace) =>
496 namespace.name
497 ? listServicesAt(namespace.name)
498 : Effect.succeed([] as servicedirectory.Service[]),
499 { concurrency: 4 },
500 );
501 const services = servicePages.flat();
502 const endpointPages = yield* Effect.forEach(
503 services,
504 (service) =>
505 service.name
506 ? listEndpointsAt(service.name)
507 : Effect.succeed([] as servicedirectory.Endpoint[]),
508 { concurrency: 4 },
509 );
510 return endpointPages
511 .flat()
512 .filter((endpoint) => hasAlchemyAnnotation(endpoint.annotations))
513 .map((endpoint) => toAttrs(endpoint, env.project, env.region));
514 }),
515
516 reconcile: Effect.fn(function* ({ id, news, output }) {
517 const env = yield* GcpEnvironment.current;
518 const endpointId = yield* toId(id, news.endpointId, output?.endpointId);
519 const parent = resolveParent(
520 env.project,
521 news.service,
522 news.namespace ?? output?.namespace,
523 news.location ?? output?.location,
524 env.region,
525 );
526 if (parent === undefined) {
527 return yield* new EndpointParentMissing({ service: news.service });
528 }
529 const name = resourceName(parent.parent, endpointId);
530 const desiredAnnotations = {
531 ...tagRecord(news.annotations),
532 ...(yield* createInternalLabels(id)),
533 };
534 const desiredAddress = news.address;
535 const desiredPort = news.port ?? DEFAULT_PORT;
536 const desiredNetwork = normalizeOptional(news.network);
537
538 let current = yield* getByName(output?.name ?? name);
539
540 if (current !== undefined && normalizeOptional(current.network) !== desiredNetwork) {
541 yield* deleteByName(current.name ?? name);
542 current = undefined;
543 }
544
545 if (current === undefined) {
546 const created = yield* servicedirectory
547 .createProjectsLocationsNamespacesServicesEndpoints({
548 parent: parent.parent,
549 endpointId,
550 body: {
551 address: desiredAddress,
552 port: desiredPort,
553 annotations: desiredAnnotations,
554 network: desiredNetwork,
555 },
556 })
557 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
558 current = created ?? undefined;
559 }
560
561 if (current === undefined) {
562 return yield* new EndpointNotResolved({ resourceName: name });
563 }
564
565 const observedAnnotations = tagRecord(current.annotations);
566 const { upsert, removed } = diffLabels(observedAnnotations, desiredAnnotations);
567 const annotationsChanged = upsert.length > 0 || removed.length > 0;
568 const addressChanged = (current.address ?? "") !== (desiredAddress ?? "");
569 const portChanged = (current.port ?? DEFAULT_PORT) !== desiredPort;
570
571 if (annotationsChanged || addressChanged || portChanged) {
572 const updateMask = [
573 annotationsChanged ? "annotations" : undefined,
574 addressChanged ? "address" : undefined,
575 portChanged ? "port" : undefined,
576 ]
577 .filter((field): field is string => field !== undefined)
578 .join(",");
579 current = yield* servicedirectory.patchProjectsLocationsNamespacesServicesEndpoints({
580 name,
581 updateMask,
582 body: {
583 name,
584 annotations: desiredAnnotations,
585 address: desiredAddress,
586 port: desiredPort,
587 },
588 });
589 }
590
591 return toAttrs(current, env.project, env.region);
592 }),
593
594 delete: Effect.fn(function* ({ output }) {
595 yield* deleteByName(output.name);
596 }),
597 });