@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 265 lines 9.69 KB
Raw
1 import * as observability from "@distilled.cloud/gcp/observability_v1";
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_TRACE_LOCATION,
14 encodeDescription,
15 expandResourceNames,
16 hasOwnershipMarker,
17 parseDescription,
18 parseScopeName,
19 sameStringList,
20 scopeResourceName,
21 toScopeId,
22 } from "./internal.ts";
23
24 export type TraceScopeProps = {
25 /**
26 * Trace scope id (the `{traceScope}` segment of
27 * `projects/{project}/locations/{location}/traceScopes/{traceScope}`).
28 * If 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 scope. The system-managed `_Default` scope
32 * cannot be deleted.
33 */
34 traceScopeId?: string;
35 /**
36 * Location. Trace scopes are only available in `global`. Immutable —
37 * changing it replaces the scope.
38 * @default "global"
39 */
40 location?: string;
41 /**
42 * Projects whose traces this scope queries together. Each entry is
43 * `projects/{project}`. At most 20 projects. Bare project ids are
44 * expanded. If omitted, the current project is used.
45 */
46 resourceNames?: string[];
47 /**
48 * Human-readable description (max 8000 characters). Trace scopes have
49 * no labels field, so Alchemy ownership is stored in a `[alchemy …]`
50 * prefix and stripped from attributes.
51 */
52 description?: string;
53 };
54
55 export type TraceScope = Resource<
56 "GCP.Observability.TraceScope",
57 TraceScopeProps,
58 {
59 /** Full resource name `projects/{project}/locations/{location}/traceScopes/{traceScopeId}`. */
60 name: string;
61 /** Trace scope id (last path segment). */
62 traceScopeId: string;
63 /** Project id. */
64 project: string;
65 /** Location (`global`). */
66 location: string;
67 /** Covered projects (`projects/{project}`). */
68 resourceNames: string[];
69 /** User description with the Alchemy ownership prefix stripped. */
70 description: string | undefined;
71 /** RFC3339 creation timestamp. */
72 createTime: string | undefined;
73 /** RFC3339 last-update timestamp. */
74 updateTime: string | undefined;
75 },
76 never,
77 Providers
78 >;
79
80 /**
81 * A Cloud Observability trace scope — a named collection of projects
82 * whose traces are queried together in Trace Explorer.
83 *
84 * Trace scopes exist only in the `global` location. They have no labels
85 * field, so Alchemy stamps ownership into the description for `list` /
86 * nuke. `traceScopeId` and `location` are identity — changing either
87 * replaces the scope. `resourceNames` and description update in place.
88 * The system-managed `_Default` scope cannot be deleted.
89 *
90 * ### Creating a Trace Scope
91 * **Example:** Generated name covering this project
92 * ```typescript
93 * const scope = yield* GCP.Observability.TraceScope("App", {
94 * resourceNames: ["projects/my-project"],
95 * description: "application traces",
96 * });
97 * ```
98 *
99 * **Example:** Named scope
100 * ```typescript
101 * const scope = yield* GCP.Observability.TraceScope("App", {
102 * traceScopeId: "app-traces",
103 * resourceNames: ["projects/my-project"],
104 * });
105 * ```
106 *
107 * ### Updating a Trace Scope
108 * Change props on the same logical id; the engine keeps the physical id.
109 *
110 * **Example:** Change the description
111 * ```typescript
112 * const scope = yield* GCP.Observability.TraceScope("App", {
113 * resourceNames: ["projects/my-project"],
114 * description: "all application traces",
115 * });
116 * ```
117 *
118 * @resource
119 * @category Observability
120 */
121 export const TraceScope = Resource<TraceScope>("GCP.Observability.TraceScope");
122
123 export class TraceScopeNotResolved extends Data.TaggedError(
124 "GCP.Observability.TraceScopeNotResolved",
125 )<{
126 resourceName: string;
127 }> {}
128
129 const traceScopeIdOf = (scope: observability.TraceScope, fallback?: string) => {
130 const parsed = parseScopeName(scope.name ?? "");
131 return parsed?.traceScopeId ?? fallback ?? (scope.name ?? "").split("/").pop() ?? "";
132 };
133
134 const toAttrs = (scope: observability.TraceScope, project: string, location: string) => {
135 const traceScopeId = traceScopeIdOf(scope);
136 const parsed = parseDescription(scope.description);
137 const parsedName = parseScopeName(scope.name ?? "");
138 const resolvedLocation = parsedName?.location ?? location;
139 const resolvedProject = parsedName?.project ?? project;
140 return {
141 name:
142 scope.name ??
143 (traceScopeId ? scopeResourceName(resolvedProject, resolvedLocation, traceScopeId) : ""),
144 traceScopeId,
145 project: resolvedProject,
146 location: resolvedLocation,
147 resourceNames: [...(scope.resourceNames ?? [])],
148 description: parsed.description,
149 createTime: scope.createTime,
150 updateTime: scope.updateTime,
151 };
152 };
153
154 const getByName = (name: string) =>
155 observability
156 .getProjectsLocationsTraceScopes({ name })
157 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
158
159 export const TraceScopeProvider = () =>
160 Provider.succeed(TraceScope, {
161 stables: ["name", "traceScopeId", "project", "location", "createTime"],
162
163 diff: Effect.fn(function* ({ news, olds, output }) {
164 if (!isResolved(news)) return undefined;
165 const previousId = olds?.traceScopeId ?? output?.traceScopeId;
166 const idChanged =
167 previousId !== undefined &&
168 news.traceScopeId !== undefined &&
169 news.traceScopeId !== previousId;
170 const previousLocation = olds?.location ?? output?.location;
171 const locationChanged =
172 previousLocation !== undefined &&
173 news.location !== undefined &&
174 news.location !== previousLocation;
175 if (!idChanged && !locationChanged) return undefined;
176 return { action: "replace" as const, deleteFirst: false };
177 }),
178
179 read: Effect.fn(function* ({ id, olds, output }) {
180 const env = yield* GcpEnvironment.current;
181 const location = olds?.location ?? output?.location ?? DEFAULT_TRACE_LOCATION;
182 const traceScopeId = yield* toScopeId(id, olds?.traceScopeId, output?.traceScopeId);
183 const name = output?.name ?? scopeResourceName(env.project, location, traceScopeId);
184 const existing = yield* getByName(name);
185 if (existing === undefined) return undefined;
186 const attrs = toAttrs(existing, env.project, location);
187 const { labels } = parseDescription(existing.description);
188 return (yield* hasAlchemyLabels(id, labels)) ? attrs : Unowned(attrs);
189 }),
190
191 list: () =>
192 Effect.gen(function* () {
193 const env = yield* GcpEnvironment.current;
194 return yield* observability.listProjectsLocationsTraceScopes
195 .pages({
196 parent: `projects/${env.project}/locations/${DEFAULT_TRACE_LOCATION}`,
197 pageSize: 1000,
198 })
199 .pipe(
200 Stream.flatMap((page) => Stream.fromIterable(page.traceScopes ?? [])),
201 Stream.filter((scope) => hasOwnershipMarker(scope.description)),
202 Stream.map((scope) => toAttrs(scope, env.project, DEFAULT_TRACE_LOCATION)),
203 Stream.runCollect,
204 Effect.map((chunk) => Array.from(chunk)),
205 Effect.catchTag("NotFound", () => Effect.succeed([] as ReturnType<typeof toAttrs>[])),
206 );
207 }),
208
209 reconcile: Effect.fn(function* ({ id, news, output }) {
210 const env = yield* GcpEnvironment.current;
211 const location = news.location ?? output?.location ?? DEFAULT_TRACE_LOCATION;
212 const traceScopeId = yield* toScopeId(id, news.traceScopeId, output?.traceScopeId);
213 const name = scopeResourceName(env.project, location, traceScopeId);
214 const ownership = yield* createInternalLabels(id);
215 const desiredDescription = encodeDescription(ownership, news.description);
216 const desiredResources = expandResourceNames(news.resourceNames, env.project);
217
218 let current = yield* getByName(output?.name ?? name);
219
220 if (current === undefined) {
221 const created = yield* observability
222 .createProjectsLocationsTraceScopes({
223 parent: `projects/${env.project}/locations/${location}`,
224 traceScopeId,
225 body: {
226 resourceNames: desiredResources,
227 description: desiredDescription,
228 },
229 })
230 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
231 current = created ?? undefined;
232 }
233
234 if (current === undefined) {
235 return yield* new TraceScopeNotResolved({ resourceName: name });
236 }
237
238 const descriptionChanged = (current.description ?? "") !== desiredDescription;
239 const resourcesChanged = !sameStringList(current.resourceNames, desiredResources);
240 const updateMask = [
241 descriptionChanged ? "description" : undefined,
242 resourcesChanged ? "resourceNames" : undefined,
243 ].filter((field): field is string => field !== undefined);
244
245 if (updateMask.length > 0) {
246 current = yield* observability.patchProjectsLocationsTraceScopes({
247 name: current.name ?? name,
248 updateMask: updateMask.join(","),
249 body: {
250 resourceNames: desiredResources,
251 description: desiredDescription,
252 },
253 });
254 }
255
256 return toAttrs(current, env.project, location);
257 }),
258
259 delete: Effect.fn(function* ({ output }) {
260 if (output.traceScopeId === "_Default") return;
261 yield* observability
262 .deleteProjectsLocationsTraceScopes({ name: output.name })
263 .pipe(Effect.catchTag("NotFound", () => Effect.void));
264 }),
265 });