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
| 1 | import * as Hetzner from "@distilled.cloud/hetzner"; |
| 2 | import type { |
| 3 | CreateLoadBalancerRequestServicesItem, |
| 4 | GetLoadBalancerResponseLoadBalancer, |
| 5 | ListLoadBalancersResponseLoadBalancersItem, |
| 6 | } from "@distilled.cloud/hetzner/load_balancers"; |
| 7 | import { Unowned } from "alchemy/AdoptPolicy"; |
| 8 | import { isResolved } from "alchemy/Diff"; |
| 9 | import { createPhysicalName } from "alchemy/PhysicalName"; |
| 10 | import * as Provider from "alchemy/Provider"; |
| 11 | import { Resource } from "alchemy/Resource"; |
| 12 | import { tagRecord } from "alchemy/Tags"; |
| 13 | import * as Data from "effect/Data"; |
| 14 | import * as Duration from "effect/Duration"; |
| 15 | import * as Effect from "effect/Effect"; |
| 16 | import * as Schedule from "effect/Schedule"; |
| 17 | import * as Stream from "effect/Stream"; |
| 18 | import { waitForAction } from "./actions.ts"; |
| 19 | import type { Certificate } from "./Certificate.ts"; |
| 20 | import { |
| 21 | alchemyStackSelector, |
| 22 | createInternalLabels, |
| 23 | diffLabels, |
| 24 | hasAlchemyLabels, |
| 25 | labelSelector, |
| 26 | stripInternalLabels, |
| 27 | toLabels, |
| 28 | } from "./Labels.ts"; |
| 29 | import type { Network } from "./Network.ts"; |
| 30 | import type { Providers } from "./Providers.ts"; |
| 31 | |
| 32 | const DEFAULT_LOCATION = "nbg1"; |
| 33 | const DEFAULT_TYPE = "lb11"; |
| 34 | const DEFAULT_ALGORITHM = "round_robin"; |
| 35 | const MAX_NAME_LENGTH = 64; |
| 36 | |
| 37 | const DEFAULT_HC_INTERVAL = 15; |
| 38 | const DEFAULT_HC_TIMEOUT = 10; |
| 39 | const DEFAULT_HC_RETRIES = 3; |
| 40 | const DEFAULT_COOKIE_NAME = "HCLBSTICKY"; |
| 41 | const DEFAULT_COOKIE_LIFETIME = 300; |
| 42 | const DEFAULT_TIMEOUT_IDLE = 15; |
| 43 | |
| 44 | /** |
| 45 | * A resource-valued prop: the resource itself, or an Effect that produces |
| 46 | * it (so `yield* Server(...)` and `Server(...)` both type-check). |
| 47 | */ |
| 48 | type Ref<T> = T | Effect.Effect<T, never, Providers>; |
| 49 | |
| 50 | /** |
| 51 | * Server identity a Load Balancer target can point at. A `Hetzner.Server` |
| 52 | * resource satisfies this via `serverId`. |
| 53 | */ |
| 54 | export type LoadBalancerServer = { |
| 55 | readonly serverId: number; |
| 56 | }; |
| 57 | |
| 58 | export type LoadBalancerAlgorithm = "round_robin" | "least_connections"; |
| 59 | |
| 60 | export type LoadBalancerProtocol = "tcp" | "http" | "https"; |
| 61 | |
| 62 | export type HealthCheckProtocol = "tcp" | "http"; |
| 63 | |
| 64 | export type TargetHealthStatus = "healthy" | "unhealthy" | "unknown"; |
| 65 | |
| 66 | export interface LoadBalancerHealthCheckHttp { |
| 67 | /** |
| 68 | * Host header sent with the HTTP health check. `null` omits the header. |
| 69 | */ |
| 70 | domain?: string | null; |
| 71 | /** |
| 72 | * HTTP path used for the health check. |
| 73 | * @default "/" |
| 74 | */ |
| 75 | path?: string; |
| 76 | /** |
| 77 | * Substring that must appear in the health-check response body. |
| 78 | */ |
| 79 | response?: string; |
| 80 | /** |
| 81 | * Status codes that count as healthy. `?` and `*` wildcards are allowed. |
| 82 | * @default ["2??", "3??"] |
| 83 | */ |
| 84 | statusCodes?: string[]; |
| 85 | /** |
| 86 | * Use HTTPS for the health-check request. |
| 87 | * @default false |
| 88 | */ |
| 89 | tls?: boolean; |
| 90 | } |
| 91 | |
| 92 | export interface LoadBalancerHealthCheck { |
| 93 | /** |
| 94 | * Health-check protocol. `tcp` for a connect check; `http` for an HTTP GET. |
| 95 | */ |
| 96 | protocol: HealthCheckProtocol; |
| 97 | /** |
| 98 | * Port the health check is performed on. |
| 99 | */ |
| 100 | port: number; |
| 101 | /** |
| 102 | * Interval between checks, in seconds. |
| 103 | * @default 15 |
| 104 | */ |
| 105 | interval?: number; |
| 106 | /** |
| 107 | * Per-attempt timeout, in seconds. |
| 108 | * @default 10 |
| 109 | */ |
| 110 | timeout?: number; |
| 111 | /** |
| 112 | * Consecutive failures (or successes) before flipping healthy/unhealthy. |
| 113 | * @default 3 |
| 114 | */ |
| 115 | retries?: number; |
| 116 | /** |
| 117 | * Extra options when `protocol` is `http`. |
| 118 | */ |
| 119 | http?: LoadBalancerHealthCheckHttp; |
| 120 | } |
| 121 | |
| 122 | export interface LoadBalancerServiceHttp { |
| 123 | /** |
| 124 | * Cookie name used for sticky sessions. |
| 125 | * @default "HCLBSTICKY" |
| 126 | */ |
| 127 | cookieName?: string; |
| 128 | /** |
| 129 | * Sticky-session cookie lifetime in seconds. |
| 130 | * @default 300 |
| 131 | */ |
| 132 | cookieLifetime?: number; |
| 133 | /** |
| 134 | * Idle timeout in seconds for client and server connections. |
| 135 | * @default 15 |
| 136 | */ |
| 137 | timeoutIdle?: number; |
| 138 | /** |
| 139 | * Pin a client to one target via a cookie. |
| 140 | * @default false |
| 141 | */ |
| 142 | stickySessions?: boolean; |
| 143 | /** |
| 144 | * Redirect HTTP to HTTPS. Only valid when the service protocol is `https`. |
| 145 | * @default false |
| 146 | */ |
| 147 | redirectHttp?: boolean; |
| 148 | /** |
| 149 | * Certificates used for TLS termination. Empty means TLS passthrough. |
| 150 | * Accepts `Hetzner.Certificate` resources. |
| 151 | */ |
| 152 | certificates?: Array<Ref<Certificate>>; |
| 153 | } |
| 154 | |
| 155 | export interface LoadBalancerService { |
| 156 | /** |
| 157 | * Listener protocol. |
| 158 | */ |
| 159 | protocol: LoadBalancerProtocol; |
| 160 | /** |
| 161 | * Port the Load Balancer listens on. Unique per Load Balancer. |
| 162 | */ |
| 163 | listenPort: number; |
| 164 | /** |
| 165 | * Port traffic is forwarded to on each target. |
| 166 | */ |
| 167 | destinationPort: number; |
| 168 | /** |
| 169 | * Enable the PROXY protocol on this service. |
| 170 | * @default false |
| 171 | */ |
| 172 | proxyprotocol?: boolean; |
| 173 | /** |
| 174 | * Health check. Defaults to a TCP (or HTTP, for `http`/`https` services) |
| 175 | * check on `destinationPort`. |
| 176 | */ |
| 177 | healthCheck?: LoadBalancerHealthCheck; |
| 178 | /** |
| 179 | * HTTP/HTTPS options. Ignored for `tcp` services. |
| 180 | */ |
| 181 | http?: LoadBalancerServiceHttp; |
| 182 | } |
| 183 | |
| 184 | export type LoadBalancerTarget = |
| 185 | | { |
| 186 | type: "server"; |
| 187 | /** |
| 188 | * Server to receive traffic. Accepts a `Hetzner.Server` or `{ serverId }`. |
| 189 | */ |
| 190 | server: Ref<LoadBalancerServer>; |
| 191 | /** |
| 192 | * Route via the Server's private IP. Requires the Server and Load |
| 193 | * Balancer to share a Network. |
| 194 | * @default false |
| 195 | */ |
| 196 | usePrivateIp?: boolean; |
| 197 | /** |
| 198 | * Optional public IP of the Server to use as the target (Primary IPv4 |
| 199 | * or an IPv6 host in the Server's `/64`). |
| 200 | */ |
| 201 | ip?: string; |
| 202 | } |
| 203 | | { |
| 204 | type: "label_selector"; |
| 205 | /** |
| 206 | * Label selector used to pick target Servers. |
| 207 | */ |
| 208 | selector: string; |
| 209 | /** |
| 210 | * Route via each Server's private IP. |
| 211 | * @default false |
| 212 | */ |
| 213 | usePrivateIp?: boolean; |
| 214 | } |
| 215 | | { |
| 216 | type: "ip"; |
| 217 | /** |
| 218 | * Public or vSwitch IP of a Hetzner Online Root Server owned by the |
| 219 | * project owner. |
| 220 | */ |
| 221 | ip: string; |
| 222 | }; |
| 223 | |
| 224 | export interface LoadBalancerProps { |
| 225 | /** |
| 226 | * Name of the Load Balancer. Must be unique per project, 1–64 characters. |
| 227 | * If omitted, a unique name is generated from the stack, stage and |
| 228 | * logical ID. |
| 229 | */ |
| 230 | name?: string; |
| 231 | /** |
| 232 | * Load Balancer type (`lb11`, `lb21`, `lb31`, …). Changing to a larger |
| 233 | * type updates in place; Hetzner cannot downgrade a type. |
| 234 | * @default "lb11" |
| 235 | */ |
| 236 | loadBalancerType?: string; |
| 237 | /** |
| 238 | * Location to create the Load Balancer in (`nbg1`, `fsn1`, `hel1`, …). |
| 239 | * Mutually exclusive with `networkZone`. Cannot be changed after |
| 240 | * creation — changing it replaces the Load Balancer. |
| 241 | * @default "nbg1" |
| 242 | */ |
| 243 | location?: string; |
| 244 | /** |
| 245 | * Network zone (`eu-central`, `us-east`, …). Mutually exclusive with |
| 246 | * `location`. Cannot be changed after creation. |
| 247 | */ |
| 248 | networkZone?: string; |
| 249 | /** |
| 250 | * Balancing algorithm. |
| 251 | * @default "round_robin" |
| 252 | */ |
| 253 | algorithm?: LoadBalancerAlgorithm; |
| 254 | /** |
| 255 | * Listeners. Synced via add/update/delete service actions, keyed by |
| 256 | * `listenPort`. |
| 257 | */ |
| 258 | services?: LoadBalancerService[]; |
| 259 | /** |
| 260 | * Backend targets. Server targets take a `Hetzner.Server` (or `{ serverId }`). |
| 261 | */ |
| 262 | targets?: LoadBalancerTarget[]; |
| 263 | /** |
| 264 | * Private Networks to attach. Accepts `Hetzner.Network` resources. |
| 265 | */ |
| 266 | networks?: Array<Ref<Network>>; |
| 267 | /** |
| 268 | * Expose the public IPv4/IPv6 interface. |
| 269 | * @default true |
| 270 | */ |
| 271 | publicInterface?: boolean; |
| 272 | /** |
| 273 | * Prevent the Load Balancer from being deleted in the Cloud Console / |
| 274 | * API until this is cleared. The provider disables protection before |
| 275 | * delete. |
| 276 | * @default false |
| 277 | */ |
| 278 | deleteProtection?: boolean; |
| 279 | /** |
| 280 | * User-defined labels. Alchemy ownership labels (`alchemy.stack` / |
| 281 | * `alchemy.stage` / `alchemy.id`) are always merged in. |
| 282 | */ |
| 283 | labels?: Record<string, string>; |
| 284 | } |
| 285 | |
| 286 | export interface LoadBalancerServiceAttr { |
| 287 | protocol: LoadBalancerProtocol; |
| 288 | listenPort: number; |
| 289 | destinationPort: number; |
| 290 | proxyprotocol: boolean; |
| 291 | healthCheck: { |
| 292 | protocol: HealthCheckProtocol; |
| 293 | port: number; |
| 294 | interval: number; |
| 295 | timeout: number; |
| 296 | retries: number; |
| 297 | http?: { |
| 298 | domain: string | null; |
| 299 | path: string; |
| 300 | response?: string; |
| 301 | statusCodes?: string[]; |
| 302 | tls?: boolean; |
| 303 | }; |
| 304 | }; |
| 305 | http?: { |
| 306 | cookieName: string; |
| 307 | cookieLifetime: number; |
| 308 | timeoutIdle: number; |
| 309 | stickySessions: boolean; |
| 310 | redirectHttp?: boolean; |
| 311 | certificates?: number[]; |
| 312 | }; |
| 313 | } |
| 314 | |
| 315 | export type LoadBalancerTargetAttr = |
| 316 | | { |
| 317 | type: "server"; |
| 318 | serverId: number; |
| 319 | ip?: string; |
| 320 | usePrivateIp: boolean; |
| 321 | healthStatus: { listenPort: number; status: TargetHealthStatus }[]; |
| 322 | } |
| 323 | | { |
| 324 | type: "label_selector"; |
| 325 | selector: string; |
| 326 | usePrivateIp: boolean; |
| 327 | } |
| 328 | | { |
| 329 | type: "ip"; |
| 330 | ip: string; |
| 331 | healthStatus: { listenPort: number; status: TargetHealthStatus }[]; |
| 332 | }; |
| 333 | |
| 334 | export type LoadBalancer = Resource< |
| 335 | "Hetzner.LoadBalancer", |
| 336 | LoadBalancerProps, |
| 337 | { |
| 338 | /** Numeric Hetzner Load Balancer ID. */ |
| 339 | id: number; |
| 340 | /** Load Balancer name (unique per project). */ |
| 341 | name: string; |
| 342 | /** Load Balancer type name (`lb11`, …). */ |
| 343 | loadBalancerType: string; |
| 344 | /** Numeric Load Balancer type ID. */ |
| 345 | loadBalancerTypeId: number; |
| 346 | /** Location name (`nbg1`, `fsn1`, …). */ |
| 347 | location: string; |
| 348 | /** Numeric location ID. */ |
| 349 | locationId: number; |
| 350 | /** Network zone (`eu-central`, …). */ |
| 351 | networkZone: string; |
| 352 | /** Balancing algorithm. */ |
| 353 | algorithm: LoadBalancerAlgorithm; |
| 354 | /** Public IPv4, or `null` when the public interface is disabled. */ |
| 355 | ipv4: string | null; |
| 356 | /** Public IPv6, or `null` when the public interface is disabled. */ |
| 357 | ipv6: string | null; |
| 358 | /** Whether the public interface is enabled. */ |
| 359 | publicInterface: boolean; |
| 360 | /** Whether delete protection is enabled. */ |
| 361 | deleteProtection: boolean; |
| 362 | /** Observed listeners. */ |
| 363 | services: LoadBalancerServiceAttr[]; |
| 364 | /** Observed targets. */ |
| 365 | targets: LoadBalancerTargetAttr[]; |
| 366 | /** Attached private Networks and the assigned IPs. */ |
| 367 | privateNetworks: { networkId: number; ip: string }[]; |
| 368 | /** User-defined labels (Alchemy ownership labels stripped). */ |
| 369 | labels: Record<string, string>; |
| 370 | /** RFC3339 creation timestamp. */ |
| 371 | created: string; |
| 372 | }, |
| 373 | never, |
| 374 | Providers |
| 375 | >; |
| 376 | |
| 377 | /** |
| 378 | * A Hetzner Cloud Load Balancer. Create it in a Location (`nbg1` by |
| 379 | * default) with type `lb11`, then sync algorithm, listeners, targets, |
| 380 | * private Networks, delete protection, and labels. |
| 381 | * |
| 382 | * Location and network zone are immutable (changing either replaces the |
| 383 | * Load Balancer). Type can grow in place. Server targets take a |
| 384 | * `Hetzner.Server`; HTTPS listeners take `Hetzner.Certificate`s. |
| 385 | * |
| 386 | * @see https://docs.hetzner.cloud/reference/cloud#load-balancers |
| 387 | * |
| 388 | * ### Creating a Load Balancer |
| 389 | * **Example:** Basic TCP Load Balancer |
| 390 | * ```typescript |
| 391 | * const lb = yield* Hetzner.LoadBalancer("edge", { |
| 392 | * location: "nbg1", |
| 393 | * loadBalancerType: "lb11", |
| 394 | * services: [ |
| 395 | * { protocol: "tcp", listenPort: 80, destinationPort: 80 }, |
| 396 | * ], |
| 397 | * }); |
| 398 | * ``` |
| 399 | * |
| 400 | * **Example:** With a Server target |
| 401 | * ```typescript |
| 402 | * const server = yield* Hetzner.Server("web", { |
| 403 | * serverType: "cx23", |
| 404 | * image: "ubuntu-24.04", |
| 405 | * location: "nbg1", |
| 406 | * }); |
| 407 | * const lb = yield* Hetzner.LoadBalancer("edge", { |
| 408 | * algorithm: "round_robin", |
| 409 | * services: [ |
| 410 | * { protocol: "tcp", listenPort: 80, destinationPort: 80 }, |
| 411 | * ], |
| 412 | * targets: [{ type: "server", server }], |
| 413 | * }); |
| 414 | * ``` |
| 415 | * |
| 416 | * ### HTTPS with a Certificate |
| 417 | * **Example:** Terminate TLS |
| 418 | * ```typescript |
| 419 | * const cert = yield* Hetzner.Certificate("web", { |
| 420 | * certificate: pem, |
| 421 | * privateKey: key, |
| 422 | * }); |
| 423 | * const lb = yield* Hetzner.LoadBalancer("edge", { |
| 424 | * services: [ |
| 425 | * { |
| 426 | * protocol: "https", |
| 427 | * listenPort: 443, |
| 428 | * destinationPort: 80, |
| 429 | * http: { certificates: [cert], redirectHttp: true }, |
| 430 | * }, |
| 431 | * ], |
| 432 | * }); |
| 433 | * ``` |
| 434 | * |
| 435 | * ### Private Networks |
| 436 | * **Example:** Attach to a Network |
| 437 | * ```typescript |
| 438 | * const network = yield* Hetzner.Network("vpc", { |
| 439 | * ipRange: "10.0.0.0/16", |
| 440 | * subnets: [ |
| 441 | * { type: "cloud", ipRange: "10.0.1.0/24", networkZone: "eu-central" }, |
| 442 | * ], |
| 443 | * }); |
| 444 | * const lb = yield* Hetzner.LoadBalancer("edge", { |
| 445 | * networks: [network], |
| 446 | * services: [ |
| 447 | * { protocol: "tcp", listenPort: 80, destinationPort: 80 }, |
| 448 | * ], |
| 449 | * }); |
| 450 | * ``` |
| 451 | * |
| 452 | * @resource |
| 453 | * @product Load Balancer |
| 454 | */ |
| 455 | export const LoadBalancer = Resource<LoadBalancer>("Hetzner.LoadBalancer"); |
| 456 | |
| 457 | type CloudLoadBalancer = |
| 458 | | GetLoadBalancerResponseLoadBalancer |
| 459 | | ListLoadBalancersResponseLoadBalancersItem; |
| 460 | |
| 461 | export class LoadBalancerNotCreated extends Data.TaggedError("Hetzner.LoadBalancerNotCreated")<{ |
| 462 | resourceName: string; |
| 463 | }> {} |
| 464 | |
| 465 | const asAlgorithm = (value: string): LoadBalancerAlgorithm => |
| 466 | value === "least_connections" ? "least_connections" : "round_robin"; |
| 467 | |
| 468 | const asProtocol = (value: string): LoadBalancerProtocol => |
| 469 | value === "https" ? "https" : value === "http" ? "http" : "tcp"; |
| 470 | |
| 471 | const asHealthProtocol = (value: string): HealthCheckProtocol => |
| 472 | value === "http" ? "http" : "tcp"; |
| 473 | |
| 474 | const asHealthStatus = (value: string): TargetHealthStatus => |
| 475 | value === "healthy" || value === "unhealthy" ? value : "unknown"; |
| 476 | |
| 477 | const userLabels = ( |
| 478 | labels: Record<string, string | undefined> | null | undefined, |
| 479 | ): Record<string, string> => stripInternalLabels(tagRecord(labels)); |
| 480 | |
| 481 | const serverIdOf = (value: unknown): number | undefined => { |
| 482 | if (value === null || typeof value !== "object") return undefined; |
| 483 | const rec = value as { serverId?: unknown; id?: unknown }; |
| 484 | if (typeof rec.serverId === "number") return rec.serverId; |
| 485 | if (typeof rec.id === "number") return rec.id; |
| 486 | return undefined; |
| 487 | }; |
| 488 | |
| 489 | const networkIdOf = (value: unknown): number | undefined => { |
| 490 | if (typeof value === "number") return value; |
| 491 | if (value === null || typeof value !== "object") return undefined; |
| 492 | const rec = value as { networkId?: unknown; id?: unknown }; |
| 493 | if (typeof rec.networkId === "number") return rec.networkId; |
| 494 | if (typeof rec.id === "number") return rec.id; |
| 495 | return undefined; |
| 496 | }; |
| 497 | |
| 498 | const certificateIdOf = (value: unknown): number | undefined => { |
| 499 | if (typeof value === "number") return value; |
| 500 | if (value === null || typeof value !== "object") return undefined; |
| 501 | const rec = value as { id?: unknown }; |
| 502 | return typeof rec.id === "number" ? rec.id : undefined; |
| 503 | }; |
| 504 | |
| 505 | const recordOf = (value: unknown): Record<string, unknown> => |
| 506 | value !== null && typeof value === "object" ? (value as Record<string, unknown>) : {}; |
| 507 | |
| 508 | const asNumber = (value: unknown): number | undefined => |
| 509 | typeof value === "number" ? value : undefined; |
| 510 | |
| 511 | const asString = (value: unknown): string | undefined => |
| 512 | typeof value === "string" ? value : undefined; |
| 513 | |
| 514 | const asBoolean = (value: unknown): boolean | undefined => |
| 515 | typeof value === "boolean" ? value : undefined; |
| 516 | |
| 517 | const asStringArray = (value: unknown): string[] | undefined => |
| 518 | Array.isArray(value) |
| 519 | ? value.filter((item): item is string => typeof item === "string") |
| 520 | : undefined; |
| 521 | |
| 522 | type NormalizedHealthHttp = { |
| 523 | domain: string | null; |
| 524 | path: string; |
| 525 | response: string; |
| 526 | statusCodes: string[]; |
| 527 | tls: boolean; |
| 528 | }; |
| 529 | |
| 530 | type NormalizedHealthCheck = { |
| 531 | protocol: HealthCheckProtocol; |
| 532 | port: number; |
| 533 | interval: number; |
| 534 | timeout: number; |
| 535 | retries: number; |
| 536 | http?: NormalizedHealthHttp; |
| 537 | }; |
| 538 | |
| 539 | type NormalizedServiceHttp = { |
| 540 | cookieName: string; |
| 541 | cookieLifetime: number; |
| 542 | timeoutIdle: number; |
| 543 | stickySessions: boolean; |
| 544 | redirectHttp?: boolean; |
| 545 | certificates?: number[]; |
| 546 | }; |
| 547 | |
| 548 | type NormalizedService = { |
| 549 | protocol: LoadBalancerProtocol; |
| 550 | listenPort: number; |
| 551 | destinationPort: number; |
| 552 | proxyprotocol: boolean; |
| 553 | healthCheck: NormalizedHealthCheck; |
| 554 | http?: NormalizedServiceHttp; |
| 555 | }; |
| 556 | |
| 557 | type NormalizedTarget = |
| 558 | | { |
| 559 | type: "server"; |
| 560 | serverId: number; |
| 561 | ip?: string; |
| 562 | usePrivateIp: boolean; |
| 563 | } |
| 564 | | { |
| 565 | type: "label_selector"; |
| 566 | selector: string; |
| 567 | usePrivateIp: boolean; |
| 568 | } |
| 569 | | { |
| 570 | type: "ip"; |
| 571 | ip: string; |
| 572 | }; |
| 573 | |
| 574 | const defaultHealthCheck = ( |
| 575 | protocol: LoadBalancerProtocol, |
| 576 | destinationPort: number, |
| 577 | override?: LoadBalancerHealthCheck, |
| 578 | ): NormalizedHealthCheck => { |
| 579 | const hcProtocol = override?.protocol ?? (protocol === "tcp" ? "tcp" : "http"); |
| 580 | const httpSource = override?.http; |
| 581 | return { |
| 582 | protocol: hcProtocol, |
| 583 | port: override?.port ?? destinationPort, |
| 584 | interval: override?.interval ?? DEFAULT_HC_INTERVAL, |
| 585 | timeout: override?.timeout ?? DEFAULT_HC_TIMEOUT, |
| 586 | retries: override?.retries ?? DEFAULT_HC_RETRIES, |
| 587 | http: |
| 588 | hcProtocol === "http" |
| 589 | ? { |
| 590 | domain: httpSource?.domain ?? null, |
| 591 | path: httpSource?.path ?? "/", |
| 592 | response: httpSource?.response ?? "", |
| 593 | statusCodes: [...(httpSource?.statusCodes ?? ["2??", "3??"])].sort(), |
| 594 | tls: httpSource?.tls ?? false, |
| 595 | } |
| 596 | : undefined, |
| 597 | }; |
| 598 | }; |
| 599 | |
| 600 | const defaultServiceHttp = ( |
| 601 | protocol: LoadBalancerProtocol, |
| 602 | http: LoadBalancerServiceHttp | undefined, |
| 603 | ): NormalizedServiceHttp | undefined => { |
| 604 | if (protocol === "tcp") return undefined; |
| 605 | const certificates = (http?.certificates ?? []) |
| 606 | .map(certificateIdOf) |
| 607 | .filter((id): id is number => id !== undefined) |
| 608 | .sort((a, b) => a - b); |
| 609 | const userProvided = http !== undefined; |
| 610 | if (!userProvided && protocol !== "https") return undefined; |
| 611 | return { |
| 612 | cookieName: http?.cookieName ?? DEFAULT_COOKIE_NAME, |
| 613 | cookieLifetime: http?.cookieLifetime ?? DEFAULT_COOKIE_LIFETIME, |
| 614 | timeoutIdle: http?.timeoutIdle ?? DEFAULT_TIMEOUT_IDLE, |
| 615 | stickySessions: http?.stickySessions ?? false, |
| 616 | ...(protocol === "https" |
| 617 | ? { |
| 618 | redirectHttp: http?.redirectHttp ?? false, |
| 619 | certificates, |
| 620 | } |
| 621 | : {}), |
| 622 | }; |
| 623 | }; |
| 624 | |
| 625 | const desiredServices = ( |
| 626 | services: readonly LoadBalancerService[] | undefined, |
| 627 | ): NormalizedService[] => |
| 628 | (services ?? []) |
| 629 | .map((service) => ({ |
| 630 | protocol: service.protocol, |
| 631 | listenPort: service.listenPort, |
| 632 | destinationPort: service.destinationPort, |
| 633 | proxyprotocol: service.proxyprotocol ?? false, |
| 634 | healthCheck: defaultHealthCheck( |
| 635 | service.protocol, |
| 636 | service.destinationPort, |
| 637 | service.healthCheck, |
| 638 | ), |
| 639 | http: defaultServiceHttp(service.protocol, service.http), |
| 640 | })) |
| 641 | .sort((a, b) => a.listenPort - b.listenPort); |
| 642 | |
| 643 | const observedHealthHttp = (value: unknown): NormalizedHealthHttp | undefined => { |
| 644 | if (value === null || typeof value !== "object") return undefined; |
| 645 | const rec = recordOf(value); |
| 646 | const statusCodes = asStringArray(rec.status_codes) ?? []; |
| 647 | return { |
| 648 | domain: rec.domain === undefined ? null : ((rec.domain as string | null) ?? null), |
| 649 | path: asString(rec.path) ?? "/", |
| 650 | response: asString(rec.response) ?? "", |
| 651 | statusCodes: [...statusCodes].sort(), |
| 652 | tls: asBoolean(rec.tls) ?? false, |
| 653 | }; |
| 654 | }; |
| 655 | |
| 656 | const observedHealthCheck = ( |
| 657 | value: unknown, |
| 658 | destinationPort: number, |
| 659 | protocol: LoadBalancerProtocol, |
| 660 | ): NormalizedHealthCheck => { |
| 661 | const rec = recordOf(value); |
| 662 | const hcProtocol = asHealthProtocol( |
| 663 | asString(rec.protocol) ?? (protocol === "tcp" ? "tcp" : "http"), |
| 664 | ); |
| 665 | return { |
| 666 | protocol: hcProtocol, |
| 667 | port: asNumber(rec.port) ?? destinationPort, |
| 668 | interval: asNumber(rec.interval) ?? DEFAULT_HC_INTERVAL, |
| 669 | timeout: asNumber(rec.timeout) ?? DEFAULT_HC_TIMEOUT, |
| 670 | retries: asNumber(rec.retries) ?? DEFAULT_HC_RETRIES, |
| 671 | http: hcProtocol === "http" ? observedHealthHttp(rec.http) : undefined, |
| 672 | }; |
| 673 | }; |
| 674 | |
| 675 | const observedServiceHttp = ( |
| 676 | protocol: LoadBalancerProtocol, |
| 677 | value: unknown, |
| 678 | ): NormalizedServiceHttp | undefined => { |
| 679 | if (protocol === "tcp") return undefined; |
| 680 | const rec = recordOf(value); |
| 681 | const certificates = Array.isArray(rec.certificates) |
| 682 | ? rec.certificates.filter((id): id is number => typeof id === "number").sort((a, b) => a - b) |
| 683 | : []; |
| 684 | return { |
| 685 | cookieName: asString(rec.cookie_name) ?? DEFAULT_COOKIE_NAME, |
| 686 | cookieLifetime: asNumber(rec.cookie_lifetime) ?? DEFAULT_COOKIE_LIFETIME, |
| 687 | timeoutIdle: asNumber(rec.timeout_idle) ?? DEFAULT_TIMEOUT_IDLE, |
| 688 | stickySessions: asBoolean(rec.sticky_sessions) ?? false, |
| 689 | ...(protocol === "https" |
| 690 | ? { |
| 691 | redirectHttp: asBoolean(rec.redirect_http) ?? false, |
| 692 | certificates, |
| 693 | } |
| 694 | : {}), |
| 695 | }; |
| 696 | }; |
| 697 | |
| 698 | const observedServices = (value: unknown): NormalizedService[] => { |
| 699 | if (!Array.isArray(value)) return []; |
| 700 | return value |
| 701 | .map((item) => { |
| 702 | const rec = recordOf(item); |
| 703 | const protocol = asProtocol(asString(rec.protocol) ?? "tcp"); |
| 704 | const destinationPort = asNumber(rec.destination_port) ?? 80; |
| 705 | return { |
| 706 | protocol, |
| 707 | listenPort: asNumber(rec.listen_port) ?? 0, |
| 708 | destinationPort, |
| 709 | proxyprotocol: asBoolean(rec.proxyprotocol) ?? false, |
| 710 | healthCheck: observedHealthCheck(rec.health_check, destinationPort, protocol), |
| 711 | http: observedServiceHttp(protocol, rec.http), |
| 712 | }; |
| 713 | }) |
| 714 | .sort((a, b) => a.listenPort - b.listenPort); |
| 715 | }; |
| 716 | |
| 717 | const serviceFingerprint = (service: NormalizedService): string => JSON.stringify(service); |
| 718 | |
| 719 | const toServiceAttr = (service: NormalizedService): LoadBalancerServiceAttr => ({ |
| 720 | protocol: service.protocol, |
| 721 | listenPort: service.listenPort, |
| 722 | destinationPort: service.destinationPort, |
| 723 | proxyprotocol: service.proxyprotocol, |
| 724 | healthCheck: { |
| 725 | protocol: service.healthCheck.protocol, |
| 726 | port: service.healthCheck.port, |
| 727 | interval: service.healthCheck.interval, |
| 728 | timeout: service.healthCheck.timeout, |
| 729 | retries: service.healthCheck.retries, |
| 730 | ...(service.healthCheck.http |
| 731 | ? { |
| 732 | http: { |
| 733 | domain: service.healthCheck.http.domain, |
| 734 | path: service.healthCheck.http.path, |
| 735 | ...(service.healthCheck.http.response |
| 736 | ? { response: service.healthCheck.http.response } |
| 737 | : {}), |
| 738 | ...(service.healthCheck.http.statusCodes.length > 0 |
| 739 | ? { statusCodes: service.healthCheck.http.statusCodes } |
| 740 | : {}), |
| 741 | ...(service.healthCheck.http.tls ? { tls: true } : {}), |
| 742 | }, |
| 743 | } |
| 744 | : {}), |
| 745 | }, |
| 746 | ...(service.http |
| 747 | ? { |
| 748 | http: { |
| 749 | cookieName: service.http.cookieName, |
| 750 | cookieLifetime: service.http.cookieLifetime, |
| 751 | timeoutIdle: service.http.timeoutIdle, |
| 752 | stickySessions: service.http.stickySessions, |
| 753 | ...(service.http.redirectHttp !== undefined |
| 754 | ? { redirectHttp: service.http.redirectHttp } |
| 755 | : {}), |
| 756 | ...(service.http.certificates !== undefined |
| 757 | ? { certificates: service.http.certificates } |
| 758 | : {}), |
| 759 | }, |
| 760 | } |
| 761 | : {}), |
| 762 | }); |
| 763 | |
| 764 | const toHealthCheckRequest = (healthCheck: NormalizedHealthCheck) => ({ |
| 765 | protocol: healthCheck.protocol, |
| 766 | port: healthCheck.port, |
| 767 | interval: healthCheck.interval, |
| 768 | timeout: healthCheck.timeout, |
| 769 | retries: healthCheck.retries, |
| 770 | ...(healthCheck.http |
| 771 | ? { |
| 772 | http: { |
| 773 | ...(healthCheck.http.domain !== null ? { domain: healthCheck.http.domain } : {}), |
| 774 | path: healthCheck.http.path, |
| 775 | ...(healthCheck.http.response ? { response: healthCheck.http.response } : {}), |
| 776 | status_codes: healthCheck.http.statusCodes, |
| 777 | tls: healthCheck.http.tls, |
| 778 | }, |
| 779 | } |
| 780 | : {}), |
| 781 | }); |
| 782 | |
| 783 | const toHttpRequest = (http: NormalizedServiceHttp | undefined) => { |
| 784 | if (http === undefined) return undefined; |
| 785 | return { |
| 786 | cookie_name: http.cookieName, |
| 787 | cookie_lifetime: http.cookieLifetime, |
| 788 | sticky_sessions: http.stickySessions, |
| 789 | ...(http.redirectHttp !== undefined ? { redirect_http: http.redirectHttp } : {}), |
| 790 | ...(http.certificates !== undefined ? { certificates: http.certificates } : {}), |
| 791 | }; |
| 792 | }; |
| 793 | |
| 794 | const toCreateService = (service: NormalizedService): CreateLoadBalancerRequestServicesItem => |
| 795 | ({ |
| 796 | protocol: service.protocol, |
| 797 | listen_port: service.listenPort, |
| 798 | destination_port: service.destinationPort, |
| 799 | proxyprotocol: service.proxyprotocol, |
| 800 | health_check: toHealthCheckRequest(service.healthCheck), |
| 801 | ...(service.http ? { http: toHttpRequest(service.http) } : {}), |
| 802 | }) as CreateLoadBalancerRequestServicesItem; |
| 803 | |
| 804 | const desiredTargets = (targets: readonly LoadBalancerTarget[] | undefined): NormalizedTarget[] => { |
| 805 | const next: NormalizedTarget[] = []; |
| 806 | for (const target of targets ?? []) { |
| 807 | if (target.type === "server") { |
| 808 | const serverId = serverIdOf(target.server); |
| 809 | if (serverId === undefined) continue; |
| 810 | next.push({ |
| 811 | type: "server", |
| 812 | serverId, |
| 813 | ...(target.ip !== undefined ? { ip: target.ip } : {}), |
| 814 | usePrivateIp: target.usePrivateIp ?? false, |
| 815 | }); |
| 816 | } else if (target.type === "label_selector") { |
| 817 | next.push({ |
| 818 | type: "label_selector", |
| 819 | selector: target.selector, |
| 820 | usePrivateIp: target.usePrivateIp ?? false, |
| 821 | }); |
| 822 | } else { |
| 823 | next.push({ type: "ip", ip: target.ip }); |
| 824 | } |
| 825 | } |
| 826 | return next.sort((a, b) => targetKey(a).localeCompare(targetKey(b))); |
| 827 | }; |
| 828 | |
| 829 | const targetKey = (target: NormalizedTarget): string => { |
| 830 | if (target.type === "server") { |
| 831 | return `server:${target.serverId}:${target.usePrivateIp ? 1 : 0}:${target.ip ?? ""}`; |
| 832 | } |
| 833 | if (target.type === "label_selector") { |
| 834 | return `label_selector:${target.selector}:${target.usePrivateIp ? 1 : 0}`; |
| 835 | } |
| 836 | return `ip:${target.ip}`; |
| 837 | }; |
| 838 | |
| 839 | const observedHealthStatus = ( |
| 840 | value: unknown, |
| 841 | ): { listenPort: number; status: TargetHealthStatus }[] => { |
| 842 | if (!Array.isArray(value)) return []; |
| 843 | return value.flatMap((item) => { |
| 844 | const rec = recordOf(item); |
| 845 | const listenPort = asNumber(rec.listen_port); |
| 846 | if (listenPort === undefined) return []; |
| 847 | return [ |
| 848 | { |
| 849 | listenPort, |
| 850 | status: asHealthStatus(asString(rec.status) ?? "unknown"), |
| 851 | }, |
| 852 | ]; |
| 853 | }); |
| 854 | }; |
| 855 | |
| 856 | const observedTargets = (value: unknown): NormalizedTarget[] => { |
| 857 | if (!Array.isArray(value)) return []; |
| 858 | const next: NormalizedTarget[] = []; |
| 859 | for (const item of value) { |
| 860 | const rec = recordOf(item); |
| 861 | const type = asString(rec.type); |
| 862 | if (type === "server") { |
| 863 | const server = recordOf(rec.server); |
| 864 | const serverId = asNumber(server.id); |
| 865 | if (serverId === undefined) continue; |
| 866 | const ip = asString(server.ip); |
| 867 | next.push({ |
| 868 | type: "server", |
| 869 | serverId, |
| 870 | ...(ip !== undefined ? { ip } : {}), |
| 871 | usePrivateIp: asBoolean(rec.use_private_ip) ?? false, |
| 872 | }); |
| 873 | } else if (type === "label_selector") { |
| 874 | const selector = asString(recordOf(rec.label_selector).selector); |
| 875 | if (selector === undefined) continue; |
| 876 | next.push({ |
| 877 | type: "label_selector", |
| 878 | selector, |
| 879 | usePrivateIp: asBoolean(rec.use_private_ip) ?? false, |
| 880 | }); |
| 881 | } else if (type === "ip") { |
| 882 | const ip = asString(recordOf(rec.ip).ip); |
| 883 | if (ip === undefined) continue; |
| 884 | next.push({ type: "ip", ip }); |
| 885 | } |
| 886 | } |
| 887 | return next.sort((a, b) => targetKey(a).localeCompare(targetKey(b))); |
| 888 | }; |
| 889 | |
| 890 | const toTargetAttr = (target: NormalizedTarget, raw: unknown): LoadBalancerTargetAttr => { |
| 891 | const rec = recordOf(raw); |
| 892 | if (target.type === "server") { |
| 893 | return { |
| 894 | type: "server", |
| 895 | serverId: target.serverId, |
| 896 | ...(target.ip !== undefined ? { ip: target.ip } : {}), |
| 897 | usePrivateIp: target.usePrivateIp, |
| 898 | healthStatus: observedHealthStatus(rec.health_status), |
| 899 | }; |
| 900 | } |
| 901 | if (target.type === "label_selector") { |
| 902 | return { |
| 903 | type: "label_selector", |
| 904 | selector: target.selector, |
| 905 | usePrivateIp: target.usePrivateIp, |
| 906 | }; |
| 907 | } |
| 908 | return { |
| 909 | type: "ip", |
| 910 | ip: target.ip, |
| 911 | healthStatus: observedHealthStatus(rec.health_status), |
| 912 | }; |
| 913 | }; |
| 914 | |
| 915 | const desiredNetworkIds = (networks: LoadBalancerProps["networks"] | undefined): number[] => { |
| 916 | const ids = new Set<number>(); |
| 917 | for (const item of networks ?? []) { |
| 918 | const id = networkIdOf(item); |
| 919 | if (id !== undefined) ids.add(id); |
| 920 | } |
| 921 | return [...ids].sort((a, b) => a - b); |
| 922 | }; |
| 923 | |
| 924 | const observedPrivateNetworks = (value: unknown): { networkId: number; ip: string }[] => { |
| 925 | if (!Array.isArray(value)) return []; |
| 926 | return value |
| 927 | .flatMap((item) => { |
| 928 | const rec = recordOf(item); |
| 929 | const networkId = asNumber(rec.network); |
| 930 | const ip = asString(rec.ip); |
| 931 | if (networkId === undefined || ip === undefined) return []; |
| 932 | return [{ networkId, ip }]; |
| 933 | }) |
| 934 | .sort((a, b) => a.networkId - b.networkId); |
| 935 | }; |
| 936 | |
| 937 | const toAttrs = (lb: CloudLoadBalancer): LoadBalancer["Attributes"] => { |
| 938 | const services = observedServices(lb.services); |
| 939 | const rawTargets = Array.isArray(lb.targets) ? lb.targets : []; |
| 940 | const targets = observedTargets(lb.targets); |
| 941 | const targetAttrs = targets.map((target, index) => toTargetAttr(target, rawTargets[index])); |
| 942 | return { |
| 943 | id: lb.id, |
| 944 | name: lb.name, |
| 945 | loadBalancerType: lb.load_balancer_type.name, |
| 946 | loadBalancerTypeId: lb.load_balancer_type.id, |
| 947 | location: lb.location.name, |
| 948 | locationId: lb.location.id, |
| 949 | networkZone: lb.location.network_zone, |
| 950 | algorithm: asAlgorithm(lb.algorithm.type), |
| 951 | ipv4: lb.public_net.ipv4.ip, |
| 952 | ipv6: lb.public_net.ipv6.ip, |
| 953 | publicInterface: lb.public_net.enabled, |
| 954 | deleteProtection: lb.protection.delete, |
| 955 | services: services.map(toServiceAttr), |
| 956 | targets: targetAttrs, |
| 957 | privateNetworks: observedPrivateNetworks(lb.private_net), |
| 958 | labels: userLabels(lb.labels), |
| 959 | created: lb.created, |
| 960 | }; |
| 961 | }; |
| 962 | |
| 963 | const retryable = (e: { readonly _tag: string }): boolean => |
| 964 | e._tag === "TooManyRequests" || |
| 965 | e._tag === "ServiceUnavailable" || |
| 966 | e._tag === "InternalServerError" || |
| 967 | e._tag === "BadGateway" || |
| 968 | e._tag === "GatewayTimeout" || |
| 969 | e._tag === "Locked" || |
| 970 | e._tag === "Conflict"; |
| 971 | |
| 972 | const backoff = Schedule.min([ |
| 973 | Schedule.exponential(Duration.millis(500), 1.5), |
| 974 | Schedule.spaced(Duration.seconds(5)), |
| 975 | ]); |
| 976 | |
| 977 | const busyRetry = { |
| 978 | while: retryable, |
| 979 | times: 8, |
| 980 | schedule: backoff, |
| 981 | } as const; |
| 982 | |
| 983 | const alreadyThere = (e: { readonly _tag: string }): boolean => |
| 984 | e._tag === "Conflict" || e._tag === "UnprocessableEntity"; |
| 985 | |
| 986 | const alreadyGone = (e: { readonly _tag: string }): boolean => |
| 987 | e._tag === "NotFound" || e._tag === "UnprocessableEntity"; |
| 988 | |
| 989 | const createLoadBalancerName = (id: string, name: string | undefined, existing?: string) => |
| 990 | Effect.gen(function* () { |
| 991 | return ( |
| 992 | name ?? |
| 993 | existing ?? |
| 994 | (yield* createPhysicalName({ |
| 995 | id, |
| 996 | maxLength: MAX_NAME_LENGTH, |
| 997 | lowercase: true, |
| 998 | })) |
| 999 | ); |
| 1000 | }); |
| 1001 | |
| 1002 | const getById = (id: number) => |
| 1003 | Hetzner.loadBalancers.getLoadBalancer({ id }).pipe( |
| 1004 | Effect.map(({ load_balancer }) => load_balancer), |
| 1005 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 1006 | ); |
| 1007 | |
| 1008 | const getByName = (name: string) => |
| 1009 | Hetzner.loadBalancers |
| 1010 | .listLoadBalancers({ name, per_page: 50 }) |
| 1011 | .pipe(Effect.map(({ load_balancers }) => load_balancers.find((item) => item.name === name))); |
| 1012 | |
| 1013 | const getByLabels = (labels: Record<string, string>) => |
| 1014 | Hetzner.loadBalancers |
| 1015 | .listLoadBalancers({ |
| 1016 | label_selector: labelSelector(labels), |
| 1017 | per_page: 50, |
| 1018 | }) |
| 1019 | .pipe(Effect.map(({ load_balancers }) => load_balancers[0])); |
| 1020 | |
| 1021 | const observe = Effect.fn(function* ({ |
| 1022 | id, |
| 1023 | name, |
| 1024 | outputId, |
| 1025 | }: { |
| 1026 | id: string; |
| 1027 | name?: string; |
| 1028 | outputId?: number; |
| 1029 | }) { |
| 1030 | if (outputId !== undefined) { |
| 1031 | const byId = yield* getById(outputId); |
| 1032 | if (byId !== undefined) return byId; |
| 1033 | } |
| 1034 | if (name !== undefined) { |
| 1035 | const byName = yield* getByName(name); |
| 1036 | if (byName !== undefined) return byName; |
| 1037 | } |
| 1038 | const internal = yield* createInternalLabels(id); |
| 1039 | return yield* getByLabels(internal); |
| 1040 | }); |
| 1041 | |
| 1042 | const refresh = (id: number) => |
| 1043 | Hetzner.loadBalancers.getLoadBalancer({ id }).pipe( |
| 1044 | Effect.map(({ load_balancer }) => load_balancer), |
| 1045 | Effect.retry({ |
| 1046 | while: (e) => e._tag === "NotFound" || retryable(e), |
| 1047 | times: 8, |
| 1048 | schedule: backoff, |
| 1049 | }), |
| 1050 | ); |
| 1051 | |
| 1052 | const runAction = <E extends { readonly _tag: string }, R>( |
| 1053 | effect: Effect.Effect<{ action: { id: number } }, E, R>, |
| 1054 | ) => |
| 1055 | effect.pipe( |
| 1056 | Effect.retry(busyRetry), |
| 1057 | Effect.flatMap(({ action }) => waitForAction(action)), |
| 1058 | ); |
| 1059 | |
| 1060 | const matchesPlacement = ( |
| 1061 | current: CloudLoadBalancer, |
| 1062 | location: string | undefined, |
| 1063 | networkZone: string | undefined, |
| 1064 | ): boolean => { |
| 1065 | if (location !== undefined && current.location.name !== location) { |
| 1066 | return false; |
| 1067 | } |
| 1068 | if (networkZone !== undefined && current.location.network_zone !== networkZone) { |
| 1069 | return false; |
| 1070 | } |
| 1071 | return true; |
| 1072 | }; |
| 1073 | |
| 1074 | const syncMetadata = (args: { |
| 1075 | current: CloudLoadBalancer; |
| 1076 | name: string; |
| 1077 | labels: Record<string, string>; |
| 1078 | }) => |
| 1079 | Effect.gen(function* () { |
| 1080 | const observedLabels = tagRecord(args.current.labels); |
| 1081 | const { removed, upsert } = diffLabels(observedLabels, args.labels); |
| 1082 | const labelsChanged = removed.length > 0 || upsert.length > 0; |
| 1083 | const nameChanged = args.current.name !== args.name; |
| 1084 | if (!labelsChanged && !nameChanged) return args.current; |
| 1085 | const updated = yield* Hetzner.loadBalancers |
| 1086 | .updateLoadBalancer({ |
| 1087 | id: args.current.id, |
| 1088 | name: nameChanged ? args.name : undefined, |
| 1089 | labels: labelsChanged ? args.labels : undefined, |
| 1090 | }) |
| 1091 | .pipe(Effect.retry(busyRetry)); |
| 1092 | return updated.load_balancer; |
| 1093 | }); |
| 1094 | |
| 1095 | const syncAlgorithm = (current: CloudLoadBalancer, desired: LoadBalancerAlgorithm) => |
| 1096 | Effect.gen(function* () { |
| 1097 | if (asAlgorithm(current.algorithm.type) === desired) return; |
| 1098 | yield* runAction( |
| 1099 | Hetzner.loadBalancerActions.changeLoadBalancerAlgorithm({ |
| 1100 | id: current.id, |
| 1101 | type: desired, |
| 1102 | }), |
| 1103 | ); |
| 1104 | }); |
| 1105 | |
| 1106 | const syncType = (current: CloudLoadBalancer, desired: string) => |
| 1107 | Effect.gen(function* () { |
| 1108 | if (current.load_balancer_type.name === desired) return; |
| 1109 | yield* runAction( |
| 1110 | Hetzner.loadBalancerActions.changeLoadBalancerType({ |
| 1111 | id: current.id, |
| 1112 | load_balancer_type: desired, |
| 1113 | }), |
| 1114 | ); |
| 1115 | }); |
| 1116 | |
| 1117 | const syncProtection = (current: CloudLoadBalancer, desired: boolean) => |
| 1118 | Effect.gen(function* () { |
| 1119 | if (current.protection.delete === desired) return; |
| 1120 | yield* runAction( |
| 1121 | Hetzner.loadBalancerActions.changeLoadBalancerProtection({ |
| 1122 | id: current.id, |
| 1123 | delete: desired, |
| 1124 | }), |
| 1125 | ); |
| 1126 | }); |
| 1127 | |
| 1128 | const syncPublicInterface = (current: CloudLoadBalancer, desired: boolean) => |
| 1129 | Effect.gen(function* () { |
| 1130 | if (current.public_net.enabled === desired) return; |
| 1131 | if (desired) { |
| 1132 | yield* runAction( |
| 1133 | Hetzner.loadBalancerActions.enableLoadBalancerPublicInterface({ |
| 1134 | id: current.id, |
| 1135 | }), |
| 1136 | ); |
| 1137 | return; |
| 1138 | } |
| 1139 | yield* runAction( |
| 1140 | Hetzner.loadBalancerActions.disableLoadBalancerPublicInterface({ |
| 1141 | id: current.id, |
| 1142 | }), |
| 1143 | ); |
| 1144 | }); |
| 1145 | |
| 1146 | const syncServices = ( |
| 1147 | loadBalancerId: number, |
| 1148 | observed: readonly NormalizedService[], |
| 1149 | desired: readonly NormalizedService[], |
| 1150 | ) => |
| 1151 | Effect.gen(function* () { |
| 1152 | const observedByPort = new Map(observed.map((service) => [service.listenPort, service])); |
| 1153 | const desiredByPort = new Map(desired.map((service) => [service.listenPort, service])); |
| 1154 | |
| 1155 | for (const service of observed) { |
| 1156 | if (desiredByPort.has(service.listenPort)) continue; |
| 1157 | yield* runAction( |
| 1158 | Hetzner.loadBalancerActions.deleteLoadBalancerService({ |
| 1159 | id: loadBalancerId, |
| 1160 | listen_port: service.listenPort, |
| 1161 | }), |
| 1162 | ).pipe(Effect.catchIf(alreadyGone, () => Effect.void)); |
| 1163 | } |
| 1164 | |
| 1165 | for (const service of desired) { |
| 1166 | const existing = observedByPort.get(service.listenPort); |
| 1167 | if (existing === undefined) { |
| 1168 | yield* runAction( |
| 1169 | Hetzner.loadBalancerActions.addLoadBalancerService({ |
| 1170 | id: loadBalancerId, |
| 1171 | protocol: service.protocol, |
| 1172 | listen_port: service.listenPort, |
| 1173 | destination_port: service.destinationPort, |
| 1174 | proxyprotocol: service.proxyprotocol, |
| 1175 | health_check: toHealthCheckRequest(service.healthCheck), |
| 1176 | http: toHttpRequest(service.http), |
| 1177 | }), |
| 1178 | ).pipe( |
| 1179 | Effect.catchIf( |
| 1180 | (e) => e._tag === "Conflict" || e._tag === "PreconditionFailed", |
| 1181 | () => Effect.void, |
| 1182 | ), |
| 1183 | ); |
| 1184 | continue; |
| 1185 | } |
| 1186 | if (serviceFingerprint(existing) === serviceFingerprint(service)) { |
| 1187 | continue; |
| 1188 | } |
| 1189 | yield* runAction( |
| 1190 | Hetzner.loadBalancerActions.updateLoadBalancerService({ |
| 1191 | id: loadBalancerId, |
| 1192 | protocol: service.protocol, |
| 1193 | listen_port: service.listenPort, |
| 1194 | destination_port: service.destinationPort, |
| 1195 | proxyprotocol: service.proxyprotocol, |
| 1196 | health_check: toHealthCheckRequest(service.healthCheck), |
| 1197 | http: toHttpRequest(service.http), |
| 1198 | }), |
| 1199 | ); |
| 1200 | } |
| 1201 | }); |
| 1202 | |
| 1203 | const addTargetRequest = (loadBalancerId: number, target: NormalizedTarget) => { |
| 1204 | if (target.type === "server") { |
| 1205 | return Hetzner.loadBalancerActions.addLoadBalancerTarget({ |
| 1206 | id: loadBalancerId, |
| 1207 | type: "server", |
| 1208 | server: { |
| 1209 | id: target.serverId, |
| 1210 | ...(target.ip !== undefined ? { ip: target.ip } : {}), |
| 1211 | }, |
| 1212 | use_private_ip: target.usePrivateIp, |
| 1213 | }); |
| 1214 | } |
| 1215 | if (target.type === "label_selector") { |
| 1216 | return Hetzner.loadBalancerActions.addLoadBalancerTarget({ |
| 1217 | id: loadBalancerId, |
| 1218 | type: "label_selector", |
| 1219 | label_selector: { selector: target.selector }, |
| 1220 | use_private_ip: target.usePrivateIp, |
| 1221 | }); |
| 1222 | } |
| 1223 | return Hetzner.loadBalancerActions.addLoadBalancerTarget({ |
| 1224 | id: loadBalancerId, |
| 1225 | type: "ip", |
| 1226 | ip: { ip: target.ip }, |
| 1227 | }); |
| 1228 | }; |
| 1229 | |
| 1230 | const removeTargetRequest = (loadBalancerId: number, target: NormalizedTarget) => { |
| 1231 | if (target.type === "server") { |
| 1232 | return Hetzner.loadBalancerActions.removeLoadBalancerTarget({ |
| 1233 | id: loadBalancerId, |
| 1234 | type: "server", |
| 1235 | server: { |
| 1236 | id: target.serverId, |
| 1237 | ...(target.ip !== undefined ? { ip: target.ip } : {}), |
| 1238 | }, |
| 1239 | }); |
| 1240 | } |
| 1241 | if (target.type === "label_selector") { |
| 1242 | return Hetzner.loadBalancerActions.removeLoadBalancerTarget({ |
| 1243 | id: loadBalancerId, |
| 1244 | type: "label_selector", |
| 1245 | label_selector: { selector: target.selector }, |
| 1246 | }); |
| 1247 | } |
| 1248 | return Hetzner.loadBalancerActions.removeLoadBalancerTarget({ |
| 1249 | id: loadBalancerId, |
| 1250 | type: "ip", |
| 1251 | ip: { ip: target.ip }, |
| 1252 | }); |
| 1253 | }; |
| 1254 | |
| 1255 | const syncTargets = ( |
| 1256 | loadBalancerId: number, |
| 1257 | observed: readonly NormalizedTarget[], |
| 1258 | desired: readonly NormalizedTarget[], |
| 1259 | ) => |
| 1260 | Effect.gen(function* () { |
| 1261 | const observedKeys = new Set(observed.map(targetKey)); |
| 1262 | const desiredKeys = new Set(desired.map(targetKey)); |
| 1263 | |
| 1264 | for (const target of observed) { |
| 1265 | if (desiredKeys.has(targetKey(target))) continue; |
| 1266 | yield* runAction(removeTargetRequest(loadBalancerId, target)).pipe( |
| 1267 | Effect.catchIf(alreadyGone, () => Effect.void), |
| 1268 | ); |
| 1269 | } |
| 1270 | |
| 1271 | for (const target of desired) { |
| 1272 | if (observedKeys.has(targetKey(target))) continue; |
| 1273 | yield* addTargetRequest(loadBalancerId, target).pipe( |
| 1274 | Effect.retry({ |
| 1275 | while: (e) => retryable(e) || e._tag === "UnprocessableEntity", |
| 1276 | times: 8, |
| 1277 | schedule: backoff, |
| 1278 | }), |
| 1279 | Effect.flatMap(({ action }) => waitForAction(action)), |
| 1280 | Effect.catchIf(alreadyThere, () => Effect.void), |
| 1281 | ); |
| 1282 | } |
| 1283 | }); |
| 1284 | |
| 1285 | const syncNetworks = ( |
| 1286 | loadBalancerId: number, |
| 1287 | observed: readonly { networkId: number }[], |
| 1288 | desired: readonly number[], |
| 1289 | ) => |
| 1290 | Effect.gen(function* () { |
| 1291 | const observedIds = new Set(observed.map((item) => item.networkId)); |
| 1292 | const desiredIds = new Set(desired); |
| 1293 | |
| 1294 | for (const item of observed) { |
| 1295 | if (desiredIds.has(item.networkId)) continue; |
| 1296 | yield* runAction( |
| 1297 | Hetzner.loadBalancerActions.detachLoadBalancerFromNetwork({ |
| 1298 | id: loadBalancerId, |
| 1299 | network: item.networkId, |
| 1300 | }), |
| 1301 | ).pipe(Effect.catchIf(alreadyGone, () => Effect.void)); |
| 1302 | } |
| 1303 | |
| 1304 | for (const networkId of desired) { |
| 1305 | if (observedIds.has(networkId)) continue; |
| 1306 | yield* runAction( |
| 1307 | Hetzner.loadBalancerActions.attachLoadBalancerToNetwork({ |
| 1308 | id: loadBalancerId, |
| 1309 | network: networkId, |
| 1310 | }), |
| 1311 | ).pipe(Effect.catchIf(alreadyThere, () => Effect.void)); |
| 1312 | } |
| 1313 | }); |
| 1314 | |
| 1315 | export const LoadBalancerProvider = () => |
| 1316 | Provider.succeed(LoadBalancer, { |
| 1317 | stables: ["id", "location", "locationId", "networkZone", "created"], |
| 1318 | |
| 1319 | list: Effect.fn(function* () { |
| 1320 | const items = yield* Hetzner.loadBalancers.listLoadBalancers |
| 1321 | .items({ label_selector: alchemyStackSelector, per_page: 50 }) |
| 1322 | .pipe( |
| 1323 | Stream.runCollect, |
| 1324 | Effect.map((chunk) => Array.from(chunk)), |
| 1325 | ); |
| 1326 | return items.map(toAttrs); |
| 1327 | }), |
| 1328 | |
| 1329 | diff: Effect.fn(function* ({ news, output }) { |
| 1330 | if (!isResolved(news)) return undefined; |
| 1331 | if (output !== undefined) { |
| 1332 | if (news.location !== undefined && news.location !== output.location) { |
| 1333 | return { action: "replace" } as const; |
| 1334 | } |
| 1335 | if (news.networkZone !== undefined && news.networkZone !== output.networkZone) { |
| 1336 | return { action: "replace" } as const; |
| 1337 | } |
| 1338 | } |
| 1339 | return undefined; |
| 1340 | }), |
| 1341 | |
| 1342 | read: Effect.fn(function* ({ id, olds, output }) { |
| 1343 | const found = yield* observe({ |
| 1344 | id, |
| 1345 | name: olds?.name ?? output?.name, |
| 1346 | outputId: output?.id, |
| 1347 | }); |
| 1348 | if (found === undefined) return undefined; |
| 1349 | const attrs = toAttrs(found); |
| 1350 | const owned = yield* hasAlchemyLabels(id, tagRecord(found.labels)); |
| 1351 | return owned ? attrs : Unowned(attrs); |
| 1352 | }), |
| 1353 | |
| 1354 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 1355 | const name = yield* createLoadBalancerName(id, news.name, output?.name); |
| 1356 | const internalLabels = yield* createInternalLabels(id); |
| 1357 | const desiredLabels = { |
| 1358 | ...toLabels(news.labels), |
| 1359 | ...internalLabels, |
| 1360 | }; |
| 1361 | const loadBalancerType = news.loadBalancerType ?? DEFAULT_TYPE; |
| 1362 | const algorithm = news.algorithm ?? DEFAULT_ALGORITHM; |
| 1363 | const location = |
| 1364 | news.location ?? (news.networkZone === undefined ? DEFAULT_LOCATION : undefined); |
| 1365 | const networkZone = news.location === undefined ? news.networkZone : undefined; |
| 1366 | const publicInterface = news.publicInterface ?? true; |
| 1367 | const deleteProtection = news.deleteProtection ?? false; |
| 1368 | const services = desiredServices(news.services); |
| 1369 | const targets = desiredTargets(news.targets); |
| 1370 | const networks = desiredNetworkIds(news.networks); |
| 1371 | |
| 1372 | // Observe by id then desired name only. Do not fall back to |
| 1373 | // ownership labels — a create-first replacement still has the old |
| 1374 | // generation live under the same logical id. |
| 1375 | let current = output?.id !== undefined ? yield* getById(output.id) : undefined; |
| 1376 | if (current === undefined) { |
| 1377 | current = yield* getByName(name); |
| 1378 | } |
| 1379 | if (current !== undefined && !matchesPlacement(current, location, networkZone)) { |
| 1380 | current = undefined; |
| 1381 | } |
| 1382 | |
| 1383 | if (current === undefined) { |
| 1384 | const created = yield* Hetzner.loadBalancers |
| 1385 | .createLoadBalancer({ |
| 1386 | name, |
| 1387 | load_balancer_type: loadBalancerType, |
| 1388 | algorithm: { type: algorithm }, |
| 1389 | labels: desiredLabels, |
| 1390 | public_interface: publicInterface, |
| 1391 | ...(location !== undefined ? { location } : {}), |
| 1392 | ...(networkZone !== undefined ? { network_zone: networkZone } : {}), |
| 1393 | ...(networks[0] !== undefined ? { network: networks[0] } : {}), |
| 1394 | ...(services.length > 0 ? { services: services.map(toCreateService) } : {}), |
| 1395 | }) |
| 1396 | .pipe( |
| 1397 | Effect.retry(busyRetry), |
| 1398 | Effect.catchTag("Conflict", () => Effect.undefined), |
| 1399 | ); |
| 1400 | if (created !== undefined) { |
| 1401 | if (created.action) { |
| 1402 | yield* waitForAction(created.action); |
| 1403 | } |
| 1404 | current = created.load_balancer; |
| 1405 | } else { |
| 1406 | const hit = yield* getByName(name); |
| 1407 | if (hit !== undefined && matchesPlacement(hit, location, networkZone)) { |
| 1408 | current = hit; |
| 1409 | } |
| 1410 | } |
| 1411 | } |
| 1412 | |
| 1413 | if (current === undefined) { |
| 1414 | return yield* new LoadBalancerNotCreated({ resourceName: name }); |
| 1415 | } |
| 1416 | |
| 1417 | current = yield* syncMetadata({ |
| 1418 | current, |
| 1419 | name, |
| 1420 | labels: desiredLabels, |
| 1421 | }); |
| 1422 | yield* syncAlgorithm(current, algorithm); |
| 1423 | yield* syncType(current, loadBalancerType); |
| 1424 | const afterType = (yield* getById(current.id)) ?? current; |
| 1425 | yield* syncServices(current.id, observedServices(afterType.services), services); |
| 1426 | const afterServices = (yield* getById(current.id)) ?? afterType; |
| 1427 | yield* syncTargets(current.id, observedTargets(afterServices.targets), targets); |
| 1428 | const afterTargets = (yield* getById(current.id)) ?? afterServices; |
| 1429 | yield* syncNetworks(current.id, observedPrivateNetworks(afterTargets.private_net), networks); |
| 1430 | const afterNetworks = (yield* getById(current.id)) ?? afterTargets; |
| 1431 | yield* syncPublicInterface(afterNetworks, publicInterface); |
| 1432 | const afterPublic = (yield* getById(current.id)) ?? afterNetworks; |
| 1433 | yield* syncProtection(afterPublic, deleteProtection); |
| 1434 | |
| 1435 | return toAttrs(yield* refresh(current.id)); |
| 1436 | }), |
| 1437 | |
| 1438 | delete: Effect.fn(function* ({ output }) { |
| 1439 | const current = yield* getById(output.id); |
| 1440 | if (current === undefined) return; |
| 1441 | |
| 1442 | if (current.protection.delete) { |
| 1443 | yield* runAction( |
| 1444 | Hetzner.loadBalancerActions.changeLoadBalancerProtection({ |
| 1445 | id: current.id, |
| 1446 | delete: false, |
| 1447 | }), |
| 1448 | ).pipe(Effect.catchIf(alreadyGone, () => Effect.void)); |
| 1449 | } |
| 1450 | |
| 1451 | yield* Hetzner.loadBalancers.deleteLoadBalancer({ id: current.id }).pipe( |
| 1452 | Effect.catchTag("NotFound", () => Effect.void), |
| 1453 | Effect.retry({ |
| 1454 | while: retryable, |
| 1455 | times: 8, |
| 1456 | schedule: backoff, |
| 1457 | }), |
| 1458 | ); |
| 1459 | }), |
| 1460 | }); |