@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 246 lines 9.53 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.Reserve" as const;
12 type TypeId = typeof TypeId;
13
14 export interface ReserveProps {
15 /**
16 * Zone whose Cache Reserve setting is managed. Stable — changing the
17 * zone triggers a replacement (the old zone's setting is restored to
18 * the value it had before Alchemy managed it).
19 */
20 zoneId: string;
21 /**
22 * Whether Cache Reserve is enabled on the zone (`value: "on"`) or
23 * disabled (`value: "off"`). Mutable — patched in place.
24 * @default true
25 */
26 enabled?: boolean;
27 /**
28 * When true, destroying the resource also clears any data already
29 * stored in Cache Reserve (after restoring the setting), waiting for
30 * the asynchronous clear operation to complete. Disabling Cache
31 * Reserve does NOT purge stored data by itself — storage continues to
32 * bill until it expires or is cleared.
33 * @default false
34 */
35 clearOnDelete?: boolean;
36 }
37
38 export interface ReserveAttributes {
39 /** Zone the setting belongs to. */
40 zoneId: string;
41 /** Resolved current value of the setting (`"on"` or `"off"`). */
42 value: string;
43 /**
44 * Whether the setting can be modified on the zone's current plan
45 * (`false` means the setting is plan-gated).
46 */
47 editable: boolean;
48 /** When the setting was last modified, if Cloudflare reports it. */
49 modifiedOn: string | undefined;
50 /**
51 * The value the setting had before Alchemy first patched it. Restored
52 * on destroy, so deleting the resource puts the zone back the way it
53 * was found.
54 */
55 initialValue: string;
56 }
57
58 export type Reserve = Resource<TypeId, ReserveProps, ReserveAttributes, never, Providers>;
59
60 /**
61 * The Cache Reserve setting of a Cloudflare zone
62 * (`/zones/{zone_id}/cache/cache_reserve`).
63 *
64 * Cache Reserve is a large, persistent data store backed by R2 that serves
65 * as the ultimate upper-tier cache, dramatically reducing origin egress for
66 * cacheable content. The setting is a zone **singleton** — it always exists
67 * on entitled zones (default `off`), so this resource never creates or
68 * deletes anything physical. Reconcile patches the setting when the
69 * observed value differs from the desired one; destroy restores the value
70 * the setting had before Alchemy first managed it (captured as
71 * `initialValue`).
72 *
73 * **Entitlement-gated**: Cache Reserve is a usage-billed add-on that must
74 * be purchased/enabled on the account. On zones without the subscription
75 * both reads and writes fail with the typed `SettingUnavailableForPlan`
76 * error ("this zone setting is not available for your plan type").
77 *
78 * Disabling Cache Reserve does not purge data already in reserve — set
79 * `clearOnDelete: true` to run the asynchronous Cache Reserve Clear
80 * operation on destroy (the provider polls until the clear completes).
81 *
82 * Only one `Reserve` resource per zone makes sense — two instances
83 * managing the same zone would fight over the singleton.
84 * ### Managing Cache Reserve
85 * **Example:** Enable Cache Reserve on a zone
86 * ```typescript
87 * const zone = yield* Cloudflare.Zone.Zone("Site", { name: "example.com" });
88 *
89 * yield* Cloudflare.Cache.Reserve("Reserve", {
90 * zoneId: zone.zoneId,
91 * });
92 * ```
93 *
94 * **Example:** Clear stored data when the resource is destroyed
95 * ```typescript
96 * yield* Cloudflare.Cache.Reserve("Reserve", {
97 * zoneId: zone.zoneId,
98 * clearOnDelete: true,
99 * });
100 * ```
101 *
102 * @see https://developers.cloudflare.com/cache/advanced-configuration/cache-reserve/
103 *
104 * @resource
105 * @product Cache
106 * @category Performance & Reliability
107 */
108 export const Reserve = Resource<Reserve>(TypeId, {
109 aliases: ["Cloudflare.Cache.CacheReserve"],
110 });
111
112 /**
113 * Returns true if the given value is a Reserve resource.
114 */
115 export const isReserve = (value: unknown): value is Reserve =>
116 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
117
118 const desiredValue = (props: ReserveProps): "on" | "off" =>
119 (props.enabled ?? true) ? "on" : "off";
120
121 export const ReserveProvider = () =>
122 Provider.succeed(Reserve, {
123 stables: ["zoneId", "initialValue"],
124
125 list: Effect.fn(function* () {
126 const { accountId } = yield* yield* CloudflareEnvironment;
127 // No account-wide API for this zone singleton — enumerate every
128 // zone in the account and read its setting. Cache Reserve is an
129 // entitlement-gated add-on, so non-subscribed zones reject the
130 // route (`SettingUnavailableForPlan`); skip those.
131 const allZones = yield* listAllZones(accountId);
132 const rows = yield* Effect.forEach(
133 allZones.map((zone) => zone.id),
134 (zoneId) =>
135 cache.getCacheReserve({ zoneId }).pipe(
136 Effect.map((observed) => toAttributes(zoneId, observed, observed.value)),
137 // Plan-gated zones (no Cache Reserve subscription) and
138 // partial/deleted zones reject the route; skip them.
139 Effect.catchTags({
140 SettingUnavailableForPlan: () => Effect.undefined,
141 InvalidRoute: () => Effect.undefined,
142 }),
143 ),
144 { concurrency: 10 },
145 );
146 return rows.filter((row): row is ReserveAttributes => row !== undefined);
147 }),
148
149 diff: Effect.fn(function* ({ olds = {}, news, output }) {
150 const o = olds as ReserveProps;
151 const n = news as ReserveProps;
152 // zoneId is Input<string>; compare only once both sides are concrete.
153 const oldZoneId = output?.zoneId ?? (typeof o.zoneId === "string" ? o.zoneId : undefined);
154 if (oldZoneId !== undefined && typeof n.zoneId === "string" && oldZoneId !== n.zoneId) {
155 return { action: "replace" } as const;
156 }
157 return undefined;
158 }),
159
160 read: Effect.fn(function* ({ output, olds }) {
161 const zoneId = output?.zoneId ?? (olds?.zoneId as string | undefined);
162 if (!zoneId) return undefined;
163 const observed = yield* cache.getCacheReserve({ zoneId }).pipe(
164 // Zone deleted out-of-band — the setting is gone with it.
165 Effect.catchTag("InvalidRoute", () => Effect.undefined),
166 );
167 if (observed === undefined) return undefined;
168 // The setting is a singleton that always exists with a Cloudflare
169 // default — there is nothing to "own", so a cold read adopts
170 // freely (never `Unowned`). The observed value at adoption time
171 // becomes the `initialValue` restored on destroy.
172 const initialValue = output !== undefined ? output.initialValue : observed.value;
173 return toAttributes(zoneId, observed, initialValue);
174 }),
175
176 reconcile: Effect.fn(function* ({ news, output }) {
177 // Inputs have been resolved to concrete strings by Plan.
178 const zoneId = news.zoneId as string;
179
180 // 1. Observe — the setting always exists (on entitled zones); read
181 // its live value. Entitlement-gated zones fail here with the
182 // typed `SettingUnavailableForPlan` error.
183 const observed = yield* cache.getCacheReserve({ zoneId });
184
185 // 2. Capture — the pre-management value, restored on destroy.
186 // `output` (including an adoption read) already carries it;
187 // otherwise this is our first touch and the observed value is
188 // the zone's original.
189 const initialValue = output !== undefined ? output.initialValue : observed.value;
190
191 // 3. Sync — patch only when the observed value differs.
192 const desired = desiredValue(news);
193 if (observed.value === desired) {
194 return toAttributes(zoneId, observed, initialValue);
195 }
196 const patched = yield* cache.patchCacheReserve({
197 zoneId,
198 value: desired,
199 });
200 return toAttributes(zoneId, patched, initialValue);
201 }),
202
203 delete: Effect.fn(function* ({ output, olds }) {
204 const { zoneId, initialValue } = output;
205 // Observe — if the zone itself is gone (or the entitlement was
206 // dropped so the setting no longer exists), nothing to restore.
207 const observed = yield* cache.getCacheReserve({ zoneId }).pipe(
208 Effect.catchTags({
209 InvalidRoute: () => Effect.undefined,
210 SettingUnavailableForPlan: () => Effect.undefined,
211 }),
212 );
213 if (observed === undefined) return;
214 // Restore the pre-management value; skip the call when it already
215 // matches (idempotent re-delete after a crashed run).
216 if (observed.value !== initialValue) {
217 yield* cache
218 .patchCacheReserve({ zoneId, value: initialValue })
219 .pipe(Effect.catchTag("InvalidRoute", () => Effect.void));
220 }
221 // Optionally clear data already stored in reserve — an async
222 // operation that we kick off and poll to completion (bounded).
223 if (olds?.clearOnDelete === true) {
224 yield* cache.clearCacheReserve({ zoneId });
225 yield* cache.statusCacheReserve({ zoneId }).pipe(
226 Effect.repeat({
227 schedule: Schedule.spaced("5 seconds"),
228 until: (status) => status.state === "Completed",
229 times: 60,
230 }),
231 );
232 }
233 }),
234 });
235
236 const toAttributes = (
237 zoneId: string,
238 setting: cache.GetCacheReserveResponse | cache.PatchCacheReserveResponse,
239 initialValue: string,
240 ): ReserveAttributes => ({
241 zoneId,
242 value: setting.value,
243 editable: setting.editable,
244 modifiedOn: setting.modifiedOn ?? undefined,
245 initialValue,
246 });