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