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