@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, 06:00 UTC

main
ts 347 lines 12.1 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 { listProjectBuckets } from "./operations.ts";
14 import {
15 encodeDescription,
16 hasOwnershipMarker,
17 lastSegment,
18 parseDescription,
19 } from "./ownership.ts";
20
21 const MAX_NAME_LENGTH = 100;
22 const DEFAULT_LOCATION = "global";
23
24 export type BucketsViewProps = {
25 /**
26 * Parent log bucket. Full name
27 * `projects/{project}/locations/{location}/buckets/{bucket}` or the
28 * bucket id (combined with `location`). Immutable — changing it
29 * replaces the view.
30 */
31 bucket: string;
32 /**
33 * View id (the `{view}` segment of
34 * `.../buckets/{bucket}/views/{view}`). If omitted, a unique name is
35 * generated from the stack, stage, and logical id. Limited to 100
36 * characters: letters, digits, underscores, hyphens. Immutable —
37 * changing it replaces the view.
38 */
39 viewId?: string;
40 /**
41 * Bucket location used when `bucket` is a bare id. Immutable — changing
42 * it replaces the view.
43 * @default "global"
44 */
45 location?: string;
46 /**
47 * Filter restricting which log entries in the bucket are visible.
48 * Must be a conjunction of `SOURCE()`, `resource.type`, and
49 * `LOG_ID()` (and their `NOT` negations). Empty shows every entry.
50 */
51 filter?: string;
52 /**
53 * Human-readable description. Log views have no labels field, so
54 * Alchemy ownership is stored in a `[alchemy …]` prefix and stripped
55 * from attributes.
56 */
57 description?: string;
58 };
59
60 export type BucketsView = Resource<
61 "GCP.Logging.BucketsView",
62 BucketsViewProps,
63 {
64 /** Full resource name `projects/{project}/locations/{location}/buckets/{bucket}/views/{viewId}`. */
65 name: string;
66 /** View id (last path segment). */
67 viewId: string;
68 /** Parent log bucket resource name. */
69 bucket: string;
70 /** Bucket id. */
71 bucketId: string;
72 /** Project id. */
73 project: string;
74 /** Location of the parent bucket. */
75 location: string;
76 /** View filter, if set. */
77 filter: string | undefined;
78 /** User description with the Alchemy ownership prefix stripped. */
79 description: string | undefined;
80 /** RFC3339 creation timestamp. */
81 createTime: string | undefined;
82 /** RFC3339 last-update timestamp. */
83 updateTime: string | undefined;
84 },
85 never,
86 Providers
87 >;
88
89 /**
90 * A Cloud Logging view over log entries in a log bucket.
91 *
92 * A bucket may contain at most 30 views. Log views have no labels field,
93 * so Alchemy stamps ownership into the description for `list` / nuke.
94 * `viewId` and the parent bucket are identity — changing either replaces
95 * the view. Filter and description update in place.
96 *
97 * ### Creating a View
98 * **Example:** Generated name over a custom bucket
99 * ```typescript
100 * const bucket = yield* GCP.Logging.LogBucket("AppLogs", {
101 * description: "application logs",
102 * });
103 * const view = yield* GCP.Logging.BucketsView("Stdout", {
104 * bucket: bucket.name,
105 * filter: 'LOG_ID("stdout")',
106 * description: "stdout only",
107 * });
108 * ```
109 *
110 * **Example:** Named view
111 * ```typescript
112 * const view = yield* GCP.Logging.BucketsView("Stdout", {
113 * bucket: bucket.name,
114 * viewId: "stdout",
115 * filter: 'LOG_ID("stdout")',
116 * });
117 * ```
118 *
119 * ### Updating a View
120 * **Example:** Change the filter
121 * ```typescript
122 * const view = yield* GCP.Logging.BucketsView("Stdout", {
123 * bucket: bucket.name,
124 * filter: 'LOG_ID("stderr")',
125 * description: "stderr only",
126 * });
127 * ```
128 *
129 * @resource
130 * @category Logging
131 */
132 export const BucketsView = Resource<BucketsView>("GCP.Logging.BucketsView");
133
134 export class BucketsViewNotResolved extends Data.TaggedError("GCP.Logging.BucketsViewNotResolved")<{
135 resourceName: string;
136 }> {}
137
138 const parseViewName = (name: string) => {
139 const match = name.match(
140 /^projects\/([^/]+)\/locations\/([^/]+)\/buckets\/([^/]+)\/views\/([^/]+)$/,
141 );
142 if (!match) return undefined;
143 return {
144 project: match[1]!,
145 location: match[2]!,
146 bucketId: match[3]!,
147 viewId: match[4]!,
148 };
149 };
150
151 const parseBucket = (bucket: string, project: string, location: string) => {
152 const match = bucket.match(/^(projects\/([^/]+)\/locations\/([^/]+)\/buckets\/([^/]+))$/);
153 if (match) {
154 return {
155 name: match[1]!,
156 project: match[2]!,
157 location: match[3]!,
158 bucketId: match[4]!,
159 };
160 }
161 return {
162 name: `projects/${project}/locations/${location}/buckets/${bucket}`,
163 project,
164 location,
165 bucketId: lastSegment(bucket),
166 };
167 };
168
169 const resourceName = (project: string, location: string, bucketId: string, viewId: string) =>
170 `projects/${project}/locations/${location}/buckets/${bucketId}/views/${viewId}`;
171
172 const viewIdOf = (view: logging.LogView, fallback?: string) => {
173 const parsed = parseViewName(view.name ?? "");
174 return parsed?.viewId ?? fallback ?? lastSegment(view.name ?? "");
175 };
176
177 const toId = (id: string, viewId: string | undefined, existing?: string) =>
178 Effect.gen(function* () {
179 if (viewId !== undefined) return viewId;
180 if (existing !== undefined) return existing;
181 const generated = yield* createPhysicalName({
182 id,
183 maxLength: MAX_NAME_LENGTH,
184 lowercase: true,
185 });
186 return /^[a-z0-9]/.test(generated) ? generated : `v${generated}`.slice(0, MAX_NAME_LENGTH);
187 });
188
189 const toAttrs = (view: logging.LogView, project: string, location: string, bucketId: string) => {
190 const viewId = viewIdOf(view);
191 const parsed = parseDescription(view.description);
192 const parsedName = parseViewName(view.name ?? "");
193 const resolvedLocation = parsedName?.location ?? location;
194 const resolvedBucketId = parsedName?.bucketId ?? bucketId;
195 const resolvedProject = parsedName?.project ?? project;
196 return {
197 name:
198 view.name ??
199 (viewId ? resourceName(resolvedProject, resolvedLocation, resolvedBucketId, viewId) : ""),
200 viewId,
201 bucket: `projects/${resolvedProject}/locations/${resolvedLocation}/buckets/${resolvedBucketId}`,
202 bucketId: resolvedBucketId,
203 project: resolvedProject,
204 location: resolvedLocation,
205 filter: view.filter,
206 description: parsed.description,
207 createTime: view.createTime,
208 updateTime: view.updateTime,
209 };
210 };
211
212 const getByName = (name: string) =>
213 logging
214 .getProjectsLocationsBucketsViews({ name })
215 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
216
217 export const BucketsViewProvider = () =>
218 Provider.succeed(BucketsView, {
219 stables: ["name", "viewId", "bucket", "bucketId", "project", "location"],
220
221 diff: Effect.fn(function* ({ news, olds, output }) {
222 if (!isResolved(news)) return undefined;
223 const previousId = olds?.viewId ?? output?.viewId;
224 const idChanged =
225 previousId !== undefined && news.viewId !== undefined && news.viewId !== previousId;
226 const previousBucket = olds?.bucket ?? output?.bucket;
227 const bucketChanged =
228 previousBucket !== undefined &&
229 news.bucket.includes("/buckets/") &&
230 news.bucket !== previousBucket;
231 if (!idChanged && !bucketChanged) return undefined;
232 return { action: "replace" as const, deleteFirst: false };
233 }),
234
235 read: Effect.fn(function* ({ id, olds, output }) {
236 const env = yield* GcpEnvironment.current;
237 const parentRef = olds?.bucket ?? output?.bucket;
238 // A recovery read of an interrupted create gets persisted props whose
239 // unresolved parent reference was stripped; without the parent there
240 // is no name to look up, so report nothing found rather than calling
241 // the API with an empty path segment.
242 if (output?.name === undefined && (typeof parentRef !== "string" || parentRef.length === 0)) {
243 return undefined;
244 }
245 const location = olds?.location ?? output?.location ?? DEFAULT_LOCATION;
246 const parent = parseBucket(olds?.bucket ?? output?.bucket ?? "", env.project, location);
247 const viewId = yield* toId(id, olds?.viewId, output?.viewId);
248 const name =
249 output?.name ?? resourceName(parent.project, parent.location, parent.bucketId, viewId);
250 const existing = yield* getByName(name);
251 if (existing === undefined) return undefined;
252 const attrs = toAttrs(existing, parent.project, parent.location, parent.bucketId);
253 const { labels } = parseDescription(existing.description);
254 return (yield* hasAlchemyLabels(id, labels)) ? attrs : Unowned(attrs);
255 }),
256
257 list: () =>
258 Effect.gen(function* () {
259 const env = yield* GcpEnvironment.current;
260 const buckets = yield* listProjectBuckets();
261 const pages = yield* Effect.forEach(
262 buckets,
263 (bucket) =>
264 logging.listProjectsLocationsBucketsViews
265 .pages({
266 parent: bucket.name!,
267 pageSize: 1000,
268 })
269 .pipe(
270 Stream.flatMap((page) => Stream.fromIterable(page.views ?? [])),
271 Stream.filter((view) => hasOwnershipMarker(view.description)),
272 Stream.map((view) => {
273 const parsed = parseViewName(view.name ?? "");
274 return toAttrs(
275 view,
276 parsed?.project ?? env.project,
277 parsed?.location ?? DEFAULT_LOCATION,
278 parsed?.bucketId ?? lastSegment(bucket.name ?? ""),
279 );
280 }),
281 Stream.runCollect,
282 Effect.map((chunk) => Array.from(chunk)),
283 Effect.catchTag("NotFound", () =>
284 Effect.succeed([] as ReturnType<typeof toAttrs>[]),
285 ),
286 ),
287 { concurrency: 4 },
288 );
289 return pages.flat();
290 }),
291
292 reconcile: Effect.fn(function* ({ id, news, output }) {
293 const env = yield* GcpEnvironment.current;
294 const location = news.location ?? output?.location ?? DEFAULT_LOCATION;
295 const parent = parseBucket(news.bucket, env.project, location);
296 const viewId = yield* toId(id, news.viewId, output?.viewId);
297 const name = resourceName(parent.project, parent.location, parent.bucketId, viewId);
298 const ownership = yield* createInternalLabels(id);
299 const desiredDescription = encodeDescription(ownership, news.description);
300
301 let current = yield* getByName(output?.name ?? name);
302
303 if (current === undefined) {
304 const created = yield* logging
305 .createProjectsLocationsBucketsViews({
306 parent: parent.name,
307 viewId,
308 body: {
309 filter: news.filter,
310 description: desiredDescription,
311 },
312 })
313 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
314 current = created ?? undefined;
315 }
316
317 if (current === undefined) {
318 return yield* new BucketsViewNotResolved({ resourceName: name });
319 }
320
321 const filterChanged = (current.filter ?? "") !== (news.filter ?? "");
322 const descriptionChanged = (current.description ?? "") !== desiredDescription;
323 const updateMask = [
324 filterChanged ? "filter" : undefined,
325 descriptionChanged ? "description" : undefined,
326 ].filter((field): field is string => field !== undefined);
327
328 if (updateMask.length > 0) {
329 current = yield* logging.patchProjectsLocationsBucketsViews({
330 name: current.name ?? name,
331 updateMask: updateMask.join(","),
332 body: {
333 filter: news.filter ?? "",
334 description: desiredDescription,
335 },
336 });
337 }
338
339 return toAttrs(current, parent.project, parent.location, parent.bucketId);
340 }),
341
342 delete: Effect.fn(function* ({ output }) {
343 yield* logging
344 .deleteProjectsLocationsBucketsViews({ name: output.name })
345 .pipe(Effect.catchTag("NotFound", () => Effect.void));
346 }),
347 });