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

main
ts 412 lines 14.3 KB
Raw
1 import * as logging from "@distilled.cloud/gcp/logging_v2";
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 Stream from "effect/Stream";
10 import { GcpEnvironment } from "../Environment.ts";
11 import { createInternalLabels, hasAlchemyLabels } from "../Labels.ts";
12 import type { Providers } from "../Providers.ts";
13 import {
14 encodeDescription,
15 hasOwnershipMarker,
16 jsonEqual,
17 lastSegment,
18 parseDescription,
19 } from "./ownership.ts";
20
21 const MAX_NAME_LENGTH = 100;
22 const DEFAULT_LOCATION = "global";
23 const DEFAULT_VISIBILITY = "PRIVATE" as const;
24
25 export type SavedQuerySummaryField = {
26 /**
27 * LogEntry field to include in the Logs Explorer summary line
28 * (e.g. `resource.type`).
29 */
30 field: string;
31 };
32
33 export type SavedQueryLoggingQuery = {
34 /**
35 * Logging Query Language filter. Maximum 20000 characters.
36 */
37 filter: string;
38 /**
39 * Summary-field start character offset.
40 */
41 summaryFieldStart?: number;
42 /**
43 * Summary-field end character offset.
44 */
45 summaryFieldEnd?: number;
46 /**
47 * Fields shown in the Logs Explorer summary line.
48 */
49 summaryFields?: SavedQuerySummaryField[];
50 };
51
52 export type SavedQueryOpsAnalyticsQuery = {
53 /**
54 * Log Analytics SQL query text.
55 */
56 sqlQueryText: string;
57 };
58
59 export type SavedQueryProps = {
60 /**
61 * Saved query id (the `{query}` segment of
62 * `projects/{project}/locations/{location}/savedQueries/{query}`). If
63 * omitted, a unique name is generated from the stack, stage, and
64 * logical id. Limited to 100 characters: letters, digits, underscores,
65 * hyphens, periods; first character must be alphanumeric. Immutable —
66 * changing it replaces the saved query.
67 */
68 savedQueryId?: string;
69 /**
70 * Location that stores the saved query. Immutable after create —
71 * changing it replaces the query.
72 * @default "global"
73 */
74 location?: string;
75 /**
76 * Title shown in Logs Explorer.
77 * @default the generated `savedQueryId`
78 */
79 displayName?: string;
80 /**
81 * Who can see the query. `PRIVATE` is owned by the creating identity.
82 * @default "PRIVATE"
83 */
84 visibility?: "PRIVATE" | "SHARED";
85 /**
86 * Logs Explorer / Logging API query. At least one of `loggingQuery`
87 * or `opsAnalyticsQuery` is required.
88 */
89 loggingQuery?: SavedQueryLoggingQuery;
90 /**
91 * Log Analytics SQL query. At least one of `loggingQuery` or
92 * `opsAnalyticsQuery` is required.
93 */
94 opsAnalyticsQuery?: SavedQueryOpsAnalyticsQuery;
95 /**
96 * Human-readable description. Saved queries have no labels field, so
97 * Alchemy ownership is stored in a `[alchemy …]` prefix and stripped
98 * from attributes.
99 */
100 description?: string;
101 };
102
103 export type SavedQuery = Resource<
104 "GCP.Logging.SavedQuery",
105 SavedQueryProps,
106 {
107 /** Full resource name `projects/{project}/locations/{location}/savedQueries/{savedQueryId}`. */
108 name: string;
109 /** Saved query id (last path segment). */
110 savedQueryId: string;
111 /** Project id. */
112 project: string;
113 /** Location that stores the query. */
114 location: string;
115 /** Title shown in Logs Explorer. */
116 displayName: string | undefined;
117 /** Visibility (`PRIVATE` or `SHARED`). */
118 visibility: string | undefined;
119 /** Logs Explorer query, if set. */
120 loggingQuery: SavedQueryLoggingQuery | undefined;
121 /** Log Analytics query, if set. */
122 opsAnalyticsQuery: SavedQueryOpsAnalyticsQuery | undefined;
123 /** User description with the Alchemy ownership prefix stripped. */
124 description: string | undefined;
125 /** RFC3339 creation timestamp. */
126 createTime: string | undefined;
127 /** RFC3339 last-update timestamp. */
128 updateTime: string | undefined;
129 },
130 never,
131 Providers
132 >;
133
134 /**
135 * A Cloud Logging saved query for Logs Explorer or Log Analytics.
136 *
137 * Saved queries have no labels field, so Alchemy stamps ownership into
138 * the description for `list` / nuke. `savedQueryId` and `location` are
139 * identity — changing either replaces the query. Display name, visibility,
140 * description, and query body update in place.
141 *
142 * ### Creating a Saved Query
143 * **Example:** Generated name, private Logs Explorer query
144 * ```typescript
145 * const query = yield* GCP.Logging.SavedQuery("Errors", {
146 * displayName: "application errors",
147 * loggingQuery: { filter: "severity>=ERROR" },
148 * });
149 * ```
150 *
151 * **Example:** Named shared query
152 * ```typescript
153 * const query = yield* GCP.Logging.SavedQuery("Errors", {
154 * savedQueryId: "app-errors",
155 * displayName: "application errors",
156 * visibility: "SHARED",
157 * loggingQuery: { filter: "severity>=ERROR" },
158 * });
159 * ```
160 *
161 * ### Updating a Saved Query
162 * **Example:** Change the filter
163 * ```typescript
164 * const query = yield* GCP.Logging.SavedQuery("Errors", {
165 * displayName: "warnings and errors",
166 * loggingQuery: { filter: "severity>=WARNING" },
167 * });
168 * ```
169 *
170 * @resource
171 * @category Logging
172 */
173 export const SavedQuery = Resource<SavedQuery>("GCP.Logging.SavedQuery");
174
175 export class SavedQueryNotResolved extends Data.TaggedError("GCP.Logging.SavedQueryNotResolved")<{
176 resourceName: string;
177 }> {}
178
179 const parseQueryName = (name: string) => {
180 const match = name.match(/^projects\/([^/]+)\/locations\/([^/]+)\/savedQueries\/([^/]+)$/);
181 if (!match) return undefined;
182 return {
183 project: match[1]!,
184 location: match[2]!,
185 savedQueryId: match[3]!,
186 };
187 };
188
189 const resourceName = (project: string, location: string, savedQueryId: string) =>
190 `projects/${project}/locations/${location}/savedQueries/${savedQueryId}`;
191
192 const savedQueryIdOf = (query: logging.SavedQuery, fallback?: string) => {
193 const parsed = parseQueryName(query.name ?? "");
194 return parsed?.savedQueryId ?? fallback ?? lastSegment(query.name ?? "");
195 };
196
197 const toId = (id: string, savedQueryId: string | undefined, existing?: string) =>
198 Effect.gen(function* () {
199 if (savedQueryId !== undefined) return savedQueryId;
200 if (existing !== undefined) return existing;
201 const generated = yield* createPhysicalName({
202 id,
203 maxLength: MAX_NAME_LENGTH,
204 lowercase: true,
205 });
206 return /^[a-z0-9]/.test(generated) ? generated : `q${generated}`.slice(0, MAX_NAME_LENGTH);
207 });
208
209 const loggingQueryOf = (
210 query: logging.LoggingQuery | undefined,
211 ): SavedQueryLoggingQuery | undefined => {
212 if (query === undefined || query.filter === undefined) return undefined;
213 const summaryFields = query.summaryFields
214 ?.filter((field) => field.field !== undefined)
215 .map((field) => ({ field: field.field! }));
216 return {
217 filter: query.filter,
218 summaryFieldStart: query.summaryFieldStart,
219 summaryFieldEnd: query.summaryFieldEnd,
220 summaryFields:
221 summaryFields !== undefined && summaryFields.length > 0 ? summaryFields : undefined,
222 };
223 };
224
225 const opsAnalyticsQueryOf = (
226 query: logging.OpsAnalyticsQuery | undefined,
227 ): SavedQueryOpsAnalyticsQuery | undefined => {
228 if (query?.sqlQueryText === undefined) return undefined;
229 return { sqlQueryText: query.sqlQueryText };
230 };
231
232 const toLoggingQueryBody = (
233 query: SavedQueryLoggingQuery | undefined,
234 ): logging.LoggingQuery | undefined => {
235 if (query === undefined) return undefined;
236 return {
237 filter: query.filter,
238 summaryFieldStart: query.summaryFieldStart,
239 summaryFieldEnd: query.summaryFieldEnd,
240 summaryFields: query.summaryFields?.map((field) => ({
241 field: field.field,
242 })),
243 };
244 };
245
246 const toOpsAnalyticsQueryBody = (
247 query: SavedQueryOpsAnalyticsQuery | undefined,
248 ): logging.OpsAnalyticsQuery | undefined => {
249 if (query === undefined) return undefined;
250 return { sqlQueryText: query.sqlQueryText };
251 };
252
253 const toAttrs = (query: logging.SavedQuery, project: string, location: string) => {
254 const savedQueryId = savedQueryIdOf(query);
255 const parsed = parseDescription(query.description);
256 const parsedName = parseQueryName(query.name ?? "");
257 const resolvedLocation = parsedName?.location ?? location;
258 const resolvedProject = parsedName?.project ?? project;
259 return {
260 name:
261 query.name ??
262 (savedQueryId ? resourceName(resolvedProject, resolvedLocation, savedQueryId) : ""),
263 savedQueryId,
264 project: resolvedProject,
265 location: resolvedLocation,
266 displayName: query.displayName,
267 visibility: query.visibility,
268 loggingQuery: loggingQueryOf(query.loggingQuery),
269 opsAnalyticsQuery: opsAnalyticsQueryOf(query.opsAnalyticsQuery),
270 description: parsed.description,
271 createTime: query.createTime,
272 updateTime: query.updateTime,
273 };
274 };
275
276 const getByName = (name: string) =>
277 logging
278 .getProjectsLocationsSavedQueries({ name })
279 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
280
281 export const SavedQueryProvider = () =>
282 Provider.succeed(SavedQuery, {
283 stables: ["name", "savedQueryId", "project", "location", "createTime"],
284
285 diff: Effect.fn(function* ({ news, olds, output }) {
286 if (!isResolved(news)) return undefined;
287 const previousId = olds?.savedQueryId ?? output?.savedQueryId;
288 const idChanged =
289 previousId !== undefined &&
290 news.savedQueryId !== undefined &&
291 news.savedQueryId !== previousId;
292 const previousLocation = olds?.location ?? output?.location;
293 const locationChanged =
294 previousLocation !== undefined &&
295 news.location !== undefined &&
296 news.location !== previousLocation;
297 if (!idChanged && !locationChanged) return undefined;
298 return { action: "replace" as const, deleteFirst: false };
299 }),
300
301 read: Effect.fn(function* ({ id, olds, output }) {
302 const env = yield* GcpEnvironment.current;
303 const location = olds?.location ?? output?.location ?? DEFAULT_LOCATION;
304 const savedQueryId = yield* toId(id, olds?.savedQueryId, output?.savedQueryId);
305 const name = output?.name ?? resourceName(env.project, location, savedQueryId);
306 const existing = yield* getByName(name);
307 if (existing === undefined) return undefined;
308 const attrs = toAttrs(existing, env.project, location);
309 const { labels } = parseDescription(existing.description);
310 return (yield* hasAlchemyLabels(id, labels)) ? attrs : Unowned(attrs);
311 }),
312
313 list: () =>
314 Effect.gen(function* () {
315 const env = yield* GcpEnvironment.current;
316 return yield* logging.listProjectsLocationsSavedQueries
317 .pages({
318 parent: `projects/${env.project}/locations/-`,
319 pageSize: 1000,
320 })
321 .pipe(
322 Stream.flatMap((page) => Stream.fromIterable(page.savedQueries ?? [])),
323 Stream.filter((query) => hasOwnershipMarker(query.description)),
324 Stream.map((query) => {
325 const parsed = parseQueryName(query.name ?? "");
326 return toAttrs(
327 query,
328 parsed?.project ?? env.project,
329 parsed?.location ?? DEFAULT_LOCATION,
330 );
331 }),
332 Stream.runCollect,
333 Effect.map((chunk) => Array.from(chunk)),
334 );
335 }),
336
337 reconcile: Effect.fn(function* ({ id, news, output }) {
338 const env = yield* GcpEnvironment.current;
339 const location = news.location ?? output?.location ?? DEFAULT_LOCATION;
340 const savedQueryId = yield* toId(id, news.savedQueryId, output?.savedQueryId);
341 const name = resourceName(env.project, location, savedQueryId);
342 const ownership = yield* createInternalLabels(id);
343 const desiredDescription = encodeDescription(ownership, news.description);
344 const desiredDisplayName = news.displayName ?? savedQueryId;
345 const desiredVisibility = news.visibility ?? DEFAULT_VISIBILITY;
346 const desiredLogging = toLoggingQueryBody(news.loggingQuery);
347 const desiredOps = toOpsAnalyticsQueryBody(news.opsAnalyticsQuery);
348
349 let current = yield* getByName(output?.name ?? name);
350
351 if (current === undefined) {
352 const created = yield* logging
353 .createProjectsLocationsSavedQueries({
354 parent: `projects/${env.project}/locations/${location}`,
355 savedQueryId,
356 body: {
357 displayName: desiredDisplayName,
358 visibility: desiredVisibility,
359 description: desiredDescription,
360 loggingQuery: desiredLogging,
361 opsAnalyticsQuery: desiredOps,
362 },
363 })
364 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
365 current = created ?? undefined;
366 }
367
368 if (current === undefined) {
369 return yield* new SavedQueryNotResolved({ resourceName: name });
370 }
371
372 const displayNameChanged = (current.displayName ?? "") !== desiredDisplayName;
373 const descriptionChanged = (current.description ?? "") !== desiredDescription;
374 const visibilityChanged = (current.visibility ?? DEFAULT_VISIBILITY) !== desiredVisibility;
375 const loggingChanged =
376 news.loggingQuery !== undefined &&
377 !jsonEqual(loggingQueryOf(current.loggingQuery), news.loggingQuery);
378 const opsChanged =
379 news.opsAnalyticsQuery !== undefined &&
380 !jsonEqual(opsAnalyticsQueryOf(current.opsAnalyticsQuery), news.opsAnalyticsQuery);
381
382 const updateMask = [
383 displayNameChanged ? "displayName" : undefined,
384 descriptionChanged ? "description" : undefined,
385 visibilityChanged ? "visibility" : undefined,
386 loggingChanged ? "loggingQuery" : undefined,
387 opsChanged ? "opsAnalyticsQuery" : undefined,
388 ].filter((field): field is string => field !== undefined);
389
390 if (updateMask.length > 0) {
391 const body: logging.SavedQuery = {};
392 if (displayNameChanged) body.displayName = desiredDisplayName;
393 if (descriptionChanged) body.description = desiredDescription;
394 if (visibilityChanged) body.visibility = desiredVisibility;
395 if (loggingChanged) body.loggingQuery = desiredLogging;
396 if (opsChanged) body.opsAnalyticsQuery = desiredOps;
397 current = yield* logging.patchProjectsLocationsSavedQueries({
398 name: current.name ?? name,
399 updateMask: updateMask.join(","),
400 body,
401 });
402 }
403
404 return toAttrs(current, env.project, location);
405 }),
406
407 delete: Effect.fn(function* ({ output }) {
408 yield* logging
409 .deleteProjectsLocationsSavedQueries({ name: output.name })
410 .pipe(Effect.catchTag("NotFound", () => Effect.void));
411 }),
412 });