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

main
ts 359 lines 13.1 KB
Raw
1 import * as logging from "@distilled.cloud/gcp/logging_v2";
2 import { unownedUnlessPrevious } 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 Schedule from "effect/Schedule";
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 {
14 DEFAULT_LOCATION,
15 billingAccountIdOf,
16 billingAccountParent,
17 encodeDescription,
18 hasOwnershipMarker,
19 lastSegment,
20 lookupProjectBillingAccountId,
21 parseDescription,
22 resolveBillingAccountId,
23 toLinkId,
24 } from "./internal.ts";
25 import { waitForDeleteOperation, waitForOperation } from "./operations.ts";
26
27 export type BillingBucketsLinkProps = {
28 /**
29 * Link id (the `{link}` segment of
30 * `billingAccounts/{billingAccount}/locations/{location}/buckets/{bucket}/links/{link}`).
31 * If omitted, a unique name is generated from the stack, stage, and
32 * logical id. Must be alphanumeric plus underscores (BigQuery dataset
33 * naming). Immutable — changing it replaces the link.
34 */
35 linkId?: string;
36 /**
37 * Analytics-enabled bucket id that owns this link. A bucket may have
38 * only one link. Immutable — changing it replaces the link.
39 */
40 bucketId: string;
41 /**
42 * Billing account id (`XXXXXX-XXXXXX-XXXXXX` or
43 * `billingAccounts/{id}`). If omitted, Alchemy uses the billing
44 * account linked to the current project. Immutable — changing it
45 * replaces the link.
46 */
47 billingAccountId?: string;
48 /**
49 * Location of the parent bucket. Immutable — changing it replaces the
50 * link.
51 * @default "global"
52 */
53 location?: string;
54 /**
55 * Human-readable description (max 8000 characters). Links have no
56 * labels or update API, so Alchemy ownership is stored in a
57 * `[alchemy …]` prefix at create time and stripped from attributes.
58 */
59 description?: string;
60 };
61
62 export type BillingBucketsLink = Resource<
63 "GCP.Logging.BillingBucketsLink",
64 BillingBucketsLinkProps,
65 {
66 /** Full resource name `billingAccounts/{billingAccount}/locations/{location}/buckets/{bucket}/links/{link}`. */
67 name: string;
68 /** Link id (last path segment). */
69 linkId: string;
70 /** Parent bucket id. */
71 bucketId: string;
72 /** Billing account id. */
73 billingAccountId: string;
74 /** Location of the parent bucket. */
75 location: string;
76 /** User description with the Alchemy ownership prefix stripped. */
77 description: string | undefined;
78 /** Linked BigQuery dataset id, if reported. */
79 bigqueryDatasetId: string | undefined;
80 /** Link lifecycle (`ACTIVE`, `CREATING`, …). */
81 lifecycleState: string | undefined;
82 /** RFC3339 creation timestamp. */
83 createTime: string | undefined;
84 },
85 never,
86 Providers
87 >;
88
89 /**
90 * A BigQuery dataset link for a billing-account log bucket.
91 *
92 * Creating a link asynchronously provisions a BigQuery dataset (and views
93 * for each log view) so Log Analytics queries can run against the bucket.
94 * A bucket may currently contain only one link. Links have no update API
95 * — they are existence-only after create. Alchemy stamps ownership into
96 * the description at create time for `list` / nuke. `linkId`, `bucketId`,
97 * `location`, and `billingAccountId` are identity.
98 *
99 * ### Creating a Billing Bucket Link
100 * **Example:** Link an analytics-enabled bucket
101 * ```typescript
102 * const bucket = yield* GCP.Logging.BillingBucket("AppLogs", {
103 * analyticsEnabled: true,
104 * });
105 * const link = yield* GCP.Logging.BillingBucketsLink("Analytics", {
106 * bucketId: bucket.bucketId,
107 * location: bucket.location,
108 * billingAccountId: bucket.billingAccountId,
109 * description: "log analytics",
110 * });
111 * ```
112 *
113 * **Example:** Named link
114 * ```typescript
115 * const link = yield* GCP.Logging.BillingBucketsLink("Analytics", {
116 * billingAccountId: "AAAAAA-BBBBBB-CCCCCC",
117 * location: "global",
118 * bucketId: "app-logs",
119 * linkId: "app_logs_link",
120 * });
121 * ```
122 *
123 * @resource
124 * @category Logging
125 */
126 export const BillingBucketsLink = Resource<BillingBucketsLink>("GCP.Logging.BillingBucketsLink");
127
128 export class BillingBucketsLinkNotResolved extends Data.TaggedError(
129 "GCP.Logging.BillingBucketsLinkNotResolved",
130 )<{
131 resourceName: string;
132 }> {}
133
134 const resourceName = (
135 billingAccountId: string,
136 location: string,
137 bucketId: string,
138 linkId: string,
139 ) =>
140 `${billingAccountParent(billingAccountId)}/locations/${location}/buckets/${bucketId}/links/${linkId}`;
141
142 const parseLinkName = (name: string) => {
143 const match = name.match(
144 /^billingAccounts\/([^/]+)\/locations\/([^/]+)\/buckets\/([^/]+)\/links\/([^/]+)$/,
145 );
146 if (!match) return undefined;
147 return {
148 billingAccountId: match[1]!,
149 location: match[2]!,
150 bucketId: match[3]!,
151 linkId: match[4]!,
152 };
153 };
154
155 const isDeleted = (link: logging.Link | undefined): link is undefined =>
156 link === undefined || link.lifecycleState === "DELETE_REQUESTED";
157
158 const isPending = (state: string | undefined) => state === "CREATING" || state === "UPDATING";
159
160 const toAttrs = (
161 link: logging.Link,
162 billingAccountId: string,
163 location: string,
164 bucketId: string,
165 ) => {
166 const parsedName = parseLinkName(link.name ?? "");
167 const linkId = parsedName?.linkId ?? lastSegment(link.name ?? "");
168 const parsed = parseDescription(link.description);
169 const account = parsedName?.billingAccountId ?? billingAccountId;
170 const resolvedLocation = parsedName?.location ?? location;
171 const resolvedBucket = parsedName?.bucketId ?? bucketId;
172 return {
173 name:
174 link.name ?? (linkId ? resourceName(account, resolvedLocation, resolvedBucket, linkId) : ""),
175 linkId,
176 bucketId: resolvedBucket,
177 billingAccountId: account,
178 location: resolvedLocation,
179 description: parsed.description,
180 bigqueryDatasetId: link.bigqueryDataset?.datasetId,
181 lifecycleState: link.lifecycleState,
182 createTime: link.createTime,
183 };
184 };
185
186 const getByName = (name: string) =>
187 logging
188 .getBillingAccountsLocationsBucketsLinks({ name })
189 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
190
191 const waitUntilActive = (name: string) =>
192 Effect.gen(function* () {
193 const link = yield* getByName(name);
194 if (link === undefined || isDeleted(link)) {
195 return yield* new BillingBucketsLinkNotResolved({ resourceName: name });
196 }
197 if (link.lifecycleState === "FAILED") {
198 return yield* new BillingBucketsLinkNotResolved({ resourceName: name });
199 }
200 if (isPending(link.lifecycleState)) {
201 return yield* new BillingBucketsLinkNotResolved({ resourceName: name });
202 }
203 return link;
204 }).pipe(
205 Effect.retry({
206 while: (error) => error._tag === "GCP.Logging.BillingBucketsLinkNotResolved",
207 times: 10,
208 schedule: Schedule.spaced("3 seconds"),
209 }),
210 );
211
212 const waitUntilDeleted = (name: string) =>
213 getByName(name).pipe(
214 Effect.flatMap((link) =>
215 isDeleted(link)
216 ? Effect.void
217 : Effect.fail(new BillingBucketsLinkNotResolved({ resourceName: name })),
218 ),
219 Effect.retry({
220 while: (error) => error._tag === "GCP.Logging.BillingBucketsLinkNotResolved",
221 times: 10,
222 schedule: Schedule.spaced("3 seconds"),
223 }),
224 );
225
226 export const BillingBucketsLinkProvider = () =>
227 Provider.succeed(BillingBucketsLink, {
228 stables: ["name", "linkId", "bucketId", "billingAccountId", "location", "createTime"],
229
230 diff: Effect.fn(function* ({ news, olds, output }) {
231 if (!isResolved(news)) return undefined;
232 const previousId = olds?.linkId ?? output?.linkId;
233 const idChanged =
234 previousId !== undefined && news.linkId !== undefined && news.linkId !== previousId;
235 const previousBucket = olds?.bucketId ?? output?.bucketId;
236 const bucketChanged = previousBucket !== undefined && news.bucketId !== previousBucket;
237 const previousLocation = olds?.location ?? output?.location;
238 const locationChanged =
239 previousLocation !== undefined &&
240 news.location !== undefined &&
241 news.location !== previousLocation;
242 const previousAccount = olds?.billingAccountId ?? output?.billingAccountId;
243 const accountChanged =
244 previousAccount !== undefined &&
245 news.billingAccountId !== undefined &&
246 billingAccountIdOf(news.billingAccountId) !== billingAccountIdOf(previousAccount);
247 if (!idChanged && !bucketChanged && !locationChanged && !accountChanged) {
248 return undefined;
249 }
250 return { action: "replace" as const, deleteFirst: true };
251 }),
252
253 read: Effect.fn(function* ({ id, olds, output, previous }) {
254 const billingAccountId = yield* resolveBillingAccountId(
255 olds?.billingAccountId,
256 output?.billingAccountId,
257 );
258 const location = olds?.location ?? output?.location ?? DEFAULT_LOCATION;
259 const bucketId = olds?.bucketId ?? output?.bucketId ?? "";
260 const linkId = yield* toLinkId(id, olds?.linkId, output?.linkId);
261 const name = output?.name ?? resourceName(billingAccountId, location, bucketId, linkId);
262 const existing = yield* getByName(name);
263 if (isDeleted(existing)) return undefined;
264 const attrs = toAttrs(existing, billingAccountId, location, bucketId);
265 const { labels } = parseDescription(existing.description);
266 return (yield* hasAlchemyLabels(id, labels))
267 ? attrs
268 : unownedUnlessPrevious(attrs, previous, "name");
269 }),
270
271 list: () =>
272 Effect.gen(function* () {
273 const env = yield* GcpEnvironment.current;
274 const billingAccountId = yield* lookupProjectBillingAccountId(env.project);
275 if (billingAccountId === undefined) return [];
276 const buckets = yield* logging.listBillingAccountsLocationsBuckets
277 .pages({
278 parent: `${billingAccountParent(billingAccountId)}/locations/-`,
279 pageSize: 1000,
280 })
281 .pipe(
282 Stream.flatMap((page) => Stream.fromIterable(page.buckets ?? [])),
283 Stream.runCollect,
284 Effect.map((chunk) => Array.from(chunk)),
285 Effect.catchTag("NotFound", () => Effect.succeed([] as logging.LogBucket[])),
286 );
287 const listed: BillingBucketsLink["Attributes"][] = [];
288 for (const bucket of buckets) {
289 if (!bucket.name) continue;
290 const links = yield* logging.listBillingAccountsLocationsBucketsLinks
291 .pages({ parent: bucket.name, pageSize: 1000 })
292 .pipe(
293 Stream.flatMap((page) => Stream.fromIterable(page.links ?? [])),
294 Stream.filter((link) => !isDeleted(link) && hasOwnershipMarker(link.description)),
295 Stream.map((link) =>
296 toAttrs(link, billingAccountId, DEFAULT_LOCATION, lastSegment(bucket.name ?? "")),
297 ),
298 Stream.runCollect,
299 Effect.map((chunk) => Array.from(chunk)),
300 Effect.catchTag("NotFound", () =>
301 Effect.succeed([] as BillingBucketsLink["Attributes"][]),
302 ),
303 );
304 listed.push(...links);
305 }
306 return listed;
307 }),
308
309 reconcile: Effect.fn(function* ({ id, news, output }) {
310 const billingAccountId = yield* resolveBillingAccountId(
311 news.billingAccountId,
312 output?.billingAccountId,
313 );
314 const location = news.location ?? output?.location ?? DEFAULT_LOCATION;
315 const bucketId = news.bucketId;
316 const linkId = yield* toLinkId(id, news.linkId, output?.linkId);
317 const name = resourceName(billingAccountId, location, bucketId, linkId);
318 const parent = `${billingAccountParent(billingAccountId)}/locations/${location}/buckets/${bucketId}`;
319 const ownership = yield* createInternalLabels(id);
320 const desiredDescription = encodeDescription(ownership, news.description);
321
322 let current = yield* getByName(output?.name ?? name);
323
324 if (current === undefined) {
325 const operation = yield* logging
326 .createBillingAccountsLocationsBucketsLinks({
327 parent,
328 linkId,
329 body: { description: desiredDescription },
330 })
331 .pipe(
332 Effect.catchTag("Conflict", () => Effect.succeed<logging.Operation>({ done: true })),
333 );
334 if (operation.done !== true || operation.name) {
335 yield* waitForOperation(operation);
336 }
337 current = yield* waitUntilActive(name);
338 } else if (isPending(current.lifecycleState)) {
339 current = yield* waitUntilActive(current.name ?? name);
340 }
341
342 if (isDeleted(current)) {
343 return yield* new BillingBucketsLinkNotResolved({ resourceName: name });
344 }
345
346 return toAttrs(current, billingAccountId, location, bucketId);
347 }),
348
349 delete: Effect.fn(function* ({ output }) {
350 if (output.lifecycleState === "DELETE_REQUESTED") return;
351 const operation = yield* logging
352 .deleteBillingAccountsLocationsBucketsLinks({ name: output.name })
353 .pipe(Effect.catchTag("NotFound", () => Effect.succeed<logging.Operation>({ done: true })));
354 if (operation.done !== true || operation.name) {
355 yield* waitForDeleteOperation(operation);
356 }
357 yield* waitUntilDeleted(output.name);
358 }),
359 });