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

main
ts 219 lines 8.37 KB
Raw
1 import * as argo from "@distilled.cloud/cloudflare/argo";
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 { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
7 import type { Providers } from "../Providers.ts";
8 import { listAllZones } from "../Zone/lookup.ts";
9
10 const TypeId = "Cloudflare.Argo.TieredCaching" as const;
11 type TypeId = typeof TypeId;
12
13 export type TieredCachingProps = {
14 /**
15 * Zone the Tiered Caching setting belongs to. Stable — changing the
16 * zone triggers a replacement (the old zone's setting is restored to
17 * the value it had before Alchemy managed it).
18 */
19 zoneId: string;
20 /**
21 * Whether Tiered Caching is enabled on the zone. Mutable — patched in
22 * place.
23 *
24 * @default true
25 */
26 enabled?: boolean;
27 };
28
29 export type TieredCachingAttributes = {
30 /** Zone the Tiered Caching setting belongs to. */
31 zoneId: string;
32 /** Resolved current value of the setting (`"on"` or `"off"`). */
33 value: "on" | "off";
34 /**
35 * Whether the setting can be modified on the zone's current plan.
36 */
37 editable: boolean;
38 /** When the setting was last modified, if Cloudflare reports it. */
39 modifiedOn: string | undefined;
40 /**
41 * The value the setting had before Alchemy first patched it. Restored
42 * on destroy, so deleting the resource puts the zone back the way it
43 * was found.
44 */
45 initialValue: "on" | "off";
46 };
47
48 export type TieredCaching = Resource<
49 TypeId,
50 TieredCachingProps,
51 TieredCachingAttributes,
52 never,
53 Providers
54 >;
55
56 /**
57 * Tiered Caching for a Cloudflare zone
58 * (`/zones/{zone_id}/argo/tiered_caching`).
59 *
60 * Tiered Caching routes cache misses through upper-tier Cloudflare data
61 * centers instead of every edge location contacting the origin directly,
62 * reducing origin load and improving cache hit ratios. It is available on
63 * all plans, free included.
64 *
65 * The setting is a singleton — it always exists on every zone with a
66 * Cloudflare default, so this resource never creates or deletes anything
67 * physical. Reconcile patches the setting when the observed value differs
68 * from the desired one; destroy restores the value the setting had before
69 * Alchemy first managed it (captured as `initialValue`).
70 *
71 * This is the generic Tiered Cache toggle (the dashboard "Tiered Cache"
72 * switch). Smart Tiered Cache (the smart-topology variant managed under
73 * `/cache/tiered_cache_smart_topology_enable`) requires Tiered Caching to
74 * be enabled — deploy this resource first when combining the two.
75 * ### Enabling Tiered Caching
76 * **Example:** Enable Tiered Caching on a zone
77 * ```typescript
78 * const zone = yield* Cloudflare.Zone.Zone("Site", { name: "example.com" });
79 *
80 * yield* Cloudflare.Argo.TieredCaching("TieredCaching", {
81 * zoneId: zone.zoneId,
82 * });
83 * ```
84 *
85 * **Example:** Explicitly disable Tiered Caching
86 * ```typescript
87 * yield* Cloudflare.Argo.TieredCaching("TieredCaching", {
88 * zoneId: zone.zoneId,
89 * enabled: false,
90 * });
91 * ```
92 *
93 * @see https://developers.cloudflare.com/cache/how-to/tiered-cache/
94 *
95 * @resource
96 * @product Argo
97 * @category Performance & Reliability
98 */
99 export const TieredCaching = Resource<TieredCaching>(TypeId);
100
101 /**
102 * Returns true if the given value is a TieredCaching resource.
103 */
104 export const isTieredCaching = (value: unknown): value is TieredCaching =>
105 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
106
107 export const TieredCachingProvider = () =>
108 Provider.succeed(TieredCaching, {
109 nuke: { singleton: true },
110 stables: ["zoneId", "initialValue"],
111
112 list: Effect.fn(function* () {
113 const { accountId } = yield* yield* CloudflareEnvironment;
114 // No account-wide API for this zone singleton — enumerate every
115 // zone in the account and read its setting (every zone has one,
116 // tiered caching is available on all plans).
117 const allZones = yield* listAllZones(accountId);
118 const rows = yield* Effect.forEach(
119 allZones.map((zone) => zone.id),
120 (zoneId) =>
121 argo.getTieredCaching({ zoneId }).pipe(
122 Effect.map((observed) => toAttributes(zoneId, observed, toValue(observed.value))),
123 // Zone deleted out-of-band between enumeration and read —
124 // the setting is gone with it; skip it. A concurrently-purged
125 // zone surfaces as `ZoneNotFound` (404 "Invalid or missing
126 // zone") rather than the 7003 object-identifier code.
127 Effect.catchTag(["InvalidObjectIdentifier", "ZoneNotFound"], () => Effect.undefined),
128 ),
129 { concurrency: 10 },
130 );
131 return rows.filter((row): row is TieredCachingAttributes => row !== undefined);
132 }),
133
134 diff: Effect.fn(function* ({ olds = {}, news, output }) {
135 const o = olds as TieredCachingProps;
136 const n = news as TieredCachingProps;
137 // zoneId is Input<string>; compare only once both sides are concrete.
138 const oldZoneId = output?.zoneId ?? (typeof o.zoneId === "string" ? o.zoneId : undefined);
139 if (oldZoneId !== undefined && typeof n.zoneId === "string" && oldZoneId !== n.zoneId) {
140 return { action: "replace" } as const;
141 }
142 return undefined;
143 }),
144
145 read: Effect.fn(function* ({ output, olds }) {
146 const zoneId = output?.zoneId ?? (olds?.zoneId as string | undefined);
147 if (!zoneId) return undefined;
148 const observed = yield* argo.getTieredCaching({ zoneId }).pipe(
149 // Zone deleted out-of-band — the setting is gone with it.
150 Effect.catchTag("InvalidObjectIdentifier", () => Effect.undefined),
151 );
152 if (observed === undefined) return undefined;
153 // The setting is a singleton that always exists with a Cloudflare
154 // default — there is nothing to "own", so a cold read adopts freely
155 // (never `Unowned`). The observed value at adoption time becomes the
156 // `initialValue` restored on destroy.
157 const initialValue = output !== undefined ? output.initialValue : toValue(observed.value);
158 return toAttributes(zoneId, observed, initialValue);
159 }),
160
161 reconcile: Effect.fn(function* ({ news, output }) {
162 // Inputs have been resolved to concrete strings by Plan.
163 const zoneId = news.zoneId as string;
164 const desired: "on" | "off" = (news.enabled ?? true) ? "on" : "off";
165
166 // 1. Observe — the setting always exists; read its live value.
167 const observed = yield* argo.getTieredCaching({ zoneId });
168
169 // 2. Capture — the pre-management value, restored on destroy.
170 // `output` (including an adoption read) already carries it;
171 // otherwise this is our first touch and the observed value is
172 // the zone's original.
173 const initialValue = output !== undefined ? output.initialValue : toValue(observed.value);
174
175 // 3. Sync — patch only when the observed value differs.
176 if (toValue(observed.value) === desired) {
177 return toAttributes(zoneId, observed, initialValue);
178 }
179 const patched = yield* argo.patchTieredCaching({
180 zoneId,
181 value: desired,
182 });
183 return toAttributes(zoneId, patched, initialValue);
184 }),
185
186 delete: Effect.fn(function* ({ output }) {
187 const { zoneId, initialValue } = output;
188 // Observe — if the zone itself is gone, so is the setting.
189 const observed = yield* argo
190 .getTieredCaching({ zoneId })
191 .pipe(Effect.catchTag("InvalidObjectIdentifier", () => Effect.undefined));
192 if (observed === undefined) return;
193 // Restore the pre-management value; skip the call when it already
194 // matches (idempotent re-delete after a crashed run).
195 if (toValue(observed.value) === initialValue) return;
196 yield* argo
197 .patchTieredCaching({ zoneId, value: initialValue })
198 .pipe(Effect.catchTag("InvalidObjectIdentifier", () => Effect.void));
199 }),
200 });
201
202 /**
203 * Narrow the distilled response's open `"on" | "off" | (string & {})`
204 * value to the closed pair — Cloudflare only ever returns the two
205 * literals for this setting.
206 */
207 const toValue = (value: string): "on" | "off" => (value === "on" ? "on" : "off");
208
209 const toAttributes = (
210 zoneId: string,
211 setting: argo.GetTieredCachingResponse | argo.PatchTieredCachingResponse,
212 initialValue: "on" | "off",
213 ): TieredCachingAttributes => ({
214 zoneId,
215 value: toValue(setting.value),
216 editable: setting.editable,
217 modifiedOn: setting.modifiedOn ?? undefined,
218 initialValue,
219 });