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

main
ts 455 lines 15.1 KB
Raw
1 import * as loadBalancers from "@distilled.cloud/cloudflare/load-balancers";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import type { Input } from "alchemy/Input";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import * as Effect from "effect/Effect";
8 import * as Predicate from "effect/Predicate";
9 import * as Stream from "effect/Stream";
10 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
11 import type { Providers } from "../Providers.ts";
12 import { listAllZones } from "../Zone/lookup.ts";
13
14 const TypeId = "Cloudflare.LoadBalancer.LoadBalancer" as const;
15 type TypeId = typeof TypeId;
16
17 /**
18 * Steering policy for a Load Balancer.
19 */
20 export type SteeringPolicy =
21 | "off"
22 | "geo"
23 | "random"
24 | "dynamic_latency"
25 | "proximity"
26 | "least_outstanding_requests"
27 | "least_connections"
28 | "";
29
30 /**
31 * Session affinity mode for a Load Balancer.
32 */
33 export type SessionAffinity = "none" | "cookie" | "ip_cookie" | "header";
34
35 /**
36 * Session affinity attributes for a Load Balancer.
37 */
38 export interface SessionAffinityAttributes {
39 /** Seconds to drain an origin of affine sessions before removal. */
40 drainDuration?: number;
41 /** Headers to base header-mode session affinity on. */
42 headers?: ReadonlyArray<string>;
43 /** Whether all configured headers must match. */
44 requireAllHeaders?: boolean;
45 /** SameSite attribute of the affinity cookie. */
46 samesite?: "Auto" | "Lax" | "None" | "Strict";
47 /** Secure attribute of the affinity cookie. */
48 secure?: "Auto" | "Always" | "Never";
49 /** Failover behavior when an affine origin becomes unavailable. */
50 zeroDowntimeFailover?: "none" | "temporary" | "sticky";
51 }
52
53 /**
54 * Location strategy for non-proxied (DNS-steered) Load Balancers.
55 */
56 export interface LocationStrategy {
57 /** Resolution mode used to determine the client's location. */
58 mode?: "pop" | "resolver_ip";
59 /** When to prefer the EDNS Client Subnet over the resolver IP. */
60 preferEcs?: "always" | "never" | "proximity" | "geo";
61 }
62
63 export interface Props {
64 /**
65 * Zone the load balancer lives in. Stable — changing the zone triggers
66 * replacement.
67 */
68 zoneId: string;
69 /**
70 * The DNS hostname to associate with the Load Balancer (e.g.
71 * `lb.example.com`). If this hostname already exists as a DNS record,
72 * the Load Balancer takes precedence. Mutable in place.
73 */
74 name: string;
75 /**
76 * Pool IDs ordered by their failover priority. Used by default, or when
77 * region/country/PoP pools are not configured for a request.
78 */
79 defaultPools: ReadonlyArray<string>;
80 /**
81 * The pool ID to use when all other pools are detected as unhealthy.
82 */
83 fallbackPool: string;
84 /**
85 * Object description.
86 */
87 description?: string;
88 /**
89 * Whether the hostname is gray clouded (false) or orange clouded /
90 * proxied through Cloudflare (true).
91 * @default false
92 */
93 proxied?: boolean;
94 /**
95 * TTL (seconds) of the DNS entry for the IP address returned by this
96 * load balancer. Only applies to unproxied load balancers — the API
97 * rejects it when `proxied: true`.
98 * @default 30
99 */
100 ttl?: number;
101 /**
102 * Steering policy for this load balancer.
103 * @default ""
104 */
105 steeringPolicy?: SteeringPolicy;
106 /**
107 * Type of session affinity to use.
108 * @default "none"
109 */
110 sessionAffinity?: SessionAffinity;
111 /**
112 * Time, in seconds, until a client's session expires after being
113 * created.
114 * @default 82800
115 */
116 sessionAffinityTtl?: number;
117 /**
118 * Attributes configuring session affinity behavior.
119 */
120 sessionAffinityAttributes?: SessionAffinityAttributes;
121 /**
122 * Routing modifications in response to dynamic conditions (e.g.
123 * zero-downtime failover between health probes).
124 */
125 adaptiveRouting?: { failoverAcrossPools?: boolean };
126 /**
127 * Location-based steering behavior for non-proxied requests.
128 */
129 locationStrategy?: LocationStrategy;
130 /**
131 * Pool weights for `random` / `least_outstanding_requests` /
132 * `least_connections` steering.
133 */
134 randomSteering?: {
135 defaultWeight?: number;
136 poolWeights?: Record<string, number>;
137 };
138 /**
139 * Region code → ordered pool IDs for that region. Regions not defined
140 * fall back to `defaultPools`.
141 */
142 regionPools?: Record<string, ReadonlyArray<string>>;
143 /**
144 * Country code → ordered pool IDs for that country. Countries not
145 * defined fall back to the corresponding region pool mapping.
146 */
147 countryPools?: Record<string, ReadonlyArray<string>>;
148 /**
149 * Enterprise only — Cloudflare PoP identifier → ordered pool IDs for
150 * that PoP.
151 */
152 popPools?: Record<string, ReadonlyArray<string>>;
153 }
154
155 export interface Attributes {
156 /** Cloudflare-assigned load balancer identifier. */
157 loadBalancerId: string;
158 /** Zone that owns the load balancer. */
159 zoneId: string;
160 /** DNS hostname of the load balancer. */
161 name: string;
162 /** Whether the load balancer is enabled. */
163 enabled: boolean;
164 /** Whether the hostname is proxied (orange clouded). */
165 proxied: boolean;
166 /** Resolved steering policy. */
167 steeringPolicy: string;
168 /** Resolved default pool ids. */
169 defaultPools: ReadonlyArray<string>;
170 /** Resolved fallback pool id. */
171 fallbackPool: string;
172 /** ISO8601 creation timestamp. */
173 createdOn: string | undefined;
174 /** ISO8601 last-modified timestamp. */
175 modifiedOn: string | undefined;
176 }
177
178 export type LoadBalancer = Resource<TypeId, Props, Attributes, never, Providers>;
179
180 /**
181 * A Cloudflare Load Balancer — a zone-level DNS hostname that distributes
182 * traffic across {@link Pool}s with health-based failover,
183 * geo/latency steering, and session affinity.
184 *
185 * Requires the Load Balancing subscription to be enabled for the zone;
186 * without it, creation fails with the typed `LoadBalancingNotEnabledForZone`
187 * error.
188 * ### Creating a Load Balancer
189 * **Example:** DNS-only (unproxied) load balancer
190 * ```typescript
191 * const lb = yield* Cloudflare.LoadBalancer.LoadBalancer("ApiLb", {
192 * zoneId: zone.zoneId,
193 * name: "api.example.com",
194 * defaultPools: [pool.poolId],
195 * fallbackPool: pool.poolId,
196 * proxied: false,
197 * ttl: 30,
198 * });
199 * ```
200 *
201 * **Example:** Proxied load balancer with steering and affinity
202 * ```typescript
203 * const lb = yield* Cloudflare.LoadBalancer.LoadBalancer("AppLb", {
204 * zoneId: zone.zoneId,
205 * name: "app.example.com",
206 * defaultPools: [primary.poolId, secondary.poolId],
207 * fallbackPool: secondary.poolId,
208 * proxied: true,
209 * steeringPolicy: "random",
210 * sessionAffinity: "cookie",
211 * });
212 * ```
213 *
214 * ### Geo steering
215 * **Example:** Region pools
216 * ```typescript
217 * yield* Cloudflare.LoadBalancer.LoadBalancer("GeoLb", {
218 * zoneId: zone.zoneId,
219 * name: "geo.example.com",
220 * defaultPools: [us.poolId],
221 * fallbackPool: us.poolId,
222 * steeringPolicy: "geo",
223 * regionPools: {
224 * WEU: [eu.poolId],
225 * ENAM: [us.poolId],
226 * },
227 * });
228 * ```
229 *
230 * @see https://developers.cloudflare.com/load-balancing/
231 *
232 * @resource
233 * @product Load Balancers
234 * @category Performance & Reliability
235 */
236 export const LoadBalancer = Resource<LoadBalancer>(TypeId, {
237 aliases: ["Cloudflare.LoadBalancer"],
238 });
239
240 /**
241 * Returns true if the given value is a LoadBalancer resource.
242 */
243 export const isLoadBalancer = (value: unknown): value is LoadBalancer =>
244 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
245
246 export const LoadBalancerProvider = () =>
247 Provider.succeed(LoadBalancer, {
248 stables: ["loadBalancerId", "zoneId", "createdOn"],
249
250 diff: Effect.fn(function* ({ olds, news }) {
251 if (!isResolved(news)) return undefined;
252 // zoneId is Input<string>; by diff time both sides are concrete
253 // strings when statically known.
254 if (
255 typeof olds.zoneId === "string" &&
256 typeof news.zoneId === "string" &&
257 olds.zoneId !== news.zoneId
258 ) {
259 return { action: "replace" } as const;
260 }
261 }),
262
263 read: Effect.fn(function* ({ output, olds }) {
264 if (output?.loadBalancerId) {
265 const observed = yield* getLoadBalancer(output.zoneId, output.loadBalancerId);
266 return observed ? toAttributes(observed, output.zoneId) : undefined;
267 }
268 // Cold read — a load balancer's hostname is unique within its zone.
269 // Load balancers carry no ownership marker, so report the match as
270 // Unowned and let the engine gate takeover behind --adopt.
271 const zoneId = output?.zoneId ?? (olds?.zoneId as string | undefined);
272 const name = output?.name ?? olds?.name;
273 if (zoneId && name) {
274 const match = yield* findByName(zoneId, name);
275 if (match?.id) {
276 const observed = yield* getLoadBalancer(zoneId, match.id);
277 if (observed) return Unowned(toAttributes(observed, zoneId));
278 }
279 }
280 return undefined;
281 }),
282
283 reconcile: Effect.fn(function* ({ news, output }) {
284 // Inputs have been resolved to concrete strings by Plan.
285 const zoneId = news.zoneId as string;
286 const body = buildBody(news);
287
288 // 1. Observe — output.loadBalancerId is a cache hint; a 404 falls
289 // through to "missing" and we recreate.
290 const observed = output?.loadBalancerId
291 ? yield* getLoadBalancer(output.zoneId ?? zoneId, output.loadBalancerId)
292 : undefined;
293
294 // 2. Ensure — missing: create with the full desired body.
295 if (!observed?.id) {
296 const created = yield* loadBalancers.createLoadBalancer({
297 zoneId,
298 ...body,
299 });
300 return toAttributes(created, zoneId);
301 }
302
303 // 3. Sync — the update endpoint is a PUT requiring the full body;
304 // diff observed against desired and skip the call on a no-op.
305 if (!loadBalancerDirty(observed, body)) {
306 return toAttributes(observed, zoneId);
307 }
308 const updated = yield* loadBalancers.updateLoadBalancer({
309 zoneId,
310 loadBalancerId: observed.id,
311 ...body,
312 });
313 return toAttributes(updated, zoneId);
314 }),
315
316 delete: Effect.fn(function* ({ output }) {
317 yield* loadBalancers
318 .deleteLoadBalancer({
319 zoneId: output.zoneId,
320 loadBalancerId: output.loadBalancerId,
321 })
322 .pipe(Effect.catchTag("LoadBalancerNotFound", () => Effect.void));
323 }),
324
325 // Load balancers are zone-scoped; enumerate every zone in the account and
326 // exhaustively paginate each zone's load balancers, hydrating each into the
327 // same Attributes shape `read` returns. Zones without the Load Balancing
328 // subscription reject the route (Forbidden) and are skipped.
329 list: Effect.fn(function* () {
330 const { accountId } = yield* yield* CloudflareEnvironment;
331 const zones = yield* listAllZones(accountId);
332 const rows = yield* Effect.forEach(
333 zones,
334 (zone) =>
335 loadBalancers.listLoadBalancers.pages({ zoneId: zone.id }).pipe(
336 Stream.runCollect,
337 Effect.map((chunk) =>
338 Array.from(chunk).flatMap((page) =>
339 (page.result ?? []).map((lb) => toAttributes(lb, zone.id)),
340 ),
341 ),
342 ),
343 { concurrency: 10 },
344 );
345 return rows.flat();
346 }),
347 });
348
349 type ObservedLoadBalancer =
350 | loadBalancers.GetLoadBalancerResponse
351 | loadBalancers.CreateLoadBalancerResponse
352 | loadBalancers.UpdateLoadBalancerResponse
353 | loadBalancers.ListLoadBalancersResponse["result"][number];
354
355 /**
356 * Read a load balancer by id, mapping "gone" (`LoadBalancerNotFound`,
357 * HTTP 404 code 1001) to `undefined`.
358 */
359 const getLoadBalancer = (zoneId: string, loadBalancerId: string) =>
360 loadBalancers
361 .getLoadBalancer({ zoneId, loadBalancerId })
362 .pipe(Effect.catchTag("LoadBalancerNotFound", () => Effect.undefined));
363
364 /**
365 * Find a load balancer by exact hostname within a zone.
366 */
367 const findByName = (zoneId: string, name: string) =>
368 loadBalancers.listLoadBalancers.items({ zoneId }).pipe(
369 Stream.filter((lb) => lb.name === name),
370 Stream.runCollect,
371 Effect.map((chunk) => Array.from(chunk).at(0)),
372 );
373
374 const resolvePools = (
375 pools: Record<string, ReadonlyArray<Input<string>>> | undefined,
376 ): Record<string, string[]> | undefined =>
377 pools === undefined
378 ? undefined
379 : Object.fromEntries(Object.entries(pools).map(([k, v]) => [k, Array.from(v as string[])]));
380
381 const buildBody = (news: Props) => ({
382 name: news.name,
383 defaultPools: news.defaultPools as string[],
384 fallbackPool: news.fallbackPool as string,
385 description: news.description,
386 proxied: news.proxied,
387 ttl: news.proxied === true ? undefined : news.ttl,
388 steeringPolicy: news.steeringPolicy,
389 sessionAffinity: news.sessionAffinity,
390 sessionAffinityTtl: news.sessionAffinityTtl,
391 sessionAffinityAttributes:
392 news.sessionAffinityAttributes === undefined
393 ? undefined
394 : {
395 ...news.sessionAffinityAttributes,
396 headers:
397 news.sessionAffinityAttributes.headers === undefined
398 ? undefined
399 : Array.from(news.sessionAffinityAttributes.headers),
400 },
401 adaptiveRouting: news.adaptiveRouting,
402 locationStrategy: news.locationStrategy,
403 randomSteering: news.randomSteering,
404 regionPools: resolvePools(news.regionPools),
405 countryPools: resolvePools(news.countryPools),
406 popPools: resolvePools(news.popPools),
407 });
408
409 /**
410 * Compare desired (explicitly set) fields against observed cloud state.
411 * Unset desired fields defer to whatever the cloud already has.
412 */
413 const loadBalancerDirty = (
414 observed: ObservedLoadBalancer,
415 body: ReturnType<typeof buildBody>,
416 ): boolean => {
417 const scalarDirty = (
418 desired: string | number | boolean | undefined,
419 actual: string | number | boolean | null | undefined,
420 ) => desired !== undefined && desired !== (actual ?? undefined);
421 const structDirty = (desired: unknown, actual: unknown) =>
422 desired !== undefined && JSON.stringify(desired) !== JSON.stringify(actual ?? {});
423
424 return (
425 (observed.name ?? "") !== body.name ||
426 JSON.stringify(observed.defaultPools ?? []) !== JSON.stringify(body.defaultPools) ||
427 (observed.fallbackPool ?? "") !== body.fallbackPool ||
428 scalarDirty(body.description, observed.description) ||
429 scalarDirty(body.proxied, observed.proxied) ||
430 scalarDirty(body.ttl, observed.ttl) ||
431 scalarDirty(body.steeringPolicy, observed.steeringPolicy) ||
432 scalarDirty(body.sessionAffinity, observed.sessionAffinity) ||
433 scalarDirty(body.sessionAffinityTtl, observed.sessionAffinityTtl) ||
434 structDirty(body.sessionAffinityAttributes, observed.sessionAffinityAttributes) ||
435 structDirty(body.adaptiveRouting, observed.adaptiveRouting) ||
436 structDirty(body.locationStrategy, observed.locationStrategy) ||
437 structDirty(body.randomSteering, observed.randomSteering) ||
438 structDirty(body.regionPools, observed.regionPools) ||
439 structDirty(body.countryPools, observed.countryPools) ||
440 structDirty(body.popPools, observed.popPools)
441 );
442 };
443
444 const toAttributes = (lb: ObservedLoadBalancer, zoneId: string): Attributes => ({
445 loadBalancerId: lb.id ?? "",
446 zoneId,
447 name: lb.name ?? "",
448 enabled: lb.enabled ?? true,
449 proxied: lb.proxied ?? false,
450 steeringPolicy: lb.steeringPolicy ?? "",
451 defaultPools: [...(lb.defaultPools ?? [])],
452 fallbackPool: lb.fallbackPool ?? "",
453 createdOn: lb.createdOn ?? undefined,
454 modifiedOn: lb.modifiedOn ?? undefined,
455 });