@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, 04:45 UTC

main
ts 355 lines 11.6 KB
Raw
1 import * as monitoring from "@distilled.cloud/gcp/monitoring_v3";
2 import { unownedUnlessPrevious } 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 { tagRecord } from "alchemy/Tags";
8 import * as Data from "effect/Data";
9 import * as Effect from "effect/Effect";
10 import * as Stream from "effect/Stream";
11 import { GcpEnvironment } from "../Environment.ts";
12 import {
13 createInternalLabels,
14 diffLabels,
15 hasAlchemyLabels,
16 stripInternalLabels,
17 toLabels,
18 } from "../Labels.ts";
19 import type { Providers } from "../Providers.ts";
20
21 const MAX_DISPLAY_NAME_LENGTH = 512;
22
23 export type NotificationChannelProps = {
24 /**
25 * Channel type. Must match a `NotificationChannelDescriptor.type`
26 * (`email`, `webhook_tokenauth`, `pubsub`, `slack`, …). Immutable —
27 * changing it replaces the channel.
28 */
29 type: string;
30 /**
31 * Human-readable display name. If omitted, a unique name is generated
32 * from the stack, stage, and logical id. Limited to 512 Unicode
33 * characters.
34 */
35 displayName?: string;
36 /**
37 * Human-readable description. Limited to 1024 Unicode characters.
38 */
39 description?: string;
40 /**
41 * Type-specific configuration (for example `email_address` for `email`,
42 * `url` for `webhook_tokenauth`). Not used for Alchemy ownership —
43 * see `userLabels`.
44 */
45 labels?: Record<string, string>;
46 /**
47 * User labels. Alchemy ownership labels are merged in automatically.
48 */
49 userLabels?: Record<string, string>;
50 /**
51 * Whether notifications are forwarded to this channel.
52 * @default true
53 */
54 enabled?: boolean;
55 };
56
57 export type NotificationChannel = Resource<
58 "GCP.Monitoring.NotificationChannel",
59 NotificationChannelProps,
60 {
61 /** Full resource name `projects/{project}/notificationChannels/{channel}`. */
62 name: string;
63 /** Server-assigned channel id (last path segment). */
64 notificationChannelId: string;
65 /** Project id. */
66 project: string;
67 /** Channel type (`email`, `webhook_tokenauth`, …). */
68 type: string;
69 /** Human-readable display name. */
70 displayName: string | undefined;
71 /** Human-readable description. */
72 description: string | undefined;
73 /** Type-specific configuration labels. */
74 labels: Record<string, string>;
75 /** User labels (Alchemy ownership labels stripped). */
76 userLabels: Record<string, string>;
77 /** Whether notifications are forwarded to this channel. */
78 enabled: boolean;
79 /** Verification status (`UNVERIFIED`, `VERIFIED`, or unset). */
80 verificationStatus: string | undefined;
81 },
82 never,
83 Providers
84 >;
85
86 /**
87 * A Cloud Monitoring notification channel — email, webhook, Pub/Sub, or
88 * another supported delivery type.
89 *
90 * Channel ids are assigned by the API. Alchemy stamps ownership into
91 * `userLabels` so `list` / `pnpm nuke:gcp` can find them. Changing `type`
92 * replaces the channel. Display name, description, labels, user labels,
93 * and enabled update in place.
94 *
95 * ### Creating a Channel
96 * **Example:** Email channel
97 * ```typescript
98 * const channel = yield* GCP.Monitoring.NotificationChannel("Alerts", {
99 * type: "email",
100 * labels: { email_address: "alerts@example.com" },
101 * });
102 * ```
103 *
104 * **Example:** Webhook channel with user labels
105 * ```typescript
106 * const channel = yield* GCP.Monitoring.NotificationChannel("Hooks", {
107 * type: "webhook_tokenauth",
108 * displayName: "incident webhook",
109 * labels: { url: "https://example.com/hooks/alerts" },
110 * userLabels: { env: "prod" },
111 * });
112 * ```
113 *
114 * ### Updating a Channel
115 * **Example:** Disable delivery without deleting the channel
116 * ```typescript
117 * const channel = yield* GCP.Monitoring.NotificationChannel("Alerts", {
118 * type: "email",
119 * labels: { email_address: "alerts@example.com" },
120 * enabled: false,
121 * });
122 * ```
123 *
124 * @resource
125 * @category Monitoring
126 */
127 export const NotificationChannel = Resource<NotificationChannel>(
128 "GCP.Monitoring.NotificationChannel",
129 );
130
131 export class NotificationChannelNotResolved extends Data.TaggedError(
132 "GCP.Monitoring.NotificationChannelNotResolved",
133 )<{
134 resourceName: string;
135 }> {}
136
137 const lastSegment = (value: string) => {
138 const trimmed = value.replace(/\/+$/, "");
139 const parts = trimmed.split("/");
140 return parts[parts.length - 1] || trimmed;
141 };
142
143 const parentOf = (project: string) => `projects/${project}`;
144
145 const userFacingLabels = (
146 labels: Record<string, string | undefined> | null | undefined,
147 ): Record<string, string> => stripInternalLabels(tagRecord(labels));
148
149 const channelLabels = (
150 labels: Record<string, string | undefined> | null | undefined,
151 ): Record<string, string> => tagRecord(labels);
152
153 const recordsEqual = (left: Record<string, string>, right: Record<string, string>) => {
154 const leftKeys = Object.keys(left).sort();
155 const rightKeys = Object.keys(right).sort();
156 return (
157 leftKeys.length === rightKeys.length &&
158 leftKeys.every((key, index) => key === rightKeys[index] && left[key] === right[key])
159 );
160 };
161
162 const toDisplayName = (id: string, displayName: string | undefined, existing?: string) =>
163 Effect.gen(function* () {
164 return (
165 displayName ??
166 existing ??
167 (yield* createPhysicalName({
168 id,
169 maxLength: MAX_DISPLAY_NAME_LENGTH,
170 lowercase: true,
171 }))
172 );
173 });
174
175 const toAttrs = (channel: monitoring.NotificationChannel, project: string) => {
176 const name = channel.name ?? "";
177 return {
178 name,
179 notificationChannelId: lastSegment(name),
180 project,
181 type: channel.type ?? "",
182 displayName: channel.displayName,
183 description: channel.description,
184 labels: channelLabels(channel.labels),
185 userLabels: userFacingLabels(channel.userLabels),
186 enabled: channel.enabled !== false,
187 verificationStatus: channel.verificationStatus,
188 };
189 };
190
191 const getByName = (name: string) =>
192 monitoring
193 .getProjectsNotificationChannels({ name })
194 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
195
196 const listOwned = (project: string) =>
197 monitoring.listProjectsNotificationChannels
198 .pages({
199 name: parentOf(project),
200 pageSize: 1000,
201 })
202 .pipe(
203 Stream.flatMap((page) => Stream.fromIterable(page.notificationChannels ?? [])),
204 Stream.filter((channel) =>
205 Object.keys(channel.userLabels ?? {}).some((key) => key.startsWith("alchemy-")),
206 ),
207 Stream.map((channel) => toAttrs(channel, project)),
208 Stream.runCollect,
209 Effect.map((chunk) => Array.from(chunk)),
210 Effect.catchTag("NotFound", () => Effect.succeed([])),
211 );
212
213 const findOwned = (project: string, id: string) =>
214 Effect.gen(function* () {
215 const owned = yield* monitoring.listProjectsNotificationChannels
216 .pages({
217 name: parentOf(project),
218 pageSize: 1000,
219 })
220 .pipe(
221 Stream.flatMap((page) => Stream.fromIterable(page.notificationChannels ?? [])),
222 Stream.runCollect,
223 Effect.map((chunk) => Array.from(chunk)),
224 Effect.catchTag("NotFound", () => Effect.succeed([])),
225 );
226 for (const channel of owned) {
227 if (yield* hasAlchemyLabels(id, tagRecord(channel.userLabels))) {
228 return channel;
229 }
230 }
231 return undefined;
232 });
233
234 const observe = (project: string, id: string, name: string | undefined) =>
235 Effect.gen(function* () {
236 if (name !== undefined) {
237 const existing = yield* getByName(name);
238 if (existing !== undefined) return existing;
239 }
240 return yield* findOwned(project, id);
241 });
242
243 export const NotificationChannelProvider = () =>
244 Provider.succeed(NotificationChannel, {
245 stables: ["name", "notificationChannelId", "project"],
246
247 diff: Effect.fn(function* ({ news, olds, output }) {
248 if (!isResolved(news)) return undefined;
249 const previous = olds?.type ?? output?.type;
250 if (previous !== undefined && news.type !== previous) {
251 return { action: "replace" as const, deleteFirst: true };
252 }
253 return undefined;
254 }),
255
256 read: Effect.fn(function* ({ id, output, previous }) {
257 const env = yield* GcpEnvironment.current;
258 const existing = yield* observe(env.project, id, output?.name);
259 if (existing === undefined) return undefined;
260 const attrs = toAttrs(existing, env.project);
261 return (yield* hasAlchemyLabels(id, tagRecord(existing.userLabels)))
262 ? attrs
263 : unownedUnlessPrevious(attrs, previous, "name");
264 }),
265
266 list: () =>
267 Effect.gen(function* () {
268 const env = yield* GcpEnvironment.current;
269 return yield* listOwned(env.project);
270 }),
271
272 reconcile: Effect.fn(function* ({ id, news, output }) {
273 const env = yield* GcpEnvironment.current;
274 const displayName = yield* toDisplayName(id, news.displayName, output?.displayName);
275 const desiredUserLabels = {
276 ...toLabels(news.userLabels),
277 ...(yield* createInternalLabels(id)),
278 };
279 const desiredLabels = news.labels ?? {};
280 const desiredEnabled = news.enabled !== false;
281 const desiredDescription = news.description ?? "";
282
283 let current = yield* observe(env.project, id, output?.name);
284 if (current !== undefined && (current.type ?? "") !== news.type) {
285 current = undefined;
286 }
287
288 if (current === undefined) {
289 const created = yield* monitoring
290 .createProjectsNotificationChannels({
291 name: parentOf(env.project),
292 body: {
293 type: news.type,
294 displayName,
295 description: news.description,
296 labels: desiredLabels,
297 userLabels: desiredUserLabels,
298 enabled: desiredEnabled,
299 },
300 })
301 .pipe(Effect.catchTag("Conflict", () => findOwned(env.project, id)));
302 current = created ?? undefined;
303 }
304
305 if (current === undefined) {
306 return yield* new NotificationChannelNotResolved({
307 resourceName: output?.name ?? displayName,
308 });
309 }
310
311 const name = current.name ?? output?.name ?? "";
312 const observedUserLabels = tagRecord(current.userLabels);
313 const { upsert, removed } = diffLabels(observedUserLabels, desiredUserLabels);
314 const userLabelsChanged = upsert.length > 0 || removed.length > 0;
315 const labelsChanged = !recordsEqual(channelLabels(current.labels), desiredLabels);
316 const displayNameChanged = (current.displayName ?? "") !== displayName;
317 const descriptionChanged = (current.description ?? "") !== desiredDescription;
318 const enabledChanged = (current.enabled !== false) !== desiredEnabled;
319
320 const updateMask = [
321 displayNameChanged ? "display_name" : undefined,
322 descriptionChanged ? "description" : undefined,
323 labelsChanged ? "labels" : undefined,
324 userLabelsChanged ? "user_labels" : undefined,
325 enabledChanged ? "enabled" : undefined,
326 ].filter((field): field is string => field !== undefined);
327
328 if (updateMask.length > 0) {
329 current = yield* monitoring.patchProjectsNotificationChannels({
330 name,
331 updateMask: updateMask.join(","),
332 body: {
333 name,
334 type: news.type,
335 displayName,
336 description: news.description ?? "",
337 labels: desiredLabels,
338 userLabels: desiredUserLabels,
339 enabled: desiredEnabled,
340 },
341 });
342 }
343
344 return toAttrs(current, env.project);
345 }),
346
347 delete: Effect.fn(function* ({ output }) {
348 yield* monitoring
349 .deleteProjectsNotificationChannels({
350 name: output.name,
351 force: true,
352 })
353 .pipe(Effect.catchTag("NotFound", () => Effect.void));
354 }),
355 });