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

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