@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 325 lines 11.7 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 type { Providers } from "../Providers.ts";
11 import {
12 DEFAULT_LOCATION,
13 createOwnership,
14 encodeDescription,
15 hasOwnershipMarker,
16 jsonEqual,
17 lastSegment,
18 locationParent,
19 ownedBy,
20 parseDescription,
21 parseLoggingName,
22 scopeParent,
23 toPhysicalId,
24 } from "./internal.ts";
25
26 export type FolderSavedQueryLoggingQuery = {
27 /**
28 * Advanced Logging Query Language filter. Max 20,000 characters.
29 */
30 filter?: string;
31 };
32
33 export type FolderSavedQueryOpsAnalyticsQuery = {
34 /**
35 * Log Analytics SQL query text.
36 */
37 sqlQueryText?: string;
38 };
39
40 export type FolderSavedQueryProps = {
41 /**
42 * Folder id (`folders/{folder}` or the numeric id). When omitted, the
43 * stack project is used. Immutable — changing it replaces the query.
44 */
45 folderId?: string;
46 /**
47 * Location of the saved query. Immutable — changing it replaces the
48 * query.
49 * @default "global"
50 */
51 location?: string;
52 /**
53 * Saved query id (the `{query}` segment of
54 * `{parent}/locations/{location}/savedQueries/{query}`). If omitted, a
55 * unique name is generated. Limited to 100 characters: letters, digits,
56 * underscores, hyphens, periods; first character must be alphanumeric.
57 * Immutable — changing it replaces the query.
58 */
59 savedQueryId?: string;
60 /**
61 * User-specified title shown in Logs Explorer.
62 */
63 displayName: string;
64 /**
65 * Visibility. `PRIVATE` queries are owned by the creating user.
66 * `SHARED` queries are owned by the parent resource.
67 * @default "PRIVATE"
68 */
69 visibility?: "PRIVATE" | "SHARED";
70 /**
71 * Human-readable description. Saved queries have no labels field, so
72 * Alchemy ownership is stored in a `[alchemy …]` prefix and stripped
73 * from attributes.
74 */
75 description?: string;
76 /**
77 * Logs Explorer query. At least one of `loggingQuery` or
78 * `opsAnalyticsQuery` is required.
79 */
80 loggingQuery?: FolderSavedQueryLoggingQuery;
81 /**
82 * Log Analytics SQL query. At least one of `loggingQuery` or
83 * `opsAnalyticsQuery` is required.
84 */
85 opsAnalyticsQuery?: FolderSavedQueryOpsAnalyticsQuery;
86 };
87
88 export type FolderSavedQuery = Resource<
89 "GCP.Logging.FolderSavedQuery",
90 FolderSavedQueryProps,
91 {
92 /** Full resource name `{parent}/locations/{location}/savedQueries/{savedQueryId}`. */
93 name: string;
94 /** Saved query id (last path segment). */
95 savedQueryId: string;
96 /** Parent resource (`folders/{folder}` or `projects/{project}`). */
97 parent: string;
98 /** Folder id when the parent is a folder. */
99 folderId: string | undefined;
100 /** Location of the saved query. */
101 location: string;
102 /** Display title. */
103 displayName: string;
104 /** Visibility (`PRIVATE` or `SHARED`). */
105 visibility: string;
106 /** User description with the Alchemy ownership prefix stripped. */
107 description: string | undefined;
108 /** Logs Explorer query, if set. */
109 loggingQuery: FolderSavedQueryLoggingQuery | undefined;
110 /** Log Analytics query, if set. */
111 opsAnalyticsQuery: FolderSavedQueryOpsAnalyticsQuery | undefined;
112 /** RFC3339 creation timestamp. */
113 createTime: string | undefined;
114 /** RFC3339 last-update timestamp. */
115 updateTime: string | undefined;
116 },
117 never,
118 Providers
119 >;
120
121 /**
122 * A Cloud Logging saved query owned by a folder (or the stack project).
123 *
124 * Saved queries have no labels field, so Alchemy stamps ownership into
125 * the description for `list` / nuke. `folderId`, `savedQueryId`, and
126 * `location` are identity — changing any of them replaces the query.
127 * Display name, visibility, description, and query text update in place.
128 *
129 * ### Creating a Folder Saved Query
130 * **Example:** Shared error query
131 * ```typescript
132 * const query = yield* GCP.Logging.FolderSavedQuery("Errors", {
133 * displayName: "application errors",
134 * visibility: "SHARED",
135 * loggingQuery: { filter: "severity>=ERROR" },
136 * description: "error log entries",
137 * });
138 * ```
139 *
140 * ### Updating a Folder Saved Query
141 * **Example:** Change the filter
142 * ```typescript
143 * const query = yield* GCP.Logging.FolderSavedQuery("Errors", {
144 * displayName: "warnings and errors",
145 * visibility: "SHARED",
146 * loggingQuery: { filter: "severity>=WARNING" },
147 * description: "warning and error log entries",
148 * });
149 * ```
150 *
151 * @resource
152 * @category Logging
153 */
154 export const FolderSavedQuery = Resource<FolderSavedQuery>("GCP.Logging.FolderSavedQuery");
155
156 export class FolderSavedQueryNotResolved extends Data.TaggedError(
157 "GCP.Logging.FolderSavedQueryNotResolved",
158 )<{
159 resourceName: string;
160 }> {}
161
162 const resourceName = (parent: string, location: string, savedQueryId: string) =>
163 `${locationParent(parent, location)}/savedQueries/${savedQueryId}`;
164
165 const folderIdOf = (parent: string) =>
166 parent.startsWith("folders/") ? lastSegment(parent) : undefined;
167
168 const toAttrs = (query: logging.SavedQuery, parent: string, location: string) => {
169 const parsed = parseLoggingName(query.name ?? "");
170 const savedQueryId = parsed.savedQueryId ?? lastSegment(query.name ?? "");
171 const resolvedParent = parsed.parent || parent;
172 const resolvedLocation = parsed.location ?? location;
173 const description = parseDescription(query.description);
174 return {
175 name:
176 query.name ??
177 (savedQueryId ? resourceName(resolvedParent, resolvedLocation, savedQueryId) : ""),
178 savedQueryId,
179 parent: resolvedParent,
180 folderId: folderIdOf(resolvedParent),
181 location: resolvedLocation,
182 displayName: query.displayName ?? "",
183 visibility: query.visibility ?? "PRIVATE",
184 description: description.description,
185 loggingQuery: query.loggingQuery ? { filter: query.loggingQuery.filter } : undefined,
186 opsAnalyticsQuery: query.opsAnalyticsQuery
187 ? { sqlQueryText: query.opsAnalyticsQuery.sqlQueryText }
188 : undefined,
189 createTime: query.createTime,
190 updateTime: query.updateTime,
191 };
192 };
193
194 const getByName = (name: string) =>
195 logging
196 .getFoldersLocationsSavedQueries({ name })
197 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
198
199 const toBody = (news: FolderSavedQueryProps, description: string): logging.SavedQuery => ({
200 displayName: news.displayName,
201 visibility: news.visibility ?? "PRIVATE",
202 description,
203 loggingQuery: news.loggingQuery,
204 opsAnalyticsQuery: news.opsAnalyticsQuery,
205 });
206
207 export const FolderSavedQueryProvider = () =>
208 Provider.succeed(FolderSavedQuery, {
209 stables: ["name", "savedQueryId", "parent", "folderId", "location", "createTime"],
210
211 diff: Effect.fn(function* ({ news, olds, output }) {
212 if (!isResolved(news)) return undefined;
213 const previousId = olds?.savedQueryId ?? output?.savedQueryId;
214 const idChanged =
215 previousId !== undefined &&
216 news.savedQueryId !== undefined &&
217 news.savedQueryId !== previousId;
218 const previousLocation = olds?.location ?? output?.location;
219 const locationChanged =
220 previousLocation !== undefined &&
221 news.location !== undefined &&
222 news.location !== previousLocation;
223 const previousFolder = olds?.folderId ?? output?.folderId;
224 const folderChanged = news.folderId !== undefined && news.folderId !== previousFolder;
225 if (!idChanged && !locationChanged && !folderChanged) return undefined;
226 return { action: "replace" as const, deleteFirst: false };
227 }),
228
229 read: Effect.fn(function* ({ id, olds, output }) {
230 const env = yield* GcpEnvironment.current;
231 const parent = scopeParent(env.project, olds?.folderId ?? output?.folderId);
232 const location = olds?.location ?? output?.location ?? DEFAULT_LOCATION;
233 const savedQueryId = yield* toPhysicalId(id, olds?.savedQueryId, output?.savedQueryId, "q");
234 const name = output?.name ?? resourceName(parent, location, savedQueryId);
235 const existing = yield* getByName(name);
236 if (existing === undefined) return undefined;
237 const attrs = toAttrs(existing, parent, location);
238 const { labels } = parseDescription(existing.description);
239 return (yield* ownedBy(id, labels)) ? attrs : Unowned(attrs);
240 }),
241
242 list: () =>
243 Effect.gen(function* () {
244 const env = yield* GcpEnvironment.current;
245 return yield* logging.listFoldersLocationsSavedQueries
246 .pages({
247 parent: `projects/${env.project}/locations/-`,
248 pageSize: 1000,
249 })
250 .pipe(
251 Stream.flatMap((page) => Stream.fromIterable(page.savedQueries ?? [])),
252 Stream.filter((query) => hasOwnershipMarker(query.description)),
253 Stream.map((query) =>
254 toAttrs(
255 query,
256 parseLoggingName(query.name ?? "").parent || `projects/${env.project}`,
257 parseLoggingName(query.name ?? "").location ?? DEFAULT_LOCATION,
258 ),
259 ),
260 Stream.runCollect,
261 Effect.map((chunk) => Array.from(chunk)),
262 );
263 }),
264
265 reconcile: Effect.fn(function* ({ id, news, output }) {
266 const env = yield* GcpEnvironment.current;
267 const parent = scopeParent(env.project, news.folderId ?? output?.folderId);
268 const location = news.location ?? output?.location ?? DEFAULT_LOCATION;
269 const savedQueryId = yield* toPhysicalId(id, news.savedQueryId, output?.savedQueryId, "q");
270 const name = resourceName(parent, location, savedQueryId);
271 const ownership = yield* createOwnership(id);
272 const desiredDescription = encodeDescription(ownership, news.description);
273 const desiredVisibility = news.visibility ?? "PRIVATE";
274
275 let current = yield* getByName(output?.name ?? name);
276
277 if (current === undefined) {
278 const created = yield* logging
279 .createFoldersLocationsSavedQueries({
280 parent: locationParent(parent, location),
281 savedQueryId,
282 body: toBody(news, desiredDescription),
283 })
284 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
285 current = created ?? undefined;
286 }
287
288 if (current === undefined) {
289 return yield* new FolderSavedQueryNotResolved({ resourceName: name });
290 }
291
292 const displayNameChanged = (current.displayName ?? "") !== news.displayName;
293 const descriptionChanged = (current.description ?? "") !== desiredDescription;
294 const visibilityChanged = (current.visibility ?? "PRIVATE") !== desiredVisibility;
295 const loggingChanged = !jsonEqual(current.loggingQuery ?? null, news.loggingQuery ?? null);
296 const analyticsChanged = !jsonEqual(
297 current.opsAnalyticsQuery?.sqlQueryText ?? null,
298 news.opsAnalyticsQuery?.sqlQueryText ?? null,
299 );
300
301 const updateMask = [
302 displayNameChanged ? "displayName" : undefined,
303 descriptionChanged ? "description" : undefined,
304 visibilityChanged ? "visibility" : undefined,
305 loggingChanged ? "loggingQuery" : undefined,
306 analyticsChanged ? "opsAnalyticsQuery" : undefined,
307 ].filter((field): field is string => field !== undefined);
308
309 if (updateMask.length > 0) {
310 current = yield* logging.patchFoldersLocationsSavedQueries({
311 name: current.name ?? name,
312 updateMask: updateMask.join(","),
313 body: toBody(news, desiredDescription),
314 });
315 }
316
317 return toAttrs(current, parent, location);
318 }),
319
320 delete: Effect.fn(function* ({ output }) {
321 yield* logging
322 .deleteFoldersLocationsSavedQueries({ name: output.name })
323 .pipe(Effect.catchTag("NotFound", () => Effect.void));
324 }),
325 });