The best way to control Claude Code, Codex and more from any computer or phone

main
ts 641 lines 19.8 KB
Raw
1 import * as healthchecks from "@distilled.cloud/cloudflare/healthchecks";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { createPhysicalName } from "alchemy/PhysicalName";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import { arrayEqualsUnordered } from "alchemy/Util/equal";
7 import * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import * as Option from "effect/Option";
10 import * as Predicate from "effect/Predicate";
11 import * as Stream from "effect/Stream";
12 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
13 import type { Providers } from "../Providers.ts";
14 import { listAllZones } from "../Zone/lookup.ts";
15
16 export class HealthcheckUnexpectedResponse extends Data.TaggedError(
17 "HealthcheckUnexpectedResponse",
18 )<{
19 readonly message: string;
20 readonly cause?: unknown;
21 }> {}
22
23 const TypeId = "Cloudflare.Healthcheck.Healthcheck" as const;
24 type TypeId = typeof TypeId;
25
26 /**
27 * Protocol used by a standalone health check probe.
28 */
29 export type Type = "HTTP" | "HTTPS" | "TCP";
30
31 /**
32 * Region a health check can probe from. `null`/omitted lets Cloudflare pick
33 * a default region; multiple regions require a Business or Enterprise plan.
34 */
35 export type Region =
36 | "WNAM"
37 | "ENAM"
38 | "WEU"
39 | "EEU"
40 | "NSAM"
41 | "SSAM"
42 | "OC"
43 | "ME"
44 | "NAF"
45 | "SAF"
46 | "IN"
47 | "SEAS"
48 | "NEAS"
49 | "ALL_REGIONS";
50
51 /**
52 * Health status Cloudflare reports for the monitored origin. New checks
53 * start as `unknown` until the first probes complete.
54 */
55 export type Status = "unknown" | "healthy" | "unhealthy" | "suspended";
56
57 /**
58 * Parameters specific to an HTTP or HTTPS health check.
59 */
60 export interface HttpConfig {
61 /**
62 * Do not validate the certificate when the health check uses HTTPS.
63 * @default false
64 */
65 allowInsecure?: boolean;
66 /**
67 * A case-insensitive substring to look for in the response body. If this
68 * string is not found, the origin will be marked as unhealthy.
69 */
70 expectedBody?: string;
71 /**
72 * The expected HTTP response codes (e.g. `"200"`) or code ranges
73 * (e.g. `"2xx"`) of the health check.
74 * @default ["200"]
75 */
76 expectedCodes?: string[];
77 /**
78 * Follow redirects if the origin returns a 3xx status code.
79 * @default false
80 */
81 followRedirects?: boolean;
82 /**
83 * HTTP request headers to send in the health check. It is recommended to
84 * set a `Host` header by default. The `User-Agent` header cannot be
85 * overridden.
86 */
87 header?: Record<string, string[]>;
88 /**
89 * The HTTP method to use for the health check.
90 * @default "GET"
91 */
92 method?: "GET" | "HEAD";
93 /**
94 * The endpoint path to health check against.
95 * @default "/"
96 */
97 path?: string;
98 /**
99 * Port number to connect to for the health check.
100 * @default 80 for HTTP, 443 for HTTPS
101 */
102 port?: number;
103 }
104
105 /**
106 * Parameters specific to a TCP health check.
107 */
108 export interface TcpConfig {
109 /**
110 * The TCP connection method to use for the health check.
111 * @default "connection_established"
112 */
113 method?: "connection_established";
114 /**
115 * Port number to connect to for the health check.
116 * @default 80
117 */
118 port?: number;
119 }
120
121 export interface Props {
122 /**
123 * Zone the health check belongs to. Stable — changing the zone triggers
124 * a replacement.
125 */
126 zoneId: string;
127 /**
128 * A short name to identify the health check. Only alphanumeric
129 * characters, hyphens and underscores are allowed. If omitted, a unique
130 * name is generated from the app, stage, and logical ID.
131 *
132 * Mutable — Cloudflare supports renaming in place.
133 * @default ${app}-${stage}-${id}
134 */
135 name?: string;
136 /**
137 * The hostname or IP address of the origin server to run health checks
138 * on.
139 */
140 address: string;
141 /**
142 * The protocol to use for the health check. Currently supported
143 * protocols are `HTTP`, `HTTPS` and `TCP`.
144 * @default "HTTP"
145 */
146 type?: Type;
147 /**
148 * A human-readable description of the health check.
149 */
150 description?: string;
151 /**
152 * A list of regions from which to run health checks. Omitting it lets
153 * Cloudflare pick a default region. Multiple regions require a Business
154 * or Enterprise plan.
155 */
156 checkRegions?: Region[];
157 /**
158 * The number of consecutive fails required from a health check before
159 * changing the health to unhealthy.
160 * @default 1
161 */
162 consecutiveFails?: number;
163 /**
164 * The number of consecutive successes required from a health check
165 * before changing the health to healthy.
166 * @default 1
167 */
168 consecutiveSuccesses?: number;
169 /**
170 * The interval between each health check, in seconds. Shorter intervals
171 * may give quicker notifications but increase load on the origin.
172 * Plan-gated minimums apply (Pro: 60, Business: 15, Enterprise: 10).
173 * @default 60
174 */
175 interval?: number;
176 /**
177 * The number of retries to attempt in case of a timeout before marking
178 * the origin as unhealthy. Retries are attempted immediately.
179 * @default 2
180 */
181 retries?: number;
182 /**
183 * The timeout (in seconds) before marking the health check as failed.
184 * @default 5
185 */
186 timeout?: number;
187 /**
188 * If suspended, no health checks are sent to the origin.
189 * @default false
190 */
191 suspended?: boolean;
192 /**
193 * Parameters specific to an HTTP or HTTPS health check. Only valid when
194 * `type` is `HTTP` or `HTTPS`.
195 */
196 httpConfig?: HttpConfig;
197 /**
198 * Parameters specific to a TCP health check. Only valid when `type` is
199 * `TCP`.
200 */
201 tcpConfig?: TcpConfig;
202 }
203
204 export interface Attributes {
205 /** Cloudflare-assigned health check identifier. */
206 healthcheckId: string;
207 /** Zone that owns this health check. */
208 zoneId: string;
209 /** Health check name. */
210 name: string;
211 /** The hostname or IP address being monitored. */
212 address: string;
213 /** Probe protocol (`HTTP`, `HTTPS` or `TCP`). */
214 type: Type;
215 /** Current origin status according to the health check. */
216 status: Status;
217 /** The current failure reason if status is unhealthy. */
218 failureReason: string | undefined;
219 /** Whether probing is suspended. */
220 suspended: boolean;
221 /** Probe interval in seconds. */
222 interval: number;
223 /** Number of immediate retries on timeout. */
224 retries: number;
225 /** Probe timeout in seconds. */
226 timeout: number;
227 /** ISO8601 creation timestamp. */
228 createdOn: string | undefined;
229 /** ISO8601 last-modified timestamp. */
230 modifiedOn: string | undefined;
231 }
232
233 export type Healthcheck = Resource<TypeId, Props, Attributes, never, Providers>;
234
235 /**
236 * A Cloudflare standalone Health Check — monitors an origin server from
237 * Cloudflare's edge and powers Health Check notifications and analytics.
238 *
239 * Zone-scoped and available on paid zone plans (Pro: 2 checks,
240 * Business: 10, Enterprise: more). Distinct from Load Balancing
241 * *Monitors*, which are account-scoped and attached to LB pools.
242 *
243 * Every property except `zoneId` is mutable in place (the API supports
244 * full PUT updates, including renames); changing the zone triggers a
245 * replacement.
246 *
247 * Safety: health checks carry no ownership markers, so when there is no
248 * prior state `read` matches by deterministic name and reports an
249 * existing check as `Unowned` — the engine refuses to take it over
250 * unless `--adopt` (or `adopt(true)`) is set.
251 * ### Creating a Health Check
252 * **Example:** Basic HTTP health check
253 * ```typescript
254 * const check = yield* Cloudflare.Healthcheck.Healthcheck("origin-check", {
255 * zoneId: zone.zoneId,
256 * address: "origin.example.com",
257 * });
258 * ```
259 *
260 * **Example:** HTTPS health check with custom path and expected codes
261 * ```typescript
262 * const check = yield* Cloudflare.Healthcheck.Healthcheck("api-health", {
263 * zoneId: zone.zoneId,
264 * address: "api.example.com",
265 * type: "HTTPS",
266 * interval: 60,
267 * retries: 2,
268 * timeout: 5,
269 * httpConfig: {
270 * path: "/healthz",
271 * expectedCodes: ["200"],
272 * followRedirects: true,
273 * },
274 * });
275 * ```
276 *
277 * ### TCP health checks
278 * **Example:** Probe a TCP port
279 * ```typescript
280 * const check = yield* Cloudflare.Healthcheck.Healthcheck("db-port", {
281 * zoneId: zone.zoneId,
282 * address: "db.example.com",
283 * type: "TCP",
284 * tcpConfig: { port: 5432 },
285 * });
286 * ```
287 *
288 * ### Suspending a check
289 * **Example:** Temporarily stop probing the origin
290 * ```typescript
291 * const check = yield* Cloudflare.Healthcheck.Healthcheck("origin-check", {
292 * zoneId: zone.zoneId,
293 * address: "origin.example.com",
294 * suspended: true,
295 * });
296 * ```
297 *
298 * @see https://developers.cloudflare.com/health-checks/
299 *
300 * @resource
301 * @product Health Checks
302 * @category Performance & Reliability
303 */
304 export const Healthcheck = Resource<Healthcheck>(TypeId, {
305 aliases: ["Cloudflare.Healthcheck"],
306 });
307
308 /**
309 * Returns true if the given value is a Healthcheck resource.
310 */
311 export const isHealthcheck = (value: unknown): value is Healthcheck =>
312 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
313
314 export const HealthcheckProvider = () =>
315 Provider.succeed(Healthcheck, {
316 stables: ["healthcheckId", "zoneId", "createdOn"],
317
318 diff: Effect.fn(function* ({ olds = {}, news }) {
319 const o = olds as Props;
320 const n = news as Props;
321 // zoneId is Input<string>; by diff time both sides are concrete
322 // strings when statically known.
323 if (typeof o.zoneId === "string" && typeof n.zoneId === "string" && o.zoneId !== n.zoneId) {
324 return { action: "replace" } as const;
325 }
326 }),
327
328 read: Effect.fn(function* ({ id, output, olds }) {
329 // Owned path: we have persisted state (our own id) — refresh it.
330 if (output?.healthcheckId) {
331 const observed = yield* getHealthcheck(output.zoneId, output.healthcheckId);
332 if (observed) return toAttributes(observed, output.zoneId);
333 return undefined;
334 }
335 // Adoption path: no state of our own, but a check with our
336 // deterministic name may already exist. Health checks carry no
337 // ownership markers we can inspect, so we cannot prove we created
338 // it — brand it `Unowned` so the engine refuses to take over
339 // unless `adopt` is set.
340 const zoneId = olds?.zoneId as string | undefined;
341 if (!zoneId) return undefined;
342 const name = yield* createHealthcheckName(id, olds?.name);
343 const match = yield* findByName(zoneId, name);
344 if (match) {
345 const attrs = toAttributes(match, zoneId);
346 if (attrs) return Unowned(attrs);
347 }
348 return undefined;
349 }),
350
351 reconcile: Effect.fn(function* ({ id, news, output }) {
352 // Inputs have been resolved to concrete strings by Plan.
353 const zoneId = news.zoneId as string;
354 const name = yield* createHealthcheckName(id, news.name);
355 const desired = buildDesiredBody(news, name);
356
357 // 1. Observe — the id cached on `output` is a hint, not a
358 // guarantee: a 404 falls through to "missing".
359 let observed: ObservedHealthcheck | undefined;
360 if (output?.healthcheckId) {
361 observed = yield* getHealthcheck(zoneId, output.healthcheckId);
362 }
363 // Fall back to matching by name (names are unique per zone), which
364 // also recovers from lost ids after the adopt gate has passed.
365 if (!observed) {
366 observed = yield* findByName(zoneId, name);
367 }
368
369 // 2. Ensure — create when missing; a concurrent create of the same
370 // name surfaces as `HealthcheckAlreadyExists`, which we treat as
371 // a race: re-read by name and converge via update below.
372 let justCreated = false;
373 if (!observed) {
374 observed = yield* healthchecks.createHealthcheck({ zoneId, ...desired }).pipe(
375 Effect.map((created): ObservedHealthcheck | undefined => created),
376 Effect.catchTag("HealthcheckAlreadyExists", () => findByName(zoneId, name)),
377 );
378 justCreated = observed !== undefined;
379 }
380
381 // 3. Sync — the update endpoint is a PUT that takes the full body;
382 // diff observed cloud state against desired and skip the call
383 // entirely on a no-op.
384 if (observed?.id && !justCreated && !desiredEqualsObserved(desired, observed)) {
385 observed = yield* healthchecks.updateHealthcheck({
386 zoneId,
387 healthcheckId: observed.id,
388 ...desired,
389 });
390 }
391
392 // 4. Return.
393 const attrs = observed ? toAttributes(observed, zoneId) : undefined;
394 if (!attrs) {
395 return yield* new HealthcheckUnexpectedResponse({
396 message: `Cloudflare did not return a usable health check for "${name}"`,
397 });
398 }
399 return attrs;
400 }),
401
402 delete: Effect.fn(function* ({ output }) {
403 yield* healthchecks
404 .deleteHealthcheck({
405 zoneId: output.zoneId,
406 healthcheckId: output.healthcheckId,
407 })
408 .pipe(
409 // Already gone — deletion is idempotent.
410 Effect.catchTag("HealthcheckNotFound", () => Effect.void),
411 );
412 }),
413
414 // Health checks are zone-scoped (`/zones/{zone_id}/healthchecks`) with no
415 // account-wide enumeration API, so fan out over every zone and list per
416 // zone. A scoped token may lack permission on a zone (eventual consistency)
417 // or a zone may be partially provisioned — skip those zones (-> []) rather
418 // than failing the whole enumeration.
419 list: Effect.fn(function* () {
420 const { accountId } = yield* yield* CloudflareEnvironment;
421 const zones = yield* listAllZones(accountId);
422 const rows = yield* Effect.forEach(
423 zones,
424 (zone) =>
425 healthchecks.listHealthchecks.pages({ zoneId: zone.id }).pipe(
426 Stream.runCollect,
427 Effect.map((chunk) =>
428 Array.from(chunk).flatMap((page) =>
429 (page.result ?? []).flatMap((h) => {
430 const attrs = toAttributes(h, zone.id);
431 return attrs ? [attrs] : [];
432 }),
433 ),
434 ),
435 Effect.catchTag("Forbidden", () => Effect.succeed([] as Attributes[])),
436 ),
437 { concurrency: 10 },
438 );
439 return rows.flat();
440 }),
441 });
442
443 type ObservedHealthcheck = healthchecks.GetHealthcheckResponse;
444
445 /**
446 * Read a health check by id, mapping "gone" (`HealthcheckNotFound`,
447 * HTTP 404) to `undefined`.
448 */
449 const getHealthcheck = (zoneId: string, healthcheckId: string) =>
450 healthchecks
451 .getHealthcheck({ zoneId, healthcheckId })
452 .pipe(Effect.catchTag("HealthcheckNotFound", () => Effect.undefined));
453
454 /**
455 * Find a health check by exact name. Names are unique per zone, so the
456 * first exact match is the resource.
457 */
458 const findByName = (zoneId: string, name: string) =>
459 healthchecks.listHealthchecks.items({ zoneId }).pipe(
460 Stream.filter((h) => h.name === name),
461 Stream.runHead,
462 Effect.map((h): ObservedHealthcheck | undefined => Option.getOrUndefined(h)),
463 );
464
465 const createHealthcheckName = (id: string, name: string | undefined) =>
466 Effect.gen(function* () {
467 return name ?? (yield* createPhysicalName({ id, lowercase: true }));
468 });
469
470 interface DesiredBody {
471 name: string;
472 address: string;
473 type: Type;
474 description?: string;
475 checkRegions?: Region[];
476 consecutiveFails: number;
477 consecutiveSuccesses: number;
478 interval: number;
479 retries: number;
480 timeout: number;
481 suspended: boolean;
482 httpConfig?: HttpConfig;
483 tcpConfig?: TcpConfig;
484 }
485
486 /**
487 * The full desired body sent on both create and PUT update. Documented
488 * Cloudflare defaults are filled in so the observed-vs-desired diff is
489 * exact and removing a prop converges back to the default.
490 */
491 const buildDesiredBody = (news: Props, name: string): DesiredBody => ({
492 name,
493 address: news.address,
494 type: news.type ?? "HTTP",
495 description: news.description ?? "",
496 checkRegions: news.checkRegions,
497 consecutiveFails: news.consecutiveFails ?? 1,
498 consecutiveSuccesses: news.consecutiveSuccesses ?? 1,
499 interval: news.interval ?? 60,
500 retries: news.retries ?? 2,
501 timeout: news.timeout ?? 5,
502 suspended: news.suspended ?? false,
503 httpConfig: news.httpConfig,
504 tcpConfig: news.tcpConfig,
505 });
506
507 const desiredEqualsObserved = (desired: DesiredBody, observed: ObservedHealthcheck): boolean => {
508 if (desired.name !== observed.name) return false;
509 if (desired.address !== observed.address) return false;
510 if (desired.type !== observed.type) return false;
511 if (desired.description !== (observed.description ?? "")) return false;
512 if (
513 desired.checkRegions !== undefined &&
514 !arrayEqualsUnordered(desired.checkRegions, observed.checkRegions ?? [])
515 ) {
516 return false;
517 }
518 if (desired.consecutiveFails !== (observed.consecutiveFails ?? 1)) {
519 return false;
520 }
521 if (desired.consecutiveSuccesses !== (observed.consecutiveSuccesses ?? 1)) {
522 return false;
523 }
524 if (desired.interval !== (observed.interval ?? 60)) return false;
525 if (desired.retries !== (observed.retries ?? 2)) return false;
526 if (desired.timeout !== (observed.timeout ?? 5)) return false;
527 if (desired.suspended !== (observed.suspended ?? false)) return false;
528 if (
529 desired.httpConfig !== undefined &&
530 !httpConfigEquals(desired.httpConfig, observed.httpConfig ?? undefined)
531 ) {
532 return false;
533 }
534 if (
535 desired.tcpConfig !== undefined &&
536 !tcpConfigEquals(desired.tcpConfig, observed.tcpConfig ?? undefined)
537 ) {
538 return false;
539 }
540 return true;
541 };
542
543 /**
544 * Compare only the http_config fields the user actually specified —
545 * Cloudflare fills the rest with plan/type-dependent defaults we should
546 * not fight.
547 */
548 const httpConfigEquals = (
549 desired: HttpConfig,
550 observed: NonNullable<ObservedHealthcheck["httpConfig"]> | undefined,
551 ): boolean => {
552 if (observed === undefined) return false;
553 if (
554 desired.allowInsecure !== undefined &&
555 desired.allowInsecure !== (observed.allowInsecure ?? false)
556 ) {
557 return false;
558 }
559 if (
560 desired.expectedBody !== undefined &&
561 desired.expectedBody !== (observed.expectedBody ?? "")
562 ) {
563 return false;
564 }
565 if (
566 desired.expectedCodes !== undefined &&
567 !arrayEqualsUnordered(desired.expectedCodes, observed.expectedCodes ?? [])
568 ) {
569 return false;
570 }
571 if (
572 desired.followRedirects !== undefined &&
573 desired.followRedirects !== (observed.followRedirects ?? false)
574 ) {
575 return false;
576 }
577 if (desired.method !== undefined && desired.method !== observed.method) {
578 return false;
579 }
580 if (desired.path !== undefined && desired.path !== observed.path) {
581 return false;
582 }
583 if (desired.port !== undefined && desired.port !== observed.port) {
584 return false;
585 }
586 if (desired.header !== undefined && !headerEquals(desired.header, observed.header)) {
587 return false;
588 }
589 return true;
590 };
591
592 const headerEquals = (
593 desired: Record<string, string[]>,
594 observed: Record<string, unknown> | null | undefined,
595 ): boolean => {
596 const obs = observed ?? {};
597 const keys = Object.keys(desired);
598 if (keys.length !== Object.keys(obs).length) return false;
599 return keys.every((k) => {
600 const o = obs[k];
601 return Array.isArray(o) && arrayEqualsUnordered(desired[k] ?? [], o.map(String));
602 });
603 };
604
605 const tcpConfigEquals = (
606 desired: TcpConfig,
607 observed: NonNullable<ObservedHealthcheck["tcpConfig"]> | undefined,
608 ): boolean => {
609 if (observed === undefined) return false;
610 if (
611 desired.method !== undefined &&
612 desired.method !== (observed.method ?? "connection_established")
613 ) {
614 return false;
615 }
616 if (desired.port !== undefined && desired.port !== observed.port) {
617 return false;
618 }
619 return true;
620 };
621
622 const toAttributes = (observed: ObservedHealthcheck, zoneId: string): Attributes | undefined => {
623 if (!observed.id || !observed.name || !observed.address || !observed.type) {
624 return undefined;
625 }
626 return {
627 healthcheckId: observed.id,
628 zoneId,
629 name: observed.name,
630 address: observed.address,
631 type: observed.type as Type,
632 status: (observed.status ?? "unknown") as Status,
633 failureReason: observed.failureReason ?? undefined,
634 suspended: observed.suspended ?? false,
635 interval: observed.interval ?? 60,
636 retries: observed.retries ?? 2,
637 timeout: observed.timeout ?? 5,
638 createdOn: observed.createdOn ?? undefined,
639 modifiedOn: observed.modifiedOn ?? undefined,
640 };
641 };