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 route53 from "@distilled.cloud/aws/route-53"; |
| 2 | import { isResolved } from "alchemy/Diff"; |
| 3 | import * as Provider from "alchemy/Provider"; |
| 4 | import { Resource } from "alchemy/Resource"; |
| 5 | import { createInternalTags, diffTags } from "alchemy/Tags"; |
| 6 | import type * as Duration from "effect/Duration"; |
| 7 | import * as Effect from "effect/Effect"; |
| 8 | import * as Schedule from "effect/Schedule"; |
| 9 | import * as Stream from "effect/Stream"; |
| 10 | import { durationToSeconds } from "../IAM/common.ts"; |
| 11 | import { plainJson } from "../internal/Observe.ts"; |
| 12 | import type { Providers } from "../Providers.ts"; |
| 13 | |
| 14 | export interface HealthCheckProps { |
| 15 | /** |
| 16 | * Health check protocol/type (e.g. `"HTTP"`, `"HTTPS"`, `"TCP"`, |
| 17 | * `"CALCULATED"`, `"CLOUDWATCH_METRIC"`). Immutable — changing it forces |
| 18 | * replacement. |
| 19 | */ |
| 20 | type: route53.HealthCheckType; |
| 21 | /** |
| 22 | * IP address of the endpoint to check. |
| 23 | */ |
| 24 | ipAddress?: string; |
| 25 | /** |
| 26 | * Port of the endpoint to check. |
| 27 | */ |
| 28 | port?: number; |
| 29 | /** |
| 30 | * Path requested for HTTP/HTTPS checks (e.g. `"/health"`). |
| 31 | */ |
| 32 | resourcePath?: string; |
| 33 | /** |
| 34 | * Fully qualified domain name of the endpoint. |
| 35 | */ |
| 36 | fullyQualifiedDomainName?: string; |
| 37 | /** |
| 38 | * String the response body must contain for the check to pass. |
| 39 | */ |
| 40 | searchString?: string; |
| 41 | /** |
| 42 | * Time between checks, e.g. `"30 seconds"` or `Duration.seconds(10)` (a |
| 43 | * bare number is milliseconds). Rounded to whole seconds on the wire |
| 44 | * (10 or 30). Immutable — changing it forces replacement. |
| 45 | * @default 30 seconds |
| 46 | */ |
| 47 | requestInterval?: Duration.Input; |
| 48 | /** |
| 49 | * Number of consecutive failures before the endpoint is considered unhealthy. |
| 50 | * @default 3 |
| 51 | */ |
| 52 | failureThreshold?: number; |
| 53 | /** |
| 54 | * Whether Route 53 measures latency. Immutable — changing it forces |
| 55 | * replacement. |
| 56 | */ |
| 57 | measureLatency?: boolean; |
| 58 | /** |
| 59 | * Invert the health check result. |
| 60 | */ |
| 61 | inverted?: boolean; |
| 62 | /** |
| 63 | * Disable the health check (treated as healthy). |
| 64 | */ |
| 65 | disabled?: boolean; |
| 66 | /** |
| 67 | * For CALCULATED checks, the number of child checks that must be healthy. |
| 68 | */ |
| 69 | healthThreshold?: number; |
| 70 | /** |
| 71 | * For CALCULATED checks, the child health check IDs. |
| 72 | */ |
| 73 | childHealthChecks?: string[]; |
| 74 | /** |
| 75 | * Send SNI to the endpoint for HTTPS checks. |
| 76 | */ |
| 77 | enableSNI?: boolean; |
| 78 | /** |
| 79 | * Regions from which Route 53 checks the endpoint. |
| 80 | */ |
| 81 | regions?: route53.HealthCheckRegion[]; |
| 82 | /** |
| 83 | * Tags applied to the health check. |
| 84 | */ |
| 85 | tags?: Record<string, string>; |
| 86 | } |
| 87 | |
| 88 | export interface HealthCheck extends Resource< |
| 89 | "AWS.Route53.HealthCheck", |
| 90 | HealthCheckProps, |
| 91 | { |
| 92 | /** |
| 93 | * Health check ID. |
| 94 | */ |
| 95 | id: string; |
| 96 | /** |
| 97 | * Alias of `id`. |
| 98 | */ |
| 99 | healthCheckId: string; |
| 100 | /** |
| 101 | * Health check type. |
| 102 | */ |
| 103 | type: route53.HealthCheckType; |
| 104 | /** |
| 105 | * Endpoint, path, port, thresholds, disabled/inverted state, SNI and |
| 106 | * tags, as observed. Lets `alchemy drift` detect out-of-band changes. |
| 107 | */ |
| 108 | configuration?: { |
| 109 | ipAddress?: string; |
| 110 | port?: number; |
| 111 | resourcePath?: string; |
| 112 | fullyQualifiedDomainName?: string; |
| 113 | searchString?: string; |
| 114 | failureThreshold?: number; |
| 115 | inverted?: boolean; |
| 116 | disabled?: boolean; |
| 117 | healthThreshold?: number; |
| 118 | enableSNI?: boolean; |
| 119 | tags: Record<string, string>; |
| 120 | }; |
| 121 | }, |
| 122 | never, |
| 123 | Providers |
| 124 | > {} |
| 125 | |
| 126 | /** |
| 127 | * A Route 53 health check. |
| 128 | * |
| 129 | * `HealthCheck` monitors the health of an endpoint and can gate failover and |
| 130 | * other routing policies on a `Record` via `record.healthCheckId`. |
| 131 | * ### Creating a Health Check |
| 132 | * **Example:** HTTP Health Check |
| 133 | * ```typescript |
| 134 | * const check = yield* HealthCheck("ApiHealth", { |
| 135 | * type: "HTTP", |
| 136 | * fullyQualifiedDomainName: "api.example.com", |
| 137 | * resourcePath: "/health", |
| 138 | * port: 80, |
| 139 | * requestInterval: "30 seconds", |
| 140 | * failureThreshold: 3, |
| 141 | * }); |
| 142 | * ``` |
| 143 | * |
| 144 | * ### Gating DNS Failover |
| 145 | * **Example:** Fail Over a Record When the Check Fails |
| 146 | * ```typescript |
| 147 | * const check = yield* HealthCheck("PrimaryHealth", { |
| 148 | * type: "HTTPS", |
| 149 | * fullyQualifiedDomainName: "primary.example.com", |
| 150 | * resourcePath: "/health", |
| 151 | * port: 443, |
| 152 | * }); |
| 153 | * // Route 53 answers with the PRIMARY record only while the check passes; |
| 154 | * // see `Record` for the matching SECONDARY record. |
| 155 | * const primary = yield* Record("Primary", { |
| 156 | * hostedZoneId: zone.id, |
| 157 | * name: "app.example.com", |
| 158 | * type: "A", |
| 159 | * ttl: "60 seconds", |
| 160 | * records: ["1.2.3.4"], |
| 161 | * setIdentifier: "primary", |
| 162 | * failover: "PRIMARY", |
| 163 | * healthCheckId: check.id, |
| 164 | * }); |
| 165 | * ``` |
| 166 | * |
| 167 | * @resource |
| 168 | */ |
| 169 | export const HealthCheck = Resource<HealthCheck>("AWS.Route53.HealthCheck"); |
| 170 | |
| 171 | /** |
| 172 | * Whether a Route 53 health check can be managed directly through Route 53. |
| 173 | * |
| 174 | * Health checks with `LinkedService` are owned by another AWS service (for |
| 175 | * example, Cloud Map). Route 53 refuses direct deletion of those checks, and |
| 176 | * the owning service may retain them as tombstones after its resource is |
| 177 | * deleted. They therefore must not be returned to account-wide nuke inventory. |
| 178 | */ |
| 179 | export const isNukeableHealthCheck = (check: { LinkedService?: route53.LinkedService }): boolean => |
| 180 | check.LinkedService === undefined; |
| 181 | |
| 182 | const toConfig = (props: HealthCheckProps): route53.HealthCheckConfig => ({ |
| 183 | Type: props.type, |
| 184 | IPAddress: props.ipAddress, |
| 185 | Port: props.port, |
| 186 | ResourcePath: props.resourcePath, |
| 187 | FullyQualifiedDomainName: props.fullyQualifiedDomainName, |
| 188 | SearchString: props.searchString, |
| 189 | RequestInterval: durationToSeconds(props.requestInterval), |
| 190 | FailureThreshold: props.failureThreshold, |
| 191 | MeasureLatency: props.measureLatency, |
| 192 | Inverted: props.inverted, |
| 193 | Disabled: props.disabled, |
| 194 | HealthThreshold: props.healthThreshold, |
| 195 | ChildHealthChecks: props.childHealthChecks, |
| 196 | EnableSNI: props.enableSNI, |
| 197 | Regions: props.regions, |
| 198 | }); |
| 199 | |
| 200 | // Fields settable via UpdateHealthCheck (i.e. everything except the immutable |
| 201 | // Type / RequestInterval / MeasureLatency). |
| 202 | const mutableFields = (props: HealthCheckProps) => ({ |
| 203 | IPAddress: props.ipAddress, |
| 204 | Port: props.port, |
| 205 | ResourcePath: props.resourcePath, |
| 206 | FullyQualifiedDomainName: props.fullyQualifiedDomainName, |
| 207 | SearchString: props.searchString, |
| 208 | FailureThreshold: props.failureThreshold, |
| 209 | // Omitted means AWS's default (false), so a check disabled or inverted |
| 210 | // out of band converges back. |
| 211 | Inverted: props.inverted ?? false, |
| 212 | Disabled: props.disabled ?? false, |
| 213 | HealthThreshold: props.healthThreshold, |
| 214 | ChildHealthChecks: props.childHealthChecks, |
| 215 | EnableSNI: props.enableSNI, |
| 216 | Regions: props.regions, |
| 217 | }); |
| 218 | |
| 219 | const mutableDiffers = ( |
| 220 | observed: route53.HealthCheckConfig, |
| 221 | desired: HealthCheckProps, |
| 222 | ): boolean => { |
| 223 | const d = mutableFields(desired); |
| 224 | return ( |
| 225 | observed.IPAddress !== d.IPAddress || |
| 226 | observed.Port !== d.Port || |
| 227 | observed.ResourcePath !== d.ResourcePath || |
| 228 | observed.FullyQualifiedDomainName !== d.FullyQualifiedDomainName || |
| 229 | observed.SearchString !== d.SearchString || |
| 230 | (observed.FailureThreshold ?? undefined) !== d.FailureThreshold || |
| 231 | (observed.Inverted ?? false) !== d.Inverted || |
| 232 | (observed.Disabled ?? false) !== d.Disabled || |
| 233 | (observed.HealthThreshold ?? undefined) !== d.HealthThreshold || |
| 234 | (observed.EnableSNI ?? undefined) !== d.EnableSNI |
| 235 | ); |
| 236 | }; |
| 237 | |
| 238 | /** |
| 239 | * The settings reconcile converges, as observed. `read` and `reconcile` |
| 240 | * share it so a converged health check reads unchanged. |
| 241 | */ |
| 242 | const observeHealthCheckConfiguration = ( |
| 243 | observed: route53.HealthCheckConfig, |
| 244 | tags: Record<string, string>, |
| 245 | ) => |
| 246 | plainJson({ |
| 247 | ipAddress: observed.IPAddress, |
| 248 | port: observed.Port, |
| 249 | resourcePath: observed.ResourcePath, |
| 250 | fullyQualifiedDomainName: observed.FullyQualifiedDomainName, |
| 251 | searchString: observed.SearchString, |
| 252 | failureThreshold: observed.FailureThreshold, |
| 253 | inverted: observed.Inverted ?? false, |
| 254 | disabled: observed.Disabled ?? false, |
| 255 | healthThreshold: observed.HealthThreshold, |
| 256 | enableSNI: observed.EnableSNI, |
| 257 | tags, |
| 258 | }); |
| 259 | |
| 260 | export const HealthCheckProvider = () => |
| 261 | Provider.effect( |
| 262 | HealthCheck, |
| 263 | Effect.gen(function* () { |
| 264 | const observe = Effect.fn(function* (id: string) { |
| 265 | return yield* route53.getHealthCheck({ HealthCheckId: id }).pipe( |
| 266 | Effect.map((r) => r.HealthCheck), |
| 267 | Effect.catchTag("NoSuchHealthCheck", () => Effect.undefined), |
| 268 | ); |
| 269 | }); |
| 270 | |
| 271 | const observedTags = Effect.fn(function* (id: string) { |
| 272 | const response = yield* route53.listTagsForResource({ |
| 273 | ResourceType: "healthcheck", |
| 274 | ResourceId: id, |
| 275 | }); |
| 276 | const record: Record<string, string> = {}; |
| 277 | for (const tag of response.ResourceTagSet.Tags ?? []) { |
| 278 | if (tag.Key !== undefined && tag.Value !== undefined) { |
| 279 | record[tag.Key] = tag.Value; |
| 280 | } |
| 281 | } |
| 282 | return record; |
| 283 | }); |
| 284 | |
| 285 | const syncTags = Effect.fn(function* ( |
| 286 | id: string, |
| 287 | logicalId: string, |
| 288 | userTags: Record<string, string> | undefined, |
| 289 | ) { |
| 290 | const internalTags = yield* createInternalTags(logicalId); |
| 291 | const newTags = { ...userTags, ...internalTags }; |
| 292 | const oldTags = yield* observedTags(id); |
| 293 | const { upsert, removed } = diffTags(oldTags, newTags); |
| 294 | if (upsert.length === 0 && removed.length === 0) { |
| 295 | return newTags; |
| 296 | } |
| 297 | yield* route53.changeTagsForResource({ |
| 298 | ResourceType: "healthcheck", |
| 299 | ResourceId: id, |
| 300 | AddTags: upsert.length > 0 ? upsert : undefined, |
| 301 | RemoveTagKeys: removed.length > 0 ? removed : undefined, |
| 302 | }); |
| 303 | return newTags; |
| 304 | }); |
| 305 | |
| 306 | return { |
| 307 | stables: ["id", "healthCheckId"], |
| 308 | list: () => |
| 309 | route53.listHealthChecks.pages({}).pipe( |
| 310 | Stream.runCollect, |
| 311 | Effect.map((chunk) => |
| 312 | Array.from(chunk).flatMap((page) => |
| 313 | (page.HealthChecks ?? []).filter(isNukeableHealthCheck).map((check) => ({ |
| 314 | id: check.Id, |
| 315 | healthCheckId: check.Id, |
| 316 | type: check.HealthCheckConfig.Type, |
| 317 | })), |
| 318 | ), |
| 319 | ), |
| 320 | ), |
| 321 | diff: Effect.fn(function* ({ olds, news }) { |
| 322 | if (!isResolved(news)) return undefined; |
| 323 | if ( |
| 324 | olds.type !== news.type || |
| 325 | (durationToSeconds(olds.requestInterval) ?? 30) !== |
| 326 | (durationToSeconds(news.requestInterval) ?? 30) || |
| 327 | (olds.measureLatency ?? false) !== (news.measureLatency ?? false) |
| 328 | ) { |
| 329 | return { action: "replace" } as const; |
| 330 | } |
| 331 | }), |
| 332 | read: Effect.fn(function* ({ output }) { |
| 333 | if (!output?.id) { |
| 334 | return undefined; |
| 335 | } |
| 336 | const check = yield* observe(output.id); |
| 337 | if (!check) { |
| 338 | return undefined; |
| 339 | } |
| 340 | return { |
| 341 | id: check.Id, |
| 342 | healthCheckId: check.Id, |
| 343 | type: check.HealthCheckConfig.Type, |
| 344 | configuration: observeHealthCheckConfiguration( |
| 345 | check.HealthCheckConfig, |
| 346 | yield* observedTags(check.Id), |
| 347 | ), |
| 348 | }; |
| 349 | }), |
| 350 | reconcile: Effect.fn(function* ({ id, instanceId, news, output }) { |
| 351 | // Observe. |
| 352 | let check = output?.id ? yield* observe(output.id) : undefined; |
| 353 | |
| 354 | // Ensure — CallerReference makes create idempotent. |
| 355 | if (!check) { |
| 356 | check = yield* route53 |
| 357 | .createHealthCheck({ |
| 358 | CallerReference: instanceId, |
| 359 | HealthCheckConfig: toConfig(news), |
| 360 | }) |
| 361 | .pipe( |
| 362 | Effect.map((r) => r.HealthCheck), |
| 363 | Effect.catchTag("HealthCheckAlreadyExists", () => |
| 364 | // Same CallerReference already created it; the engine stores |
| 365 | // output, so on a true re-run output.id observes above. A bare |
| 366 | // race here means we must re-read — but the API gives us no id, |
| 367 | // so fall back to the stored output if present. |
| 368 | output?.id |
| 369 | ? observe(output.id).pipe( |
| 370 | Effect.flatMap((existing) => |
| 371 | existing |
| 372 | ? Effect.succeed(existing) |
| 373 | : Effect.die( |
| 374 | new Error("health check exists but could not be observed"), |
| 375 | ), |
| 376 | ), |
| 377 | ) |
| 378 | : Effect.die(new Error("health check already exists for caller reference")), |
| 379 | ), |
| 380 | ); |
| 381 | } |
| 382 | |
| 383 | // Sync config — diff observed mutable fields against desired. |
| 384 | if (mutableDiffers(check.HealthCheckConfig, news)) { |
| 385 | const updated = yield* route53 |
| 386 | .updateHealthCheck({ |
| 387 | HealthCheckId: check.Id, |
| 388 | HealthCheckVersion: check.HealthCheckVersion, |
| 389 | ...mutableFields(news), |
| 390 | }) |
| 391 | .pipe( |
| 392 | Effect.map((r) => r.HealthCheck), |
| 393 | // Optimistic-lock retry: re-read for the latest version. |
| 394 | Effect.retry({ |
| 395 | while: (e) => e._tag === "HealthCheckVersionMismatch", |
| 396 | schedule: Schedule.max([Schedule.fixed("1 second"), Schedule.recurs(5)]), |
| 397 | }), |
| 398 | ); |
| 399 | check = updated; |
| 400 | } |
| 401 | |
| 402 | // Sync tags. |
| 403 | const tags = yield* syncTags(check.Id, id, news.tags); |
| 404 | |
| 405 | return { |
| 406 | id: check.Id, |
| 407 | healthCheckId: check.Id, |
| 408 | type: check.HealthCheckConfig.Type, |
| 409 | configuration: observeHealthCheckConfiguration(check.HealthCheckConfig, tags), |
| 410 | }; |
| 411 | }), |
| 412 | delete: Effect.fn(function* ({ output }) { |
| 413 | yield* route53.deleteHealthCheck({ HealthCheckId: output.id }).pipe( |
| 414 | Effect.asVoid, |
| 415 | Effect.catchTag("NoSuchHealthCheck", () => Effect.void), |
| 416 | // Still referenced by a record whose delete is propagating. |
| 417 | Effect.retry({ |
| 418 | while: (e) => e._tag === "HealthCheckInUse", |
| 419 | schedule: Schedule.max([Schedule.fixed("3 seconds"), Schedule.recurs(10)]), |
| 420 | }), |
| 421 | Effect.catchTag("HealthCheckInUse", () => Effect.void), |
| 422 | ); |
| 423 | }), |
| 424 | }; |
| 425 | }), |
| 426 | ); |