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

main
ts 287 lines 10.2 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 type { Providers } from "../Providers.ts";
12 import {
13 createOwnership,
14 encodeDescription,
15 hasOwnershipMarker,
16 lastSegment,
17 ownedBy,
18 parseDescription,
19 parseLoggingName,
20 toLinkId,
21 } from "./internal.ts";
22 import { waitForDeleteOperation } from "./operations.ts";
23
24 export type LocationsBucketsLinkProps = {
25 /**
26 * Full resource name of the parent analytics-enabled log bucket
27 * (`{parent}/locations/{location}/buckets/{bucket}`). A bucket may
28 * contain only one link. Immutable — changing it replaces the link
29 * (delete first).
30 */
31 bucketName: string;
32 /**
33 * Link id (also the BigQuery dataset id). If omitted, a unique name is
34 * generated. Up to 100 characters: letters, digits, and underscores.
35 * Immutable — changing it replaces the link (delete first).
36 */
37 linkId?: string;
38 /**
39 * Human-readable description. Links have no labels field, so Alchemy
40 * ownership is stored in a `[alchemy …]` prefix and stripped from
41 * attributes. Changing the description replaces the link.
42 */
43 description?: string;
44 };
45
46 export type LocationsBucketsLink = Resource<
47 "GCP.Logging.LocationsBucketsLink",
48 LocationsBucketsLinkProps,
49 {
50 /** Full resource name `{bucket}/links/{linkId}`. */
51 name: string;
52 /** Link id (last path segment). */
53 linkId: string;
54 /** Parent bucket resource name. */
55 bucketName: string;
56 /** User description with the Alchemy ownership prefix stripped. */
57 description: string | undefined;
58 /** BigQuery dataset resource name, if created. */
59 bigqueryDatasetId: string | undefined;
60 /** Link lifecycle (`ACTIVE`, `CREATING`, …). */
61 lifecycleState: string | undefined;
62 /** RFC3339 creation timestamp. */
63 createTime: string | undefined;
64 },
65 never,
66 Providers
67 >;
68
69 /**
70 * A BigQuery linked dataset for an analytics-enabled log bucket, managed
71 * through the generic locations APIs.
72 *
73 * Create is asynchronous and also provisions a BigQuery dataset whose id
74 * matches `linkId`. A bucket may currently contain only one link. Links
75 * have no labels field, so Alchemy stamps ownership into the description
76 * for `list` / nuke. There is no update API — changing `linkId`,
77 * `bucketName`, or `description` replaces the link (delete first).
78 *
79 * ### Creating a Locations Bucket Link
80 * **Example:** Link an analytics bucket to BigQuery
81 * ```typescript
82 * const bucket = yield* GCP.Logging.LocationsBucket("Analytics", {
83 * analyticsEnabled: true,
84 * });
85 * const link = yield* GCP.Logging.LocationsBucketsLink("Bq", {
86 * bucketName: bucket.name,
87 * description: "log analytics dataset",
88 * });
89 * ```
90 *
91 * @resource
92 * @category Logging
93 */
94 export const LocationsBucketsLink = Resource<LocationsBucketsLink>(
95 "GCP.Logging.LocationsBucketsLink",
96 );
97
98 export class LocationsBucketsLinkNotResolved extends Data.TaggedError(
99 "GCP.Logging.LocationsBucketsLinkNotResolved",
100 )<{
101 resourceName: string;
102 }> {}
103
104 export class LocationsBucketsLinkFailed extends Data.TaggedError(
105 "GCP.Logging.LocationsBucketsLinkFailed",
106 )<{
107 resourceName: string;
108 state: string | undefined;
109 }> {}
110
111 const resourceName = (bucketName: string, linkId: string) => `${bucketName}/links/${linkId}`;
112
113 const isDeleted = (link: logging.Link | undefined): link is undefined =>
114 link === undefined || link.lifecycleState === "DELETE_REQUESTED";
115
116 const isPending = (state: string | undefined) => state === "CREATING" || state === "UPDATING";
117
118 const toAttrs = (link: logging.Link, bucketName: string) => {
119 const parsed = parseLoggingName(link.name ?? "");
120 const linkId = parsed.linkId ?? lastSegment(link.name ?? "");
121 const description = parseDescription(link.description);
122 return {
123 name: link.name ?? resourceName(bucketName, linkId),
124 linkId,
125 bucketName,
126 description: description.description,
127 bigqueryDatasetId: link.bigqueryDataset?.datasetId,
128 lifecycleState: link.lifecycleState,
129 createTime: link.createTime,
130 };
131 };
132
133 const getByName = (name: string) =>
134 logging
135 .getLocationsBucketsLinks({ name })
136 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
137
138 const waitUntilActive = (name: string) =>
139 Effect.gen(function* () {
140 const link = yield* getByName(name);
141 if (link === undefined || isDeleted(link)) {
142 return yield* new LocationsBucketsLinkNotResolved({ resourceName: name });
143 }
144 if (link.lifecycleState === "FAILED") {
145 return yield* new LocationsBucketsLinkFailed({
146 resourceName: name,
147 state: link.lifecycleState,
148 });
149 }
150 if (isPending(link.lifecycleState)) {
151 return yield* new LocationsBucketsLinkNotResolved({ resourceName: name });
152 }
153 return link;
154 }).pipe(
155 Effect.retry({
156 while: (error) => error._tag === "GCP.Logging.LocationsBucketsLinkNotResolved",
157 times: 10,
158 schedule: Schedule.spaced("5 seconds"),
159 }),
160 );
161
162 export const LocationsBucketsLinkProvider = () =>
163 Provider.succeed(LocationsBucketsLink, {
164 stables: ["name", "linkId", "bucketName", "createTime"],
165
166 diff: Effect.fn(function* ({ news, olds, output }) {
167 if (!isResolved(news)) return undefined;
168 const previousId = olds?.linkId ?? output?.linkId;
169 const idChanged =
170 previousId !== undefined && news.linkId !== undefined && news.linkId !== previousId;
171 const previousBucket = olds?.bucketName ?? output?.bucketName;
172 const bucketChanged = previousBucket !== undefined && news.bucketName !== previousBucket;
173 const previousDescription = olds?.description ?? output?.description;
174 const descriptionChanged =
175 news.description !== undefined &&
176 previousDescription !== undefined &&
177 news.description !== previousDescription;
178 if (!idChanged && !bucketChanged && !descriptionChanged) {
179 return undefined;
180 }
181 return { action: "replace" as const, deleteFirst: true };
182 }),
183
184 read: Effect.fn(function* ({ id, olds, output, previous }) {
185 const linkId = yield* toLinkId(id, olds?.linkId, output?.linkId);
186 const bucketName = olds?.bucketName ?? output?.bucketName;
187 if (bucketName === undefined) return undefined;
188 const name = output?.name ?? resourceName(bucketName, linkId);
189 const existing = yield* getByName(name);
190 if (isDeleted(existing)) return undefined;
191 const attrs = toAttrs(existing, bucketName);
192 const { labels } = parseDescription(existing.description);
193 return (yield* ownedBy(id, labels)) ? attrs : unownedUnlessPrevious(attrs, previous, "name");
194 }),
195
196 list: () =>
197 Effect.gen(function* () {
198 const env = yield* GcpEnvironment.current;
199 const buckets = yield* logging.listLocationsBuckets
200 .pages({
201 parent: `projects/${env.project}/locations/-`,
202 pageSize: 1000,
203 })
204 .pipe(
205 Stream.flatMap((page) => Stream.fromIterable(page.buckets ?? [])),
206 Stream.filter((bucket) => bucket.analyticsEnabled === true),
207 Stream.runCollect,
208 Effect.map((chunk) => Array.from(chunk)),
209 );
210 const links: ReturnType<typeof toAttrs>[] = [];
211 for (const bucket of buckets) {
212 if (bucket.name === undefined) continue;
213 const listed = yield* logging.listLocationsBucketsLinks
214 .pages({
215 parent: bucket.name,
216 pageSize: 1000,
217 })
218 .pipe(
219 Stream.flatMap((page) => Stream.fromIterable(page.links ?? [])),
220 Stream.filter((link) => !isDeleted(link) && hasOwnershipMarker(link.description)),
221 Stream.map((link) => toAttrs(link, bucket.name ?? "")),
222 Stream.runCollect,
223 Effect.map((chunk) => Array.from(chunk)),
224 Effect.catchTag("NotFound", () => Effect.succeed([] as ReturnType<typeof toAttrs>[])),
225 );
226 links.push(...listed);
227 }
228 return links;
229 }),
230
231 reconcile: Effect.fn(function* ({ id, news, output }) {
232 const linkId = yield* toLinkId(id, news.linkId, output?.linkId);
233 const name = resourceName(news.bucketName, linkId);
234 const ownership = yield* createOwnership(id);
235 const desiredDescription = encodeDescription(ownership, news.description);
236
237 let current = yield* getByName(output?.name ?? name);
238
239 if (current !== undefined && current.lifecycleState === "DELETE_REQUESTED") {
240 current = undefined;
241 }
242
243 if (current === undefined) {
244 yield* logging
245 .createLocationsBucketsLinks({
246 parent: news.bucketName,
247 linkId,
248 body: { description: desiredDescription },
249 })
250 .pipe(
251 Effect.catchTag("Conflict", () => Effect.succeed<logging.Operation>({ done: true })),
252 Effect.asVoid,
253 );
254 current = yield* waitUntilActive(name);
255 }
256
257 if (isDeleted(current)) {
258 return yield* new LocationsBucketsLinkNotResolved({ resourceName: name });
259 }
260
261 if (isPending(current.lifecycleState)) {
262 current = yield* waitUntilActive(current.name ?? name);
263 }
264
265 return toAttrs(current, news.bucketName);
266 }),
267
268 delete: Effect.fn(function* ({ output }) {
269 if (output.lifecycleState === "DELETE_REQUESTED") return;
270 yield* logging.deleteLocationsBucketsLinks({ name: output.name }).pipe(
271 Effect.flatMap((operation) => waitForDeleteOperation(operation)),
272 Effect.catchTag(["NotFound", "BadRequest"], () => Effect.void),
273 );
274 yield* getByName(output.name).pipe(
275 Effect.flatMap((link) =>
276 isDeleted(link)
277 ? Effect.void
278 : Effect.fail(new LocationsBucketsLinkNotResolved({ resourceName: output.name })),
279 ),
280 Effect.retry({
281 while: (error) => error._tag === "GCP.Logging.LocationsBucketsLinkNotResolved",
282 times: 10,
283 schedule: Schedule.spaced("3 seconds"),
284 }),
285 );
286 }),
287 });