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