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

main
ts 369 lines 12.8 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_BUCKET_ID,
14 DEFAULT_LOCATION,
15 encodeDescription,
16 hasOwnershipMarker,
17 lastSegment,
18 organizationIdOf,
19 parseDescription,
20 resolveOrganization,
21 toPhysicalId,
22 tryResolveOrganization,
23 } from "./internal.ts";
24
25 export type OrganizationBucketsViewProps = {
26 /**
27 * View id (the last segment of the view resource name). If omitted, a
28 * unique name is generated from the stack, stage, and logical id.
29 * Limited to 100 characters: letters, digits, underscores, hyphens;
30 * first character must be alphanumeric. Immutable — changing it
31 * replaces the view.
32 */
33 viewId?: string;
34 /**
35 * Parent organization (`organizations/{organization}` or the numeric
36 * id). Defaults to the project ancestor organization. Immutable —
37 * changing it replaces the view.
38 */
39 organization?: string;
40 /**
41 * Parent log bucket resource name
42 * (`organizations/{organization}/locations/{location}/buckets/{bucket}`).
43 * If omitted, Alchemy uses the organization `_Default` bucket.
44 * Immutable — changing it replaces the view.
45 */
46 bucket?: string;
47 /**
48 * Bucket id when `bucket` is omitted.
49 * @default "_Default"
50 */
51 bucketId?: string;
52 /**
53 * Location of the parent bucket when `bucket` is omitted.
54 * @default "global"
55 */
56 location?: string;
57 /**
58 * Filter restricting which log entries in the bucket are visible.
59 * Must be a conjunction of `SOURCE()`, `resource.type`, and `LOG_ID()`.
60 */
61 filter?: string;
62 /**
63 * Human-readable description. Log views have no labels field, so
64 * Alchemy ownership is stored in a `[alchemy …]` prefix and stripped
65 * from attributes.
66 */
67 description?: string;
68 };
69
70 export type OrganizationBucketsView = Resource<
71 "GCP.Logging.OrganizationBucketsView",
72 OrganizationBucketsViewProps,
73 {
74 /** Full resource name `organizations/{organization}/locations/{location}/buckets/{bucket}/views/{view}`. */
75 name: string;
76 /** View id (last path segment). */
77 viewId: string;
78 /** Parent bucket resource name. */
79 bucket: string;
80 /** Bucket id. */
81 bucketId: string;
82 /** Organization resource name. */
83 organization: string;
84 /** Organization id. */
85 organizationId: string;
86 /** Project id of the deploying stack. */
87 project: string;
88 /** Location of the parent bucket. */
89 location: string;
90 /** View filter. */
91 filter: string | undefined;
92 /** User description with the Alchemy ownership prefix stripped. */
93 description: string | undefined;
94 /** RFC3339 creation timestamp. */
95 createTime: string | undefined;
96 /** RFC3339 last-update timestamp. */
97 updateTime: string | undefined;
98 },
99 never,
100 Providers
101 >;
102
103 /**
104 * A Cloud Logging view over log entries in an organization log bucket.
105 *
106 * Views have no labels field, so Alchemy stamps ownership into the
107 * description for `list` / nuke. `viewId`, organization, and the parent
108 * bucket are identity — changing any replaces the view.
109 *
110 * ### Creating an Organization View
111 * **Example:** View on the organization `_Default` bucket
112 * ```typescript
113 * const view = yield* GCP.Logging.OrganizationBucketsView("Errors", {
114 * filter: 'resource.type = "gce_instance"',
115 * description: "compute instance logs",
116 * });
117 * ```
118 *
119 * **Example:** Named view on a custom organization bucket
120 * ```typescript
121 * const view = yield* GCP.Logging.OrganizationBucketsView("Errors", {
122 * viewId: "app-errors",
123 * bucket: bucket.name,
124 * filter: 'resource.type = "gce_instance"',
125 * });
126 * ```
127 *
128 * ### Updating an Organization View
129 * **Example:** Change the filter
130 * ```typescript
131 * const view = yield* GCP.Logging.OrganizationBucketsView("Errors", {
132 * bucket: bucket.name,
133 * filter: 'resource.type = "gce_instance" AND LOG_ID("syslog")',
134 * description: "syslog from compute",
135 * });
136 * ```
137 *
138 * @resource
139 * @category Logging
140 */
141 export const OrganizationBucketsView = Resource<OrganizationBucketsView>(
142 "GCP.Logging.OrganizationBucketsView",
143 );
144
145 export class OrganizationBucketsViewNotResolved extends Data.TaggedError(
146 "GCP.Logging.OrganizationBucketsViewNotResolved",
147 )<{
148 resourceName: string;
149 }> {}
150
151 const parseViewName = (name: string) => {
152 const match = name.match(
153 /^(organizations\/[^/]+)\/locations\/([^/]+)\/buckets\/([^/]+)\/views\/([^/]+)$/,
154 );
155 if (!match) return undefined;
156 return {
157 organization: match[1]!,
158 location: match[2]!,
159 bucketId: match[3]!,
160 viewId: match[4]!,
161 };
162 };
163
164 const parseBucketName = (name: string) => {
165 const match = name.match(/^(organizations\/[^/]+)\/locations\/([^/]+)\/buckets\/([^/]+)$/);
166 if (!match) return undefined;
167 return {
168 organization: match[1]!,
169 location: match[2]!,
170 bucketId: match[3]!,
171 };
172 };
173
174 const parentBucket = (organization: string, location: string, bucketId: string, bucket?: string) =>
175 bucket ?? `${organization}/locations/${location}/buckets/${bucketId}`;
176
177 const resourceName = (bucket: string, viewId: string) => `${bucket}/views/${viewId}`;
178
179 const toAttrs = (view: logging.LogView, fallbackBucket: string, project: string) => {
180 const name = view.name ?? "";
181 const parsed = parseViewName(name);
182 const bucket =
183 parsed !== undefined
184 ? `${parsed.organization}/locations/${parsed.location}/buckets/${parsed.bucketId}`
185 : fallbackBucket;
186 const bucketParsed = parseBucketName(bucket);
187 const description = parseDescription(view.description);
188 const organization = parsed?.organization ?? bucketParsed?.organization ?? "";
189 return {
190 name: name || resourceName(bucket, parsed?.viewId ?? lastSegment(name)),
191 viewId: parsed?.viewId ?? lastSegment(name),
192 bucket,
193 bucketId: parsed?.bucketId ?? bucketParsed?.bucketId ?? "",
194 organization,
195 organizationId: organizationIdOf(organization),
196 project,
197 location: parsed?.location ?? bucketParsed?.location ?? DEFAULT_LOCATION,
198 filter: view.filter,
199 description: description.description,
200 createTime: view.createTime,
201 updateTime: view.updateTime,
202 };
203 };
204
205 const getByName = (name: string) =>
206 logging
207 .getOrganizationsLocationsBucketsViews({ name })
208 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
209
210 const resolveParent = (
211 organization: string,
212 news: Pick<OrganizationBucketsViewProps, "bucket" | "bucketId" | "location">,
213 output?: { bucket?: string; bucketId?: string; location?: string },
214 ) => {
215 const location = news.location ?? output?.location ?? DEFAULT_LOCATION;
216 const bucketId = news.bucketId ?? output?.bucketId ?? DEFAULT_BUCKET_ID;
217 return parentBucket(organization, location, bucketId, news.bucket ?? output?.bucket);
218 };
219
220 export const OrganizationBucketsViewProvider = () =>
221 Provider.succeed(OrganizationBucketsView, {
222 stables: [
223 "name",
224 "viewId",
225 "bucket",
226 "bucketId",
227 "organization",
228 "organizationId",
229 "project",
230 "location",
231 "createTime",
232 ],
233
234 diff: Effect.fn(function* ({ news, olds, output }) {
235 if (!isResolved(news)) return undefined;
236 const previousId = olds?.viewId ?? output?.viewId;
237 const idChanged =
238 previousId !== undefined && news.viewId !== undefined && news.viewId !== previousId;
239 const previousBucket = olds?.bucket ?? output?.bucket;
240 const bucketChanged =
241 news.bucket !== undefined && previousBucket !== undefined && news.bucket !== previousBucket;
242 const previousLocation = olds?.location ?? output?.location;
243 const locationChanged =
244 previousLocation !== undefined &&
245 news.location !== undefined &&
246 news.location !== previousLocation;
247 const previousBucketId = olds?.bucketId ?? output?.bucketId;
248 const bucketIdChanged =
249 previousBucketId !== undefined &&
250 news.bucketId !== undefined &&
251 news.bucketId !== previousBucketId;
252 const previousOrg = olds?.organization ?? output?.organization;
253 const orgChanged =
254 previousOrg !== undefined &&
255 news.organization !== undefined &&
256 news.organization !== previousOrg;
257 if (!idChanged && !bucketChanged && !locationChanged && !bucketIdChanged && !orgChanged) {
258 return undefined;
259 }
260 return { action: "replace" as const, deleteFirst: false };
261 }),
262
263 read: Effect.fn(function* ({ id, olds, output }) {
264 const env = yield* GcpEnvironment.current;
265 const organization = yield* resolveOrganization(
266 olds?.organization ?? output?.organization,
267 output?.organization,
268 );
269 const viewId = yield* toPhysicalId(id, olds?.viewId, output?.viewId, "v");
270 const bucket = resolveParent(organization, olds ?? {}, output);
271 const name = output?.name ?? resourceName(bucket, viewId);
272 const existing = yield* getByName(name);
273 if (existing === undefined) return undefined;
274 const attrs = toAttrs(existing, bucket, env.project);
275 const { labels } = parseDescription(existing.description);
276 return (yield* hasAlchemyLabels(id, labels)) ? attrs : Unowned(attrs);
277 }),
278
279 list: () =>
280 Effect.gen(function* () {
281 const env = yield* GcpEnvironment.current;
282 const organization = yield* tryResolveOrganization();
283 if (organization === undefined) return [];
284 return yield* logging.listOrganizationsLocationsBuckets
285 .pages({
286 parent: `${organization}/locations/-`,
287 pageSize: 1000,
288 })
289 .pipe(
290 Stream.flatMap((page) => Stream.fromIterable(page.buckets ?? [])),
291 Stream.flatMap(
292 (bucket) =>
293 bucket.name
294 ? logging.listOrganizationsLocationsBucketsViews
295 .pages({
296 parent: bucket.name,
297 pageSize: 1000,
298 })
299 .pipe(
300 Stream.flatMap((page) => Stream.fromIterable(page.views ?? [])),
301 Stream.filter((view) => hasOwnershipMarker(view.description)),
302 Stream.map((view) => toAttrs(view, bucket.name ?? "", env.project)),
303 Stream.catchTag("NotFound", () => Stream.empty),
304 )
305 : Stream.empty,
306 { concurrency: 4 },
307 ),
308 Stream.runCollect,
309 Effect.map((chunk) => Array.from(chunk)),
310 Effect.catchTag("NotFound", () => Effect.succeed([])),
311 );
312 }),
313
314 reconcile: Effect.fn(function* ({ id, news, output }) {
315 const env = yield* GcpEnvironment.current;
316 const organization = yield* resolveOrganization(news.organization, output?.organization);
317 const viewId = yield* toPhysicalId(id, news.viewId, output?.viewId, "v");
318 const bucket = resolveParent(organization, news, output);
319 const name = resourceName(bucket, viewId);
320 const ownership = yield* createInternalLabels(id);
321 const desiredDescription = encodeDescription(ownership, news.description);
322
323 let current = yield* getByName(output?.name ?? name);
324
325 if (current === undefined) {
326 const created = yield* logging
327 .createOrganizationsLocationsBucketsViews({
328 parent: bucket,
329 viewId,
330 body: {
331 filter: news.filter,
332 description: desiredDescription,
333 },
334 })
335 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
336 current = created ?? undefined;
337 }
338
339 if (current === undefined) {
340 return yield* new OrganizationBucketsViewNotResolved({ resourceName: name });
341 }
342
343 const filterChanged = (current.filter ?? "") !== (news.filter ?? "");
344 const descriptionChanged = (current.description ?? "") !== desiredDescription;
345 const updateMask = [
346 filterChanged ? "filter" : undefined,
347 descriptionChanged ? "description" : undefined,
348 ].filter((field): field is string => field !== undefined);
349
350 if (updateMask.length > 0) {
351 current = yield* logging.patchOrganizationsLocationsBucketsViews({
352 name: current.name ?? name,
353 updateMask: updateMask.join(","),
354 body: {
355 filter: news.filter ?? "",
356 description: desiredDescription,
357 },
358 });
359 }
360
361 return toAttrs(current, bucket, env.project);
362 }),
363
364 delete: Effect.fn(function* ({ output }) {
365 yield* logging
366 .deleteOrganizationsLocationsBucketsViews({ name: output.name })
367 .pipe(Effect.catchTag("NotFound", () => Effect.void));
368 }),
369 });