@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 419 lines 13 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 Schedule from "effect/Schedule";
10 import * as Stream from "effect/Stream";
11 import { GcpEnvironment } from "../Environment.ts";
12 import { alchemyLabelKeys, createInternalLabels, hasAlchemyLabels } from "../Labels.ts";
13 import type { Providers } from "../Providers.ts";
14 import { waitGlobalOperation } from "./operations.ts";
15
16 const DEFAULT_CHECK_INTERVAL = 5;
17 const DEFAULT_TIMEOUT = 5;
18 const DEFAULT_HEALTHY = 2;
19 const DEFAULT_UNHEALTHY = 2;
20 const DEFAULT_PORT = 80;
21 const DEFAULT_REQUEST_PATH = "/";
22
23 export type HttpHealthCheckProps = {
24 /**
25 * Health check name (RFC1035, 1-63 chars). If omitted, a unique name is
26 * generated from the stack, stage, and logical id. Changing it replaces
27 * the resource.
28 */
29 httpHealthCheckName?: string;
30 /**
31 * Optional description. Alchemy ownership is stored in a `[alchemy …]`
32 * prefix so `list` / nuke can find resources (legacy HttpHealthCheck has
33 * no labels field).
34 */
35 description?: string;
36 /**
37 * How often to probe, in seconds.
38 * @default 5
39 */
40 checkIntervalSec?: number;
41 /**
42 * Probe timeout in seconds. Must be ≤ `checkIntervalSec`.
43 * @default 5
44 */
45 timeoutSec?: number;
46 /**
47 * Consecutive successes before an instance is healthy.
48 * @default 2
49 */
50 healthyThreshold?: number;
51 /**
52 * Consecutive failures before an instance is unhealthy.
53 * @default 2
54 */
55 unhealthyThreshold?: number;
56 /**
57 * TCP port for the HTTP probe.
58 * @default 80
59 */
60 port?: number;
61 /**
62 * Request path. Query parameters are not supported.
63 * @default "/"
64 */
65 requestPath?: string;
66 /**
67 * Host header. Empty uses the destination IP.
68 */
69 host?: string;
70 };
71
72 export type HttpHealthCheck = Resource<
73 "GCP.Compute.HttpHealthCheck",
74 HttpHealthCheckProps,
75 {
76 /** Health check name. */
77 httpHealthCheckName: string;
78 /** Project id. */
79 project: string;
80 /** User description with the Alchemy ownership prefix stripped. */
81 description: string | undefined;
82 /** Probe interval in seconds. */
83 checkIntervalSec: number;
84 /** Probe timeout in seconds. */
85 timeoutSec: number;
86 /** Consecutive successes before healthy. */
87 healthyThreshold: number;
88 /** Consecutive failures before unhealthy. */
89 unhealthyThreshold: number;
90 /** TCP port. */
91 port: number;
92 /** Request path. */
93 requestPath: string;
94 /** Host header, if set. */
95 host: string | undefined;
96 /** Server-defined URL. */
97 selfLink: string | undefined;
98 /** Server-assigned numeric id. */
99 httpHealthCheckId: string | undefined;
100 /** RFC3339 creation timestamp. */
101 creationTimestamp: string | undefined;
102 /** Resource kind. */
103 kind: string | undefined;
104 },
105 never,
106 Providers
107 >;
108
109 /**
110 * A legacy global Compute Engine HTTP health check.
111 *
112 * Legacy HTTP health checks are required by target-pool network load
113 * balancers. Other load balancers and MIG autohealing should use
114 * `HealthCheck`. Compute HttpHealthCheck has no labels field — Alchemy
115 * ownership is stored in the description so nuke can find leaked checks.
116 *
117 * ### Creating an HTTP Health Check
118 * **Example:** Generated name
119 * ```typescript
120 * const check = yield* GCP.Compute.HttpHealthCheck("api", {});
121 * ```
122 *
123 * **Example:** Path, port, and interval
124 * ```typescript
125 * const check = yield* GCP.Compute.HttpHealthCheck("api", {
126 * description: "frontend /health",
127 * port: 80,
128 * requestPath: "/health",
129 * checkIntervalSec: 10,
130 * timeoutSec: 5,
131 * });
132 * ```
133 *
134 * ### Target Pools
135 * **Example:** Attach to a target pool
136 * ```typescript
137 * const check = yield* GCP.Compute.HttpHealthCheck("api", {
138 * requestPath: "/health",
139 * });
140 * const pool = yield* GCP.Compute.TargetPool("backends", {
141 * healthChecks: [check.httpHealthCheckName],
142 * });
143 * ```
144 *
145 * @resource
146 * @category Compute
147 */
148 export const HttpHealthCheck = Resource<HttpHealthCheck>("GCP.Compute.HttpHealthCheck");
149
150 export class HttpHealthCheckNotResolved extends Data.TaggedError(
151 "GCP.Compute.HttpHealthCheckNotResolved",
152 )<{
153 httpHealthCheckName: string;
154 }> {}
155
156 const rfc1035 = (name: string): string => {
157 let next = name
158 .toLowerCase()
159 .replace(/[^a-z0-9-]/g, "-")
160 .replace(/-+/g, "-")
161 .replace(/^-+/, "")
162 .replace(/-+$/, "");
163 if (!/^[a-z]/.test(next)) {
164 next = `h${next}`;
165 }
166 next = next.slice(0, 63).replace(/-+$/, "");
167 return next.length > 0 ? next : "httphealthcheck";
168 };
169
170 const toName = (id: string, name: string | undefined, existing?: string) =>
171 Effect.gen(function* () {
172 if (name !== undefined) return name;
173 if (existing !== undefined) return existing;
174 return rfc1035(
175 yield* createPhysicalName({
176 id,
177 maxLength: 63,
178 lowercase: true,
179 }),
180 );
181 });
182
183 const encodeDescription = (
184 labels: Record<string, string>,
185 description: string | undefined,
186 ): string => {
187 const marker = `[alchemy ${alchemyLabelKeys.stack}=${labels[alchemyLabelKeys.stack]} ${alchemyLabelKeys.stage}=${labels[alchemyLabelKeys.stage]} ${alchemyLabelKeys.id}=${labels[alchemyLabelKeys.id]}]`;
188 return description ? `${marker}\n${description}` : marker;
189 };
190
191 const parseDescription = (
192 description: string | undefined,
193 ): {
194 labels: Record<string, string>;
195 description: string | undefined;
196 } => {
197 if (!description?.startsWith("[alchemy ")) {
198 return { labels: {}, description };
199 }
200 const end = description.indexOf("]");
201 if (end < 0) return { labels: {}, description };
202 const labels: Record<string, string> = {};
203 for (const part of description.slice("[alchemy ".length, end).split(/\s+/)) {
204 const eq = part.indexOf("=");
205 if (eq > 0) {
206 labels[part.slice(0, eq)] = part.slice(eq + 1);
207 }
208 }
209 const rest = description.slice(end + 1).replace(/^\n/, "");
210 return { labels, description: rest.length > 0 ? rest : undefined };
211 };
212
213 const toBody = (
214 httpHealthCheckName: string,
215 props: HttpHealthCheckProps,
216 ownership: Record<string, string>,
217 ): compute.HttpHealthCheck => ({
218 name: httpHealthCheckName,
219 description: encodeDescription(ownership, props.description),
220 checkIntervalSec: props.checkIntervalSec ?? DEFAULT_CHECK_INTERVAL,
221 timeoutSec: props.timeoutSec ?? DEFAULT_TIMEOUT,
222 healthyThreshold: props.healthyThreshold ?? DEFAULT_HEALTHY,
223 unhealthyThreshold: props.unhealthyThreshold ?? DEFAULT_UNHEALTHY,
224 port: props.port ?? DEFAULT_PORT,
225 requestPath: props.requestPath ?? DEFAULT_REQUEST_PATH,
226 host: props.host,
227 });
228
229 const toAttrs = (
230 check: compute.HttpHealthCheck,
231 project: string,
232 ): HttpHealthCheck["Attributes"] => {
233 const parsed = parseDescription(check.description);
234 const host = check.host && check.host.length > 0 ? check.host : undefined;
235 return {
236 httpHealthCheckName: check.name ?? check.id ?? "",
237 project,
238 description: parsed.description,
239 checkIntervalSec: check.checkIntervalSec ?? DEFAULT_CHECK_INTERVAL,
240 timeoutSec: check.timeoutSec ?? DEFAULT_TIMEOUT,
241 healthyThreshold: check.healthyThreshold ?? DEFAULT_HEALTHY,
242 unhealthyThreshold: check.unhealthyThreshold ?? DEFAULT_UNHEALTHY,
243 port: check.port ?? DEFAULT_PORT,
244 requestPath: check.requestPath ?? DEFAULT_REQUEST_PATH,
245 host,
246 selfLink: check.selfLink,
247 httpHealthCheckId: check.id,
248 creationTimestamp: check.creationTimestamp,
249 kind: check.kind,
250 };
251 };
252
253 const needsUpdate = (current: compute.HttpHealthCheck, desired: compute.HttpHealthCheck) => {
254 if ((current.description ?? "") !== (desired.description ?? "")) return true;
255 if (
256 (current.checkIntervalSec ?? DEFAULT_CHECK_INTERVAL) !==
257 (desired.checkIntervalSec ?? DEFAULT_CHECK_INTERVAL)
258 ) {
259 return true;
260 }
261 if ((current.timeoutSec ?? DEFAULT_TIMEOUT) !== (desired.timeoutSec ?? DEFAULT_TIMEOUT)) {
262 return true;
263 }
264 if (
265 (current.healthyThreshold ?? DEFAULT_HEALTHY) !== (desired.healthyThreshold ?? DEFAULT_HEALTHY)
266 ) {
267 return true;
268 }
269 if (
270 (current.unhealthyThreshold ?? DEFAULT_UNHEALTHY) !==
271 (desired.unhealthyThreshold ?? DEFAULT_UNHEALTHY)
272 ) {
273 return true;
274 }
275 if ((current.port ?? DEFAULT_PORT) !== (desired.port ?? DEFAULT_PORT)) {
276 return true;
277 }
278 if (
279 (current.requestPath ?? DEFAULT_REQUEST_PATH) !== (desired.requestPath ?? DEFAULT_REQUEST_PATH)
280 ) {
281 return true;
282 }
283 return (current.host ?? "") !== (desired.host ?? "");
284 };
285
286 const getByName = (project: string, httpHealthCheck: string) =>
287 compute
288 .getHttpHealthChecks({ project, httpHealthCheck })
289 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
290
291 const awaitResource = (project: string, httpHealthCheckName: string) =>
292 getByName(project, httpHealthCheckName).pipe(
293 Effect.repeat({
294 schedule: Schedule.spaced("1 second"),
295 until: (check) => check !== undefined,
296 times: 8,
297 }),
298 );
299
300 export const HttpHealthCheckProvider = () =>
301 Provider.succeed(HttpHealthCheck, {
302 stables: [
303 "httpHealthCheckName",
304 "project",
305 "httpHealthCheckId",
306 "selfLink",
307 "creationTimestamp",
308 ],
309
310 diff: Effect.fn(function* ({ news, olds, output }) {
311 if (!isResolved(news)) return undefined;
312 const previousName = olds?.httpHealthCheckName ?? output?.httpHealthCheckName;
313 const nextName = news.httpHealthCheckName;
314 if (previousName !== undefined && nextName !== undefined && previousName !== nextName) {
315 return { action: "replace" as const };
316 }
317 return undefined;
318 }),
319
320 read: Effect.fn(function* ({ id, olds, output }) {
321 const env = yield* GcpEnvironment.current;
322 const httpHealthCheckName = yield* toName(
323 id,
324 olds?.httpHealthCheckName,
325 output?.httpHealthCheckName,
326 );
327 const existing = yield* getByName(env.project, httpHealthCheckName);
328 if (existing === undefined) return undefined;
329 const attrs = toAttrs(existing, env.project);
330 const { labels } = parseDescription(existing.description);
331 return (yield* hasAlchemyLabels(id, labels)) ? attrs : Unowned(attrs);
332 }),
333
334 list: () =>
335 Effect.gen(function* () {
336 const env = yield* GcpEnvironment.current;
337 return yield* compute.listHttpHealthChecks
338 .items({ project: env.project, maxResults: 500 })
339 .pipe(
340 Stream.filter((check) => {
341 const { labels } = parseDescription(check.description);
342 return Object.keys(labels).some((key) => key.startsWith("alchemy-"));
343 }),
344 Stream.map((check) => toAttrs(check, env.project)),
345 Stream.runCollect,
346 Effect.map((chunk) => Array.from(chunk)),
347 );
348 }),
349
350 reconcile: Effect.fn(function* ({ id, news, output }) {
351 const env = yield* GcpEnvironment.current;
352 const httpHealthCheckName = yield* toName(
353 id,
354 news.httpHealthCheckName,
355 output?.httpHealthCheckName,
356 );
357 const ownership = yield* createInternalLabels(id);
358 const desired = toBody(httpHealthCheckName, news, ownership);
359
360 let current = yield* getByName(env.project, httpHealthCheckName);
361
362 if (current === undefined) {
363 yield* compute
364 .insertHttpHealthChecks({
365 project: env.project,
366 body: desired,
367 })
368 .pipe(
369 Effect.flatMap((operation) => waitGlobalOperation(env.project, operation)),
370 Effect.catchTag("Conflict", () => Effect.undefined),
371 );
372 current = yield* awaitResource(env.project, httpHealthCheckName);
373 }
374
375 if (current === undefined) {
376 return yield* new HttpHealthCheckNotResolved({ httpHealthCheckName });
377 }
378
379 if (needsUpdate(current, desired)) {
380 yield* compute
381 .patchHttpHealthChecks({
382 project: env.project,
383 httpHealthCheck: httpHealthCheckName,
384 body: desired,
385 })
386 .pipe(Effect.flatMap((operation) => waitGlobalOperation(env.project, operation)));
387 current = yield* getByName(env.project, httpHealthCheckName);
388 if (current === undefined) {
389 return yield* new HttpHealthCheckNotResolved({
390 httpHealthCheckName,
391 });
392 }
393 }
394
395 return toAttrs(current, env.project);
396 }),
397
398 delete: Effect.fn(function* ({ output }) {
399 const env = yield* GcpEnvironment.current;
400 const operation = yield* compute
401 .deleteHttpHealthChecks({
402 project: env.project,
403 httpHealthCheck: output.httpHealthCheckName,
404 })
405 .pipe(
406 Effect.retry({
407 while: (error) => error._tag === "Conflict",
408 schedule: Schedule.spaced("2 seconds"),
409 times: 8,
410 }),
411 Effect.catchTag("NotFound", () => Effect.undefined),
412 );
413 if (operation !== undefined) {
414 yield* waitGlobalOperation(env.project, operation).pipe(
415 Effect.catchTag("NotFound", () => Effect.void),
416 );
417 }
418 }),
419 });