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 | export type HealthCheckType = "TCP" | "SSL" | "HTTP" | "HTTPS" | "HTTP2" | "GRPC" | "GRPC_WITH_TLS"; |
| 17 | |
| 18 | export type HealthCheckPortSpecification = "USE_FIXED_PORT" | "USE_NAMED_PORT" | "USE_SERVING_PORT"; |
| 19 | |
| 20 | export type HealthCheckProxyHeader = "NONE" | "PROXY_V1"; |
| 21 | |
| 22 | export type HttpHealthCheck = { |
| 23 | /** Host header. Empty uses the destination IP. */ |
| 24 | host?: string; |
| 25 | /** TCP port (default 80). */ |
| 26 | port?: number; |
| 27 | /** Named port on the instance group. Not supported on most backends. */ |
| 28 | portName?: string; |
| 29 | /** How the health-check port is selected. */ |
| 30 | portSpecification?: HealthCheckPortSpecification; |
| 31 | /** Request path. Default `/`. */ |
| 32 | requestPath?: string; |
| 33 | /** ASCII response body that must appear in the first 1024 bytes. */ |
| 34 | response?: string; |
| 35 | /** Proxy header prepended to the probe. Default `NONE`. */ |
| 36 | proxyHeader?: HealthCheckProxyHeader; |
| 37 | }; |
| 38 | |
| 39 | export type HttpsHealthCheck = HttpHealthCheck; |
| 40 | export type Http2HealthCheck = HttpHealthCheck; |
| 41 | |
| 42 | export type TcpHealthCheck = { |
| 43 | /** TCP port (default 80). */ |
| 44 | port?: number; |
| 45 | /** Named port on the instance group. Not supported on most backends. */ |
| 46 | portName?: string; |
| 47 | /** How the health-check port is selected. */ |
| 48 | portSpecification?: HealthCheckPortSpecification; |
| 49 | /** ASCII payload sent after the TCP handshake. */ |
| 50 | request?: string; |
| 51 | /** ASCII response that must be received for the probe to pass. */ |
| 52 | response?: string; |
| 53 | /** Proxy header prepended to the probe. Default `NONE`. */ |
| 54 | proxyHeader?: HealthCheckProxyHeader; |
| 55 | }; |
| 56 | |
| 57 | export type SslHealthCheck = TcpHealthCheck; |
| 58 | |
| 59 | export type GrpcHealthCheck = { |
| 60 | /** TCP port. */ |
| 61 | port?: number; |
| 62 | /** Named port on the instance group. Not supported on most backends. */ |
| 63 | portName?: string; |
| 64 | /** How the health-check port is selected. */ |
| 65 | portSpecification?: HealthCheckPortSpecification; |
| 66 | /** gRPC service name. Empty checks all services at the backend. */ |
| 67 | grpcServiceName?: string; |
| 68 | }; |
| 69 | |
| 70 | export type HealthCheckLogConfig = { |
| 71 | /** Export health-check logs. Default false. */ |
| 72 | enable?: boolean; |
| 73 | }; |
| 74 | |
| 75 | export type HealthCheckProps = { |
| 76 | /** |
| 77 | * Health check name (RFC1035, 1-63 chars). If omitted, a unique name is |
| 78 | * generated from the stack, stage, and logical id. Changing it replaces |
| 79 | * the resource. |
| 80 | */ |
| 81 | healthCheckName?: string; |
| 82 | /** |
| 83 | * Optional description. Alchemy ownership is stored in a `[alchemy …]` |
| 84 | * prefix so `list` / nuke can find resources (Compute HealthCheck has no |
| 85 | * labels field). |
| 86 | */ |
| 87 | description?: string; |
| 88 | /** |
| 89 | * How often to probe, in seconds. |
| 90 | * @default 5 |
| 91 | */ |
| 92 | checkIntervalSec?: number; |
| 93 | /** |
| 94 | * Probe timeout in seconds. Must be ≤ `checkIntervalSec`. |
| 95 | * @default 5 |
| 96 | */ |
| 97 | timeoutSec?: number; |
| 98 | /** |
| 99 | * Consecutive successes before an instance is healthy. |
| 100 | * @default 2 |
| 101 | */ |
| 102 | healthyThreshold?: number; |
| 103 | /** |
| 104 | * Consecutive failures before an instance is unhealthy. |
| 105 | * @default 2 |
| 106 | */ |
| 107 | unhealthyThreshold?: number; |
| 108 | /** |
| 109 | * Protocol. Inferred from the nested `*HealthCheck` block when omitted. |
| 110 | * @default "HTTP" |
| 111 | */ |
| 112 | type?: HealthCheckType; |
| 113 | /** HTTP probe. Used when `type` is `HTTP` (the default). */ |
| 114 | httpHealthCheck?: HttpHealthCheck; |
| 115 | /** HTTPS probe. */ |
| 116 | httpsHealthCheck?: HttpsHealthCheck; |
| 117 | /** HTTP/2 probe. */ |
| 118 | http2HealthCheck?: Http2HealthCheck; |
| 119 | /** TCP probe. */ |
| 120 | tcpHealthCheck?: TcpHealthCheck; |
| 121 | /** SSL probe. */ |
| 122 | sslHealthCheck?: SslHealthCheck; |
| 123 | /** gRPC probe. */ |
| 124 | grpcHealthCheck?: GrpcHealthCheck; |
| 125 | /** gRPC-with-TLS probe. */ |
| 126 | grpcTlsHealthCheck?: GrpcHealthCheck; |
| 127 | /** Health-check logging. */ |
| 128 | logConfig?: HealthCheckLogConfig; |
| 129 | /** |
| 130 | * Source regions for global health checks. If set, exactly 3 valid |
| 131 | * Google Cloud regions are required. |
| 132 | */ |
| 133 | sourceRegions?: string[]; |
| 134 | }; |
| 135 | |
| 136 | export type HealthCheck = Resource< |
| 137 | "GCP.Compute.HealthCheck", |
| 138 | HealthCheckProps, |
| 139 | { |
| 140 | /** Health check name. */ |
| 141 | healthCheckName: string; |
| 142 | /** Project id. */ |
| 143 | project: string; |
| 144 | /** Protocol. */ |
| 145 | type: HealthCheckType; |
| 146 | /** User description with the Alchemy ownership prefix stripped. */ |
| 147 | description: string | undefined; |
| 148 | /** Probe interval in seconds. */ |
| 149 | checkIntervalSec: number; |
| 150 | /** Probe timeout in seconds. */ |
| 151 | timeoutSec: number; |
| 152 | /** Consecutive successes before healthy. */ |
| 153 | healthyThreshold: number; |
| 154 | /** Consecutive failures before unhealthy. */ |
| 155 | unhealthyThreshold: number; |
| 156 | /** HTTP probe, if this is an HTTP health check. */ |
| 157 | httpHealthCheck: HttpHealthCheck | undefined; |
| 158 | /** HTTPS probe, if this is an HTTPS health check. */ |
| 159 | httpsHealthCheck: HttpsHealthCheck | undefined; |
| 160 | /** HTTP/2 probe, if this is an HTTP/2 health check. */ |
| 161 | http2HealthCheck: Http2HealthCheck | undefined; |
| 162 | /** TCP probe, if this is a TCP health check. */ |
| 163 | tcpHealthCheck: TcpHealthCheck | undefined; |
| 164 | /** SSL probe, if this is an SSL health check. */ |
| 165 | sslHealthCheck: SslHealthCheck | undefined; |
| 166 | /** gRPC probe, if this is a gRPC health check. */ |
| 167 | grpcHealthCheck: GrpcHealthCheck | undefined; |
| 168 | /** gRPC-with-TLS probe, if this is a gRPC_WITH_TLS health check. */ |
| 169 | grpcTlsHealthCheck: GrpcHealthCheck | undefined; |
| 170 | /** Logging configuration. */ |
| 171 | logConfig: HealthCheckLogConfig | undefined; |
| 172 | /** Source regions, if set. */ |
| 173 | sourceRegions: string[] | undefined; |
| 174 | /** Server-defined URL. */ |
| 175 | selfLink: string | undefined; |
| 176 | /** Server-assigned numeric id. */ |
| 177 | healthCheckId: string | undefined; |
| 178 | /** RFC3339 creation timestamp. */ |
| 179 | creationTimestamp: string | undefined; |
| 180 | /** Resource kind. */ |
| 181 | kind: string | undefined; |
| 182 | }, |
| 183 | never, |
| 184 | Providers |
| 185 | >; |
| 186 | |
| 187 | /** |
| 188 | * A global Compute Engine health check. |
| 189 | * |
| 190 | * Health checks probe backends for load balancing and managed-instance-group |
| 191 | * autohealing. This resource maps to the global `healthChecks` collection |
| 192 | * (`regionHealthChecks` is a separate resource). Compute HealthCheck has no |
| 193 | * labels field — Alchemy ownership is stored in the description so nuke can |
| 194 | * find leaked checks. |
| 195 | * |
| 196 | * ### Creating a Health Check |
| 197 | * **Example:** Generated name (HTTP on port 80) |
| 198 | * ```typescript |
| 199 | * const check = yield* GCP.Compute.HealthCheck("api", {}); |
| 200 | * ``` |
| 201 | * |
| 202 | * **Example:** HTTP path and thresholds |
| 203 | * ```typescript |
| 204 | * const check = yield* GCP.Compute.HealthCheck("api", { |
| 205 | * description: "frontend /health", |
| 206 | * checkIntervalSec: 10, |
| 207 | * timeoutSec: 5, |
| 208 | * httpHealthCheck: { port: 80, requestPath: "/health" }, |
| 209 | * }); |
| 210 | * ``` |
| 211 | * |
| 212 | * **Example:** TCP health check |
| 213 | * ```typescript |
| 214 | * const check = yield* GCP.Compute.HealthCheck("tcp", { |
| 215 | * type: "TCP", |
| 216 | * tcpHealthCheck: { port: 8080 }, |
| 217 | * }); |
| 218 | * ``` |
| 219 | * |
| 220 | * @resource |
| 221 | * @category Compute |
| 222 | */ |
| 223 | export const HealthCheck = Resource<HealthCheck>("GCP.Compute.HealthCheck"); |
| 224 | |
| 225 | export class HealthCheckNotResolved extends Data.TaggedError("GCP.Compute.HealthCheckNotResolved")<{ |
| 226 | healthCheckName: string; |
| 227 | }> {} |
| 228 | |
| 229 | const DEFAULT_CHECK_INTERVAL = 5; |
| 230 | const DEFAULT_TIMEOUT = 5; |
| 231 | const DEFAULT_HEALTHY = 2; |
| 232 | const DEFAULT_UNHEALTHY = 2; |
| 233 | |
| 234 | const rfc1035 = (name: string): string => { |
| 235 | let next = name |
| 236 | .toLowerCase() |
| 237 | .replace(/[^a-z0-9-]/g, "-") |
| 238 | .replace(/-+/g, "-") |
| 239 | .replace(/^-+/, "") |
| 240 | .replace(/-+$/, ""); |
| 241 | if (!/^[a-z]/.test(next)) { |
| 242 | next = `h${next}`; |
| 243 | } |
| 244 | next = next.slice(0, 63).replace(/-+$/, ""); |
| 245 | return next.length > 0 ? next : "healthcheck"; |
| 246 | }; |
| 247 | |
| 248 | const toName = (id: string, name: string | undefined, existing?: string) => |
| 249 | Effect.gen(function* () { |
| 250 | if (name !== undefined) return name; |
| 251 | if (existing !== undefined) return existing; |
| 252 | return rfc1035( |
| 253 | yield* createPhysicalName({ |
| 254 | id, |
| 255 | maxLength: 63, |
| 256 | lowercase: true, |
| 257 | }), |
| 258 | ); |
| 259 | }); |
| 260 | |
| 261 | const inferType = (props: HealthCheckProps): HealthCheckType => { |
| 262 | if (props.type) return props.type; |
| 263 | if (props.httpsHealthCheck) return "HTTPS"; |
| 264 | if (props.http2HealthCheck) return "HTTP2"; |
| 265 | if (props.sslHealthCheck) return "SSL"; |
| 266 | if (props.tcpHealthCheck) return "TCP"; |
| 267 | if (props.grpcHealthCheck) return "GRPC"; |
| 268 | if (props.grpcTlsHealthCheck) return "GRPC_WITH_TLS"; |
| 269 | return "HTTP"; |
| 270 | }; |
| 271 | |
| 272 | const encodeDescription = ( |
| 273 | labels: Record<string, string>, |
| 274 | description: string | undefined, |
| 275 | ): string => { |
| 276 | const marker = `[alchemy ${alchemyLabelKeys.stack}=${labels[alchemyLabelKeys.stack]} ${alchemyLabelKeys.stage}=${labels[alchemyLabelKeys.stage]} ${alchemyLabelKeys.id}=${labels[alchemyLabelKeys.id]}]`; |
| 277 | return description ? `${marker}\n${description}` : marker; |
| 278 | }; |
| 279 | |
| 280 | const parseDescription = ( |
| 281 | description: string | undefined, |
| 282 | ): { |
| 283 | labels: Record<string, string>; |
| 284 | description: string | undefined; |
| 285 | } => { |
| 286 | if (!description?.startsWith("[alchemy ")) { |
| 287 | return { labels: {}, description }; |
| 288 | } |
| 289 | const end = description.indexOf("]"); |
| 290 | if (end < 0) return { labels: {}, description }; |
| 291 | const labels: Record<string, string> = {}; |
| 292 | for (const part of description.slice("[alchemy ".length, end).split(/\s+/)) { |
| 293 | const eq = part.indexOf("="); |
| 294 | if (eq > 0) { |
| 295 | labels[part.slice(0, eq)] = part.slice(eq + 1); |
| 296 | } |
| 297 | } |
| 298 | const rest = description.slice(end + 1).replace(/^\n/, ""); |
| 299 | return { labels, description: rest.length > 0 ? rest : undefined }; |
| 300 | }; |
| 301 | |
| 302 | const protocolBody = ( |
| 303 | type: HealthCheckType, |
| 304 | props: HealthCheckProps, |
| 305 | ): Pick< |
| 306 | compute.HealthCheck, |
| 307 | | "httpHealthCheck" |
| 308 | | "httpsHealthCheck" |
| 309 | | "http2HealthCheck" |
| 310 | | "tcpHealthCheck" |
| 311 | | "sslHealthCheck" |
| 312 | | "grpcHealthCheck" |
| 313 | | "grpcTlsHealthCheck" |
| 314 | > => { |
| 315 | switch (type) { |
| 316 | case "HTTPS": |
| 317 | return { |
| 318 | httpsHealthCheck: { |
| 319 | port: 443, |
| 320 | requestPath: "/", |
| 321 | ...props.httpsHealthCheck, |
| 322 | }, |
| 323 | }; |
| 324 | case "HTTP2": |
| 325 | return { |
| 326 | http2HealthCheck: { |
| 327 | port: 443, |
| 328 | requestPath: "/", |
| 329 | ...props.http2HealthCheck, |
| 330 | }, |
| 331 | }; |
| 332 | case "TCP": |
| 333 | return { tcpHealthCheck: { port: 80, ...props.tcpHealthCheck } }; |
| 334 | case "SSL": |
| 335 | return { sslHealthCheck: { port: 443, ...props.sslHealthCheck } }; |
| 336 | case "GRPC": |
| 337 | return { grpcHealthCheck: { port: 443, ...props.grpcHealthCheck } }; |
| 338 | case "GRPC_WITH_TLS": |
| 339 | return { |
| 340 | grpcTlsHealthCheck: { port: 443, ...props.grpcTlsHealthCheck }, |
| 341 | }; |
| 342 | default: |
| 343 | return { |
| 344 | httpHealthCheck: { |
| 345 | port: 80, |
| 346 | requestPath: "/", |
| 347 | ...props.httpHealthCheck, |
| 348 | }, |
| 349 | }; |
| 350 | } |
| 351 | }; |
| 352 | |
| 353 | const toBody = ( |
| 354 | healthCheckName: string, |
| 355 | props: HealthCheckProps, |
| 356 | ownership: Record<string, string>, |
| 357 | ): compute.HealthCheck => { |
| 358 | const type = inferType(props); |
| 359 | return { |
| 360 | name: healthCheckName, |
| 361 | description: encodeDescription(ownership, props.description), |
| 362 | checkIntervalSec: props.checkIntervalSec ?? DEFAULT_CHECK_INTERVAL, |
| 363 | timeoutSec: props.timeoutSec ?? DEFAULT_TIMEOUT, |
| 364 | healthyThreshold: props.healthyThreshold ?? DEFAULT_HEALTHY, |
| 365 | unhealthyThreshold: props.unhealthyThreshold ?? DEFAULT_UNHEALTHY, |
| 366 | type, |
| 367 | logConfig: { enable: props.logConfig?.enable === true }, |
| 368 | sourceRegions: props.sourceRegions, |
| 369 | ...protocolBody(type, props), |
| 370 | }; |
| 371 | }; |
| 372 | |
| 373 | const asType = (type: string | undefined): HealthCheckType => { |
| 374 | switch (type) { |
| 375 | case "TCP": |
| 376 | case "SSL": |
| 377 | case "HTTP": |
| 378 | case "HTTPS": |
| 379 | case "HTTP2": |
| 380 | case "GRPC": |
| 381 | case "GRPC_WITH_TLS": |
| 382 | return type; |
| 383 | default: |
| 384 | return "HTTP"; |
| 385 | } |
| 386 | }; |
| 387 | |
| 388 | const asPortSpecification = ( |
| 389 | value: string | undefined, |
| 390 | ): HealthCheckPortSpecification | undefined => { |
| 391 | switch (value) { |
| 392 | case "USE_FIXED_PORT": |
| 393 | case "USE_NAMED_PORT": |
| 394 | case "USE_SERVING_PORT": |
| 395 | return value; |
| 396 | default: |
| 397 | return undefined; |
| 398 | } |
| 399 | }; |
| 400 | |
| 401 | const asProxyHeader = (value: string | undefined): HealthCheckProxyHeader | undefined => { |
| 402 | switch (value) { |
| 403 | case "NONE": |
| 404 | case "PROXY_V1": |
| 405 | return value; |
| 406 | default: |
| 407 | return undefined; |
| 408 | } |
| 409 | }; |
| 410 | |
| 411 | const toHttpProbe = ( |
| 412 | check: compute.HTTPHealthCheck | compute.HTTPSHealthCheck | compute.HTTP2HealthCheck | undefined, |
| 413 | ): HttpHealthCheck | undefined => { |
| 414 | if (check === undefined) return undefined; |
| 415 | return { |
| 416 | host: check.host, |
| 417 | port: check.port, |
| 418 | portName: check.portName, |
| 419 | portSpecification: asPortSpecification(check.portSpecification), |
| 420 | requestPath: check.requestPath, |
| 421 | response: check.response, |
| 422 | proxyHeader: asProxyHeader(check.proxyHeader), |
| 423 | }; |
| 424 | }; |
| 425 | |
| 426 | const toTcpProbe = ( |
| 427 | check: compute.TCPHealthCheck | compute.SSLHealthCheck | undefined, |
| 428 | ): TcpHealthCheck | undefined => { |
| 429 | if (check === undefined) return undefined; |
| 430 | return { |
| 431 | port: check.port, |
| 432 | portName: check.portName, |
| 433 | portSpecification: asPortSpecification(check.portSpecification), |
| 434 | request: check.request, |
| 435 | response: check.response, |
| 436 | proxyHeader: asProxyHeader(check.proxyHeader), |
| 437 | }; |
| 438 | }; |
| 439 | |
| 440 | const toGrpcProbe = ( |
| 441 | check: compute.GRPCHealthCheck | compute.GRPCTLSHealthCheck | undefined, |
| 442 | ): GrpcHealthCheck | undefined => { |
| 443 | if (check === undefined) return undefined; |
| 444 | return { |
| 445 | port: check.port, |
| 446 | portName: "portName" in check ? check.portName : undefined, |
| 447 | portSpecification: asPortSpecification(check.portSpecification), |
| 448 | grpcServiceName: check.grpcServiceName, |
| 449 | }; |
| 450 | }; |
| 451 | |
| 452 | const toAttrs = (check: compute.HealthCheck, project: string): HealthCheck["Attributes"] => { |
| 453 | const parsed = parseDescription(check.description); |
| 454 | return { |
| 455 | healthCheckName: check.name ?? check.id ?? "", |
| 456 | project, |
| 457 | type: asType(check.type), |
| 458 | description: parsed.description, |
| 459 | checkIntervalSec: check.checkIntervalSec ?? DEFAULT_CHECK_INTERVAL, |
| 460 | timeoutSec: check.timeoutSec ?? DEFAULT_TIMEOUT, |
| 461 | healthyThreshold: check.healthyThreshold ?? DEFAULT_HEALTHY, |
| 462 | unhealthyThreshold: check.unhealthyThreshold ?? DEFAULT_UNHEALTHY, |
| 463 | httpHealthCheck: toHttpProbe(check.httpHealthCheck), |
| 464 | httpsHealthCheck: toHttpProbe(check.httpsHealthCheck), |
| 465 | http2HealthCheck: toHttpProbe(check.http2HealthCheck), |
| 466 | tcpHealthCheck: toTcpProbe(check.tcpHealthCheck), |
| 467 | sslHealthCheck: toTcpProbe(check.sslHealthCheck), |
| 468 | grpcHealthCheck: toGrpcProbe(check.grpcHealthCheck), |
| 469 | grpcTlsHealthCheck: toGrpcProbe(check.grpcTlsHealthCheck), |
| 470 | logConfig: check.logConfig === undefined ? undefined : { enable: check.logConfig.enable }, |
| 471 | sourceRegions: check.sourceRegions === undefined ? undefined : [...check.sourceRegions], |
| 472 | selfLink: check.selfLink, |
| 473 | healthCheckId: check.id, |
| 474 | creationTimestamp: check.creationTimestamp, |
| 475 | kind: check.kind, |
| 476 | }; |
| 477 | }; |
| 478 | |
| 479 | const subsetEqual = ( |
| 480 | observed: Record<string, unknown> | undefined, |
| 481 | desired: Record<string, unknown> | undefined, |
| 482 | ): boolean => { |
| 483 | if (desired === undefined) return true; |
| 484 | const current = observed ?? {}; |
| 485 | for (const [key, value] of Object.entries(desired)) { |
| 486 | if (value === undefined) continue; |
| 487 | if (current[key] !== value) return false; |
| 488 | } |
| 489 | return true; |
| 490 | }; |
| 491 | |
| 492 | const asRecord = (value: object | undefined): Record<string, unknown> | undefined => { |
| 493 | if (value === undefined) return undefined; |
| 494 | const record: Record<string, unknown> = {}; |
| 495 | for (const [key, entry] of Object.entries(value)) { |
| 496 | record[key] = entry; |
| 497 | } |
| 498 | return record; |
| 499 | }; |
| 500 | |
| 501 | const protocolConfig = (check: compute.HealthCheck, type: HealthCheckType) => { |
| 502 | switch (type) { |
| 503 | case "HTTPS": |
| 504 | return check.httpsHealthCheck; |
| 505 | case "HTTP2": |
| 506 | return check.http2HealthCheck; |
| 507 | case "TCP": |
| 508 | return check.tcpHealthCheck; |
| 509 | case "SSL": |
| 510 | return check.sslHealthCheck; |
| 511 | case "GRPC": |
| 512 | return check.grpcHealthCheck; |
| 513 | case "GRPC_WITH_TLS": |
| 514 | return check.grpcTlsHealthCheck; |
| 515 | default: |
| 516 | return check.httpHealthCheck; |
| 517 | } |
| 518 | }; |
| 519 | |
| 520 | const sameRegions = (observed?: readonly string[], desired?: readonly string[]) => |
| 521 | JSON.stringify([...(observed ?? [])].sort()) === JSON.stringify([...(desired ?? [])].sort()); |
| 522 | |
| 523 | const needsUpdate = (current: compute.HealthCheck, desired: compute.HealthCheck) => { |
| 524 | const currentType = asType(current.type); |
| 525 | const desiredType = asType(desired.type); |
| 526 | if (currentType !== desiredType) return true; |
| 527 | if ( |
| 528 | (current.checkIntervalSec ?? DEFAULT_CHECK_INTERVAL) !== |
| 529 | (desired.checkIntervalSec ?? DEFAULT_CHECK_INTERVAL) |
| 530 | ) { |
| 531 | return true; |
| 532 | } |
| 533 | if ((current.timeoutSec ?? DEFAULT_TIMEOUT) !== (desired.timeoutSec ?? DEFAULT_TIMEOUT)) { |
| 534 | return true; |
| 535 | } |
| 536 | if ( |
| 537 | (current.healthyThreshold ?? DEFAULT_HEALTHY) !== (desired.healthyThreshold ?? DEFAULT_HEALTHY) |
| 538 | ) { |
| 539 | return true; |
| 540 | } |
| 541 | if ( |
| 542 | (current.unhealthyThreshold ?? DEFAULT_UNHEALTHY) !== |
| 543 | (desired.unhealthyThreshold ?? DEFAULT_UNHEALTHY) |
| 544 | ) { |
| 545 | return true; |
| 546 | } |
| 547 | if ((current.description ?? "") !== (desired.description ?? "")) return true; |
| 548 | if ((current.logConfig?.enable === true) !== (desired.logConfig?.enable === true)) { |
| 549 | return true; |
| 550 | } |
| 551 | if (!sameRegions(current.sourceRegions, desired.sourceRegions)) return true; |
| 552 | return !subsetEqual( |
| 553 | asRecord(protocolConfig(current, desiredType)), |
| 554 | asRecord(protocolConfig(desired, desiredType)), |
| 555 | ); |
| 556 | }; |
| 557 | |
| 558 | const getByName = (project: string, healthCheck: string) => |
| 559 | compute |
| 560 | .getHealthChecks({ project, healthCheck }) |
| 561 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 562 | |
| 563 | const awaitResource = (project: string, healthCheckName: string) => |
| 564 | getByName(project, healthCheckName).pipe( |
| 565 | Effect.repeat({ |
| 566 | schedule: Schedule.spaced("1 second"), |
| 567 | until: (check) => check !== undefined, |
| 568 | times: 8, |
| 569 | }), |
| 570 | ); |
| 571 | |
| 572 | export const HealthCheckProvider = () => |
| 573 | Provider.succeed(HealthCheck, { |
| 574 | stables: ["healthCheckName", "project", "healthCheckId", "selfLink", "creationTimestamp"], |
| 575 | |
| 576 | diff: Effect.fn(function* ({ news, olds, output }) { |
| 577 | if (!isResolved(news)) return undefined; |
| 578 | const previousName = olds?.healthCheckName ?? output?.healthCheckName; |
| 579 | const nextName = news.healthCheckName; |
| 580 | if (previousName !== undefined && nextName !== undefined && previousName !== nextName) { |
| 581 | return { action: "replace" as const }; |
| 582 | } |
| 583 | const previousType = (olds !== undefined ? inferType(olds) : undefined) ?? output?.type; |
| 584 | const nextType = inferType(news); |
| 585 | if (previousType !== undefined && previousType !== nextType) { |
| 586 | return { |
| 587 | action: "replace" as const, |
| 588 | deleteFirst: |
| 589 | previousName !== undefined && (nextName === undefined || nextName === previousName), |
| 590 | }; |
| 591 | } |
| 592 | return undefined; |
| 593 | }), |
| 594 | |
| 595 | read: Effect.fn(function* ({ id, olds, output }) { |
| 596 | const env = yield* GcpEnvironment.current; |
| 597 | const healthCheckName = yield* toName(id, olds?.healthCheckName, output?.healthCheckName); |
| 598 | const existing = yield* getByName(env.project, healthCheckName); |
| 599 | if (existing === undefined) return undefined; |
| 600 | const attrs = toAttrs(existing, env.project); |
| 601 | const { labels } = parseDescription(existing.description); |
| 602 | return (yield* hasAlchemyLabels(id, labels)) ? attrs : Unowned(attrs); |
| 603 | }), |
| 604 | |
| 605 | list: () => |
| 606 | Effect.gen(function* () { |
| 607 | const env = yield* GcpEnvironment.current; |
| 608 | return yield* compute.listHealthChecks.items({ project: env.project }).pipe( |
| 609 | Stream.filter((check) => { |
| 610 | const { labels } = parseDescription(check.description); |
| 611 | return Object.keys(labels).some((key) => key.startsWith("alchemy-")); |
| 612 | }), |
| 613 | Stream.map((check) => toAttrs(check, env.project)), |
| 614 | Stream.runCollect, |
| 615 | Effect.map((chunk) => Array.from(chunk)), |
| 616 | ); |
| 617 | }), |
| 618 | |
| 619 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 620 | const env = yield* GcpEnvironment.current; |
| 621 | const healthCheckName = yield* toName(id, news.healthCheckName, output?.healthCheckName); |
| 622 | const ownership = yield* createInternalLabels(id); |
| 623 | const desired = toBody(healthCheckName, news, ownership); |
| 624 | |
| 625 | let current = yield* getByName(env.project, healthCheckName); |
| 626 | |
| 627 | if (current === undefined) { |
| 628 | yield* compute |
| 629 | .insertHealthChecks({ |
| 630 | project: env.project, |
| 631 | body: desired, |
| 632 | }) |
| 633 | .pipe( |
| 634 | Effect.flatMap((operation) => waitGlobalOperation(env.project, operation)), |
| 635 | Effect.catchTag("Conflict", () => Effect.undefined), |
| 636 | ); |
| 637 | current = yield* awaitResource(env.project, healthCheckName); |
| 638 | } |
| 639 | |
| 640 | if (current === undefined) { |
| 641 | return yield* new HealthCheckNotResolved({ healthCheckName }); |
| 642 | } |
| 643 | |
| 644 | if (needsUpdate(current, desired)) { |
| 645 | yield* compute |
| 646 | .updateHealthChecks({ |
| 647 | project: env.project, |
| 648 | healthCheck: healthCheckName, |
| 649 | body: desired, |
| 650 | }) |
| 651 | .pipe(Effect.flatMap((operation) => waitGlobalOperation(env.project, operation))); |
| 652 | current = yield* getByName(env.project, healthCheckName); |
| 653 | if (current === undefined) { |
| 654 | return yield* new HealthCheckNotResolved({ healthCheckName }); |
| 655 | } |
| 656 | } |
| 657 | |
| 658 | return toAttrs(current, env.project); |
| 659 | }), |
| 660 | |
| 661 | delete: Effect.fn(function* ({ output }) { |
| 662 | const env = yield* GcpEnvironment.current; |
| 663 | const operation = yield* compute |
| 664 | .deleteHealthChecks({ |
| 665 | project: env.project, |
| 666 | healthCheck: output.healthCheckName, |
| 667 | }) |
| 668 | .pipe( |
| 669 | Effect.retry({ |
| 670 | while: (error) => error._tag === "Conflict", |
| 671 | schedule: Schedule.spaced("2 seconds"), |
| 672 | times: 8, |
| 673 | }), |
| 674 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 675 | ); |
| 676 | if (operation !== undefined) { |
| 677 | yield* waitGlobalOperation(env.project, operation).pipe( |
| 678 | Effect.catchTag("NotFound", () => Effect.void), |
| 679 | ); |
| 680 | } |
| 681 | }), |
| 682 | }); |