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

main
ts 613 lines 20 KB
Raw
1 import * as waitingRooms from "@distilled.cloud/cloudflare/waiting-rooms";
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 Stream from "effect/Stream";
9 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
10 import type { Providers } from "../Providers.ts";
11 import { listAllZones } from "../Zone/lookup.ts";
12
13 const TypeId = "Cloudflare.WaitingRoom.WaitingRoom" as const;
14 type TypeId = typeof TypeId;
15
16 /**
17 * Queueing method used by a waiting room. Changing this from the default
18 * `fifo` requires the Waiting Room Advanced subscription.
19 */
20 export type QueueingMethod = "fifo" | "random" | "passthrough" | "reject";
21
22 /**
23 * HTTP status code returned to a user while in the queue.
24 */
25 export type QueueingStatusCode = 200 | 202 | 429;
26
27 /**
28 * Which Turnstile widget type the waiting room uses for detecting bot
29 * traffic.
30 */
31 export type TurnstileMode = "off" | "invisible" | "visible_non_interactive" | "visible_managed";
32
33 /**
34 * What to do when Turnstile detects a bot: `log` only records it in
35 * analytics; `infinite_queue` sends the bot to a queue that never lets it
36 * through.
37 */
38 export type TurnstileAction = "log" | "infinite_queue";
39
40 /**
41 * Cookie attributes for the waiting room cookie (`__cf_waitingroom`).
42 */
43 export interface CookieAttributes {
44 /**
45 * SameSite attribute of the waiting room cookie.
46 * @default "auto"
47 */
48 samesite?: "auto" | "lax" | "none" | "strict";
49 /**
50 * Secure attribute of the waiting room cookie.
51 * @default "auto"
52 */
53 secure?: "auto" | "always" | "never";
54 }
55
56 /**
57 * An additional hostname + path combination the waiting room is applied to.
58 * Only available with the Waiting Room Advanced subscription.
59 */
60 export interface Route {
61 /**
62 * Hostname (no scheme, no wildcards).
63 */
64 host?: string;
65 /**
66 * Path within the host. There is an implied wildcard at the end.
67 * @default "/"
68 */
69 path?: string;
70 }
71
72 export interface Props {
73 /**
74 * Zone the waiting room belongs to. Stable — changing the zone triggers
75 * a replacement.
76 */
77 zoneId: string;
78 /**
79 * A unique name to identify the waiting room. Only alphanumeric
80 * characters, hyphens, and underscores are allowed. If omitted, a unique
81 * name is generated from the app, stage, and logical ID. Mutable.
82 * @default ${app}-${stage}-${id}
83 */
84 name?: string;
85 /**
86 * The host name to which the waiting room will be applied (no
87 * wildcards). Do not include the scheme. The host and path combination
88 * must be unique per zone. Mutable.
89 */
90 host: string;
91 /**
92 * The path within the host to enable the waiting room on, including all
93 * subpaths. Mutable.
94 * @default "/"
95 */
96 path?: string;
97 /**
98 * Total number of active user sessions on the route at a point in time
99 * (minimum 200). Mutable.
100 */
101 totalActiveUsers: number;
102 /**
103 * Number of new users that will be let into the route every minute
104 * (minimum 200). Mutable.
105 */
106 newUsersPerMinute: number;
107 /**
108 * A note with more details about the waiting room. Mutable.
109 * @default ""
110 */
111 description?: string;
112 /**
113 * Lifetime of a cookie (in minutes, 1–30) set for users who get access
114 * to the route. Mutable.
115 * @default 5
116 */
117 sessionDuration?: number;
118 /**
119 * Disables automatic renewal of session cookies (Waiting Room Advanced
120 * only). Mutable.
121 * @default false
122 */
123 disableSessionRenewal?: boolean;
124 /**
125 * If `true`, all traffic to the route is sent to the waiting room.
126 * Mutable.
127 * @default false
128 */
129 queueAll?: boolean;
130 /**
131 * Queueing method. Non-`fifo` methods require the Waiting Room Advanced
132 * subscription. Mutable.
133 * @default "fifo"
134 */
135 queueingMethod?: QueueingMethod;
136 /**
137 * HTTP status code returned to a user while in the queue. Mutable.
138 * @default "200"
139 */
140 queueingStatusCode?: QueueingStatusCode;
141 /**
142 * Suspends the waiting room — traffic flows straight to the route.
143 * Mutable.
144 * @default false
145 */
146 suspended?: boolean;
147 /**
148 * If `true`, requests with `Accept: application/json` receive a JSON
149 * response describing the queue (Waiting Room Advanced only). Mutable.
150 * @default false
151 */
152 jsonResponseEnabled?: boolean;
153 /**
154 * Custom HTML template rendered at the edge instead of the default
155 * waiting room page (Waiting Room Advanced only). Mutable.
156 */
157 customPageHtml?: string;
158 /**
159 * Language of the default page template. Mutable.
160 * @default "en-US"
161 */
162 defaultTemplateLanguage?: string;
163 /**
164 * Appends `_` + this suffix to the waiting room cookie name. Mutable.
165 */
166 cookieSuffix?: string;
167 /**
168 * Cookie attributes for the waiting room cookie. Mutable.
169 */
170 cookieAttributes?: CookieAttributes;
171 /**
172 * Additional hostname/path combinations the waiting room applies to
173 * (Waiting Room Advanced only). Mutable.
174 */
175 additionalRoutes?: Route[];
176 /**
177 * Enabled origin commands (currently only `revoke`). Mutable.
178 * @default []
179 */
180 enabledOriginCommands?: "revoke"[];
181 /**
182 * Turnstile widget type used for detecting bot traffic. Mutable.
183 * @default "off"
184 */
185 turnstileMode?: TurnstileMode;
186 /**
187 * Action taken when Turnstile detects a bot. Mutable.
188 * @default "log"
189 */
190 turnstileAction?: TurnstileAction;
191 }
192
193 export interface Attributes {
194 /** Cloudflare-assigned identifier of the waiting room. */
195 waitingRoomId: string;
196 /** Zone the waiting room belongs to. */
197 zoneId: string;
198 /** The waiting room's unique name. */
199 name: string;
200 /** Host the waiting room is applied to. */
201 host: string;
202 /** Path within the host the waiting room is enabled on. */
203 path: string;
204 /** Total number of active user sessions allowed on the route. */
205 totalActiveUsers: number;
206 /** Number of new users let into the route per minute. */
207 newUsersPerMinute: number;
208 /** Note describing the waiting room. */
209 description: string;
210 /** Session cookie lifetime in minutes. */
211 sessionDuration: number;
212 /** Whether all traffic is sent to the waiting room. */
213 queueAll: boolean;
214 /** Queueing method in effect. */
215 queueingMethod: QueueingMethod;
216 /** HTTP status code returned to queued users. */
217 queueingStatusCode: QueueingStatusCode;
218 /** Whether the waiting room is suspended. */
219 suspended: boolean;
220 /** ISO8601 creation timestamp. */
221 createdOn: string | undefined;
222 /** ISO8601 last-modified timestamp. */
223 modifiedOn: string | undefined;
224 }
225
226 export type WaitingRoom = Resource<TypeId, Props, Attributes, never, Providers>;
227
228 /**
229 * A Cloudflare Waiting Room — places visitors in a virtual queue when
230 * traffic to a host + path exceeds the configured thresholds, protecting
231 * the origin from overload.
232 *
233 * Waiting Rooms require a Business or Enterprise zone plan; on unentitled
234 * zones every write fails with the typed `ZoneNotEntitled` error
235 * (Cloudflare code 1034). Several props (`additionalRoutes`,
236 * `customPageHtml`, non-`fifo` `queueingMethod`, `disableSessionRenewal`,
237 * `jsonResponseEnabled`) additionally require the Waiting Room Advanced
238 * subscription.
239 *
240 * Everything except the zone is mutable in place via a full-body PUT.
241 * Waiting rooms carry no ownership markers, so when state is lost `read`
242 * matches by name and reports the room as `Unowned` — the engine refuses
243 * to take it over unless `--adopt` (or `adopt(true)`) is set.
244 * ### Creating a Waiting Room
245 * **Example:** Basic waiting room on a host
246 * ```typescript
247 * const room = yield* Cloudflare.WaitingRoom.WaitingRoom("checkout", {
248 * zoneId: zone.zoneId,
249 * host: "shop.example.com",
250 * path: "/checkout",
251 * totalActiveUsers: 200,
252 * newUsersPerMinute: 200,
253 * });
254 * ```
255 *
256 * **Example:** Queue all traffic during an incident
257 * ```typescript
258 * yield* Cloudflare.WaitingRoom.WaitingRoom("incident-gate", {
259 * zoneId: zone.zoneId,
260 * host: "example.com",
261 * totalActiveUsers: 500,
262 * newUsersPerMinute: 200,
263 * queueAll: true,
264 * queueingStatusCode: 429,
265 * });
266 * ```
267 *
268 * ### Customizing behavior
269 * **Example:** Short sessions with a custom cookie suffix
270 * ```typescript
271 * yield* Cloudflare.WaitingRoom.WaitingRoom("flash-sale", {
272 * zoneId: zone.zoneId,
273 * host: "example.com",
274 * path: "/sale",
275 * totalActiveUsers: 1000,
276 * newUsersPerMinute: 500,
277 * sessionDuration: 1,
278 * cookieSuffix: "sale",
279 * defaultTemplateLanguage: "de-DE",
280 * });
281 * ```
282 *
283 * @see https://developers.cloudflare.com/waiting-room/
284 *
285 * @resource
286 * @product Waiting Rooms
287 * @category Performance & Reliability
288 */
289 export const WaitingRoom = Resource<WaitingRoom>(TypeId, {
290 aliases: ["Cloudflare.WaitingRoom"],
291 });
292
293 /**
294 * Returns true if the given value is a WaitingRoom resource.
295 */
296 export const isWaitingRoom = (value: unknown): value is WaitingRoom =>
297 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
298
299 export const WaitingRoomProvider = () =>
300 Provider.succeed(WaitingRoom, {
301 stables: ["waitingRoomId", "zoneId", "createdOn"],
302
303 diff: Effect.fn(function* ({ olds = {}, news, output }) {
304 const o = olds as Props;
305 const n = news as Props;
306 // zoneId is Input<string>; compare only once both sides are concrete.
307 const oldZoneId = output?.zoneId ?? (typeof o.zoneId === "string" ? o.zoneId : undefined);
308 if (oldZoneId !== undefined && typeof n.zoneId === "string" && oldZoneId !== n.zoneId) {
309 return { action: "replace" } as const;
310 }
311 return undefined;
312 }),
313
314 read: Effect.fn(function* ({ id, output, olds }) {
315 const zoneId = output?.zoneId ?? (olds?.zoneId as string | undefined);
316 if (!zoneId) return undefined;
317
318 // Owned path: refresh by our persisted waiting room id.
319 if (output?.waitingRoomId) {
320 const observed = yield* getRoom(zoneId, output.waitingRoomId);
321 if (observed) return toAttributes(observed, zoneId);
322 }
323
324 // Cold read — recover from lost state by matching the deterministic
325 // physical name. Waiting rooms carry no ownership markers, so report
326 // the match as `Unowned` and let the adopt policy gate takeover.
327 const name = yield* createRoomName(id, olds?.name);
328 const match = yield* findByName(zoneId, name);
329 if (match) return Unowned(toAttributes(match, zoneId));
330 return undefined;
331 }),
332
333 reconcile: Effect.fn(function* ({ id, news, output }) {
334 // Inputs have been resolved to concrete strings by Plan.
335 const zoneId = news.zoneId as string;
336 const name = yield* createRoomName(id, news.name);
337
338 // 1. Observe — the id cached on `output` is a hint, not a guarantee:
339 // a missing room falls through to the name scan and then to create.
340 let observed = output?.waitingRoomId
341 ? yield* getRoom(zoneId, output.waitingRoomId)
342 : undefined;
343 if (!observed) {
344 observed = yield* findByName(zoneId, name);
345 }
346
347 // 2. Ensure — create with the full desired body when missing.
348 if (!observed) {
349 const created = yield* waitingRooms.createWaitingRoom({
350 zoneId,
351 name,
352 ...desiredBody(news),
353 });
354 return toAttributes(created, zoneId);
355 }
356
357 // 3. Sync — the update API is a full-body PUT; diff observed cloud
358 // state against the desired body and skip the call on a no-op.
359 const desired = desiredBody(news);
360 if (!isDirty(observed, name, desired)) {
361 return toAttributes(observed, zoneId);
362 }
363 const updated = yield* waitingRooms.updateWaitingRoom({
364 zoneId,
365 waitingRoomId: observed.id as string,
366 name,
367 ...desired,
368 });
369 return toAttributes(updated, zoneId);
370 }),
371
372 delete: Effect.fn(function* ({ output }) {
373 yield* waitingRooms
374 .deleteWaitingRoom({
375 zoneId: output.zoneId,
376 waitingRoomId: output.waitingRoomId,
377 })
378 .pipe(
379 // Already gone (code 1001) — deletion is idempotent.
380 Effect.catchTags({
381 WaitingRoomNotFound: () => Effect.void,
382 // Zone deleted out-of-band — the room is gone with it.
383 InvalidRoute: () => Effect.void,
384 }),
385 );
386 }),
387
388 list: Effect.fn(function* () {
389 const { accountId } = yield* yield* CloudflareEnvironment;
390 // Waiting rooms live inside a zone with no account-wide enumeration
391 // API — fan out across every zone and list rooms per zone, then
392 // exhaustively paginate each.
393 const zones = yield* listAllZones(accountId);
394 const rows = yield* Effect.forEach(
395 zones,
396 (zone) =>
397 waitingRooms.listWaitingRoomsForZone.pages({ zoneId: zone.id }).pipe(
398 Stream.runCollect,
399 Effect.map((chunk) =>
400 Array.from(chunk).flatMap((page) =>
401 (page.result ?? []).map((room) => toAttributes(room, zone.id)),
402 ),
403 ),
404 // Plan-gated / partial-permission zones reject the route, and a
405 // zone deleted out-of-band has no rooms; skip both.
406 Effect.catchTags({
407 Forbidden: () => Effect.succeed([] as Attributes[]),
408 InvalidRoute: () => Effect.succeed([] as Attributes[]),
409 }),
410 ),
411 { concurrency: 10 },
412 );
413 return rows.flat();
414 }),
415 });
416
417 type ObservedRoom = waitingRooms.GetWaitingRoomResponse;
418
419 /**
420 * Read a waiting room by id, mapping "gone" (`WaitingRoomNotFound`,
421 * Cloudflare code 1001) and a deleted zone (`InvalidRoute`, code 7003) to
422 * `undefined`.
423 */
424 const getRoom = (zoneId: string, waitingRoomId: string) =>
425 waitingRooms.getWaitingRoom({ zoneId, waitingRoomId }).pipe(
426 Effect.map((room): ObservedRoom | undefined => room),
427 Effect.catchTags({
428 WaitingRoomNotFound: () => Effect.undefined,
429 InvalidRoute: () => Effect.undefined,
430 }),
431 );
432
433 /**
434 * Find a waiting room by exact name. Names are unique per zone, so at most
435 * one room can match.
436 */
437 const findByName = (zoneId: string, name: string) =>
438 waitingRooms.listWaitingRoomsForZone.items({ zoneId }).pipe(
439 Stream.runCollect,
440 Effect.map((chunk) =>
441 Array.from(chunk).find((room): room is ObservedRoom => room.name === name),
442 ),
443 // Zone deleted out-of-band — nothing to find.
444 Effect.catchTag("InvalidRoute", () => Effect.undefined),
445 );
446
447 /**
448 * Waiting room names only allow alphanumerics, hyphens, and underscores.
449 */
450 const createRoomName = (id: string, name: string | undefined) =>
451 Effect.gen(function* () {
452 return name ?? (yield* createPhysicalName({ id, lowercase: true }));
453 });
454
455 /**
456 * The full desired body sent on create and PUT update. Optional props are
457 * omitted when unspecified so Cloudflare applies (or resets to) its
458 * defaults — sending Advanced-only fields explicitly would fail on
459 * non-Advanced plans.
460 */
461 const desiredBody = (news: Props) => ({
462 host: news.host,
463 totalActiveUsers: news.totalActiveUsers,
464 newUsersPerMinute: news.newUsersPerMinute,
465 path: news.path,
466 description: news.description,
467 sessionDuration: news.sessionDuration,
468 disableSessionRenewal: news.disableSessionRenewal,
469 queueAll: news.queueAll,
470 queueingMethod: news.queueingMethod,
471 queueingStatusCode: news.queueingStatusCode,
472 suspended: news.suspended,
473 jsonResponseEnabled: news.jsonResponseEnabled,
474 customPageHtml: news.customPageHtml,
475 defaultTemplateLanguage:
476 news.defaultTemplateLanguage as waitingRooms.UpdateWaitingRoomRequest["defaultTemplateLanguage"],
477 cookieSuffix: news.cookieSuffix,
478 cookieAttributes: news.cookieAttributes,
479 additionalRoutes: news.additionalRoutes,
480 enabledOriginCommands: news.enabledOriginCommands,
481 turnstileMode: news.turnstileMode,
482 turnstileAction: news.turnstileAction,
483 });
484
485 /**
486 * Cloudflare defaults for props with a documented default — used so that a
487 * prop the user removed from the program converges back to the default.
488 */
489 const DEFAULTS = {
490 path: "/",
491 description: "",
492 sessionDuration: 5,
493 disableSessionRenewal: false,
494 queueAll: false,
495 queueingMethod: "fifo",
496 queueingStatusCode: 200,
497 suspended: false,
498 jsonResponseEnabled: false,
499 defaultTemplateLanguage: "en-US",
500 turnstileMode: "off",
501 turnstileAction: "log",
502 } as const;
503
504 /**
505 * Compare the observed room against the desired body. Props with a known
506 * default compare against the default when unspecified (so removals
507 * converge); props without one (cookieSuffix, customPageHtml, Advanced
508 * structures) only count when explicitly specified.
509 */
510 const isDirty = (
511 observed: ObservedRoom,
512 name: string,
513 desired: ReturnType<typeof desiredBody>,
514 ): boolean => {
515 if ((observed.name ?? "") !== name) return true;
516 if ((observed.host ?? "") !== desired.host) return true;
517 if (observed.totalActiveUsers !== desired.totalActiveUsers) return true;
518 if (observed.newUsersPerMinute !== desired.newUsersPerMinute) return true;
519
520 const defaulted = <K extends keyof typeof DEFAULTS>(key: K, observedValue: unknown): boolean => {
521 const want = desired[key as keyof typeof desired] ?? DEFAULTS[key];
522 return (observedValue ?? DEFAULTS[key]) !== want;
523 };
524 if (defaulted("path", observed.path)) return true;
525 if (defaulted("description", observed.description)) return true;
526 if (defaulted("sessionDuration", observed.sessionDuration)) return true;
527 if (defaulted("disableSessionRenewal", observed.disableSessionRenewal)) {
528 return true;
529 }
530 if (defaulted("queueAll", observed.queueAll)) return true;
531 if (defaulted("queueingMethod", observed.queueingMethod)) return true;
532 if (defaulted("queueingStatusCode", observed.queueingStatusCode)) {
533 return true;
534 }
535 if (defaulted("suspended", observed.suspended)) return true;
536 if (defaulted("jsonResponseEnabled", observed.jsonResponseEnabled)) {
537 return true;
538 }
539 if (defaulted("defaultTemplateLanguage", observed.defaultTemplateLanguage)) {
540 return true;
541 }
542 if (defaulted("turnstileMode", observed.turnstileMode)) return true;
543 if (defaulted("turnstileAction", observed.turnstileAction)) return true;
544
545 // Only-when-specified props (no reliable server default to reset to).
546 if (
547 desired.cookieSuffix !== undefined &&
548 (observed.cookieSuffix ?? "") !== desired.cookieSuffix
549 ) {
550 return true;
551 }
552 if (
553 desired.customPageHtml !== undefined &&
554 (observed.customPageHtml ?? "") !== desired.customPageHtml
555 ) {
556 return true;
557 }
558 if (desired.cookieAttributes !== undefined) {
559 const o = observed.cookieAttributes ?? {};
560 if ((o.samesite ?? "auto") !== (desired.cookieAttributes.samesite ?? "auto")) {
561 return true;
562 }
563 if ((o.secure ?? "auto") !== (desired.cookieAttributes.secure ?? "auto")) {
564 return true;
565 }
566 }
567 if (desired.additionalRoutes !== undefined) {
568 const o = observed.additionalRoutes ?? [];
569 const d = desired.additionalRoutes;
570 if (
571 o.length !== d.length ||
572 o.some(
573 (route, i) =>
574 (route.host ?? "") !== (d[i]?.host ?? "") || (route.path ?? "/") !== (d[i]?.path ?? "/"),
575 )
576 ) {
577 return true;
578 }
579 }
580 if (desired.enabledOriginCommands !== undefined) {
581 const o = observed.enabledOriginCommands ?? [];
582 const d = desired.enabledOriginCommands;
583 if (o.length !== d.length || o.some((c, i) => c !== d[i])) return true;
584 }
585 return false;
586 };
587
588 const toAttributes = (
589 room:
590 | waitingRooms.GetWaitingRoomResponse
591 | waitingRooms.CreateWaitingRoomResponse
592 | waitingRooms.UpdateWaitingRoomResponse
593 | waitingRooms.ListWaitingRoomsResponse["result"][number],
594 zoneId: string,
595 ): Attributes => ({
596 // Cloudflare always echoes an id for a persisted room; distilled types it
597 // optional/nullable.
598 waitingRoomId: room.id ?? "",
599 zoneId,
600 name: room.name ?? "",
601 host: room.host ?? "",
602 path: room.path ?? "/",
603 totalActiveUsers: room.totalActiveUsers ?? 0,
604 newUsersPerMinute: room.newUsersPerMinute ?? 0,
605 description: room.description ?? "",
606 sessionDuration: room.sessionDuration ?? 5,
607 queueAll: room.queueAll ?? false,
608 queueingMethod: (room.queueingMethod ?? "fifo") as QueueingMethod,
609 queueingStatusCode: room.queueingStatusCode ?? 200,
610 suspended: room.suspended ?? false,
611 createdOn: room.createdOn ?? undefined,
612 modifiedOn: room.modifiedOn ?? undefined,
613 });