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

main
ts 492 lines 16.4 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 * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import * as Schedule from "effect/Schedule";
10 import * as Stream from "effect/Stream";
11 import { GcpEnvironment } from "../Environment.ts";
12 import { createInternalLabels, hasAlchemyLabels } from "../Labels.ts";
13 import type { Providers } from "../Providers.ts";
14 import {
15 encodeDescription,
16 hasOwnershipMarker,
17 jsonEqual,
18 parentOf,
19 parseMarker,
20 } from "./ownership.ts";
21
22 const MAX_TYPE_LENGTH = 100;
23 const CUSTOM_PREFIX = "custom.googleapis.com/";
24 const DEFAULT_METRIC_KIND = "GAUGE";
25 const DEFAULT_VALUE_TYPE = "DOUBLE";
26 const DEFAULT_UNIT = "1";
27
28 export type MetricKind = "GAUGE" | "DELTA" | "CUMULATIVE" | (string & {});
29
30 export type MetricValueType =
31 | "BOOL"
32 | "INT64"
33 | "DOUBLE"
34 | "STRING"
35 | "DISTRIBUTION"
36 | "MONEY"
37 | (string & {});
38
39 export type MetricLabelDescriptor = {
40 /**
41 * Label key. Must match `[a-zA-Z][a-zA-Z0-9_]*` and be at most 100
42 * characters.
43 */
44 key?: string;
45 /** Human-readable description of the label. */
46 description?: string;
47 /**
48 * Label value type.
49 * @default "STRING"
50 */
51 valueType?: "STRING" | "BOOL" | "INT64" | (string & {});
52 };
53
54 export type MetricDescriptorMetadata = {
55 /** Sampling period of written data points (for example `"60s"`). */
56 samplePeriod?: string;
57 /** Ingest delay after which points are guaranteed available. */
58 ingestDelay?: string;
59 /** Hierarchy levels that emit this metric (`PROJECT`, `FOLDER`, …). */
60 timeSeriesResourceHierarchyLevel?: string[];
61 /** Deprecated launch stage; prefer the top-level `launchStage`. */
62 launchStage?: string;
63 };
64
65 export type MetricDescriptorProps = {
66 /**
67 * Metric type, including DNS prefix (for example
68 * `custom.googleapis.com/invoice/paid/amount`). If omitted, a unique
69 * `custom.googleapis.com/` type is generated from the stack, stage,
70 * and logical id. Immutable — changing it replaces the descriptor.
71 */
72 type?: string;
73 /**
74 * Whether the metric records a point-in-time value or a change.
75 * Custom metrics support `GAUGE` and `CUMULATIVE` (`DELTA` is
76 * rejected). Immutable after create — changing it replaces the
77 * descriptor.
78 * @default "GAUGE"
79 */
80 metricKind?: MetricKind;
81 /**
82 * Measurement type. Immutable after create — changing it replaces
83 * the descriptor.
84 * @default "DOUBLE"
85 */
86 valueType?: MetricValueType;
87 /**
88 * Unit of the stored value (`"1"`, `"s"`, `"By"`, …).
89 * @default "1"
90 */
91 unit?: string;
92 /**
93 * Concise display name shown in Monitoring UIs.
94 */
95 displayName?: string;
96 /**
97 * Detailed description. Metric descriptors have no resource labels,
98 * so Alchemy stamps ownership into this field for `list` / nuke.
99 */
100 description?: string;
101 /**
102 * Time-series labels. New keys may be added; existing keys cannot be
103 * removed or have their value type changed without replacing the
104 * descriptor.
105 */
106 labels?: MetricLabelDescriptor[];
107 /**
108 * Optional launch stage of the metric definition.
109 */
110 launchStage?: string;
111 /**
112 * Optional usage metadata (sample period, ingest delay).
113 */
114 metadata?: MetricDescriptorMetadata;
115 };
116
117 export type MetricDescriptor = Resource<
118 "GCP.Monitoring.MetricDescriptor",
119 MetricDescriptorProps,
120 {
121 /** Full resource name `projects/{project}/metricDescriptors/{type}`. */
122 name: string;
123 /** Metric type, including DNS prefix. */
124 type: string;
125 /** Project id. */
126 project: string;
127 /** Metric kind (`GAUGE`, `DELTA`, `CUMULATIVE`). */
128 metricKind: string | undefined;
129 /** Value type (`DOUBLE`, `INT64`, …). */
130 valueType: string | undefined;
131 /** Unit of the stored value. */
132 unit: string | undefined;
133 /** Concise display name. */
134 displayName: string | undefined;
135 /** User description with the Alchemy ownership prefix stripped. */
136 description: string | undefined;
137 /** Time-series label descriptors. */
138 labels: MetricLabelDescriptor[];
139 /** Launch stage, if set. */
140 launchStage: string | undefined;
141 /** Usage metadata, if set. */
142 metadata: MetricDescriptorMetadata | undefined;
143 /** Compatible monitored resource types, if the API reports them. */
144 monitoredResourceTypes: ReadonlyArray<string>;
145 },
146 never,
147 Providers
148 >;
149
150 /**
151 * A Cloud Monitoring metric descriptor — the schema for a custom or
152 * external metric type.
153 *
154 * Descriptors have no resource labels. Alchemy stamps ownership into
155 * `description` (`[alchemy alchemy-stack=… alchemy-stage=…
156 * alchemy-id=…]`) so `list` / `pnpm nuke:gcp` can find them. `type`,
157 * `metricKind`, and `valueType` are immutable — changing them replaces
158 * the descriptor. Display name, description, unit, metadata, and added
159 * labels update in place via create-as-upsert.
160 *
161 * ### Creating a Descriptor
162 * **Example:** Generated custom gauge
163 * ```typescript
164 * const metric = yield* GCP.Monitoring.MetricDescriptor("Paid", {
165 * displayName: "Invoice paid amount",
166 * description: "amount collected per invoice",
167 * });
168 * ```
169 *
170 * **Example:** Explicit type, kind, and labels
171 * ```typescript
172 * const metric = yield* GCP.Monitoring.MetricDescriptor("Paid", {
173 * type: "custom.googleapis.com/invoice/paid/amount",
174 * metricKind: "DELTA",
175 * valueType: "INT64",
176 * unit: "1",
177 * labels: [{ key: "currency", valueType: "STRING" }],
178 * });
179 * ```
180 *
181 * ### Updating a Descriptor
182 * **Example:** Change the display name and unit
183 * ```typescript
184 * const metric = yield* GCP.Monitoring.MetricDescriptor("Paid", {
185 * displayName: "Invoice paid (cents)",
186 * unit: "1",
187 * description: "amount collected per invoice in cents",
188 * });
189 * ```
190 *
191 * @resource
192 * @category Monitoring
193 */
194 export const MetricDescriptor = Resource<MetricDescriptor>("GCP.Monitoring.MetricDescriptor");
195
196 export class MetricDescriptorNotResolved extends Data.TaggedError(
197 "GCP.Monitoring.MetricDescriptorNotResolved",
198 )<{
199 resourceName: string;
200 }> {}
201
202 const METRIC_DESCRIPTORS = "/metricDescriptors/";
203
204 const typeOf = (descriptor: monitoring.MetricDescriptor) => {
205 if (descriptor.type !== undefined && descriptor.type.length > 0) {
206 return descriptor.type;
207 }
208 const name = descriptor.name ?? "";
209 const at = name.indexOf(METRIC_DESCRIPTORS);
210 return at >= 0 ? name.slice(at + METRIC_DESCRIPTORS.length) : name;
211 };
212
213 const resourceName = (project: string, type: string) =>
214 `projects/${project}/metricDescriptors/${type}`;
215
216 const qualifyType = (type: string) =>
217 type.includes(".googleapis.com/") ? type : `${CUSTOM_PREFIX}${type.replace(/^\/+/, "")}`;
218
219 const toType = (id: string, type: string | undefined, existing?: string) =>
220 Effect.gen(function* () {
221 if (type !== undefined) return qualifyType(type);
222 if (existing !== undefined) return existing;
223 const generated = yield* createPhysicalName({
224 id,
225 maxLength: MAX_TYPE_LENGTH,
226 lowercase: true,
227 delimiter: "_",
228 });
229 const metricName = generated.replace(/-/g, "_").replace(/_+/g, "_");
230 const named = /^[a-z]/.test(metricName) ? metricName : `m_${metricName}`;
231 return qualifyType(named);
232 });
233
234 const toLabels = (labels: monitoring.LabelDescriptorList | undefined): MetricLabelDescriptor[] =>
235 (labels ?? []).flatMap((label) =>
236 label.key
237 ? [
238 {
239 key: label.key,
240 description: label.description,
241 valueType: label.valueType,
242 },
243 ]
244 : [],
245 );
246
247 const toMetadata = (
248 metadata: monitoring.MetricDescriptorMetadata | undefined,
249 ): MetricDescriptorMetadata | undefined => {
250 if (metadata === undefined) return undefined;
251 return {
252 samplePeriod: metadata.samplePeriod,
253 ingestDelay: metadata.ingestDelay,
254 timeSeriesResourceHierarchyLevel: metadata.timeSeriesResourceHierarchyLevel,
255 launchStage: metadata.launchStage,
256 };
257 };
258
259 const toAttrs = (descriptor: monitoring.MetricDescriptor, project: string) => {
260 const type = typeOf(descriptor);
261 const parsed = parseMarker(descriptor.description);
262 return {
263 name: descriptor.name?.includes(METRIC_DESCRIPTORS)
264 ? descriptor.name
265 : resourceName(project, type),
266 type,
267 project,
268 metricKind: descriptor.metricKind,
269 valueType: descriptor.valueType,
270 unit: descriptor.unit,
271 displayName: descriptor.displayName,
272 description: parsed.rest,
273 labels: toLabels(descriptor.labels),
274 launchStage: descriptor.launchStage,
275 metadata: toMetadata(descriptor.metadata),
276 monitoredResourceTypes: descriptor.monitoredResourceTypes ?? [],
277 };
278 };
279
280 const canonLabels = (labels: MetricLabelDescriptor[] | undefined) =>
281 [...(labels ?? [])]
282 .map((label) => ({
283 key: label.key ?? "",
284 description: label.description ?? "",
285 valueType: (label.valueType ?? "STRING").toUpperCase(),
286 }))
287 .filter((label) => label.key.length > 0)
288 .sort((left, right) => left.key.localeCompare(right.key));
289
290 const labelsRemoved = (
291 observed: MetricLabelDescriptor[],
292 desired: MetricLabelDescriptor[] | undefined,
293 ) => {
294 if (desired === undefined) return false;
295 const next = new Set(canonLabels(desired).map((label) => label.key));
296 return canonLabels(observed).some((label) => !next.has(label.key));
297 };
298
299 const toBody = (
300 type: string,
301 news: MetricDescriptorProps,
302 ownership: Record<string, string>,
303 ): monitoring.MetricDescriptor => ({
304 type,
305 metricKind: news.metricKind ?? DEFAULT_METRIC_KIND,
306 valueType: news.valueType ?? DEFAULT_VALUE_TYPE,
307 unit: news.unit ?? DEFAULT_UNIT,
308 displayName: news.displayName,
309 description: encodeDescription(ownership, news.description),
310 labels: news.labels as monitoring.LabelDescriptorList | undefined,
311 launchStage: news.launchStage,
312 metadata: news.metadata as monitoring.MetricDescriptorMetadata | undefined,
313 });
314
315 const getByName = (name: string) =>
316 monitoring
317 .getProjectsMetricDescriptors({ name })
318 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
319
320 const waitUntilSynced = (name: string, desired: { displayName?: string; description: string }) =>
321 getByName(name).pipe(
322 Effect.flatMap((value) => {
323 if (value === undefined) {
324 return Effect.fail(new MetricDescriptorNotResolved({ resourceName: name }));
325 }
326 const displayOk =
327 desired.displayName === undefined || (value.displayName ?? "") === desired.displayName;
328 const descriptionOk = (value.description ?? "") === desired.description;
329 return displayOk && descriptionOk
330 ? Effect.succeed(value)
331 : Effect.fail(new MetricDescriptorNotResolved({ resourceName: name }));
332 }),
333 // Descriptor writes take up to a minute to become readable.
334 Effect.retry({
335 times: 30,
336 schedule: Schedule.spaced("2 seconds"),
337 while: (error) => error._tag === "GCP.Monitoring.MetricDescriptorNotResolved",
338 }),
339 );
340
341 const listCustom = (project: string) =>
342 monitoring.listProjectsMetricDescriptors
343 .pages({
344 name: parentOf(project),
345 pageSize: 1000,
346 filter: `metric.type = starts_with("${CUSTOM_PREFIX}")`,
347 })
348 .pipe(
349 Stream.flatMap((page) => Stream.fromIterable(page.metricDescriptors ?? [])),
350 Stream.runCollect,
351 Effect.map((chunk) => Array.from(chunk)),
352 Effect.catchTag("NotFound", () => Effect.succeed([] as monitoring.MetricDescriptor[])),
353 );
354
355 const listOwned = (project: string) =>
356 Effect.gen(function* () {
357 const descriptors = yield* listCustom(project);
358 return descriptors
359 .filter((descriptor) => hasOwnershipMarker(descriptor.description))
360 .map((descriptor) => toAttrs(descriptor, project));
361 });
362
363 const findOwned = (project: string, id: string) =>
364 Effect.gen(function* () {
365 const descriptors = yield* listCustom(project);
366 for (const descriptor of descriptors) {
367 if (yield* hasAlchemyLabels(id, parseMarker(descriptor.description).labels)) {
368 return descriptor;
369 }
370 }
371 return undefined;
372 });
373
374 const observe = (project: string, id: string, name: string | undefined) =>
375 Effect.gen(function* () {
376 if (name !== undefined) {
377 const existing = yield* getByName(name);
378 if (existing !== undefined) return existing;
379 }
380 return yield* findOwned(project, id);
381 });
382
383 export const MetricDescriptorProvider = () =>
384 Provider.succeed(MetricDescriptor, {
385 stables: ["name", "type", "project"],
386
387 diff: Effect.fn(function* ({ news, olds, output }) {
388 if (!isResolved(news)) return undefined;
389 const previousType = olds?.type ?? output?.type;
390 const typeChanged =
391 news.type !== undefined &&
392 previousType !== undefined &&
393 qualifyType(news.type) !== previousType;
394
395 const previousKind = (olds?.metricKind ?? output?.metricKind)?.toUpperCase();
396 const nextKind = news.metricKind?.toUpperCase();
397 const kindChanged =
398 nextKind !== undefined && previousKind !== undefined && nextKind !== previousKind;
399
400 const previousValue = (olds?.valueType ?? output?.valueType)?.toUpperCase();
401 const nextValue = news.valueType?.toUpperCase();
402 const valueChanged =
403 nextValue !== undefined && previousValue !== undefined && nextValue !== previousValue;
404
405 const removed = labelsRemoved(output?.labels ?? [], news.labels);
406
407 if (!typeChanged && !kindChanged && !valueChanged && !removed) {
408 return undefined;
409 }
410 return {
411 action: "replace" as const,
412 deleteFirst: !typeChanged,
413 };
414 }),
415
416 read: Effect.fn(function* ({ id, output }) {
417 const env = yield* GcpEnvironment.current;
418 const existing = yield* observe(env.project, id, output?.name);
419 if (existing === undefined) return undefined;
420 const attrs = toAttrs(existing, env.project);
421 return (yield* hasAlchemyLabels(id, parseMarker(existing.description).labels))
422 ? attrs
423 : Unowned(attrs);
424 }),
425
426 list: () =>
427 Effect.gen(function* () {
428 const env = yield* GcpEnvironment.current;
429 return yield* listOwned(env.project);
430 }),
431
432 reconcile: Effect.fn(function* ({ id, news, output }) {
433 const env = yield* GcpEnvironment.current;
434 const type = yield* toType(id, news.type, output?.type);
435 const name = resourceName(env.project, type);
436 const ownership = yield* createInternalLabels(id);
437 const desiredDescription = encodeDescription(ownership, news.description);
438 const desiredKind = (news.metricKind ?? DEFAULT_METRIC_KIND).toUpperCase();
439 const desiredValue = (news.valueType ?? DEFAULT_VALUE_TYPE).toUpperCase();
440 const desiredUnit = news.unit ?? DEFAULT_UNIT;
441
442 let current = yield* observe(env.project, id, output?.name ?? name);
443
444 const upsert = () =>
445 monitoring
446 .createProjectsMetricDescriptors({
447 name: parentOf(env.project),
448 body: toBody(type, news, ownership),
449 })
450 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
451
452 if (current === undefined) {
453 current = (yield* upsert()) ?? undefined;
454 }
455
456 if (current === undefined) {
457 return yield* new MetricDescriptorNotResolved({ resourceName: name });
458 }
459
460 const observedLabels = toLabels(current.labels);
461 const needsUpdate =
462 (current.displayName ?? "") !== (news.displayName ?? "") ||
463 (current.description ?? "") !== desiredDescription ||
464 (current.unit ?? DEFAULT_UNIT) !== desiredUnit ||
465 (current.metricKind ?? "").toUpperCase() !== desiredKind ||
466 (current.valueType ?? "").toUpperCase() !== desiredValue ||
467 (news.launchStage !== undefined && (current.launchStage ?? "") !== news.launchStage) ||
468 (news.metadata !== undefined &&
469 !jsonEqual(toMetadata(current.metadata) ?? null, news.metadata)) ||
470 (news.labels !== undefined &&
471 !jsonEqual(canonLabels(observedLabels), canonLabels(news.labels)));
472
473 if (needsUpdate) {
474 current = (yield* upsert()) ?? current;
475 }
476
477 const latest = yield* waitUntilSynced(
478 current.name?.includes(METRIC_DESCRIPTORS) ? current.name : name,
479 {
480 displayName: news.displayName,
481 description: desiredDescription,
482 },
483 );
484 return toAttrs(latest, env.project);
485 }),
486
487 delete: Effect.fn(function* ({ output }) {
488 yield* monitoring
489 .deleteProjectsMetricDescriptors({ name: output.name })
490 .pipe(Effect.catchTag("NotFound", () => Effect.void));
491 }),
492 });