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

main
ts 377 lines 13.7 KB
Raw
1 import * as speed from "@distilled.cloud/cloudflare/speed";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Effect from "effect/Effect";
6 import * as Predicate from "effect/Predicate";
7 import * as Stream from "effect/Stream";
8 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
9 import type { Providers } from "../Providers.ts";
10 import { listAllZones } from "../Zone/lookup.ts";
11
12 const TypeId = "Cloudflare.Speed.TestSchedule" as const;
13 type TypeId = typeof TypeId;
14
15 /**
16 * Region a scheduled Observatory (speed) test runs from. GCP-style region
17 * identifiers — Cloudflare keys schedules per `(url, region)` pair.
18 */
19 export type TestRegion =
20 | "asia-east1"
21 | "asia-northeast1"
22 | "asia-northeast2"
23 | "asia-south1"
24 | "asia-southeast1"
25 | "australia-southeast1"
26 | "europe-north1"
27 | "europe-southwest1"
28 | "europe-west1"
29 | "europe-west2"
30 | "europe-west3"
31 | "europe-west4"
32 | "europe-west8"
33 | "europe-west9"
34 | "me-west1"
35 | "southamerica-east1"
36 | "us-central1"
37 | "us-east1"
38 | "us-east4"
39 | "us-south1"
40 | "us-west1";
41
42 /**
43 * How often a scheduled test runs.
44 */
45 export type TestFrequency = "DAILY" | "WEEKLY";
46
47 export interface TestScheduleProps {
48 /**
49 * Zone the scheduled test belongs to.
50 *
51 * Immutable — moving a schedule to a different zone triggers a
52 * replacement.
53 */
54 zoneId: string;
55 /**
56 * The page URL to test, e.g. `example.com/` or `example.com/pricing`.
57 * Must be a page on the zone. Cloudflare normalizes a bare hostname to
58 * `host/` (trailing slash).
59 *
60 * Immutable — the URL is the schedule's identity (path parameter), so
61 * changing it triggers a replacement. Deliberately a plain `string` (not
62 * `string`) so it is statically knowable inside `diff`.
63 */
64 url: string;
65 /**
66 * Region the test runs from. Schedules are keyed per `(url, region)` —
67 * changing the region triggers a replacement (a new schedule in the new
68 * region is created and the old one deleted).
69 * @default "us-central1"
70 */
71 region?: TestRegion;
72 /**
73 * How often the test runs. The API has no update call, so changing the
74 * frequency is converged in place by deleting and re-creating the
75 * schedule (same identity — not a replacement).
76 * @default WEEKLY for free plans, DAILY for paid plans (API default)
77 */
78 frequency?: TestFrequency;
79 }
80
81 export interface TestScheduleAttributes {
82 /** Zone the schedule belongs to. */
83 zoneId: string;
84 /** The tested page URL as normalized by Cloudflare (e.g. `example.com/`). */
85 url: string;
86 /** Region the test runs from. */
87 region: TestRegion;
88 /** How often the test runs. */
89 frequency: TestFrequency;
90 }
91
92 export type TestSchedule = Resource<
93 TypeId,
94 TestScheduleProps,
95 TestScheduleAttributes,
96 never,
97 Providers
98 >;
99
100 /**
101 * A recurring Cloudflare Observatory (Speed) test schedule — Cloudflare runs
102 * a Lighthouse test against a page on your zone on a `DAILY` or `WEEKLY`
103 * cadence from a region of your choice.
104 *
105 * A schedule's identity is the `(zoneId, url, region)` triple: the API keys
106 * schedules per URL and region, rejects duplicates, and has no update call.
107 * Changing `url`, `region`, or `zoneId` therefore replaces the schedule,
108 * while a `frequency` change is converged in place (delete + re-create under
109 * the same identity). Creating a schedule implicitly enqueues an initial
110 * test run.
111 *
112 * Plan quota applies: the number of allowed schedules per zone depends on
113 * the zone's plan (e.g. 5 on Free/Pro) — see the Observatory availabilities
114 * endpoint for the zone's remaining quota.
115 *
116 * Safety: schedules carry no ownership markers. When there is no prior
117 * state, `read` reports an existing schedule for the same `(url, region)` as
118 * `Unowned`, so the engine refuses to take it over unless `--adopt` (or
119 * `adopt(true)`) is set.
120 * ### Scheduling a test
121 * **Example:** Weekly test of the home page
122 * ```typescript
123 * yield* Cloudflare.Speed.TestSchedule("HomePageSpeed", {
124 * zoneId: zone.zoneId,
125 * url: "example.com/",
126 * frequency: "WEEKLY",
127 * });
128 * ```
129 *
130 * **Example:** Daily test of a specific page from Europe
131 * ```typescript
132 * yield* Cloudflare.Speed.TestSchedule("PricingSpeedEU", {
133 * zoneId: zone.zoneId,
134 * url: "example.com/pricing",
135 * region: "europe-west2",
136 * frequency: "DAILY",
137 * });
138 * ```
139 *
140 * @see https://developers.cloudflare.com/speed/speed-test/
141 *
142 * @resource
143 * @product Speed
144 * @category Performance & Reliability
145 */
146 export const TestSchedule = Resource<TestSchedule>(TypeId);
147
148 /**
149 * Returns true if the given value is a TestSchedule resource.
150 */
151 export const isTestSchedule = (value: unknown): value is TestSchedule =>
152 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
153
154 const DEFAULT_REGION: TestRegion = "us-central1";
155
156 /**
157 * Cloudflare normalizes schedule URLs: the scheme is dropped and a bare
158 * hostname gains a trailing slash (`example.com` -> `example.com/`). Apply
159 * the same normalization locally so `diff` doesn't flag a replacement for a
160 * cosmetic respelling of the same page.
161 */
162 const normalizeUrl = (url: string): string => {
163 const stripped = url.replace(/^https?:\/\//, "");
164 return stripped.includes("/") ? stripped : `${stripped}/`;
165 };
166
167 export const TestScheduleProvider = () =>
168 Provider.succeed(TestSchedule, {
169 stables: ["zoneId", "url", "region"],
170
171 list: Effect.fn(function* () {
172 const { accountId } = yield* yield* CloudflareEnvironment;
173 // Schedules live inside a zone and are keyed per `(url, region)` —
174 // there is no account-wide enumeration API. Fan out over every zone,
175 // enumerate the zone's Observatory pages, and resolve each page's
176 // schedule with the exact `(url, region)` keying `read` uses.
177 const zones = yield* listAllZones(accountId);
178 const rows = yield* Effect.forEach(
179 zones,
180 (zone) =>
181 speed.listPages.pages({ zoneId: zone.id }).pipe(
182 Stream.runCollect,
183 Effect.map((chunk) =>
184 Array.from(chunk).flatMap((page) =>
185 (page.result ?? []).flatMap((p) =>
186 p.url
187 ? [
188 {
189 url: p.url,
190 region: (p.region?.value as TestRegion | undefined) ?? DEFAULT_REGION,
191 },
192 ]
193 : [],
194 ),
195 ),
196 ),
197 Effect.flatMap((pages) =>
198 Effect.forEach(
199 pages,
200 ({ url, region }) =>
201 getSchedule(zone.id, url, region).pipe(
202 Effect.map((observed) =>
203 observed ? toAttributes(observed, zone.id, url, region) : undefined,
204 ),
205 // Plan-gated zone rejects the schedule route; skip it.
206 Effect.catchTag("Forbidden", () => Effect.undefined),
207 ),
208 { concurrency: 10 },
209 ),
210 ),
211 Effect.map((items) =>
212 items.filter((item): item is TestScheduleAttributes => item !== undefined),
213 ),
214 // Plan-gated / partial zones reject the pages route; skip them.
215 Effect.catchTag("InvalidRoute", () => Effect.succeed([])),
216 ),
217 { concurrency: 10 },
218 );
219 return rows.flat();
220 }),
221
222 diff: Effect.fn(function* ({ olds, news }) {
223 const o = olds as TestScheduleProps | undefined;
224 const n = news as TestScheduleProps;
225 // No prior props to compare against — let the engine decide.
226 if (o?.url === undefined) return undefined;
227 // The URL is the schedule's path identity.
228 if (normalizeUrl(o.url) !== normalizeUrl(n.url)) {
229 return { action: "replace" } as const;
230 }
231 // Schedules are keyed per region — a region change is a new schedule.
232 if ((o.region ?? DEFAULT_REGION) !== (n.region ?? DEFAULT_REGION)) {
233 return { action: "replace" } as const;
234 }
235 // zoneId is Input<string>; compare only once both are concrete.
236 if (typeof o.zoneId === "string" && typeof n.zoneId === "string" && o.zoneId !== n.zoneId) {
237 return { action: "replace" } as const;
238 }
239 // frequency converges in place (reconcile deletes + re-creates).
240 return undefined;
241 }),
242
243 read: Effect.fn(function* ({ output, olds }) {
244 const zoneId = output?.zoneId ?? (olds?.zoneId as string | undefined);
245 const url = output?.url ?? olds?.url;
246 const region = output?.region ?? (olds?.region as TestRegion) ?? DEFAULT_REGION;
247 if (!zoneId || !url) return undefined;
248
249 const observed = yield* getSchedule(zoneId, url, region);
250 if (!observed) return undefined;
251
252 const attrs = toAttributes(observed, zoneId, url, region);
253 // Owned path: we have persisted state for this schedule.
254 if (output) return attrs;
255 // Adoption path: a schedule for this `(url, region)` already exists
256 // but schedules carry no ownership markers, so we cannot prove we
257 // created it — brand it `Unowned` so the engine refuses to take over
258 // unless `adopt` is set.
259 return Unowned(attrs);
260 }),
261
262 reconcile: Effect.fn(function* ({ news }) {
263 // Inputs have been resolved to concrete strings by Plan.
264 const zoneId = news.zoneId as string;
265 const region = news.region ?? DEFAULT_REGION;
266
267 // 1. Observe — cloud state is authoritative. `output` is only a cache
268 // of the stable identity, which `news` fully determines anyway.
269 let observed = yield* getSchedule(zoneId, news.url, region);
270
271 // 2. Ensure — create when missing. A concurrent create surfaces as
272 // `TestScheduleAlreadyExists`: converge by re-reading the schedule
273 // that won the race.
274 if (!observed) {
275 observed = yield* createAndObserve(zoneId, news.url, region, news.frequency);
276 }
277
278 // 3. Sync — the only mutable aspect is `frequency`, and the API has
279 // no update call: converge drift by deleting and re-creating the
280 // schedule under the same identity. Skip entirely on a no-op (or
281 // when the user left frequency to the API default).
282 if (news.frequency !== undefined && observed.frequency !== news.frequency) {
283 const previous = observed;
284 yield* speed
285 .deleteSchedule({ zoneId, url: news.url, region })
286 .pipe(Effect.catchTag("TestScheduleNotFound", () => Effect.void));
287 observed = yield* createAndObserve(zoneId, news.url, region, news.frequency).pipe(
288 // Cloudflare caps DAILY-schedule creations per URL per day. We
289 // already deleted the old schedule — restore it so a quota
290 // rejection degrades to "unchanged" rather than "lost", then
291 // surface the typed error.
292 Effect.catchTag("TestScheduleQuotaReached", (error) =>
293 createAndObserve(
294 zoneId,
295 news.url,
296 region,
297 (previous.frequency ?? undefined) as TestFrequency | undefined,
298 ).pipe(Effect.flatMap(() => Effect.fail(error))),
299 ),
300 );
301 }
302
303 return toAttributes(observed, zoneId, news.url, region);
304 }),
305
306 delete: Effect.fn(function* ({ output }) {
307 // The API is idempotent server-side (DELETE on a missing schedule
308 // still answers 200), but tolerate the typed not-found anyway.
309 yield* speed
310 .deleteSchedule({
311 zoneId: output.zoneId,
312 url: output.url,
313 region: output.region,
314 })
315 .pipe(Effect.catchTag("TestScheduleNotFound", () => Effect.void));
316 }),
317 });
318
319 /** The observed shape shared by get and create responses. */
320 interface ObservedSchedule {
321 url?: string | null;
322 region?: string | null;
323 frequency?: string | null;
324 }
325
326 /**
327 * Read a schedule, mapping "gone" (`TestScheduleNotFound`, Cloudflare
328 * `speed.errors.schedule_not_found`) to `undefined`.
329 */
330 const getSchedule = (zoneId: string, url: string, region: TestRegion) =>
331 speed.getSchedule({ zoneId, url, region }).pipe(
332 Effect.map((s): ObservedSchedule | undefined => s),
333 Effect.catchTag("TestScheduleNotFound", () => Effect.undefined),
334 );
335
336 /**
337 * Create a schedule and return the observed result. A concurrent create
338 * surfaces as `TestScheduleAlreadyExists` — converge by re-reading the
339 * schedule that won the race (and fail with the original error if it
340 * vanished again in between).
341 */
342 const createAndObserve = (
343 zoneId: string,
344 url: string,
345 region: TestRegion,
346 frequency: TestFrequency | undefined,
347 ) =>
348 speed.createSchedule({ zoneId, url, region, frequency }).pipe(
349 Effect.flatMap((created) =>
350 created.schedule
351 ? Effect.succeed(created.schedule as ObservedSchedule)
352 : // The create succeeded but echoed no schedule — re-observe.
353 getScheduleOrFail(zoneId, url, region),
354 ),
355 Effect.catchTag("TestScheduleAlreadyExists", () => getScheduleOrFail(zoneId, url, region)),
356 );
357
358 const getScheduleOrFail = (zoneId: string, url: string, region: TestRegion) =>
359 // Let the typed `TestScheduleNotFound` propagate — reaching this state
360 // means the schedule vanished between our calls; surfacing the typed
361 // error is more honest than inventing one.
362 speed.getSchedule({ zoneId, url, region }).pipe(Effect.map((s): ObservedSchedule => s));
363
364 const toAttributes = (
365 observed: ObservedSchedule,
366 zoneId: string,
367 url: string,
368 region: TestRegion,
369 ): TestScheduleAttributes => ({
370 zoneId,
371 // Prefer the server-normalized URL (e.g. trailing slash added).
372 url: observed.url ?? normalizeUrl(url),
373 region: (observed.region ?? region) as TestRegion,
374 // Cloudflare always echoes a frequency for a persisted schedule; the
375 // distilled type is open/nullable, so default defensively.
376 frequency: (observed.frequency ?? "WEEKLY") as TestFrequency,
377 });