The best way to control Claude Code, Codex and more from any computer or phone
| 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 = 443; |
| 21 | const DEFAULT_REQUEST_PATH = "/"; |
| 22 | |
| 23 | export type HttpsHealthCheckProps = { |
| 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 | httpsHealthCheckName?: string; |
| 30 | /** |
| 31 | * Optional description. Alchemy ownership is stored in a `[alchemy …]` |
| 32 | * prefix so `list` / nuke can find resources (legacy HttpsHealthCheck 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 HTTPS probe. |
| 58 | * @default 443 |
| 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 HttpsHealthCheckResource = Resource< |
| 73 | "GCP.Compute.HttpsHealthCheck", |
| 74 | HttpsHealthCheckProps, |
| 75 | { |
| 76 | /** Health check name. */ |
| 77 | httpsHealthCheckName: 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 | httpsHealthCheckId: 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 HTTPS health check. |
| 111 | * |
| 112 | * Legacy HTTPS health checks are deprecated for most load balancers — |
| 113 | * prefer `HealthCheck` with `httpsHealthCheck`. Compute HttpsHealthCheck |
| 114 | * has no labels field — Alchemy ownership is stored in the description so |
| 115 | * nuke can find leaked checks. |
| 116 | * |
| 117 | * ### Creating an HTTPS Health Check |
| 118 | * **Example:** Generated name |
| 119 | * ```typescript |
| 120 | * const check = yield* GCP.Compute.HttpsHealthCheck("api", {}); |
| 121 | * ``` |
| 122 | * |
| 123 | * **Example:** Path, port, and interval |
| 124 | * ```typescript |
| 125 | * const check = yield* GCP.Compute.HttpsHealthCheck("api", { |
| 126 | * description: "frontend /health", |
| 127 | * port: 443, |
| 128 | * requestPath: "/health", |
| 129 | * checkIntervalSec: 10, |
| 130 | * timeoutSec: 5, |
| 131 | * }); |
| 132 | * ``` |
| 133 | * |
| 134 | * @resource |
| 135 | * @category Compute |
| 136 | */ |
| 137 | export const HttpsHealthCheck = Resource<HttpsHealthCheckResource>("GCP.Compute.HttpsHealthCheck"); |
| 138 | |
| 139 | export class HttpsHealthCheckNotResolved extends Data.TaggedError( |
| 140 | "GCP.Compute.HttpsHealthCheckNotResolved", |
| 141 | )<{ |
| 142 | httpsHealthCheckName: string; |
| 143 | }> {} |
| 144 | |
| 145 | const rfc1035 = (name: string): string => { |
| 146 | let next = name |
| 147 | .toLowerCase() |
| 148 | .replace(/[^a-z0-9-]/g, "-") |
| 149 | .replace(/-+/g, "-") |
| 150 | .replace(/^-+/, "") |
| 151 | .replace(/-+$/, ""); |
| 152 | if (!/^[a-z]/.test(next)) { |
| 153 | next = `h${next}`; |
| 154 | } |
| 155 | next = next.slice(0, 63).replace(/-+$/, ""); |
| 156 | return next.length > 0 ? next : "httpshealthcheck"; |
| 157 | }; |
| 158 | |
| 159 | const toName = (id: string, name: string | undefined, existing?: string) => |
| 160 | Effect.gen(function* () { |
| 161 | if (name !== undefined) return name; |
| 162 | if (existing !== undefined) return existing; |
| 163 | return rfc1035( |
| 164 | yield* createPhysicalName({ |
| 165 | id, |
| 166 | maxLength: 63, |
| 167 | lowercase: true, |
| 168 | }), |
| 169 | ); |
| 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 toBody = ( |
| 203 | httpsHealthCheckName: string, |
| 204 | props: HttpsHealthCheckProps, |
| 205 | ownership: Record<string, string>, |
| 206 | ): compute.HttpsHealthCheck => ({ |
| 207 | name: httpsHealthCheckName, |
| 208 | description: encodeDescription(ownership, props.description), |
| 209 | checkIntervalSec: props.checkIntervalSec ?? DEFAULT_CHECK_INTERVAL, |
| 210 | timeoutSec: props.timeoutSec ?? DEFAULT_TIMEOUT, |
| 211 | healthyThreshold: props.healthyThreshold ?? DEFAULT_HEALTHY, |
| 212 | unhealthyThreshold: props.unhealthyThreshold ?? DEFAULT_UNHEALTHY, |
| 213 | port: props.port ?? DEFAULT_PORT, |
| 214 | requestPath: props.requestPath ?? DEFAULT_REQUEST_PATH, |
| 215 | host: props.host, |
| 216 | }); |
| 217 | |
| 218 | const toAttrs = ( |
| 219 | check: compute.HttpsHealthCheck, |
| 220 | project: string, |
| 221 | ): HttpsHealthCheckResource["Attributes"] => { |
| 222 | const parsed = parseDescription(check.description); |
| 223 | const host = check.host && check.host.length > 0 ? check.host : undefined; |
| 224 | return { |
| 225 | httpsHealthCheckName: check.name ?? check.id ?? "", |
| 226 | project, |
| 227 | description: parsed.description, |
| 228 | checkIntervalSec: check.checkIntervalSec ?? DEFAULT_CHECK_INTERVAL, |
| 229 | timeoutSec: check.timeoutSec ?? DEFAULT_TIMEOUT, |
| 230 | healthyThreshold: check.healthyThreshold ?? DEFAULT_HEALTHY, |
| 231 | unhealthyThreshold: check.unhealthyThreshold ?? DEFAULT_UNHEALTHY, |
| 232 | port: check.port ?? DEFAULT_PORT, |
| 233 | requestPath: check.requestPath ?? DEFAULT_REQUEST_PATH, |
| 234 | host, |
| 235 | selfLink: check.selfLink, |
| 236 | httpsHealthCheckId: check.id, |
| 237 | creationTimestamp: check.creationTimestamp, |
| 238 | kind: check.kind, |
| 239 | }; |
| 240 | }; |
| 241 | |
| 242 | const needsUpdate = (current: compute.HttpsHealthCheck, desired: compute.HttpsHealthCheck) => { |
| 243 | if ((current.description ?? "") !== (desired.description ?? "")) return true; |
| 244 | if ( |
| 245 | (current.checkIntervalSec ?? DEFAULT_CHECK_INTERVAL) !== |
| 246 | (desired.checkIntervalSec ?? DEFAULT_CHECK_INTERVAL) |
| 247 | ) { |
| 248 | return true; |
| 249 | } |
| 250 | if ((current.timeoutSec ?? DEFAULT_TIMEOUT) !== (desired.timeoutSec ?? DEFAULT_TIMEOUT)) { |
| 251 | return true; |
| 252 | } |
| 253 | if ( |
| 254 | (current.healthyThreshold ?? DEFAULT_HEALTHY) !== (desired.healthyThreshold ?? DEFAULT_HEALTHY) |
| 255 | ) { |
| 256 | return true; |
| 257 | } |
| 258 | if ( |
| 259 | (current.unhealthyThreshold ?? DEFAULT_UNHEALTHY) !== |
| 260 | (desired.unhealthyThreshold ?? DEFAULT_UNHEALTHY) |
| 261 | ) { |
| 262 | return true; |
| 263 | } |
| 264 | if ((current.port ?? DEFAULT_PORT) !== (desired.port ?? DEFAULT_PORT)) { |
| 265 | return true; |
| 266 | } |
| 267 | if ( |
| 268 | (current.requestPath ?? DEFAULT_REQUEST_PATH) !== (desired.requestPath ?? DEFAULT_REQUEST_PATH) |
| 269 | ) { |
| 270 | return true; |
| 271 | } |
| 272 | return (current.host ?? "") !== (desired.host ?? ""); |
| 273 | }; |
| 274 | |
| 275 | const getByName = (project: string, httpsHealthCheck: string) => |
| 276 | compute |
| 277 | .getHttpsHealthChecks({ project, httpsHealthCheck }) |
| 278 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 279 | |
| 280 | const awaitResource = (project: string, httpsHealthCheckName: string) => |
| 281 | getByName(project, httpsHealthCheckName).pipe( |
| 282 | Effect.repeat({ |
| 283 | schedule: Schedule.spaced("1 second"), |
| 284 | until: (check) => check !== undefined, |
| 285 | times: 8, |
| 286 | }), |
| 287 | ); |
| 288 | |
| 289 | export const HttpsHealthCheckProvider = () => |
| 290 | Provider.succeed(HttpsHealthCheck, { |
| 291 | stables: [ |
| 292 | "httpsHealthCheckName", |
| 293 | "project", |
| 294 | "httpsHealthCheckId", |
| 295 | "selfLink", |
| 296 | "creationTimestamp", |
| 297 | ], |
| 298 | |
| 299 | diff: Effect.fn(function* ({ news, olds, output }) { |
| 300 | if (!isResolved(news)) return undefined; |
| 301 | const previousName = olds?.httpsHealthCheckName ?? output?.httpsHealthCheckName; |
| 302 | const nextName = news.httpsHealthCheckName; |
| 303 | if (previousName !== undefined && nextName !== undefined && previousName !== nextName) { |
| 304 | return { action: "replace" as const }; |
| 305 | } |
| 306 | return undefined; |
| 307 | }), |
| 308 | |
| 309 | read: Effect.fn(function* ({ id, olds, output }) { |
| 310 | const env = yield* GcpEnvironment.current; |
| 311 | const httpsHealthCheckName = yield* toName( |
| 312 | id, |
| 313 | olds?.httpsHealthCheckName, |
| 314 | output?.httpsHealthCheckName, |
| 315 | ); |
| 316 | const existing = yield* getByName(env.project, httpsHealthCheckName); |
| 317 | if (existing === undefined) return undefined; |
| 318 | const attrs = toAttrs(existing, env.project); |
| 319 | const { labels } = parseDescription(existing.description); |
| 320 | return (yield* hasAlchemyLabels(id, labels)) ? attrs : Unowned(attrs); |
| 321 | }), |
| 322 | |
| 323 | list: () => |
| 324 | Effect.gen(function* () { |
| 325 | const env = yield* GcpEnvironment.current; |
| 326 | return yield* compute.listHttpsHealthChecks |
| 327 | .items({ project: env.project, maxResults: 500 }) |
| 328 | .pipe( |
| 329 | Stream.filter((check) => { |
| 330 | const { labels } = parseDescription(check.description); |
| 331 | return Object.keys(labels).some((key) => key.startsWith("alchemy-")); |
| 332 | }), |
| 333 | Stream.map((check) => toAttrs(check, env.project)), |
| 334 | Stream.runCollect, |
| 335 | Effect.map((chunk) => Array.from(chunk)), |
| 336 | ); |
| 337 | }), |
| 338 | |
| 339 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 340 | const env = yield* GcpEnvironment.current; |
| 341 | const httpsHealthCheckName = yield* toName( |
| 342 | id, |
| 343 | news.httpsHealthCheckName, |
| 344 | output?.httpsHealthCheckName, |
| 345 | ); |
| 346 | const ownership = yield* createInternalLabels(id); |
| 347 | const desired = toBody(httpsHealthCheckName, news, ownership); |
| 348 | |
| 349 | let current = yield* getByName(env.project, httpsHealthCheckName); |
| 350 | |
| 351 | if (current === undefined) { |
| 352 | yield* compute |
| 353 | .insertHttpsHealthChecks({ |
| 354 | project: env.project, |
| 355 | body: desired, |
| 356 | }) |
| 357 | .pipe( |
| 358 | Effect.flatMap((operation) => waitGlobalOperation(env.project, operation)), |
| 359 | Effect.catchTag("Conflict", () => Effect.undefined), |
| 360 | ); |
| 361 | current = yield* awaitResource(env.project, httpsHealthCheckName); |
| 362 | } |
| 363 | |
| 364 | if (current === undefined) { |
| 365 | return yield* new HttpsHealthCheckNotResolved({ |
| 366 | httpsHealthCheckName, |
| 367 | }); |
| 368 | } |
| 369 | |
| 370 | if (needsUpdate(current, desired)) { |
| 371 | yield* compute |
| 372 | .patchHttpsHealthChecks({ |
| 373 | project: env.project, |
| 374 | httpsHealthCheck: httpsHealthCheckName, |
| 375 | body: desired, |
| 376 | }) |
| 377 | .pipe(Effect.flatMap((operation) => waitGlobalOperation(env.project, operation))); |
| 378 | current = yield* getByName(env.project, httpsHealthCheckName); |
| 379 | if (current === undefined) { |
| 380 | return yield* new HttpsHealthCheckNotResolved({ |
| 381 | httpsHealthCheckName, |
| 382 | }); |
| 383 | } |
| 384 | } |
| 385 | |
| 386 | return toAttrs(current, env.project); |
| 387 | }), |
| 388 | |
| 389 | delete: Effect.fn(function* ({ output }) { |
| 390 | const env = yield* GcpEnvironment.current; |
| 391 | const operation = yield* compute |
| 392 | .deleteHttpsHealthChecks({ |
| 393 | project: env.project, |
| 394 | httpsHealthCheck: output.httpsHealthCheckName, |
| 395 | }) |
| 396 | .pipe( |
| 397 | Effect.retry({ |
| 398 | while: (error) => error._tag === "Conflict", |
| 399 | schedule: Schedule.spaced("2 seconds"), |
| 400 | times: 8, |
| 401 | }), |
| 402 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 403 | ); |
| 404 | if (operation !== undefined) { |
| 405 | yield* waitGlobalOperation(env.project, operation).pipe( |
| 406 | Effect.catchTag("NotFound", () => Effect.void), |
| 407 | ); |
| 408 | } |
| 409 | }), |
| 410 | }); |