@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 427 lines 14.8 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 createInternalLabels,
14 diffLabels,
15 hasAlchemyLabels,
16 stripInternalLabels,
17 } from "../Labels.ts";
18 import type { Providers } from "../Providers.ts";
19
20 const MAX_SERVICE_ID_LENGTH = 63;
21
22 export type ServiceProps = {
23 /**
24 * Parent namespace. Full name
25 * `projects/{project}/locations/{location}/namespaces/{namespace}` or
26 * the namespace id (combined with `location`). Immutable — changing it
27 * replaces the service.
28 */
29 namespace: string;
30 /**
31 * Location of the service (e.g. `us-central1`). Used when `namespace`
32 * is a bare id. Immutable — changing it replaces the service.
33 * `US-CENTRAL1` is accepted and normalized to `us-central1`.
34 * @default the stack's GCP region (`GCP.Region`, else the profile
35 * region, else `us-central1`)
36 */
37 location?: string;
38 /**
39 * Service id (the `{service}` segment of
40 * `projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}`).
41 * If omitted, a unique name is generated from the stack, stage, and
42 * logical id. Must be 1-63 characters and match
43 * `[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?`. Immutable — changing it
44 * replaces the service.
45 */
46 serviceId?: string;
47 /**
48 * User annotations consumed by service clients. Alchemy ownership
49 * keys (`alchemy-stack` / `alchemy-stage` / `alchemy-id`) are merged
50 * in automatically — Service Directory services have no labels field.
51 * The entire map may contain at most 2000 characters.
52 */
53 annotations?: Record<string, string>;
54 };
55
56 export type Service = Resource<
57 "GCP.ServiceDirectory.Service",
58 ServiceProps,
59 {
60 /** Full resource name `projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}`. */
61 name: string;
62 /** Service id (last path segment). */
63 serviceId: string;
64 /** Parent namespace resource name. */
65 namespace: string;
66 /** Namespace id (last path segment of the parent). */
67 namespaceId: string;
68 /** Project id. */
69 project: string;
70 /** Location id (e.g. `us-central1`). */
71 location: string;
72 /** User annotations (Alchemy ownership keys stripped). */
73 annotations: Record<string, string>;
74 /** Server-assigned UUID4. */
75 uid: string | undefined;
76 },
77 never,
78 Providers
79 >;
80
81 /**
82 * A Service Directory service — a named registration that holds
83 * endpoints and client-facing annotations.
84 *
85 * Changing `serviceId`, `namespace`, or `location` replaces the service.
86 * Annotations update in place. Services have no labels field; Alchemy
87 * stamps ownership into annotations so `list` / `pnpm nuke:gcp` can find
88 * them.
89 *
90 * ### Creating a Service
91 * **Example:** Generated name in a namespace
92 * ```typescript
93 * const ns = yield* GCP.ServiceDirectory.Namespace("Services", {});
94 * const api = yield* GCP.ServiceDirectory.Service("Api", {
95 * namespace: ns.name,
96 * });
97 * ```
98 *
99 * **Example:** Explicit id and annotations
100 * ```typescript
101 * const api = yield* GCP.ServiceDirectory.Service("Api", {
102 * namespace: ns.name,
103 * serviceId: "checkout",
104 * annotations: { protocol: "http" },
105 * });
106 * ```
107 *
108 * ### Resolving Endpoints
109 * **Example:** Resolve the service at runtime
110 * ```typescript
111 * const resolve = yield* GCP.ServiceDirectory.Resolve(api);
112 * const { service } = yield* resolve();
113 * ```
114 *
115 * @resource
116 * @category ServiceDirectory
117 */
118 export const Service = Resource<Service>("GCP.ServiceDirectory.Service");
119
120 export class ServiceNotResolved extends Data.TaggedError(
121 "GCP.ServiceDirectory.ServiceNotResolved",
122 )<{
123 resourceName: string;
124 }> {}
125
126 const lastSegment = (value: string) => {
127 const trimmed = value.replace(/\/+$/, "");
128 const parts = trimmed.split("/");
129 return parts[parts.length - 1] || trimmed;
130 };
131
132 const normalizeLocation = (location: string | undefined, defaultLocation: string) =>
133 lastSegment(location ?? defaultLocation).toLowerCase();
134
135 const parseName = (name: string, defaultLocation: string) => {
136 const parts = name.split("/").filter((part) => part.length > 0);
137 const servicesAt = parts.lastIndexOf("services");
138 const namespacesAt = parts.lastIndexOf("namespaces");
139 const locationsAt = parts.lastIndexOf("locations");
140 const projectsAt = parts.lastIndexOf("projects");
141 const namespace = namespacesAt >= 0 ? parts.slice(0, namespacesAt + 2).join("/") : "";
142 return {
143 project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "",
144 location:
145 locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : defaultLocation,
146 namespace,
147 namespaceId: namespacesAt >= 0 && parts[namespacesAt + 1] ? parts[namespacesAt + 1]! : "",
148 serviceId:
149 servicesAt >= 0 && parts[servicesAt + 1] ? parts[servicesAt + 1]! : lastSegment(name),
150 };
151 };
152
153 const resolveParent = (
154 project: string,
155 namespace: string,
156 location: string | undefined,
157 region: string,
158 ) => {
159 if (namespace.includes("/")) {
160 const parsed = parseName(
161 namespace.includes("/services/") ? namespace : `${namespace}/services/_`,
162 region,
163 );
164 return {
165 parent: parsed.namespace,
166 location: parsed.location,
167 project: parsed.project || project,
168 namespaceId: parsed.namespaceId,
169 };
170 }
171 const loc = normalizeLocation(location, region);
172 return {
173 parent: `projects/${project}/locations/${loc}/namespaces/${namespace}`,
174 location: loc,
175 project,
176 namespaceId: namespace,
177 };
178 };
179
180 const resourceName = (parent: string, serviceId: string) => `${parent}/services/${serviceId}`;
181
182 const locationParent = (project: string, location: string) =>
183 `projects/${project}/locations/${location}`;
184
185 const userAnnotations = (
186 annotations: Record<string, string | undefined> | null | undefined,
187 ): Record<string, string> => stripInternalLabels(tagRecord(annotations));
188
189 const toId = (id: string, serviceId: string | undefined, existing?: string) =>
190 Effect.gen(function* () {
191 if (serviceId !== undefined) return serviceId;
192 if (existing !== undefined) return existing;
193 const generated = yield* createPhysicalName({
194 id,
195 maxLength: MAX_SERVICE_ID_LENGTH,
196 lowercase: true,
197 });
198 const named = /^[a-z]/.test(generated) ? generated : `s${generated}`;
199 return named.replace(/-+$/g, "").slice(0, MAX_SERVICE_ID_LENGTH).replace(/-+$/g, "");
200 });
201
202 const toAttrs = (service: servicedirectory.Service, project: string, region: string) => {
203 const name = service.name ?? "";
204 const parsed = parseName(name, region);
205 return {
206 name,
207 serviceId: parsed.serviceId,
208 namespace: parsed.namespace,
209 namespaceId: parsed.namespaceId,
210 project: parsed.project || project,
211 location: parsed.location,
212 annotations: userAnnotations(service.annotations),
213 uid: service.uid,
214 };
215 };
216
217 const getByName = (name: string) =>
218 servicedirectory
219 .getProjectsLocationsNamespacesServices({ name })
220 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
221
222 const hasAlchemyAnnotation = (annotations: Record<string, string | undefined> | null | undefined) =>
223 Object.keys(annotations ?? {}).some((key) => key.startsWith("alchemy-"));
224
225 const listServicesAt = (parent: string, project: string, region: string) =>
226 Effect.gen(function* () {
227 const found: ReturnType<typeof toAttrs>[] = [];
228 let pageToken: string | undefined;
229 do {
230 const response = yield* servicedirectory.listProjectsLocationsNamespacesServices({
231 parent,
232 pageSize: 1000,
233 pageToken,
234 });
235 for (const service of response.services ?? []) {
236 if (hasAlchemyAnnotation(service.annotations)) {
237 found.push(toAttrs(service, project, region));
238 }
239 }
240 pageToken = response.nextPageToken;
241 } while (pageToken !== undefined && pageToken !== "");
242 return found;
243 }).pipe(Effect.catchTag("NotFound", () => Effect.succeed([] as ReturnType<typeof toAttrs>[])));
244
245 const listNamespaceNamesAt = (parent: string) =>
246 Effect.gen(function* () {
247 const found: string[] = [];
248 let pageToken: string | undefined;
249 do {
250 const response = yield* servicedirectory.listProjectsLocationsNamespaces({
251 parent,
252 pageSize: 1000,
253 pageToken,
254 });
255 for (const namespace of response.namespaces ?? []) {
256 if (namespace.name) found.push(namespace.name);
257 }
258 pageToken = response.nextPageToken;
259 } while (pageToken !== undefined && pageToken !== "");
260 return found;
261 }).pipe(Effect.catchTag("NotFound", () => Effect.succeed([] as string[])));
262
263 export const ServiceProvider = () =>
264 Provider.succeed(Service, {
265 stables: ["name", "serviceId", "namespace", "namespaceId", "project", "location", "uid"],
266
267 diff: Effect.fn(function* ({ news, olds, output }) {
268 if (!isResolved(news)) return undefined;
269 const env = yield* GcpEnvironment.current;
270 const previousId = olds?.serviceId ?? output?.serviceId;
271 const nextId = news.serviceId ?? previousId;
272 const idChanged = previousId !== undefined && nextId !== undefined && nextId !== previousId;
273
274 const previousParent = output?.namespace ?? olds?.namespace;
275 const previousParentId = previousParent ? lastSegment(previousParent) : undefined;
276 const nextParentId = lastSegment(news.namespace);
277 const parentChanged = previousParentId !== undefined && previousParentId !== nextParentId;
278
279 const previousLocation = normalizeLocation(olds?.location ?? output?.location, env.region);
280 const nextLocation = news.namespace.includes("/")
281 ? parseName(
282 news.namespace.includes("/services/") ? news.namespace : `${news.namespace}/services/_`,
283 env.region,
284 ).location
285 : normalizeLocation(news.location ?? output?.location, env.region);
286
287 if (idChanged || parentChanged || previousLocation !== nextLocation) {
288 return { action: "replace" as const };
289 }
290 return undefined;
291 }),
292
293 read: Effect.fn(function* ({ id, olds, output }) {
294 const env = yield* GcpEnvironment.current;
295 const serviceId = yield* toId(id, olds?.serviceId, output?.serviceId);
296 const namespaceRef = olds?.namespace ?? output?.namespace;
297 const name =
298 output?.name ??
299 (namespaceRef
300 ? resourceName(
301 resolveParent(
302 env.project,
303 namespaceRef,
304 olds?.location ?? output?.location,
305 env.region,
306 ).parent,
307 serviceId,
308 )
309 : undefined);
310 if (name === undefined) return undefined;
311 const existing = yield* getByName(name);
312 if (existing === undefined) return undefined;
313 const attrs = toAttrs(existing, env.project, env.region);
314 return (yield* hasAlchemyLabels(id, tagRecord(existing.annotations)))
315 ? attrs
316 : Unowned(attrs);
317 }),
318
319 list: () =>
320 Effect.gen(function* () {
321 const env = yield* GcpEnvironment.current;
322 const fallback = [locationParent(env.project, env.region)];
323 const found: ReturnType<typeof toAttrs>[] = [];
324 let pageToken: string | undefined;
325 do {
326 const response = yield* servicedirectory
327 .listProjectsLocations({
328 name: `projects/${env.project}`,
329 pageSize: 100,
330 pageToken,
331 })
332 .pipe(
333 Effect.catchTag("NotFound", () =>
334 Effect.succeed({
335 locations: [
336 {
337 name: fallback[0],
338 locationId: env.region,
339 } satisfies servicedirectory.Location,
340 ],
341 nextPageToken: undefined as string | undefined,
342 }),
343 ),
344 );
345 const parents = (response.locations ?? [])
346 .map((location) => location.name)
347 .filter((name): name is string => !!name);
348 const namespacePages = yield* Effect.forEach(
349 parents.length > 0 ? parents : fallback,
350 (parent) => listNamespaceNamesAt(parent),
351 { concurrency: 4 },
352 );
353 const namespaceNames = namespacePages.flat();
354 const servicePages = yield* Effect.forEach(
355 namespaceNames,
356 (parent) => listServicesAt(parent, env.project, env.region),
357 { concurrency: 4 },
358 );
359 for (const services of servicePages) {
360 found.push(...services);
361 }
362 pageToken = response.nextPageToken;
363 } while (pageToken !== undefined && pageToken !== "");
364 return found;
365 }),
366
367 reconcile: Effect.fn(function* ({ id, news, output }) {
368 const env = yield* GcpEnvironment.current;
369 const parent = resolveParent(
370 env.project,
371 news.namespace,
372 news.location ?? output?.location,
373 env.region,
374 );
375 const serviceId = yield* toId(id, news.serviceId, output?.serviceId);
376 const name = resourceName(parent.parent, serviceId);
377 const desiredAnnotations = {
378 ...tagRecord(news.annotations),
379 ...(yield* createInternalLabels(id)),
380 };
381
382 let current = yield* getByName(name);
383
384 if (current === undefined) {
385 const created = yield* servicedirectory
386 .createProjectsLocationsNamespacesServices({
387 parent: parent.parent,
388 serviceId,
389 body: {
390 annotations: desiredAnnotations,
391 },
392 })
393 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
394 current = created ?? undefined;
395 }
396
397 if (current === undefined) {
398 return yield* new ServiceNotResolved({ resourceName: name });
399 }
400
401 const observedAnnotations = tagRecord(current.annotations);
402 const { upsert, removed } = diffLabels(observedAnnotations, desiredAnnotations);
403 if (upsert.length > 0 || removed.length > 0) {
404 current = yield* servicedirectory.patchProjectsLocationsNamespacesServices({
405 name,
406 updateMask: "annotations",
407 body: {
408 name,
409 annotations: desiredAnnotations,
410 },
411 });
412 }
413
414 return toAttrs(current, env.project, env.region);
415 }),
416
417 delete: Effect.fn(function* ({ output }) {
418 yield* servicedirectory.deleteProjectsLocationsNamespacesServices({ name: output.name }).pipe(
419 Effect.retry({
420 while: (error) => error._tag === "Conflict",
421 times: 8,
422 schedule: Schedule.spaced("1 second"),
423 }),
424 Effect.catchTag("NotFound", () => Effect.void),
425 );
426 }),
427 });