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

main
ts 222 lines 8.58 KB
Raw
1 import * as waitingRooms from "@distilled.cloud/cloudflare/waiting-rooms";
2 import * as Provider from "alchemy/Provider";
3 import { Resource } from "alchemy/Resource";
4 import * as Effect from "effect/Effect";
5 import * as Predicate from "effect/Predicate";
6 import * as Schedule from "effect/Schedule";
7 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
8 import type { Providers } from "../Providers.ts";
9 import { listAllZones } from "../Zone/lookup.ts";
10
11 const TypeId = "Cloudflare.WaitingRoom.Settings" as const;
12 type TypeId = typeof TypeId;
13
14 export type SettingsProps = {
15 /**
16 * Zone whose waiting room settings are managed. Stable — changing the
17 * zone triggers a replacement (the old zone's settings are restored to
18 * the value they had before Alchemy managed them).
19 */
20 zoneId: string;
21 /**
22 * Whether to allow verified search engine crawlers to bypass all waiting
23 * rooms on this zone. Enabling the bypass requires the Waiting Room
24 * Advanced subscription. Mutable.
25 * @default false
26 */
27 searchEngineCrawlerBypass?: boolean;
28 };
29
30 export type SettingsAttributes = {
31 /** Zone the settings belong to. */
32 zoneId: string;
33 /** Whether verified search engine crawlers bypass all waiting rooms. */
34 searchEngineCrawlerBypass: boolean;
35 /**
36 * The value the setting had before Alchemy first managed it. Restored on
37 * destroy, so deleting the resource puts the zone back the way it was
38 * found.
39 */
40 initialSearchEngineCrawlerBypass: boolean;
41 };
42
43 export type Settings = Resource<TypeId, SettingsProps, SettingsAttributes, never, Providers>;
44
45 /**
46 * Zone-wide Cloudflare Waiting Room settings
47 * (`/zones/{zone_id}/waiting_rooms/settings`).
48 *
49 * The settings object is a zone singleton — it always exists with
50 * Cloudflare defaults, so this resource never creates or deletes anything
51 * physical. Reconcile PUTs the settings when the observed value differs
52 * from the desired one; destroy restores the value the zone had before
53 * Alchemy first managed it.
54 *
55 * Writes are plan-gated: on zones without a Waiting Rooms entitlement
56 * (Business/Enterprise) every PUT fails with the typed `ZoneNotEntitled`
57 * error (Cloudflare code 1034). Reads work on every plan, and a no-op
58 * reconcile (desired equals observed) skips the API call entirely.
59 * ### Managing settings
60 * **Example:** Let search engine crawlers bypass waiting rooms
61 * ```typescript
62 * yield* Cloudflare.WaitingRoom.Settings("CrawlerBypass", {
63 * zoneId: zone.zoneId,
64 * searchEngineCrawlerBypass: true,
65 * });
66 * ```
67 *
68 * **Example:** Pin the settings to their defaults
69 * ```typescript
70 * yield* Cloudflare.WaitingRoom.Settings("Defaults", {
71 * zoneId: zone.zoneId,
72 * searchEngineCrawlerBypass: false,
73 * });
74 * ```
75 *
76 * @see https://developers.cloudflare.com/waiting-room/
77 *
78 * @resource
79 * @product Waiting Rooms
80 * @category Performance & Reliability
81 */
82 export const Settings = Resource<Settings>(TypeId);
83
84 /**
85 * Returns true if the given value is a Settings resource.
86 */
87 export const isSettings = (value: unknown): value is Settings =>
88 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
89
90 export const SettingsProvider = () =>
91 Provider.succeed(Settings, {
92 nuke: { singleton: true },
93 stables: ["zoneId", "initialSearchEngineCrawlerBypass"],
94
95 list: Effect.fn(function* () {
96 const { accountId } = yield* yield* CloudflareEnvironment;
97 // No account-wide API for this zone singleton — enumerate every
98 // zone in the account and read its settings (every zone has one).
99 const allZones = yield* listAllZones(accountId);
100 const rows = yield* Effect.forEach(
101 allZones.map((zone) => zone.id),
102 (zoneId) =>
103 waitingRooms.getSetting({ zoneId }).pipe(
104 // A freshly-minted scoped token propagates eventually-
105 // consistently across Cloudflare's edge — ride out transient
106 // 403 blips before giving up on a zone. The backoff is CAPPED at
107 // 5s and bounded to ~8 attempts (~40s): an uncapped
108 // `Schedule.exponential` reaches a 64s single delay by the 8th
109 // retry (~128s total) which, fanned across every zone, blows the
110 // test timeout when a zone is persistently 403.
111 Effect.retry({
112 while: (e) => e._tag === "Forbidden",
113 schedule: Schedule.max([
114 Schedule.min([Schedule.exponential("500 millis"), Schedule.spaced("5 seconds")]),
115 Schedule.recurs(8),
116 ]),
117 }),
118 Effect.map((observed) =>
119 toAttributes(
120 zoneId,
121 observed.searchEngineCrawlerBypass,
122 observed.searchEngineCrawlerBypass,
123 ),
124 ),
125 // Plan-gated or partial zones reject the route; a zone the token
126 // still can't read (persistent 403) isn't ours to enumerate —
127 // skip both rather than failing the whole listing.
128 Effect.catchTags({
129 InvalidRoute: () => Effect.undefined,
130 Forbidden: () => Effect.undefined,
131 }),
132 ),
133 { concurrency: 10 },
134 );
135 return rows.filter((row): row is SettingsAttributes => row !== undefined);
136 }),
137
138 diff: Effect.fn(function* ({ olds = {}, news, output }) {
139 const o = olds as SettingsProps;
140 const n = news as SettingsProps;
141 // zoneId is Input<string>; compare only once both sides are concrete.
142 const oldZoneId = output?.zoneId ?? (typeof o.zoneId === "string" ? o.zoneId : undefined);
143 if (oldZoneId !== undefined && typeof n.zoneId === "string" && oldZoneId !== n.zoneId) {
144 return { action: "replace" } as const;
145 }
146 return undefined;
147 }),
148
149 read: Effect.fn(function* ({ output, olds }) {
150 const zoneId = output?.zoneId ?? (olds?.zoneId as string | undefined);
151 if (!zoneId) return undefined;
152 const observed = yield* waitingRooms.getSetting({ zoneId }).pipe(
153 // Zone deleted out-of-band — the settings are gone with it.
154 Effect.catchTag("InvalidRoute", () => Effect.undefined),
155 );
156 if (observed === undefined) return undefined;
157 // The settings singleton always exists with a Cloudflare default —
158 // there is nothing to "own", so a cold read adopts freely. The
159 // observed value at adoption time becomes the initial value restored
160 // on destroy.
161 const initial =
162 output !== undefined
163 ? output.initialSearchEngineCrawlerBypass
164 : observed.searchEngineCrawlerBypass;
165 return toAttributes(zoneId, observed.searchEngineCrawlerBypass, initial);
166 }),
167
168 reconcile: Effect.fn(function* ({ news, output }) {
169 // Inputs have been resolved to concrete strings by Plan.
170 const zoneId = news.zoneId as string;
171
172 // 1. Observe — the settings singleton always exists.
173 const observed = yield* waitingRooms.getSetting({ zoneId });
174
175 // 2. Capture — the pre-management value, restored on destroy.
176 const initial =
177 output !== undefined
178 ? output.initialSearchEngineCrawlerBypass
179 : observed.searchEngineCrawlerBypass;
180
181 // 3. Sync — PUT only when the observed value differs.
182 const desired = news.searchEngineCrawlerBypass ?? false;
183 if (observed.searchEngineCrawlerBypass === desired) {
184 return toAttributes(zoneId, observed.searchEngineCrawlerBypass, initial);
185 }
186 const updated = yield* waitingRooms.putSetting({
187 zoneId,
188 searchEngineCrawlerBypass: desired,
189 });
190 return toAttributes(zoneId, updated.searchEngineCrawlerBypass, initial);
191 }),
192
193 delete: Effect.fn(function* ({ output }) {
194 const { zoneId, initialSearchEngineCrawlerBypass } = output;
195 // Observe — if the zone itself is gone, so are the settings.
196 const observed = yield* waitingRooms
197 .getSetting({ zoneId })
198 .pipe(Effect.catchTag("InvalidRoute", () => Effect.undefined));
199 if (observed === undefined) return;
200 // Restore the pre-management value; skip the call when it already
201 // matches (idempotent re-delete after a crashed run).
202 if (observed.searchEngineCrawlerBypass === initialSearchEngineCrawlerBypass) {
203 return;
204 }
205 yield* waitingRooms
206 .putSetting({
207 zoneId,
208 searchEngineCrawlerBypass: initialSearchEngineCrawlerBypass,
209 })
210 .pipe(Effect.catchTag("InvalidRoute", () => Effect.void));
211 }),
212 });
213
214 const toAttributes = (
215 zoneId: string,
216 searchEngineCrawlerBypass: boolean,
217 initialSearchEngineCrawlerBypass: boolean,
218 ): SettingsAttributes => ({
219 zoneId,
220 searchEngineCrawlerBypass,
221 initialSearchEngineCrawlerBypass,
222 });