@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 408 lines 14.5 KB
Raw
1 import * as compute from "@distilled.cloud/gcp/compute_v1";
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 import { waitRegionOperation } from "./operations.ts";
14
15 export type RegionNotificationEndpointGrpcSettings = {
16 /**
17 * gRPCLB DNS name of the notification service
18 * (e.g. `example.googleapis.com` or `health.example.com:443`).
19 */
20 endpoint: string;
21 /**
22 * Seconds spent retrying notifications until a successful response.
23 * Default 30, max 1200.
24 */
25 retryDurationSec?: number;
26 /**
27 * Optional value written to the gRPC `name` field.
28 */
29 payloadName?: string;
30 /**
31 * Optional authority header sent with notifications.
32 */
33 authority?: string;
34 /**
35 * How often to resend a full update of unhealthy backends (600–3600s).
36 * Regional endpoints only.
37 */
38 resendInterval?: compute.Duration;
39 };
40
41 export type RegionNotificationEndpointProps = {
42 /**
43 * Endpoint name (RFC1035, 1-63 characters). If omitted, a unique name
44 * is generated from the stack, stage, and logical id. Changing it
45 * replaces the resource.
46 */
47 notificationEndpointName?: string;
48 /**
49 * Region the endpoint lives in (e.g. `us-central1`). Immutable —
50 * changing it replaces the resource. `US-CENTRAL1` is accepted and
51 * normalized to `us-central1`.
52 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
53 */
54 region?: string;
55 /**
56 * Optional description. Compute NotificationEndpoint has no labels
57 * field and no update API, so Alchemy ownership is stored in a
58 * `[alchemy …]` prefix and any description change replaces the
59 * endpoint.
60 */
61 description?: string;
62 /**
63 * gRPC notification settings. Immutable — changing any field replaces
64 * the endpoint.
65 */
66 grpcSettings: RegionNotificationEndpointGrpcSettings;
67 };
68
69 export type RegionNotificationEndpoint = Resource<
70 "GCP.Compute.RegionNotificationEndpoint",
71 RegionNotificationEndpointProps,
72 {
73 /** NotificationEndpoint name. */
74 notificationEndpointName: string;
75 /** Project id. */
76 project: string;
77 /** Region short name (`us-central1`). */
78 region: string;
79 /** User description with the Alchemy ownership prefix stripped. */
80 description: string | undefined;
81 /** gRPC endpoint DNS name. */
82 grpcEndpoint: string | undefined;
83 /** Retry duration in seconds. */
84 retryDurationSec: number | undefined;
85 /** Optional gRPC payload name. */
86 payloadName: string | undefined;
87 /** Optional authority header. */
88 authority: string | undefined;
89 /** Full-update resend interval, if set. */
90 resendInterval: compute.Duration | undefined;
91 /** Server-defined URL. */
92 selfLink: string | undefined;
93 /** Server-assigned numeric id. */
94 notificationEndpointId: string | undefined;
95 /** RFC3339 creation timestamp. */
96 creationTimestamp: string | undefined;
97 /** Resource kind. */
98 kind: string | undefined;
99 },
100 never,
101 Providers
102 >;
103
104 /**
105 * A regional Compute Engine notification endpoint.
106 *
107 * Notification endpoints receive gRPC callbacks when a health-check
108 * service detects backend status changes. This resource maps to the
109 * `regionNotificationEndpoints` collection. There is no update API and
110 * no labels field — Alchemy stamps ownership into the description so
111 * nuke can find leaked endpoints. Changing any user-facing field
112 * replaces the resource.
113 *
114 * ### Creating a Notification Endpoint
115 * **Example:** Generated name
116 * ```typescript
117 * const endpoint = yield* GCP.Compute.RegionNotificationEndpoint("Health", {
118 * region: "us-central1",
119 * grpcSettings: { endpoint: "health.example.com:443" },
120 * });
121 * ```
122 *
123 * **Example:** Named endpoint with retry settings
124 * ```typescript
125 * const endpoint = yield* GCP.Compute.RegionNotificationEndpoint("Health", {
126 * notificationEndpointName: "app-health",
127 * region: "us-central1",
128 * description: "regional health callbacks",
129 * grpcSettings: {
130 * endpoint: "health.example.com:443",
131 * retryDurationSec: 30,
132 * },
133 * });
134 * ```
135 *
136 * @resource
137 * @category Compute
138 */
139 export const RegionNotificationEndpoint = Resource<RegionNotificationEndpoint>(
140 "GCP.Compute.RegionNotificationEndpoint",
141 );
142
143 export class RegionNotificationEndpointNotResolved extends Data.TaggedError(
144 "GCP.Compute.RegionNotificationEndpointNotResolved",
145 )<{
146 notificationEndpointName: string;
147 region: string;
148 }> {}
149
150 const lastSegment = (value: string | undefined) => {
151 if (value === undefined || value.length === 0) return "";
152 const trimmed = value.replace(/\/+$/, "");
153 const parts = trimmed.split("/");
154 return parts[parts.length - 1] || trimmed;
155 };
156
157 const normalizeRegion = (region: string | undefined, defaultRegion: string) =>
158 lastSegment(region ?? defaultRegion).toLowerCase();
159
160 const toName = (id: string, name: string | undefined, existing?: string) =>
161 Effect.gen(function* () {
162 if (name !== undefined) return name;
163 if (existing !== undefined) return existing;
164 const generated = yield* createPhysicalName({
165 id,
166 maxLength: 63,
167 lowercase: true,
168 });
169 return /^[a-z]/.test(generated) ? generated : `n${generated}`.slice(0, 63);
170 });
171
172 const encodeDescription = (
173 labels: Record<string, string>,
174 description: string | undefined,
175 ): string => {
176 const marker = `[alchemy ${alchemyLabelKeys.stack}=${labels[alchemyLabelKeys.stack]} ${alchemyLabelKeys.stage}=${labels[alchemyLabelKeys.stage]} ${alchemyLabelKeys.id}=${labels[alchemyLabelKeys.id]}]`;
177 return description ? `${marker}\n${description}` : marker;
178 };
179
180 const parseDescription = (
181 description: string | undefined,
182 ): {
183 labels: Record<string, string>;
184 description: string | undefined;
185 } => {
186 if (!description?.startsWith("[alchemy ")) {
187 return { labels: {}, description };
188 }
189 const end = description.indexOf("]");
190 if (end < 0) return { labels: {}, description };
191 const labels: Record<string, string> = {};
192 for (const part of description.slice("[alchemy ".length, end).split(/\s+/)) {
193 const eq = part.indexOf("=");
194 if (eq > 0) {
195 labels[part.slice(0, eq)] = part.slice(eq + 1);
196 }
197 }
198 const rest = description.slice(end + 1).replace(/^\n/, "");
199 return { labels, description: rest.length > 0 ? rest : undefined };
200 };
201
202 const hasOwnershipMarker = (description: string | undefined) =>
203 Object.keys(parseDescription(description).labels).some((key) => key.startsWith("alchemy-"));
204
205 const sameInterval = (left: compute.Duration | undefined, right: compute.Duration | undefined) =>
206 (left?.seconds ?? "") === (right?.seconds ?? "") && (left?.nanos ?? 0) === (right?.nanos ?? 0);
207
208 const toAttrs = (endpoint: compute.NotificationEndpoint, project: string) => {
209 const parsed = parseDescription(endpoint.description);
210 return {
211 notificationEndpointName: endpoint.name ?? endpoint.id ?? "",
212 project,
213 region: lastSegment(endpoint.region).toLowerCase(),
214 description: parsed.description,
215 grpcEndpoint: endpoint.grpcSettings?.endpoint,
216 retryDurationSec: endpoint.grpcSettings?.retryDurationSec,
217 payloadName: endpoint.grpcSettings?.payloadName,
218 authority: endpoint.grpcSettings?.authority,
219 resendInterval: endpoint.grpcSettings?.resendInterval,
220 selfLink: endpoint.selfLink,
221 notificationEndpointId: endpoint.id,
222 creationTimestamp: endpoint.creationTimestamp,
223 kind: endpoint.kind,
224 };
225 };
226
227 const getByName = (project: string, region: string, notificationEndpoint: string) =>
228 compute
229 .getRegionNotificationEndpoints({
230 project,
231 region,
232 notificationEndpoint,
233 })
234 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
235
236 const immutableChanged = (
237 news: RegionNotificationEndpointProps,
238 olds: RegionNotificationEndpointProps | undefined,
239 output: RegionNotificationEndpoint["Attributes"] | undefined,
240 ) => {
241 const previousDescription = olds?.description ?? output?.description ?? "";
242 if ((news.description ?? "") !== previousDescription) return true;
243 const previousEndpoint = olds?.grpcSettings.endpoint ?? output?.grpcEndpoint ?? "";
244 if (news.grpcSettings.endpoint !== previousEndpoint) return true;
245 const previousRetry = olds?.grpcSettings.retryDurationSec ?? output?.retryDurationSec;
246 if (
247 news.grpcSettings.retryDurationSec !== undefined &&
248 news.grpcSettings.retryDurationSec !== previousRetry
249 ) {
250 return true;
251 }
252 const previousPayload = olds?.grpcSettings.payloadName ?? output?.payloadName ?? "";
253 if ((news.grpcSettings.payloadName ?? "") !== previousPayload) return true;
254 const previousAuthority = olds?.grpcSettings.authority ?? output?.authority ?? "";
255 if ((news.grpcSettings.authority ?? "") !== previousAuthority) return true;
256 if (
257 news.grpcSettings.resendInterval !== undefined &&
258 !sameInterval(
259 news.grpcSettings.resendInterval,
260 olds?.grpcSettings.resendInterval ?? output?.resendInterval,
261 )
262 ) {
263 return true;
264 }
265 return false;
266 };
267
268 export const RegionNotificationEndpointProvider = () =>
269 Provider.succeed(RegionNotificationEndpoint, {
270 stables: [
271 "notificationEndpointName",
272 "project",
273 "region",
274 "notificationEndpointId",
275 "selfLink",
276 "creationTimestamp",
277 ],
278
279 diff: Effect.fn(function* ({ news, olds, output }) {
280 if (!isResolved(news)) return undefined;
281 const env = yield* GcpEnvironment.current;
282 const previousName = olds?.notificationEndpointName ?? output?.notificationEndpointName;
283 const nextName = news.notificationEndpointName ?? previousName;
284 const previousRegion = normalizeRegion(olds?.region ?? output?.region, env.region);
285 const nextRegion = normalizeRegion(news.region ?? output?.region, env.region);
286 const regionChanged = previousRegion !== nextRegion;
287 const nameChanged =
288 previousName !== undefined && nextName !== undefined && previousName !== nextName;
289 if (nameChanged || regionChanged || immutableChanged(news, olds, output)) {
290 return {
291 action: "replace" as const,
292 deleteFirst: !regionChanged,
293 };
294 }
295 return undefined;
296 }),
297
298 read: Effect.fn(function* ({ id, olds, output }) {
299 const env = yield* GcpEnvironment.current;
300 const notificationEndpointName = yield* toName(
301 id,
302 olds?.notificationEndpointName,
303 output?.notificationEndpointName,
304 );
305 const region = normalizeRegion(olds?.region ?? output?.region, env.region);
306 const existing = yield* getByName(env.project, region, notificationEndpointName);
307 if (existing === undefined) return undefined;
308 const attrs = toAttrs(existing, env.project);
309 const { labels } = parseDescription(existing.description);
310 return (yield* hasAlchemyLabels(id, labels)) ? attrs : Unowned(attrs);
311 }),
312
313 list: () =>
314 Effect.gen(function* () {
315 const env = yield* GcpEnvironment.current;
316 const pages = yield* compute.aggregatedListRegionNotificationEndpoints
317 .pages({
318 project: env.project,
319 returnPartialSuccess: true,
320 maxResults: 500,
321 })
322 .pipe(Stream.runCollect);
323 return Array.from(pages).flatMap((page) =>
324 Object.values(page.items ?? {}).flatMap((scoped) =>
325 (scoped?.resources ?? [])
326 .filter((endpoint) => hasOwnershipMarker(endpoint.description))
327 .map((endpoint) => toAttrs(endpoint, env.project)),
328 ),
329 );
330 }),
331
332 reconcile: Effect.fn(function* ({ id, news, output }) {
333 const env = yield* GcpEnvironment.current;
334 const notificationEndpointName = yield* toName(
335 id,
336 news.notificationEndpointName,
337 output?.notificationEndpointName,
338 );
339 const region = normalizeRegion(news.region ?? output?.region, env.region);
340 const ownership = yield* createInternalLabels(id);
341 const desiredDescription = encodeDescription(ownership, news.description);
342
343 let current = yield* getByName(env.project, region, notificationEndpointName);
344
345 if (current === undefined) {
346 const grpcSettings: compute.NotificationEndpointGrpcSettings = {
347 endpoint: news.grpcSettings.endpoint,
348 };
349 if (news.grpcSettings.retryDurationSec !== undefined) {
350 grpcSettings.retryDurationSec = news.grpcSettings.retryDurationSec;
351 }
352 if (news.grpcSettings.payloadName !== undefined) {
353 grpcSettings.payloadName = news.grpcSettings.payloadName;
354 }
355 if (news.grpcSettings.authority !== undefined) {
356 grpcSettings.authority = news.grpcSettings.authority;
357 }
358 if (news.grpcSettings.resendInterval !== undefined) {
359 grpcSettings.resendInterval = news.grpcSettings.resendInterval;
360 }
361 yield* compute
362 .insertRegionNotificationEndpoints({
363 project: env.project,
364 region,
365 body: {
366 name: notificationEndpointName,
367 description: desiredDescription,
368 grpcSettings,
369 },
370 })
371 .pipe(
372 Effect.flatMap((operation) =>
373 waitRegionOperation(env.project, region, operation, {
374 ignore: ["RESOURCE_ALREADY_EXISTS"],
375 }),
376 ),
377 Effect.catchTag("Conflict", () => Effect.undefined),
378 );
379 current = yield* getByName(env.project, region, notificationEndpointName);
380 }
381
382 if (current === undefined) {
383 return yield* new RegionNotificationEndpointNotResolved({
384 notificationEndpointName,
385 region,
386 });
387 }
388
389 return toAttrs(current, env.project);
390 }),
391
392 delete: Effect.fn(function* ({ output }) {
393 const env = yield* GcpEnvironment.current;
394 const region = normalizeRegion(output.region, env.region);
395 const operation = yield* compute
396 .deleteRegionNotificationEndpoints({
397 project: env.project,
398 region,
399 notificationEndpoint: output.notificationEndpointName,
400 })
401 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
402 if (operation !== undefined) {
403 yield* waitRegionOperation(env.project, region, operation).pipe(
404 Effect.catchTag("NotFound", () => Effect.void),
405 );
406 }
407 }),
408 });