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

main
ts 565 lines 17.2 KB
Raw
1 import * as monitoring from "@distilled.cloud/gcp/monitoring_v3";
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 Stream from "effect/Stream";
11 import { GcpEnvironment } from "../Environment.ts";
12 import {
13 createInternalLabels,
14 diffLabels,
15 hasAlchemyLabels,
16 stripInternalLabels,
17 toLabels,
18 } from "../Labels.ts";
19 import type { Providers } from "../Providers.ts";
20 import { compactStringMap, jsonEqual, lastSegment, parentOf, toEmptyObject } from "./ownership.ts";
21
22 const MAX_SERVICE_ID_LENGTH = 63;
23
24 export type GkeServiceIdentifier = {
25 /** Project that owns the Kubernetes service. */
26 projectId?: string;
27 /** Parent cluster name. */
28 clusterName?: string;
29 /** Parent namespace name. */
30 namespaceName?: string;
31 /** Kubernetes service name. */
32 serviceName?: string;
33 /** Cluster location (zone or region). */
34 location?: string;
35 };
36
37 export type ClusterIstioIdentifier = {
38 /** Istio destination service name. */
39 serviceName?: string;
40 /** Cluster location. */
41 location?: string;
42 /** Kubernetes cluster name. */
43 clusterName?: string;
44 /** Istio destination service namespace. */
45 serviceNamespace?: string;
46 };
47
48 export type AppEngineIdentifier = {
49 /** App Engine module id (`module_id` on `gae_app`). */
50 moduleId?: string;
51 };
52
53 export type GkeNamespaceIdentifier = {
54 /** Cluster location. */
55 location?: string;
56 /** Parent cluster name. */
57 clusterName?: string;
58 /** Project that owns the namespace. */
59 projectId?: string;
60 /** Namespace name. */
61 namespaceName?: string;
62 };
63
64 export type BasicServiceIdentifier = {
65 /**
66 * Well-known service type (`APP_ENGINE`, `CLOUD_RUN`,
67 * `ISTIO_CANONICAL_SERVICE`, …).
68 */
69 serviceType?: string;
70 /** Labels identifying the telemetry resource. */
71 serviceLabels?: Record<string, string>;
72 };
73
74 export type MeshIstioIdentifier = {
75 /** Istio destination service name. */
76 serviceName?: string;
77 /** Istio destination service namespace. */
78 serviceNamespace?: string;
79 /** Mesh uid (`mesh_uid` metric label). */
80 meshUid?: string;
81 };
82
83 export type IstioCanonicalServiceIdentifier = {
84 /** Canonical service namespace. */
85 canonicalServiceNamespace?: string;
86 /** Canonical service name. */
87 canonicalService?: string;
88 /** Mesh uid. */
89 meshUid?: string;
90 };
91
92 export type CloudRunIdentifier = {
93 /** Cloud Run service name. */
94 serviceName?: string;
95 /** Region the service runs in. */
96 location?: string;
97 };
98
99 export type GkeWorkloadIdentifier = {
100 /** Cluster location. */
101 location?: string;
102 /** Workload kind (`Deployment`, `DaemonSet`, …). */
103 topLevelControllerType?: string;
104 /** Parent namespace name. */
105 namespaceName?: string;
106 /** Parent cluster name. */
107 clusterName?: string;
108 /** Project that owns the workload. */
109 projectId?: string;
110 /** Workload name. */
111 topLevelControllerName?: string;
112 };
113
114 export type CloudEndpointsIdentifier = {
115 /** Cloud Endpoints service name. */
116 service?: string;
117 };
118
119 export type ServiceTelemetry = {
120 /** Full resource name of the telemetry source. */
121 resourceName?: string;
122 };
123
124 export type ServiceProps = {
125 /**
126 * Service id (the `{service}` segment of
127 * `projects/{project}/services/{service}`). If omitted, a unique id
128 * is generated from the stack, stage, and logical id. Must match
129 * `[a-z0-9-]`. Immutable — changing it replaces the service.
130 */
131 serviceId?: string;
132 /**
133 * Human-readable display name. If omitted, the service id is used.
134 */
135 displayName?: string;
136 /**
137 * User labels. Alchemy ownership labels are merged in automatically.
138 */
139 labels?: Record<string, string>;
140 /**
141 * Custom service identifier. Used when no other identifier is set.
142 */
143 custom?: Record<string, never>;
144 /**
145 * Well-known basic service type and labels.
146 */
147 basicService?: BasicServiceIdentifier;
148 /** App Engine module identifier. */
149 appEngine?: AppEngineIdentifier;
150 /** Cloud Run identifier. */
151 cloudRun?: CloudRunIdentifier;
152 /** Cloud Endpoints identifier. */
153 cloudEndpoints?: CloudEndpointsIdentifier;
154 /** GKE Service identifier. */
155 gkeService?: GkeServiceIdentifier;
156 /** GKE Namespace identifier. */
157 gkeNamespace?: GkeNamespaceIdentifier;
158 /** GKE Workload identifier. */
159 gkeWorkload?: GkeWorkloadIdentifier;
160 /** Cluster-scoped Istio identifier. */
161 clusterIstio?: ClusterIstioIdentifier;
162 /** Mesh-scoped Istio identifier. */
163 meshIstio?: MeshIstioIdentifier;
164 /** Canonical Istio service identifier. */
165 istioCanonicalService?: IstioCanonicalServiceIdentifier;
166 /**
167 * Telemetry resource to query for this service.
168 */
169 telemetry?: ServiceTelemetry;
170 };
171
172 export type Service = Resource<
173 "GCP.Monitoring.Service",
174 ServiceProps,
175 {
176 /** Full resource name `projects/{project}/services/{service}`. */
177 name: string;
178 /** Service id (last path segment). */
179 serviceId: string;
180 /** Project id. */
181 project: string;
182 /** Human-readable display name. */
183 displayName: string | undefined;
184 /** User labels (Alchemy ownership labels stripped). */
185 labels: Record<string, string>;
186 /** Custom identifier, if this is a custom service. */
187 custom: Record<string, never> | undefined;
188 /** Well-known basic service identifier, if set. */
189 basicService: BasicServiceIdentifier | undefined;
190 /** App Engine identifier, if set. */
191 appEngine: AppEngineIdentifier | undefined;
192 /** Cloud Run identifier, if set. */
193 cloudRun: CloudRunIdentifier | undefined;
194 /** Cloud Endpoints identifier, if set. */
195 cloudEndpoints: CloudEndpointsIdentifier | undefined;
196 /** GKE Service identifier, if set. */
197 gkeService: GkeServiceIdentifier | undefined;
198 /** GKE Namespace identifier, if set. */
199 gkeNamespace: GkeNamespaceIdentifier | undefined;
200 /** GKE Workload identifier, if set. */
201 gkeWorkload: GkeWorkloadIdentifier | undefined;
202 /** Cluster-scoped Istio identifier, if set. */
203 clusterIstio: ClusterIstioIdentifier | undefined;
204 /** Mesh-scoped Istio identifier, if set. */
205 meshIstio: MeshIstioIdentifier | undefined;
206 /** Canonical Istio identifier, if set. */
207 istioCanonicalService: IstioCanonicalServiceIdentifier | undefined;
208 /** Telemetry resource, if set. */
209 telemetry: ServiceTelemetry | undefined;
210 },
211 never,
212 Providers
213 >;
214
215 /**
216 * A Cloud Monitoring service — the root resource for SLO monitoring.
217 *
218 * Custom services (`custom: {}`) are the default when no other
219 * identifier is set. Alchemy stamps ownership into `userLabels` so
220 * `list` / `pnpm nuke:gcp` can find them. Changing `serviceId` or the
221 * identifier kind replaces the service. Display name, labels, and
222 * telemetry update in place.
223 *
224 * ### Creating a Service
225 * **Example:** Generated custom service
226 * ```typescript
227 * const checkout = yield* GCP.Monitoring.Service("Checkout", {
228 * displayName: "Checkout",
229 * labels: { env: "prod" },
230 * });
231 * ```
232 *
233 * **Example:** Explicit id
234 * ```typescript
235 * const checkout = yield* GCP.Monitoring.Service("Checkout", {
236 * serviceId: "checkout",
237 * displayName: "Checkout API",
238 * });
239 * ```
240 *
241 * ### Updating a Service
242 * **Example:** Rename and relabel
243 * ```typescript
244 * const checkout = yield* GCP.Monitoring.Service("Checkout", {
245 * displayName: "Checkout v2",
246 * labels: { env: "prod", team: "payments" },
247 * });
248 * ```
249 *
250 * @resource
251 * @category Monitoring
252 */
253 export const Service = Resource<Service>("GCP.Monitoring.Service");
254
255 export class ServiceNotResolved extends Data.TaggedError("GCP.Monitoring.ServiceNotResolved")<{
256 resourceName: string;
257 }> {}
258
259 export type IdentifierKind =
260 | "custom"
261 | "basicService"
262 | "appEngine"
263 | "cloudRun"
264 | "cloudEndpoints"
265 | "gkeService"
266 | "gkeNamespace"
267 | "gkeWorkload"
268 | "clusterIstio"
269 | "meshIstio"
270 | "istioCanonicalService";
271
272 const IDENTIFIER_KINDS = [
273 "basicService",
274 "appEngine",
275 "cloudRun",
276 "cloudEndpoints",
277 "gkeService",
278 "gkeNamespace",
279 "gkeWorkload",
280 "clusterIstio",
281 "meshIstio",
282 "istioCanonicalService",
283 "custom",
284 ] as const satisfies readonly IdentifierKind[];
285
286 const identifierKindOf = (value: {
287 basicService?: unknown;
288 appEngine?: unknown;
289 cloudRun?: unknown;
290 cloudEndpoints?: unknown;
291 gkeService?: unknown;
292 gkeNamespace?: unknown;
293 gkeWorkload?: unknown;
294 clusterIstio?: unknown;
295 meshIstio?: unknown;
296 istioCanonicalService?: unknown;
297 custom?: unknown;
298 }): IdentifierKind => {
299 for (const kind of IDENTIFIER_KINDS) {
300 if (value[kind] !== undefined) return kind;
301 }
302 return "custom";
303 };
304
305 const resourceName = (project: string, serviceId: string) =>
306 `${parentOf(project)}/services/${serviceId}`;
307
308 const userFacingLabels = (
309 labels: Record<string, string | undefined> | null | undefined,
310 ): Record<string, string> => stripInternalLabels(tagRecord(labels));
311
312 const toId = (id: string, serviceId: string | undefined, existing?: string) =>
313 Effect.gen(function* () {
314 if (serviceId !== undefined) return serviceId;
315 if (existing !== undefined) return existing;
316 const generated = yield* createPhysicalName({
317 id,
318 maxLength: MAX_SERVICE_ID_LENGTH,
319 lowercase: true,
320 });
321 return generated.replace(/-+$/g, "").slice(0, MAX_SERVICE_ID_LENGTH);
322 });
323
324 const toBasicService = (
325 value: monitoring.BasicService | undefined,
326 ): BasicServiceIdentifier | undefined => {
327 if (value === undefined) return undefined;
328 return {
329 serviceType: value.serviceType,
330 serviceLabels: compactStringMap(value.serviceLabels),
331 };
332 };
333
334 const toAttrs = (service: monitoring.Service, project: string) => {
335 const name = service.name ?? "";
336 return {
337 name,
338 serviceId: lastSegment(name),
339 project,
340 displayName: service.displayName,
341 labels: userFacingLabels(service.userLabels),
342 custom: toEmptyObject(service.custom),
343 basicService: toBasicService(service.basicService),
344 appEngine: service.appEngine,
345 cloudRun: service.cloudRun,
346 cloudEndpoints: service.cloudEndpoints,
347 gkeService: service.gkeService,
348 gkeNamespace: service.gkeNamespace,
349 gkeWorkload: service.gkeWorkload,
350 clusterIstio: service.clusterIstio,
351 meshIstio: service.meshIstio,
352 istioCanonicalService: service.istioCanonicalService,
353 telemetry: service.telemetry,
354 };
355 };
356
357 const identifierBody = (
358 news: ServiceProps,
359 ): Pick<
360 monitoring.Service,
361 | "custom"
362 | "basicService"
363 | "appEngine"
364 | "cloudRun"
365 | "cloudEndpoints"
366 | "gkeService"
367 | "gkeNamespace"
368 | "gkeWorkload"
369 | "clusterIstio"
370 | "meshIstio"
371 | "istioCanonicalService"
372 > => {
373 switch (identifierKindOf(news)) {
374 case "basicService":
375 return { basicService: news.basicService };
376 case "appEngine":
377 return { appEngine: news.appEngine };
378 case "cloudRun":
379 return { cloudRun: news.cloudRun };
380 case "cloudEndpoints":
381 return { cloudEndpoints: news.cloudEndpoints };
382 case "gkeService":
383 return { gkeService: news.gkeService };
384 case "gkeNamespace":
385 return { gkeNamespace: news.gkeNamespace };
386 case "gkeWorkload":
387 return { gkeWorkload: news.gkeWorkload };
388 case "clusterIstio":
389 return { clusterIstio: news.clusterIstio };
390 case "meshIstio":
391 return { meshIstio: news.meshIstio };
392 case "istioCanonicalService":
393 return { istioCanonicalService: news.istioCanonicalService };
394 default:
395 return { custom: news.custom ?? {} };
396 }
397 };
398
399 const getByName = (name: string) =>
400 monitoring.getServices({ name }).pipe(Effect.catchTag("NotFound", () => Effect.undefined));
401
402 const listPages = (project: string) =>
403 monitoring.listServices
404 .pages({
405 parent: parentOf(project),
406 pageSize: 1000,
407 })
408 .pipe(
409 Stream.flatMap((page) => Stream.fromIterable(page.services ?? [])),
410 Stream.runCollect,
411 Effect.map((chunk) => Array.from(chunk)),
412 Effect.catchTag("NotFound", () => Effect.succeed([])),
413 );
414
415 const listOwned = (project: string) =>
416 Effect.gen(function* () {
417 const services = yield* listPages(project);
418 return services
419 .filter((service) =>
420 Object.keys(service.userLabels ?? {}).some((key) => key.startsWith("alchemy-")),
421 )
422 .map((service) => toAttrs(service, project));
423 });
424
425 const findOwned = (project: string, id: string) =>
426 Effect.gen(function* () {
427 const services = yield* listPages(project);
428 for (const service of services) {
429 if (yield* hasAlchemyLabels(id, tagRecord(service.userLabels))) {
430 return service;
431 }
432 }
433 return undefined;
434 });
435
436 const observe = (project: string, id: string, name: string | undefined) =>
437 Effect.gen(function* () {
438 if (name !== undefined) {
439 const existing = yield* getByName(name);
440 if (existing !== undefined) return existing;
441 }
442 return yield* findOwned(project, id);
443 });
444
445 export const ServiceProvider = () =>
446 Provider.succeed(Service, {
447 stables: ["name", "serviceId", "project"],
448
449 diff: Effect.fn(function* ({ news, olds, output }) {
450 if (!isResolved(news)) return undefined;
451 const previousId = olds?.serviceId ?? output?.serviceId;
452 const idChanged =
453 news.serviceId !== undefined && previousId !== undefined && news.serviceId !== previousId;
454 const previousKind = identifierKindOf({
455 basicService: olds?.basicService ?? output?.basicService,
456 appEngine: olds?.appEngine ?? output?.appEngine,
457 cloudRun: olds?.cloudRun ?? output?.cloudRun,
458 cloudEndpoints: olds?.cloudEndpoints ?? output?.cloudEndpoints,
459 gkeService: olds?.gkeService ?? output?.gkeService,
460 gkeNamespace: olds?.gkeNamespace ?? output?.gkeNamespace,
461 gkeWorkload: olds?.gkeWorkload ?? output?.gkeWorkload,
462 clusterIstio: olds?.clusterIstio ?? output?.clusterIstio,
463 meshIstio: olds?.meshIstio ?? output?.meshIstio,
464 istioCanonicalService: olds?.istioCanonicalService ?? output?.istioCanonicalService,
465 custom: olds?.custom ?? output?.custom ?? {},
466 });
467 const nextKind = identifierKindOf(news);
468 const kindChanged = previousKind !== nextKind;
469 if (!idChanged && !kindChanged) return undefined;
470 return {
471 action: "replace" as const,
472 deleteFirst: !idChanged,
473 };
474 }),
475
476 read: Effect.fn(function* ({ id, output }) {
477 const env = yield* GcpEnvironment.current;
478 const existing = yield* observe(env.project, id, output?.name);
479 if (existing === undefined) return undefined;
480 const attrs = toAttrs(existing, env.project);
481 return (yield* hasAlchemyLabels(id, tagRecord(existing.userLabels))) ? attrs : Unowned(attrs);
482 }),
483
484 list: () =>
485 Effect.gen(function* () {
486 const env = yield* GcpEnvironment.current;
487 return yield* listOwned(env.project);
488 }),
489
490 reconcile: Effect.fn(function* ({ id, news, output }) {
491 const env = yield* GcpEnvironment.current;
492 const serviceId = yield* toId(id, news.serviceId, output?.serviceId);
493 const name = resourceName(env.project, serviceId);
494 const displayName = news.displayName ?? serviceId;
495 const desiredLabels = {
496 ...toLabels(news.labels),
497 ...(yield* createInternalLabels(id)),
498 };
499
500 let current = yield* observe(env.project, id, output?.name ?? name);
501
502 const body: monitoring.Service = {
503 ...identifierBody(news),
504 displayName,
505 userLabels: desiredLabels,
506 telemetry: news.telemetry,
507 };
508
509 if (current === undefined) {
510 const created = yield* monitoring
511 .createServices({
512 parent: parentOf(env.project),
513 serviceId,
514 body,
515 })
516 .pipe(
517 Effect.catchTag("Conflict", () =>
518 getByName(name).pipe(
519 Effect.flatMap((existing) =>
520 existing !== undefined ? Effect.succeed(existing) : findOwned(env.project, id),
521 ),
522 ),
523 ),
524 );
525 current = created ?? undefined;
526 }
527
528 if (current === undefined) {
529 return yield* new ServiceNotResolved({ resourceName: name });
530 }
531
532 const resource = current.name ?? name;
533 const observedLabels = tagRecord(current.userLabels);
534 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
535 const labelsChanged = upsert.length > 0 || removed.length > 0;
536 const displayNameChanged = (current.displayName ?? "") !== displayName;
537 const telemetryChanged =
538 news.telemetry !== undefined && !jsonEqual(current.telemetry ?? null, news.telemetry);
539
540 const updateMask = [
541 displayNameChanged ? "display_name" : undefined,
542 labelsChanged ? "user_labels" : undefined,
543 telemetryChanged ? "telemetry" : undefined,
544 ].filter((field): field is string => field !== undefined);
545
546 if (updateMask.length > 0) {
547 current = yield* monitoring.patchServices({
548 name: resource,
549 updateMask: updateMask.join(","),
550 body: {
551 ...body,
552 name: resource,
553 },
554 });
555 }
556
557 return toAttrs(current, env.project);
558 }),
559
560 delete: Effect.fn(function* ({ output }) {
561 yield* monitoring
562 .deleteServices({ name: output.name })
563 .pipe(Effect.catchTag("NotFound", () => Effect.void));
564 }),
565 });