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

main
ts 240 lines 9.62 KB
Raw
1 import * as cache from "@distilled.cloud/cloudflare/cache";
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.Cache.RegionalTieredCache" as const;
12 type TypeId = typeof TypeId;
13
14 export interface RegionalTieredCacheProps {
15 /**
16 * Zone whose Regional Tiered Cache setting is managed. Stable —
17 * changing the zone triggers a replacement (the old zone's setting is
18 * restored to the value it had before Alchemy managed it).
19 */
20 zoneId: string;
21 /**
22 * Whether Regional Tiered Cache is enabled on the zone (`value: "on"`)
23 * or disabled (`value: "off"`). Mutable — patched in place.
24 * @default true
25 */
26 enabled?: boolean;
27 }
28
29 export interface RegionalTieredCacheAttributes {
30 /** Zone the setting belongs to. */
31 zoneId: string;
32 /** Resolved current value of the setting (`"on"` or `"off"`). */
33 value: string;
34 /**
35 * Whether the setting can be modified on the zone's current plan
36 * (`false` means the setting is plan-gated).
37 */
38 editable: boolean;
39 /** When the setting was last modified, if Cloudflare reports it. */
40 modifiedOn: string | undefined;
41 /**
42 * The value the setting had before Alchemy first patched it. Restored
43 * on destroy, so deleting the resource puts the zone back the way it
44 * was found.
45 */
46 initialValue: string;
47 }
48
49 export type RegionalTieredCache = Resource<
50 TypeId,
51 RegionalTieredCacheProps,
52 RegionalTieredCacheAttributes,
53 never,
54 Providers
55 >;
56
57 /**
58 * The Regional Tiered Cache setting of a Cloudflare zone
59 * (`/zones/{zone_id}/cache/regional_tiered_cache`).
60 *
61 * Regional Tiered Cache adds a regional layer between Cloudflare's lower
62 * tiers and the upper-tier data center, so cache misses in a region only
63 * travel to the regional hub instead of crossing the globe. The setting is
64 * a zone **singleton** — it always exists on entitled zones (default
65 * `off`), so this resource never creates or deletes anything physical.
66 * Reconcile patches the setting when the observed value differs from the
67 * desired one; destroy restores the value the setting had before Alchemy
68 * first managed it (captured as `initialValue`).
69 *
70 * **Plan-gated**: Regional Tiered Cache requires an Enterprise zone. On
71 * lower plans both reads and writes fail with Cloudflare error code 1135
72 * ("this zone setting is not available for your plan type"), surfaced as
73 * the typed `SettingUnavailableForPlan` error.
74 *
75 * Only one `RegionalTieredCache` resource per zone makes sense — two
76 * instances managing the same zone would fight over the singleton.
77 * ### Managing Regional Tiered Cache
78 * **Example:** Enable Regional Tiered Cache on an Enterprise zone
79 * ```typescript
80 * const zone = yield* Cloudflare.Zone.Zone("Site", { name: "example.com" });
81 *
82 * yield* Cloudflare.Cache.RegionalTieredCache("RegionalCache", {
83 * zoneId: zone.zoneId,
84 * });
85 * ```
86 *
87 * **Example:** Explicitly disable Regional Tiered Cache
88 * ```typescript
89 * yield* Cloudflare.Cache.RegionalTieredCache("RegionalCache", {
90 * zoneId: zone.zoneId,
91 * enabled: false,
92 * });
93 * ```
94 *
95 * @see https://developers.cloudflare.com/cache/how-to/tiered-cache/#regional-tiered-cache
96 *
97 * @resource
98 * @product Cache
99 * @category Performance & Reliability
100 */
101 export const RegionalTieredCache = Resource<RegionalTieredCache>(TypeId);
102
103 /**
104 * Returns true if the given value is a RegionalTieredCache resource.
105 */
106 export const isRegionalTieredCache = (value: unknown): value is RegionalTieredCache =>
107 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
108
109 const desiredValue = (props: RegionalTieredCacheProps): "on" | "off" =>
110 (props.enabled ?? true) ? "on" : "off";
111
112 // Cloudflare can transiently fail to authenticate a valid token, surfacing as
113 // `Unauthorized`/`Forbidden`. Retry with exponential backoff capped at 5s,
114 // bounded to ~8 attempts so a persistently-failing call still fails fast.
115 const transientAuthRetrySchedule = Schedule.max([
116 Schedule.min([Schedule.exponential("500 millis"), Schedule.spaced("5 seconds")]),
117 Schedule.recurs(8),
118 ]);
119
120 export const RegionalTieredCacheProvider = () =>
121 Provider.succeed(RegionalTieredCache, {
122 stables: ["zoneId", "initialValue"],
123
124 list: Effect.fn(function* () {
125 const { accountId } = yield* yield* CloudflareEnvironment;
126 // No account-wide API for this zone singleton — enumerate every
127 // zone in the account and read its setting. Regional Tiered Cache
128 // is Enterprise-only, so non-entitled zones reject the route with
129 // the typed `SettingUnavailableForPlan` error and are skipped.
130 const allZones = yield* listAllZones(accountId);
131 const rows = yield* Effect.forEach(
132 allZones.map((zone) => zone.id),
133 (zoneId) =>
134 cache.getRegionalTieredCache({ zoneId }).pipe(
135 // Cloudflare intermittently rejects a *valid* token with
136 // `Unauthorized`/`Forbidden` (a transient edge auth failure).
137 // Retry with capped backoff rather than dropping the zone, so a
138 // genuinely accessible zone never falls out of the enumeration on
139 // a blip.
140 Effect.retry({
141 while: (e) => e._tag === "Unauthorized" || e._tag === "Forbidden",
142 schedule: transientAuthRetrySchedule,
143 }),
144 Effect.map((observed) => toAttributes(zoneId, observed, observed.value)),
145 // Zone deleted out-of-band or plan-gated: skip it.
146 Effect.catchTags({
147 InvalidRoute: () => Effect.undefined,
148 SettingUnavailableForPlan: () => Effect.undefined,
149 }),
150 ),
151 { concurrency: 10 },
152 );
153 return rows.filter((row): row is RegionalTieredCacheAttributes => row !== undefined);
154 }),
155
156 diff: Effect.fn(function* ({ olds = {}, news, output }) {
157 const o = olds as RegionalTieredCacheProps;
158 const n = news as RegionalTieredCacheProps;
159 // zoneId is Input<string>; compare only once both sides are concrete.
160 const oldZoneId = output?.zoneId ?? (typeof o.zoneId === "string" ? o.zoneId : undefined);
161 if (oldZoneId !== undefined && typeof n.zoneId === "string" && oldZoneId !== n.zoneId) {
162 return { action: "replace" } as const;
163 }
164 return undefined;
165 }),
166
167 read: Effect.fn(function* ({ output, olds }) {
168 const zoneId = output?.zoneId ?? (olds?.zoneId as string | undefined);
169 if (!zoneId) return undefined;
170 const observed = yield* cache.getRegionalTieredCache({ zoneId }).pipe(
171 // Zone deleted out-of-band — the setting is gone with it.
172 Effect.catchTag("InvalidRoute", () => Effect.undefined),
173 );
174 if (observed === undefined) return undefined;
175 // The setting is a singleton that always exists with a Cloudflare
176 // default — there is nothing to "own", so a cold read adopts
177 // freely (never `Unowned`). The observed value at adoption time
178 // becomes the `initialValue` restored on destroy.
179 const initialValue = output !== undefined ? output.initialValue : observed.value;
180 return toAttributes(zoneId, observed, initialValue);
181 }),
182
183 reconcile: Effect.fn(function* ({ news, output }) {
184 // Inputs have been resolved to concrete strings by Plan.
185 const zoneId = news.zoneId as string;
186
187 // 1. Observe — the setting always exists (on entitled zones); read
188 // its live value. Plan-gated zones fail here with the typed
189 // `SettingUnavailableForPlan` error.
190 const observed = yield* cache.getRegionalTieredCache({ zoneId });
191
192 // 2. Capture — the pre-management value, restored on destroy.
193 // `output` (including an adoption read) already carries it;
194 // otherwise this is our first touch and the observed value is
195 // the zone's original.
196 const initialValue = output !== undefined ? output.initialValue : observed.value;
197
198 // 3. Sync — patch only when the observed value differs.
199 const desired = desiredValue(news);
200 if (observed.value === desired) {
201 return toAttributes(zoneId, observed, initialValue);
202 }
203 const patched = yield* cache.patchRegionalTieredCache({
204 zoneId,
205 value: desired,
206 });
207 return toAttributes(zoneId, patched, initialValue);
208 }),
209
210 delete: Effect.fn(function* ({ output }) {
211 const { zoneId, initialValue } = output;
212 // Observe — if the zone itself is gone (or the plan was downgraded
213 // so the setting no longer exists for the zone), nothing to restore.
214 const observed = yield* cache.getRegionalTieredCache({ zoneId }).pipe(
215 Effect.catchTags({
216 InvalidRoute: () => Effect.undefined,
217 SettingUnavailableForPlan: () => Effect.undefined,
218 }),
219 );
220 if (observed === undefined) return;
221 // Restore the pre-management value; skip the call when it already
222 // matches (idempotent re-delete after a crashed run).
223 if (observed.value === initialValue) return;
224 yield* cache
225 .patchRegionalTieredCache({ zoneId, value: initialValue })
226 .pipe(Effect.catchTag("InvalidRoute", () => Effect.void));
227 }),
228 });
229
230 const toAttributes = (
231 zoneId: string,
232 setting: cache.GetRegionalTieredCacheResponse | cache.PatchRegionalTieredCacheResponse,
233 initialValue: string,
234 ): RegionalTieredCacheAttributes => ({
235 zoneId,
236 value: setting.value,
237 editable: setting.editable,
238 modifiedOn: setting.modifiedOn ?? undefined,
239 initialValue,
240 });