@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 478 lines 15.2 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.Pool" as const;
14 type TypeId = typeof TypeId;
15
16 /**
17 * A single origin server within a Load Balancing pool.
18 */
19 export interface PoolOrigin {
20 /**
21 * The IP address (IPv4 or IPv6) or publicly-resolvable hostname of the
22 * origin server.
23 */
24 address: string;
25 /**
26 * A human-identifiable name for the origin.
27 */
28 name?: string;
29 /**
30 * Whether to enable (the default) this origin within the pool.
31 * @default true
32 */
33 enabled?: boolean;
34 /**
35 * Relative weight of this origin (`0`–`1`) for traffic distribution.
36 * @default 1
37 */
38 weight?: number;
39 /**
40 * The port to override the standard port for this origin.
41 */
42 port?: number;
43 /**
44 * Request headers to send to this origin — typically a `Host` header.
45 */
46 header?: { host?: ReadonlyArray<string> };
47 /**
48 * Whether to flatten a CNAME `address` to its final IP.
49 */
50 flattenCname?: boolean;
51 /**
52 * The virtual network subnet the origin belongs to (private origins).
53 */
54 virtualNetworkId?: string;
55 }
56
57 /**
58 * Load shedding configuration for a pool.
59 */
60 export interface PoolLoadShedding {
61 /** Percent (0–100) of new (non-affine) traffic to shed. @default 0 */
62 defaultPercent?: number;
63 /** Policy for shedding new traffic. @default "random" */
64 defaultPolicy?: "random" | "hash";
65 /** Percent (0–100) of session-affine traffic to shed. @default 0 */
66 sessionPercent?: number;
67 /** Policy for shedding session-affine traffic. */
68 sessionPolicy?: "hash";
69 }
70
71 /**
72 * Filters pool/origin health notifications by resource type or health
73 * status.
74 */
75 export interface PoolNotificationFilter {
76 origin?: { disable?: boolean; healthy?: boolean };
77 pool?: { disable?: boolean; healthy?: boolean };
78 }
79
80 export interface PoolProps {
81 /**
82 * A short name (tag) for the pool. Only alphanumeric characters, hyphens,
83 * and underscores are allowed. If omitted, a unique name is generated
84 * from the app, stage, and logical ID.
85 * @default ${app}-${stage}-${id}
86 */
87 name?: string;
88 /**
89 * The list of origins within this pool. Traffic directed at this pool is
90 * balanced across all currently healthy origins.
91 */
92 origins: ReadonlyArray<PoolOrigin>;
93 /**
94 * A human-readable description of the pool.
95 */
96 description?: string;
97 /**
98 * Whether to enable (the default) or disable this pool. Disabled pools
99 * receive no traffic and are excluded from health checks.
100 * @default true
101 */
102 enabled?: boolean;
103 /**
104 * The ID of the Monitor to use for checking the health of origins within
105 * this pool. Mutually exclusive with `monitorGroup`.
106 */
107 monitor?: string;
108 /**
109 * The ID of the Monitor Group to use for checking the health of origins
110 * within this pool. Mutually exclusive with `monitor`.
111 */
112 monitorGroup?: string;
113 /**
114 * The minimum number of origins that must be healthy for this pool to
115 * serve traffic.
116 * @default 1
117 */
118 minimumOrigins?: number;
119 /**
120 * The latitude of the data center containing this pool's origins, in
121 * decimal degrees. Must be set together with `longitude`.
122 */
123 latitude?: number;
124 /**
125 * The longitude of the data center containing this pool's origins, in
126 * decimal degrees. Must be set together with `latitude`.
127 */
128 longitude?: number;
129 /**
130 * Load shedding policies and percentages for the pool.
131 */
132 loadShedding?: PoolLoadShedding;
133 /**
134 * How origins are selected for new sessions / traffic without session
135 * affinity.
136 * @default { policy: "random" }
137 */
138 originSteering?: {
139 policy?: "random" | "hash" | "least_outstanding_requests" | "least_connections";
140 };
141 /**
142 * Filter pool and origin health notifications by resource type or health
143 * status.
144 */
145 notificationFilter?: PoolNotificationFilter;
146 /**
147 * Deprecated upstream — the email address to send health status
148 * notifications to. Prefer Cloudflare's centralized notification service.
149 */
150 notificationEmail?: string;
151 }
152
153 export interface PoolAttributes {
154 /** Cloudflare-assigned pool identifier. */
155 poolId: string;
156 /** The Cloudflare account the pool belongs to. */
157 accountId: string;
158 /** Pool name. */
159 name: string;
160 /** Whether the pool is enabled. */
161 enabled: boolean;
162 /** Resolved monitor id attached to the pool, if any. */
163 monitor: string | undefined;
164 /** ISO8601 creation timestamp. */
165 createdOn: string | undefined;
166 /** ISO8601 last-modified timestamp. */
167 modifiedOn: string | undefined;
168 }
169
170 export type Pool = Resource<TypeId, PoolProps, PoolAttributes, never, Providers>;
171
172 /**
173 * A Cloudflare Load Balancing pool — an account-scoped group of origin
174 * servers that Load Balancers route traffic to. Pools optionally reference
175 * a {@link Monitor} for active health checking.
176 *
177 * Requires the Load Balancing subscription on the account; without it, pool
178 * creation fails with the typed `PoolAccessFailed` error.
179 * ### Creating a Pool
180 * **Example:** Pool with one origin
181 * ```typescript
182 * const pool = yield* Cloudflare.LoadBalancer.Pool("ApiPool", {
183 * origins: [{ name: "origin-1", address: "203.0.113.10" }],
184 * });
185 * ```
186 *
187 * **Example:** Health-checked pool
188 * ```typescript
189 * const monitor = yield* Cloudflare.LoadBalancer.Monitor("ApiMonitor", {
190 * type: "https",
191 * path: "/health",
192 * expectedCodes: "2xx",
193 * });
194 *
195 * const pool = yield* Cloudflare.LoadBalancer.Pool("ApiPool", {
196 * origins: [
197 * { name: "origin-1", address: "203.0.113.10", weight: 0.7 },
198 * { name: "origin-2", address: "203.0.113.11", weight: 0.3 },
199 * ],
200 * monitor: monitor.monitorId,
201 * minimumOrigins: 1,
202 * });
203 * ```
204 *
205 * ### Using with a Load Balancer
206 * **Example:** Pool as default and fallback
207 * ```typescript
208 * yield* Cloudflare.LoadBalancer.LoadBalancer("ApiLb", {
209 * zoneId: zone.zoneId,
210 * name: "api.example.com",
211 * defaultPools: [pool.poolId],
212 * fallbackPool: pool.poolId,
213 * });
214 * ```
215 *
216 * @see https://developers.cloudflare.com/load-balancing/pools/
217 *
218 * @resource
219 * @product Load Balancers
220 * @category Performance & Reliability
221 */
222 export const Pool = Resource<Pool>(TypeId);
223
224 /**
225 * Returns true if the given value is a Pool resource.
226 */
227 export const isPool = (value: unknown): value is Pool =>
228 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
229
230 export const PoolProvider = () =>
231 Provider.succeed(Pool, {
232 stables: ["poolId", "accountId", "createdOn"],
233
234 diff: Effect.fn(function* ({ output }) {
235 const { accountId } = yield* yield* CloudflareEnvironment;
236 if ((output?.accountId ?? accountId) !== accountId) {
237 return { action: "replace" } as const;
238 }
239 return undefined;
240 }),
241
242 read: Effect.fn(function* ({ id, output, olds }) {
243 const { accountId } = yield* yield* CloudflareEnvironment;
244 const acct = output?.accountId ?? accountId;
245
246 if (output?.poolId) {
247 const observed = yield* getPool(acct, output.poolId);
248 return observed ? toAttributes(observed, acct) : undefined;
249 }
250 // Cold read — recover from lost state by matching the deterministic
251 // pool name. Pools carry no ownership marker, so the match is
252 // reported as Unowned and the engine gates takeover behind --adopt.
253 const name = yield* createPoolName(id, olds?.name);
254 const match = yield* findByName(acct, name);
255 if (match?.id) {
256 const observed = yield* getPool(acct, match.id);
257 if (observed) return Unowned(toAttributes(observed, acct));
258 }
259 return undefined;
260 }),
261
262 list: Effect.fn(function* () {
263 const { accountId } = yield* yield* CloudflareEnvironment;
264 return yield* loadBalancers.listPools.pages({ accountId }).pipe(
265 Stream.runCollect,
266 Effect.map((chunk) =>
267 Array.from(chunk).flatMap((page) =>
268 (page.result ?? []).map((pool): PoolAttributes => ({
269 poolId: pool.id ?? "",
270 accountId,
271 name: pool.name ?? "",
272 enabled: pool.enabled ?? true,
273 monitor: pool.monitor ?? undefined,
274 createdOn: pool.createdOn ?? undefined,
275 modifiedOn: pool.modifiedOn ?? undefined,
276 })),
277 ),
278 ),
279 );
280 }),
281
282 reconcile: Effect.fn(function* ({ id, news, output }) {
283 const { accountId } = yield* yield* CloudflareEnvironment;
284 const name = yield* createPoolName(id, news.name);
285 const body = buildBody(news, name);
286
287 // 1. Observe — output.poolId is a cache hint; a 404 falls through
288 // to "missing" and we recreate.
289 const observed = output?.poolId
290 ? yield* getPool(output.accountId ?? accountId, output.poolId)
291 : undefined;
292
293 // 2. Ensure — missing: create with the full desired body.
294 if (!observed?.id) {
295 const created = yield* loadBalancers.createPool({
296 accountId,
297 ...body,
298 });
299 return toAttributes(created, accountId);
300 }
301
302 // 3. Sync — the update endpoint is a PUT requiring name + origins;
303 // diff observed against desired and skip the call on a no-op.
304 if (!poolDirty(observed, body)) {
305 return toAttributes(observed, accountId);
306 }
307 const updated = yield* loadBalancers.updatePool({
308 accountId,
309 poolId: observed.id,
310 ...body,
311 });
312 return toAttributes(updated, accountId);
313 }),
314
315 delete: Effect.fn(function* ({ output }) {
316 // A pool still referenced by a Load Balancer cannot be deleted — the
317 // engine deletes the LB first, but eventual consistency may lag, so
318 // retry the typed PoolInUse tag with bounded backoff.
319 yield* loadBalancers
320 .deletePool({
321 accountId: output.accountId,
322 poolId: output.poolId,
323 })
324 .pipe(
325 Effect.retry({
326 while: (e) => e._tag === "PoolInUse",
327 schedule: Schedule.max([Schedule.exponential("1 second"), Schedule.recurs(6)]),
328 }),
329 Effect.catchTag("PoolNotFound", () => Effect.void),
330 );
331 }),
332 });
333
334 type ObservedPool =
335 | loadBalancers.GetPoolResponse
336 | loadBalancers.CreatePoolResponse
337 | loadBalancers.UpdatePoolResponse;
338
339 /**
340 * Read a pool by id, mapping "gone" (`PoolNotFound`, HTTP 404 code 1001)
341 * to `undefined`.
342 */
343 const getPool = (accountId: string, poolId: string) =>
344 loadBalancers
345 .getPool({ accountId, poolId })
346 .pipe(Effect.catchTag("PoolNotFound", () => Effect.undefined));
347
348 /**
349 * Find a pool by exact name. If several pools carry the same name, pick
350 * the oldest for determinism.
351 */
352 const findByName = (accountId: string, name: string) =>
353 loadBalancers.listPools.items({ accountId }).pipe(
354 Stream.filter((p) => p.name === name),
355 Stream.runCollect,
356 Effect.map((chunk) =>
357 Array.from(chunk)
358 .sort((a, b) => (a.createdOn ?? "").localeCompare(b.createdOn ?? ""))
359 .at(0),
360 ),
361 );
362
363 const createPoolName = (id: string, name: string | undefined) =>
364 Effect.gen(function* () {
365 return name ?? (yield* createPhysicalName({ id, lowercase: true }));
366 });
367
368 const buildBody = (news: PoolProps, name: string) => ({
369 name,
370 origins: news.origins.map((o) => ({
371 address: o.address,
372 name: o.name,
373 enabled: o.enabled,
374 weight: o.weight,
375 port: o.port,
376 header:
377 o.header === undefined
378 ? undefined
379 : {
380 host: o.header.host === undefined ? undefined : Array.from(o.header.host),
381 },
382 flattenCname: o.flattenCname,
383 // Inputs are resolved to concrete strings by Plan.
384 virtualNetworkId: o.virtualNetworkId as string | undefined,
385 })),
386 description: news.description,
387 enabled: news.enabled,
388 monitor: news.monitor as string | undefined,
389 monitorGroup: news.monitorGroup as string | undefined,
390 minimumOrigins: news.minimumOrigins,
391 latitude: news.latitude,
392 longitude: news.longitude,
393 loadShedding: news.loadShedding,
394 originSteering: news.originSteering,
395 notificationFilter: news.notificationFilter,
396 notificationEmail: news.notificationEmail,
397 });
398
399 /**
400 * Compare desired (explicitly set) fields against observed cloud state.
401 * Unset desired fields defer to whatever the cloud already has.
402 */
403 const poolDirty = (observed: ObservedPool, body: ReturnType<typeof buildBody>): boolean => {
404 const scalarDirty = (
405 desired: string | number | boolean | undefined,
406 actual: string | number | boolean | null | undefined,
407 ) => desired !== undefined && desired !== (actual ?? undefined);
408
409 const desiredOrigins = body.origins.map(normalizeOrigin);
410 const observedOrigins = (observed.origins ?? []).map((o) =>
411 normalizeOrigin({
412 address: o.address ?? "",
413 name: o.name ?? undefined,
414 enabled: o.enabled ?? undefined,
415 weight: o.weight ?? undefined,
416 port: o.port ?? undefined,
417 header:
418 o.header == null
419 ? undefined
420 : { host: o.header.host == null ? undefined : [...o.header.host] },
421 flattenCname: o.flattenCname ?? undefined,
422 virtualNetworkId: o.virtualNetworkId ?? undefined,
423 }),
424 );
425
426 return (
427 (observed.name ?? "") !== body.name ||
428 JSON.stringify(desiredOrigins) !== JSON.stringify(observedOrigins) ||
429 scalarDirty(body.description, observed.description) ||
430 scalarDirty(body.enabled, observed.enabled) ||
431 scalarDirty(body.monitor, observed.monitor) ||
432 scalarDirty(body.monitorGroup, observed.monitorGroup) ||
433 scalarDirty(body.minimumOrigins, observed.minimumOrigins) ||
434 scalarDirty(body.latitude, observed.latitude) ||
435 scalarDirty(body.longitude, observed.longitude) ||
436 scalarDirty(body.notificationEmail, observed.notificationEmail) ||
437 (body.loadShedding !== undefined &&
438 JSON.stringify(body.loadShedding) !== JSON.stringify(observed.loadShedding ?? {})) ||
439 (body.originSteering !== undefined &&
440 JSON.stringify(body.originSteering) !== JSON.stringify(observed.originSteering ?? {})) ||
441 (body.notificationFilter !== undefined &&
442 JSON.stringify(body.notificationFilter) !== JSON.stringify(observed.notificationFilter ?? {}))
443 );
444 };
445
446 /**
447 * Normalize an origin to its API defaults so desired-vs-observed
448 * comparison is stable.
449 */
450 const normalizeOrigin = (o: {
451 address: string;
452 name?: string;
453 enabled?: boolean;
454 weight?: number;
455 port?: number;
456 header?: { host?: string[] };
457 flattenCname?: boolean;
458 virtualNetworkId?: string;
459 }) => ({
460 address: o.address,
461 name: o.name ?? "",
462 enabled: o.enabled ?? true,
463 weight: o.weight ?? 1,
464 port: o.port ?? 0,
465 host: o.header?.host ?? [],
466 flattenCname: o.flattenCname ?? false,
467 virtualNetworkId: o.virtualNetworkId ?? "",
468 });
469
470 const toAttributes = (pool: ObservedPool, accountId: string): PoolAttributes => ({
471 poolId: pool.id ?? "",
472 accountId,
473 name: pool.name ?? "",
474 enabled: pool.enabled ?? true,
475 monitor: pool.monitor ?? undefined,
476 createdOn: pool.createdOn ?? undefined,
477 modifiedOn: pool.modifiedOn ?? undefined,
478 });