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

main
ts 84 lines 3.46 KB
Raw
1 import * as Cloudflare from "@alchemy.run/cloudflare";
2 import { describe, expect } from "@alchemy.run/test";
3 import * as Test from "@alchemy.run/test/Alchemy";
4 import * as Effect from "effect/Effect";
5 import * as HttpClient from "effect/http/HttpClient";
6 import { MinimumLogLevel } from "effect/References";
7 import * as Schedule from "effect/Schedule";
8 import Stack from "./fixtures/stack.ts";
9
10 const { test, beforeAll, afterAll, deploy, destroy } = Test.make({
11 providers: Cloudflare.providers(),
12 });
13
14 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
15
16 const stack = beforeAll(deploy(Stack));
17 afterAll.skipIf(!!process.env.NO_DESTROY)(destroy(Stack));
18
19 // The worker calls `rateLimit.limit({ key })` `n` times inside a single
20 // request and returns the per-call `success` flags. Hitting the binding from
21 // one isolate makes the throttling deterministic and avoids relying on edge
22 // propagation between separate HTTP requests.
23 const burst = Effect.fn(function* (url: string, key: string, n: number) {
24 const client = yield* HttpClient.HttpClient;
25 const res = yield* client.get(`${url}/burst?key=${encodeURIComponent(key)}&n=${n}`).pipe(
26 Effect.flatMap((res) =>
27 res.status === 200
28 ? Effect.succeed(res)
29 : Effect.fail(new Error(`Worker not ready: ${res.status}`)),
30 ),
31 Effect.retry({ schedule: Schedule.exponential("500 millis"), times: 15 }),
32 );
33 return (yield* res.json) as { key: string; results: boolean[] };
34 });
35
36 const freshKey = () => `fresh-${Math.random().toString(36).slice(2)}`;
37
38 // Both worker styles bind the same RateLimit shape (`limit: 2`, `period: 10`)
39 // and expose the identical `/burst` contract, so they share one behavioral
40 // suite parameterized by which deployed URL to hit.
41 const behaviorSuite = (label: string, getUrl: () => Effect.Effect<string>) =>
42 describe(label, { tags: ["provider:cloudflare", "provider:cloudflare:worker", "live"] }, () => {
43 test(
44 "throttles requests past the configured limit",
45 Effect.gen(function* () {
46 const url = yield* getUrl();
47 expect(url).toBeTypeOf("string");
48
49 // Limit is 2 over a 10s window. Cloudflare's limiter is best-effort
50 // (per-colo, approximate counting), so we don't assert an exact
51 // allowed count — only the observable contract: the first call is
52 // allowed, the burst is eventually throttled, and once the budget is
53 // exhausted later calls stay denied.
54 const n = 10;
55 const { results } = yield* burst(url, freshKey(), n);
56
57 expect(results).toHaveLength(n);
58 expect(results[0]).toBe(true);
59 expect(results.at(-1)).toBe(false);
60 // Some calls were allowed, some denied.
61 const allowed = results.filter(Boolean).length;
62 expect(allowed).toBeGreaterThan(0);
63 expect(allowed).toBeLessThan(n);
64 }).pipe(logLevel),
65 { timeout: 180_000 },
66 );
67
68 test(
69 "tracks each key independently",
70 Effect.gen(function* () {
71 const url = yield* getUrl();
72
73 // A distinct key gets its own fresh budget regardless of how much a
74 // previous key was throttled.
75 const fresh = yield* burst(url, freshKey(), 1);
76 expect(fresh.results).toEqual([true]);
77 }).pipe(logLevel),
78 { timeout: 180_000 },
79 );
80 });
81
82 behaviorSuite("async worker (env binding)", () => stack.pipe(Effect.map((s) => s.asyncUrl)));
83
84 behaviorSuite("effect worker (yield* RateLimit)", () => stack.pipe(Effect.map((s) => s.effectUrl)));