@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

main
ts 377 lines 12.8 KB
Raw
1 import * as loadBalancers from "@distilled.cloud/cloudflare/load-balancers";
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 * as Effect from "effect/Effect";
7 import * as Predicate from "effect/Predicate";
8 import * as Schedule from "effect/Schedule";
9 import * as Stream from "effect/Stream";
10 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
11 import type { Providers } from "../Providers.ts";
12
13 const TypeId = "Cloudflare.LoadBalancer.Monitor" as const;
14 type TypeId = typeof TypeId;
15
16 /**
17 * Protocol a Load Balancing monitor probes origins with.
18 */
19 export type MonitorType = "http" | "https" | "tcp" | "udp_icmp" | "icmp_ping" | "smtp";
20
21 export interface MonitorProps {
22 /**
23 * The protocol to use for the health check.
24 * @default "http"
25 */
26 type?: MonitorType;
27 /**
28 * Object description. Monitors have no name field, so the description
29 * doubles as the monitor's identity for state recovery — if omitted, a
30 * unique name is generated from the app, stage, and logical ID.
31 * @default ${app}-${stage}-${id}
32 */
33 description?: string;
34 /**
35 * The method to use for the health check. Defaults to `GET` for
36 * HTTP/HTTPS based checks and `connection_established` for TCP based
37 * health checks.
38 */
39 method?: string;
40 /**
41 * The endpoint path to conduct the health check against. Only valid for
42 * HTTP and HTTPS monitors.
43 * @default "/"
44 */
45 path?: string;
46 /**
47 * The port number to connect to for the health check. Required for TCP,
48 * UDP, and SMTP checks; HTTP/HTTPS checks only need it for non-standard
49 * ports.
50 */
51 port?: number;
52 /**
53 * The interval between each health check, in seconds. Shorter intervals
54 * improve failover time but increase origin load. The allowed range is
55 * plan-dependent.
56 * @default 60
57 */
58 interval?: number;
59 /**
60 * The timeout (in seconds) before marking the health check as failed.
61 * @default 5
62 */
63 timeout?: number;
64 /**
65 * The number of retries to attempt in case of a timeout before marking
66 * the origin as unhealthy. Retries are attempted immediately.
67 * @default 2
68 */
69 retries?: number;
70 /**
71 * To be marked healthy the monitored origin must pass this healthcheck N
72 * consecutive times.
73 * @default 0
74 */
75 consecutiveUp?: number;
76 /**
77 * To be marked unhealthy the monitored origin must fail this healthcheck
78 * N consecutive times.
79 * @default 0
80 */
81 consecutiveDown?: number;
82 /**
83 * The expected HTTP response code or code range of the health check
84 * (e.g. `"2xx"`). Only valid for HTTP and HTTPS monitors.
85 */
86 expectedCodes?: string;
87 /**
88 * A case-insensitive sub-string to look for in the response body. If not
89 * found, the origin is marked unhealthy. HTTP/HTTPS only.
90 */
91 expectedBody?: string;
92 /**
93 * Follow redirects returned by the origin. HTTP/HTTPS only.
94 * @default false
95 */
96 followRedirects?: boolean;
97 /**
98 * Do not validate the certificate when the monitor uses HTTPS.
99 * @default false
100 */
101 allowInsecure?: boolean;
102 /**
103 * The HTTP request headers to send in the health check (e.g. a `Host`
104 * header). The `User-Agent` header cannot be overridden. HTTP/HTTPS only.
105 */
106 header?: Record<string, ReadonlyArray<string>>;
107 /**
108 * Assign this monitor to emulate the specified zone while probing.
109 * HTTP/HTTPS only.
110 */
111 probeZone?: string;
112 }
113
114 export interface MonitorAttributes {
115 /** Cloudflare-assigned monitor identifier. */
116 monitorId: string;
117 /** The Cloudflare account the monitor belongs to. */
118 accountId: string;
119 /** Monitor description (carries the physical name when generated). */
120 description: string;
121 /** Probe protocol. */
122 type: MonitorType;
123 /** ISO8601 creation timestamp. */
124 createdOn: string | undefined;
125 /** ISO8601 last-modified timestamp. */
126 modifiedOn: string | undefined;
127 }
128
129 export type Monitor = Resource<TypeId, MonitorProps, MonitorAttributes, never, Providers>;
130
131 /**
132 * A Cloudflare Load Balancing monitor — an active health check (HTTP,
133 * HTTPS, TCP, ICMP, or SMTP probe) that Load Balancing pools reference to
134 * decide which origins are healthy.
135 *
136 * Monitors are account-scoped and have no name field; the `description`
137 * carries the physical name so lost state can be recovered. All properties
138 * are mutable in place.
139 *
140 * Requires the Load Balancing subscription on the account. The allowed
141 * `interval` range is plan-dependent.
142 * ### Creating a Monitor
143 * **Example:** HTTPS health check
144 * ```typescript
145 * const monitor = yield* Cloudflare.LoadBalancer.Monitor("ApiMonitor", {
146 * type: "https",
147 * path: "/health",
148 * expectedCodes: "2xx",
149 * });
150 * ```
151 *
152 * **Example:** TCP port check
153 * ```typescript
154 * const tcp = yield* Cloudflare.LoadBalancer.Monitor("DbMonitor", {
155 * type: "tcp",
156 * port: 5432,
157 * });
158 * ```
159 *
160 * ### Using with a Pool
161 * **Example:** Attach the monitor to a pool
162 * ```typescript
163 * const pool = yield* Cloudflare.LoadBalancer.Pool("ApiPool", {
164 * origins: [{ name: "origin-1", address: "203.0.113.10" }],
165 * monitor: monitor.monitorId,
166 * });
167 * ```
168 *
169 * @see https://developers.cloudflare.com/load-balancing/monitors/
170 *
171 * @resource
172 * @product Load Balancers
173 * @category Performance & Reliability
174 */
175 export const Monitor = Resource<Monitor>(TypeId);
176
177 /**
178 * Returns true if the given value is a Monitor resource.
179 */
180 export const isMonitor = (value: unknown): value is Monitor =>
181 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
182
183 export const MonitorProvider = () =>
184 Provider.succeed(Monitor, {
185 stables: ["monitorId", "accountId", "createdOn"],
186
187 // Account-scoped collection: monitors are enumerated by the account-wide
188 // listMonitors endpoint, whose result items already carry the full monitor
189 // shape — map each directly into the exact `read` Attributes shape.
190 list: Effect.fn(function* () {
191 const { accountId } = yield* yield* CloudflareEnvironment;
192 return yield* loadBalancers.listMonitors.pages({ accountId }).pipe(
193 Stream.runCollect,
194 Effect.map((chunk) =>
195 Array.from(chunk).flatMap((page) =>
196 (page.result ?? []).map((monitor) => toAttributes(monitor, accountId)),
197 ),
198 ),
199 );
200 }),
201
202 diff: Effect.fn(function* ({ output }) {
203 const { accountId } = yield* yield* CloudflareEnvironment;
204 if ((output?.accountId ?? accountId) !== accountId) {
205 return { action: "replace" } as const;
206 }
207 return undefined;
208 }),
209
210 read: Effect.fn(function* ({ id, output, olds }) {
211 const { accountId } = yield* yield* CloudflareEnvironment;
212 const acct = output?.accountId ?? accountId;
213
214 if (output?.monitorId) {
215 const observed = yield* getMonitor(acct, output.monitorId);
216 return observed ? toAttributes(observed, acct) : undefined;
217 }
218 // Cold read — recover from lost state by matching the deterministic
219 // description (our physical name). Descriptions are not unique on
220 // Cloudflare's side and carry no ownership marker, so report the
221 // match as Unowned and let the engine gate takeover behind --adopt.
222 const description = yield* createDescription(id, olds?.description);
223 const match = yield* findByDescription(acct, description);
224 if (match?.id) {
225 const observed = yield* getMonitor(acct, match.id);
226 if (observed) return Unowned(toAttributes(observed, acct));
227 }
228 return undefined;
229 }),
230
231 reconcile: Effect.fn(function* ({ id, news, output }) {
232 const { accountId } = yield* yield* CloudflareEnvironment;
233 const description = yield* createDescription(id, news.description);
234 const body = buildBody(news, description);
235
236 // 1. Observe — output.monitorId is a hint, not a guarantee.
237 const observed = output?.monitorId
238 ? yield* getMonitor(output.accountId ?? accountId, output.monitorId)
239 : undefined;
240
241 // 2. Ensure — missing (greenfield or out-of-band delete): create.
242 if (!observed?.id) {
243 const created = yield* loadBalancers.createMonitor({
244 accountId,
245 ...body,
246 });
247 return toAttributes(created, accountId);
248 }
249
250 // 3. Sync — the update endpoint is a PUT requiring the full body;
251 // diff observed against desired and skip the call on a no-op.
252 if (!monitorDirty(observed, body)) {
253 return toAttributes(observed, accountId);
254 }
255 const updated = yield* loadBalancers.updateMonitor({
256 accountId,
257 monitorId: observed.id,
258 ...body,
259 });
260 return toAttributes(updated, accountId);
261 }),
262
263 delete: Effect.fn(function* ({ output }) {
264 // A monitor still referenced by a pool cannot be deleted — the engine
265 // deletes the pool first, but eventual consistency may lag, so retry
266 // the typed MonitorInUse tag with bounded backoff.
267 yield* loadBalancers
268 .deleteMonitor({
269 accountId: output.accountId,
270 monitorId: output.monitorId,
271 })
272 .pipe(
273 Effect.retry({
274 while: (e) => e._tag === "MonitorInUse",
275 schedule: Schedule.max([Schedule.exponential("1 second"), Schedule.recurs(6)]),
276 }),
277 Effect.catchTag("MonitorNotFound", () => Effect.void),
278 );
279 }),
280 });
281
282 type ObservedMonitor =
283 | loadBalancers.GetMonitorResponse
284 | loadBalancers.CreateMonitorResponse
285 | loadBalancers.UpdateMonitorResponse;
286
287 /**
288 * Read a monitor by id, mapping "gone" (`MonitorNotFound`, HTTP 404 code
289 * 1001) to `undefined`.
290 */
291 const getMonitor = (accountId: string, monitorId: string) =>
292 loadBalancers
293 .getMonitor({ accountId, monitorId })
294 .pipe(Effect.catchTag("MonitorNotFound", () => Effect.undefined));
295
296 /**
297 * Find a monitor by exact description. If several monitors carry the same
298 * description, pick the oldest for determinism.
299 */
300 const findByDescription = (accountId: string, description: string) =>
301 loadBalancers.listMonitors.items({ accountId }).pipe(
302 Stream.filter((m) => m.description === description),
303 Stream.runCollect,
304 Effect.map((chunk) =>
305 Array.from(chunk)
306 .sort((a, b) => (a.createdOn ?? "").localeCompare(b.createdOn ?? ""))
307 .at(0),
308 ),
309 );
310
311 const createDescription = (id: string, description: string | undefined) =>
312 Effect.gen(function* () {
313 return description ?? (yield* createPhysicalName({ id, lowercase: true }));
314 });
315
316 const buildBody = (news: MonitorProps, description: string) => ({
317 description,
318 type: news.type ?? ("http" as const),
319 method: news.method,
320 path: news.path,
321 port: news.port,
322 interval: news.interval,
323 timeout: news.timeout,
324 retries: news.retries,
325 consecutiveUp: news.consecutiveUp,
326 consecutiveDown: news.consecutiveDown,
327 expectedCodes: news.expectedCodes,
328 expectedBody: news.expectedBody,
329 followRedirects: news.followRedirects,
330 allowInsecure: news.allowInsecure,
331 header:
332 news.header === undefined
333 ? undefined
334 : (Object.fromEntries(
335 Object.entries(news.header).map(([k, v]) => [k, Array.from(v)]),
336 ) as Record<string, string[]>),
337 probeZone: news.probeZone,
338 });
339
340 /**
341 * Compare desired (explicitly set) fields against observed cloud state.
342 * Unset desired fields defer to whatever the cloud already has.
343 */
344 const monitorDirty = (observed: ObservedMonitor, body: ReturnType<typeof buildBody>): boolean => {
345 const scalarDirty = (
346 desired: string | number | boolean | undefined,
347 actual: string | number | boolean | null | undefined,
348 ) => desired !== undefined && desired !== (actual ?? undefined);
349 return (
350 observed.description !== body.description ||
351 (observed.type ?? "http") !== body.type ||
352 scalarDirty(body.method, observed.method) ||
353 scalarDirty(body.path, observed.path) ||
354 scalarDirty(body.port, observed.port) ||
355 scalarDirty(body.interval, observed.interval) ||
356 scalarDirty(body.timeout, observed.timeout) ||
357 scalarDirty(body.retries, observed.retries) ||
358 scalarDirty(body.consecutiveUp, observed.consecutiveUp) ||
359 scalarDirty(body.consecutiveDown, observed.consecutiveDown) ||
360 scalarDirty(body.expectedCodes, observed.expectedCodes) ||
361 scalarDirty(body.expectedBody, observed.expectedBody) ||
362 scalarDirty(body.followRedirects, observed.followRedirects) ||
363 scalarDirty(body.allowInsecure, observed.allowInsecure) ||
364 scalarDirty(body.probeZone, observed.probeZone) ||
365 (body.header !== undefined &&
366 JSON.stringify(body.header) !== JSON.stringify(observed.header ?? {}))
367 );
368 };
369
370 const toAttributes = (monitor: ObservedMonitor, accountId: string): MonitorAttributes => ({
371 monitorId: monitor.id ?? "",
372 accountId,
373 description: monitor.description ?? "",
374 type: (monitor.type ?? "http") as MonitorType,
375 createdOn: monitor.createdOn ?? undefined,
376 modifiedOn: monitor.modifiedOn ?? undefined,
377 });