@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 300 lines 10.2 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 { alchemyLabelKeys, createInternalLabels, hasAlchemyLabels } from "../Labels.ts";
12 import type { Providers } from "../Providers.ts";
13
14 const MAX_NAME_LENGTH = 100;
15
16 export type ExclusionProps = {
17 /**
18 * Exclusion id (the `{exclusion}` segment of
19 * `projects/{project}/exclusions/{exclusion}`). If omitted, a unique
20 * name is generated from the stack, stage, and logical id. Limited to
21 * 100 characters: letters, digits, underscores, hyphens, periods; first
22 * character must be alphanumeric. Immutable — changing it replaces the
23 * exclusion.
24 */
25 exclusionId?: string;
26 /**
27 * Advanced logs filter matching entries to exclude from the `_Default`
28 * sink. Required. Use `sample()` to exclude a fraction of matches.
29 */
30 filter: string;
31 /**
32 * Human-readable description. Logging exclusions have no labels field,
33 * so Alchemy ownership is stored in a `[alchemy …]` prefix and stripped
34 * from attributes.
35 */
36 description?: string;
37 /**
38 * When true, the exclusion exists but does not exclude any entries.
39 * @default false
40 */
41 disabled?: boolean;
42 };
43
44 export type Exclusion = Resource<
45 "GCP.Logging.Exclusion",
46 ExclusionProps,
47 {
48 /** Full resource name `projects/{project}/exclusions/{exclusionId}`. */
49 name: string;
50 /** Exclusion id (last path segment). */
51 exclusionId: string;
52 /** Project id. */
53 project: string;
54 /** Advanced logs filter. */
55 filter: string;
56 /** User description with the Alchemy ownership prefix stripped. */
57 description: string | undefined;
58 /** Whether the exclusion is disabled. */
59 disabled: boolean;
60 /** RFC3339 creation timestamp. */
61 createTime: string | undefined;
62 /** RFC3339 last-update timestamp. */
63 updateTime: string | undefined;
64 },
65 never,
66 Providers
67 >;
68
69 /**
70 * A Cloud Logging exclusion on the `_Default` sink.
71 *
72 * Exclusions drop matching log entries before they are stored in the
73 * `_Default` bucket (they do not apply to `_Required`). A project can have
74 * up to 10. Logging exclusions have no labels field, so Alchemy stamps
75 * ownership into the description for `list` / nuke. Name is identity —
76 * changing `exclusionId` replaces the exclusion.
77 *
78 * ### Creating an Exclusion
79 * **Example:** Generated name, drop debug logs
80 * ```typescript
81 * const exclusion = yield* GCP.Logging.Exclusion("DropDebug", {
82 * filter: "severity=DEBUG",
83 * description: "drop debug entries",
84 * });
85 * ```
86 *
87 * **Example:** Named exclusion
88 * ```typescript
89 * const exclusion = yield* GCP.Logging.Exclusion("DropDebug", {
90 * exclusionId: "drop-debug",
91 * filter: "severity=DEBUG",
92 * description: "drop debug entries",
93 * });
94 * ```
95 *
96 * ### Updating an Exclusion
97 * **Example:** Change the filter and disable
98 * ```typescript
99 * const exclusion = yield* GCP.Logging.Exclusion("DropDebug", {
100 * filter: "severity<ERROR",
101 * description: "drop non-errors",
102 * disabled: true,
103 * });
104 * ```
105 *
106 * @resource
107 * @category Logging
108 */
109 export const Exclusion = Resource<Exclusion>("GCP.Logging.Exclusion");
110
111 export class ExclusionNotResolved extends Data.TaggedError("GCP.Logging.ExclusionNotResolved")<{
112 resourceName: string;
113 }> {}
114
115 const lastSegment = (value: string) => {
116 const trimmed = value.replace(/\/+$/, "");
117 const parts = trimmed.split("/");
118 return parts[parts.length - 1] || trimmed;
119 };
120
121 const resourceName = (project: string, exclusionId: string) =>
122 `projects/${project}/exclusions/${exclusionId}`;
123
124 const exclusionIdOf = (exclusion: logging.LogExclusion) => {
125 const raw = exclusion.name ?? "";
126 return raw.includes("/") ? lastSegment(raw) : raw;
127 };
128
129 const toId = (id: string, exclusionId: string | undefined, existing?: string) =>
130 Effect.gen(function* () {
131 if (exclusionId !== undefined) return exclusionId;
132 if (existing !== undefined) return existing;
133 const generated = yield* createPhysicalName({
134 id,
135 maxLength: MAX_NAME_LENGTH,
136 lowercase: true,
137 });
138 return /^[a-z0-9]/.test(generated) ? generated : `e${generated}`.slice(0, MAX_NAME_LENGTH);
139 });
140
141 const encodeDescription = (
142 labels: Record<string, string>,
143 description: string | undefined,
144 ): string => {
145 const marker = `[alchemy ${alchemyLabelKeys.stack}=${labels[alchemyLabelKeys.stack]} ${alchemyLabelKeys.stage}=${labels[alchemyLabelKeys.stage]} ${alchemyLabelKeys.id}=${labels[alchemyLabelKeys.id]}]`;
146 return description ? `${marker}\n${description}` : marker;
147 };
148
149 const parseDescription = (
150 description: string | undefined,
151 ): {
152 labels: Record<string, string>;
153 description: string | undefined;
154 } => {
155 if (!description?.startsWith("[alchemy ")) {
156 return { labels: {}, description };
157 }
158 const end = description.indexOf("]");
159 if (end < 0) return { labels: {}, description };
160 const labels: Record<string, string> = {};
161 for (const part of description.slice("[alchemy ".length, end).split(/\s+/)) {
162 const eq = part.indexOf("=");
163 if (eq > 0) {
164 labels[part.slice(0, eq)] = part.slice(eq + 1);
165 }
166 }
167 const rest = description.slice(end + 1).replace(/^\n/, "");
168 return { labels, description: rest.length > 0 ? rest : undefined };
169 };
170
171 const hasOwnershipMarker = (description: string | undefined) =>
172 Object.keys(parseDescription(description).labels).some((key) => key.startsWith("alchemy-"));
173
174 const toAttrs = (exclusion: logging.LogExclusion, project: string) => {
175 const exclusionId = exclusionIdOf(exclusion);
176 const parsed = parseDescription(exclusion.description);
177 return {
178 name: exclusionId.includes("/")
179 ? exclusionId
180 : exclusion.name?.includes("/")
181 ? exclusion.name
182 : resourceName(project, exclusionId),
183 exclusionId,
184 project,
185 filter: exclusion.filter ?? "",
186 description: parsed.description,
187 disabled: exclusion.disabled === true,
188 createTime: exclusion.createTime,
189 updateTime: exclusion.updateTime,
190 };
191 };
192
193 const getByName = (name: string) =>
194 logging.getProjectsExclusions({ name }).pipe(Effect.catchTag("NotFound", () => Effect.undefined));
195
196 export const ExclusionProvider = () =>
197 Provider.succeed(Exclusion, {
198 stables: ["name", "exclusionId", "project", "createTime"],
199
200 diff: Effect.fn(function* ({ news, olds, output }) {
201 if (!isResolved(news)) return undefined;
202 const previous = olds?.exclusionId ?? output?.exclusionId;
203 if (
204 previous !== undefined &&
205 news.exclusionId !== undefined &&
206 news.exclusionId !== previous
207 ) {
208 return { action: "replace" as const, deleteFirst: false };
209 }
210 return undefined;
211 }),
212
213 read: Effect.fn(function* ({ id, olds, output }) {
214 const env = yield* GcpEnvironment.current;
215 const exclusionId = yield* toId(id, olds?.exclusionId, output?.exclusionId);
216 const name = output?.name ?? resourceName(env.project, exclusionId);
217 const existing = yield* getByName(name);
218 if (existing === undefined) return undefined;
219 const attrs = toAttrs(existing, env.project);
220 const { labels } = parseDescription(existing.description);
221 return (yield* hasAlchemyLabels(id, labels)) ? attrs : Unowned(attrs);
222 }),
223
224 list: () =>
225 Effect.gen(function* () {
226 const env = yield* GcpEnvironment.current;
227 return yield* logging.listProjectsExclusions
228 .pages({
229 parent: `projects/${env.project}`,
230 pageSize: 1000,
231 })
232 .pipe(
233 Stream.flatMap((page) => Stream.fromIterable(page.exclusions ?? [])),
234 Stream.filter((exclusion) => hasOwnershipMarker(exclusion.description)),
235 Stream.map((exclusion) => toAttrs(exclusion, env.project)),
236 Stream.runCollect,
237 Effect.map((chunk) => Array.from(chunk)),
238 );
239 }),
240
241 reconcile: Effect.fn(function* ({ id, news, output }) {
242 const env = yield* GcpEnvironment.current;
243 const exclusionId = yield* toId(id, news.exclusionId, output?.exclusionId);
244 const name = resourceName(env.project, exclusionId);
245 const ownership = yield* createInternalLabels(id);
246 const desiredDescription = encodeDescription(ownership, news.description);
247
248 let current = yield* getByName(output?.name ?? name);
249
250 if (current === undefined) {
251 const created = yield* logging
252 .createProjectsExclusions({
253 parent: `projects/${env.project}`,
254 body: {
255 name: exclusionId,
256 filter: news.filter,
257 description: desiredDescription,
258 disabled: news.disabled === true ? true : undefined,
259 },
260 })
261 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
262 current = created ?? undefined;
263 }
264
265 if (current === undefined) {
266 return yield* new ExclusionNotResolved({ resourceName: name });
267 }
268
269 const desiredDisabled = news.disabled === true;
270 const filterChanged = (current.filter ?? "") !== news.filter;
271 const descriptionChanged = (current.description ?? "") !== desiredDescription;
272 const disabledChanged = (current.disabled === true) !== desiredDisabled;
273
274 const updateMask = [
275 filterChanged ? "filter" : undefined,
276 descriptionChanged ? "description" : undefined,
277 disabledChanged ? "disabled" : undefined,
278 ].filter((field): field is string => field !== undefined);
279
280 if (updateMask.length > 0) {
281 current = yield* logging.patchProjectsExclusions({
282 name: current.name?.includes("/") ? current.name : name,
283 updateMask: updateMask.join(","),
284 body: {
285 filter: news.filter,
286 description: desiredDescription,
287 disabled: desiredDisabled,
288 },
289 });
290 }
291
292 return toAttrs(current, env.project);
293 }),
294
295 delete: Effect.fn(function* ({ output }) {
296 yield* logging
297 .deleteProjectsExclusions({ name: output.name })
298 .pipe(Effect.catchTag("NotFound", () => Effect.void));
299 }),
300 });