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

main
ts 283 lines 10 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 {
14 encodeDescription,
15 hasOwnershipMarker,
16 lastSegment,
17 parseDescription,
18 sortedStrings,
19 } from "./ownership.ts";
20
21 const MAX_NAME_LENGTH = 100;
22 const DEFAULT_LOCATION = "global";
23
24 export type LogScopeProps = {
25 /**
26 * Log scope id (the `{logScope}` segment of
27 * `projects/{project}/locations/{location}/logScopes/{logScope}`). If
28 * omitted, a unique name is generated from the stack, stage, and
29 * logical id. Limited to 100 characters: letters, digits, underscores,
30 * hyphens, periods; first character must be alphanumeric. Immutable —
31 * changing it replaces the log scope.
32 */
33 logScopeId?: string;
34 /**
35 * Location. Log scopes are only available in `global`. Immutable —
36 * changing it replaces the log scope.
37 * @default "global"
38 */
39 location?: string;
40 /**
41 * Parent resources whose logs this scope covers. Each entry is
42 * `projects/{project}` or a log view
43 * `projects/{project}/locations/{location}/buckets/{bucket}/views/{view}`.
44 * At most 5 projects and 100 resources total. Organizations and folders
45 * are not supported.
46 */
47 resourceNames: string[];
48 /**
49 * Human-readable description (max 8000 characters). Log scopes have no
50 * labels field, so Alchemy ownership is stored in a `[alchemy …]`
51 * prefix and stripped from attributes.
52 */
53 description?: string;
54 };
55
56 export type LogScope = Resource<
57 "GCP.Logging.LogScope",
58 LogScopeProps,
59 {
60 /** Full resource name `projects/{project}/locations/{location}/logScopes/{logScopeId}`. */
61 name: string;
62 /** Log scope id (last path segment). */
63 logScopeId: string;
64 /** Project id. */
65 project: string;
66 /** Location (`global`). */
67 location: string;
68 /** Covered parent resources. */
69 resourceNames: string[];
70 /** User description with the Alchemy ownership prefix stripped. */
71 description: string | undefined;
72 /** RFC3339 creation timestamp. */
73 createTime: string | undefined;
74 /** RFC3339 last-update timestamp. */
75 updateTime: string | undefined;
76 },
77 never,
78 Providers
79 >;
80
81 /**
82 * A Cloud Logging log scope — a named collection of projects and log
83 * views to query together.
84 *
85 * Log scopes exist only in the `global` location. They have no labels
86 * field, so Alchemy stamps ownership into the description for `list` /
87 * nuke. `logScopeId` and `location` are identity — changing either
88 * replaces the scope. `resourceNames` and description update in place.
89 *
90 * ### Creating a Log Scope
91 * **Example:** Generated name covering this project
92 * ```typescript
93 * const scope = yield* GCP.Logging.LogScope("App", {
94 * resourceNames: ["projects/my-project"],
95 * description: "application logs",
96 * });
97 * ```
98 *
99 * **Example:** Named scope
100 * ```typescript
101 * const scope = yield* GCP.Logging.LogScope("App", {
102 * logScopeId: "app-logs",
103 * resourceNames: ["projects/my-project"],
104 * });
105 * ```
106 *
107 * ### Updating a Log Scope
108 * **Example:** Change the description
109 * ```typescript
110 * const scope = yield* GCP.Logging.LogScope("App", {
111 * resourceNames: ["projects/my-project"],
112 * description: "all application logs",
113 * });
114 * ```
115 *
116 * @resource
117 * @category Logging
118 */
119 export const LogScope = Resource<LogScope>("GCP.Logging.LogScope");
120
121 export class LogScopeNotResolved extends Data.TaggedError("GCP.Logging.LogScopeNotResolved")<{
122 resourceName: string;
123 }> {}
124
125 const parseScopeName = (name: string) => {
126 const match = name.match(/^projects\/([^/]+)\/locations\/([^/]+)\/logScopes\/([^/]+)$/);
127 if (!match) return undefined;
128 return {
129 project: match[1]!,
130 location: match[2]!,
131 logScopeId: match[3]!,
132 };
133 };
134
135 const resourceName = (project: string, location: string, logScopeId: string) =>
136 `projects/${project}/locations/${location}/logScopes/${logScopeId}`;
137
138 const logScopeIdOf = (scope: logging.LogScope, fallback?: string) => {
139 const parsed = parseScopeName(scope.name ?? "");
140 return parsed?.logScopeId ?? fallback ?? lastSegment(scope.name ?? "");
141 };
142
143 const toId = (id: string, logScopeId: string | undefined, existing?: string) =>
144 Effect.gen(function* () {
145 if (logScopeId !== undefined) return logScopeId;
146 if (existing !== undefined) return existing;
147 const generated = yield* createPhysicalName({
148 id,
149 maxLength: MAX_NAME_LENGTH,
150 lowercase: true,
151 });
152 return /^[a-z0-9]/.test(generated) ? generated : `s${generated}`.slice(0, MAX_NAME_LENGTH);
153 });
154
155 const toAttrs = (scope: logging.LogScope, project: string, location: string) => {
156 const logScopeId = logScopeIdOf(scope);
157 const parsed = parseDescription(scope.description);
158 const parsedName = parseScopeName(scope.name ?? "");
159 const resolvedLocation = parsedName?.location ?? location;
160 const resolvedProject = parsedName?.project ?? project;
161 return {
162 name:
163 scope.name ?? (logScopeId ? resourceName(resolvedProject, resolvedLocation, logScopeId) : ""),
164 logScopeId,
165 project: resolvedProject,
166 location: resolvedLocation,
167 resourceNames: [...(scope.resourceNames ?? [])],
168 description: parsed.description,
169 createTime: scope.createTime,
170 updateTime: scope.updateTime,
171 };
172 };
173
174 const getByName = (name: string) =>
175 logging
176 .getProjectsLocationsLogScopes({ name })
177 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
178
179 export const LogScopeProvider = () =>
180 Provider.succeed(LogScope, {
181 stables: ["name", "logScopeId", "project", "location", "createTime"],
182
183 diff: Effect.fn(function* ({ news, olds, output }) {
184 if (!isResolved(news)) return undefined;
185 const previousId = olds?.logScopeId ?? output?.logScopeId;
186 const idChanged =
187 previousId !== undefined && news.logScopeId !== undefined && news.logScopeId !== previousId;
188 const previousLocation = olds?.location ?? output?.location;
189 const locationChanged =
190 previousLocation !== undefined &&
191 news.location !== undefined &&
192 news.location !== previousLocation;
193 if (!idChanged && !locationChanged) return undefined;
194 return { action: "replace" as const, deleteFirst: false };
195 }),
196
197 read: Effect.fn(function* ({ id, olds, output }) {
198 const env = yield* GcpEnvironment.current;
199 const location = olds?.location ?? output?.location ?? DEFAULT_LOCATION;
200 const logScopeId = yield* toId(id, olds?.logScopeId, output?.logScopeId);
201 const name = output?.name ?? resourceName(env.project, location, logScopeId);
202 const existing = yield* getByName(name);
203 if (existing === undefined) return undefined;
204 const attrs = toAttrs(existing, env.project, location);
205 const { labels } = parseDescription(existing.description);
206 return (yield* hasAlchemyLabels(id, labels)) ? attrs : Unowned(attrs);
207 }),
208
209 list: () =>
210 Effect.gen(function* () {
211 const env = yield* GcpEnvironment.current;
212 return yield* logging.listProjectsLocationsLogScopes
213 .pages({
214 parent: `projects/${env.project}/locations/${DEFAULT_LOCATION}`,
215 pageSize: 1000,
216 })
217 .pipe(
218 Stream.flatMap((page) => Stream.fromIterable(page.logScopes ?? [])),
219 Stream.filter((scope) => hasOwnershipMarker(scope.description)),
220 Stream.map((scope) => toAttrs(scope, env.project, DEFAULT_LOCATION)),
221 Stream.runCollect,
222 Effect.map((chunk) => Array.from(chunk)),
223 );
224 }),
225
226 reconcile: Effect.fn(function* ({ id, news, output }) {
227 const env = yield* GcpEnvironment.current;
228 const location = news.location ?? output?.location ?? DEFAULT_LOCATION;
229 const logScopeId = yield* toId(id, news.logScopeId, output?.logScopeId);
230 const name = resourceName(env.project, location, logScopeId);
231 const ownership = yield* createInternalLabels(id);
232 const desiredDescription = encodeDescription(ownership, news.description);
233 const desiredResources = [...news.resourceNames];
234
235 let current = yield* getByName(output?.name ?? name);
236
237 if (current === undefined) {
238 const created = yield* logging
239 .createProjectsLocationsLogScopes({
240 parent: `projects/${env.project}/locations/${location}`,
241 logScopeId,
242 body: {
243 resourceNames: desiredResources,
244 description: desiredDescription,
245 },
246 })
247 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
248 current = created ?? undefined;
249 }
250
251 if (current === undefined) {
252 return yield* new LogScopeNotResolved({ resourceName: name });
253 }
254
255 const descriptionChanged = (current.description ?? "") !== desiredDescription;
256 const resourcesChanged =
257 JSON.stringify(sortedStrings(current.resourceNames)) !==
258 JSON.stringify(sortedStrings(desiredResources));
259 const updateMask = [
260 descriptionChanged ? "description" : undefined,
261 resourcesChanged ? "resourceNames" : undefined,
262 ].filter((field): field is string => field !== undefined);
263
264 if (updateMask.length > 0) {
265 current = yield* logging.patchProjectsLocationsLogScopes({
266 name: current.name ?? name,
267 updateMask: updateMask.join(","),
268 body: {
269 resourceNames: desiredResources,
270 description: desiredDescription,
271 },
272 });
273 }
274
275 return toAttrs(current, env.project, location);
276 }),
277
278 delete: Effect.fn(function* ({ output }) {
279 yield* logging
280 .deleteProjectsLocationsLogScopes({ name: output.name })
281 .pipe(Effect.catchTag("NotFound", () => Effect.void));
282 }),
283 });