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

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