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

main
ts 135 lines 4.37 KB
Raw
1 import type * as cf from "@cloudflare/workers-types";
2 import type { RuntimeContext } from "alchemy/RuntimeContext";
3 import * as Data from "effect/Data";
4 import type * as Effect from "effect/Effect";
5 import * as Binding from "./Binding.ts";
6 import type { RateLimitBinding } from "./RateLimitBinding.ts";
7
8 const TypeId = "Cloudflare.RateLimit" as const;
9 type TypeId = typeof TypeId;
10
11 export type RateLimitPeriod = 10 | 60;
12
13 export class RateLimitError extends Data.TaggedError("RateLimitError")<{
14 message: string;
15 cause: unknown;
16 }> {}
17
18 /**
19 * Effect-native client for a Cloudflare Rate Limit binding. Wraps the runtime
20 * `cf.RateLimit` so `limit` returns an `Effect` tagged with {@link RateLimitError}.
21 */
22 export interface RateLimitClient {
23 /** Effect resolving to the raw Cloudflare runtime binding. */
24 raw: Effect.Effect<cf.RateLimit, never, RuntimeContext>;
25 limit(
26 options: Parameters<cf.RateLimit["limit"]>[0],
27 ): Effect.Effect<Awaited<ReturnType<cf.RateLimit["limit"]>>, RateLimitError, RuntimeContext>;
28 }
29
30 export type RateLimitProps = {
31 /**
32 * Positive integer or string that uniquely identifies this rate limit
33 * configuration.
34 */
35 namespaceId: number | string;
36 /** Simple rate limiting configuration. */
37 simple: {
38 /** The number of requests allowed within the period. */
39 limit: number;
40 /** The period, in seconds, over which requests are counted. */
41 period: RateLimitPeriod;
42 };
43 };
44
45 /**
46 * A Cloudflare Rate Limit binding for counting arbitrary keys inside Workers — a
47 * Worker-only binding with no backing cloud resource.
48 *
49 * `RateLimit` is a single value that is at once the `Binding.Service` tag, the
50 * callable that produces a {@link RateLimitBinding}, and the type. Declare it on
51 * a Worker's `env` (it flows through `InferEnv` → the native `cf.RateLimit`) or
52 * `yield*` it inside an Effect-native Worker to attach the binding and obtain
53 * the {@link RateLimitClient}.
54 *
55 * ### Declaring on a Worker's env
56 * **Example:** Async (non-Effect) Worker
57 * ```typescript
58 * export const Worker = Cloudflare.Worker("Worker", {
59 * main: "./src/worker.ts",
60 * env: {
61 * THROTTLE: Cloudflare.RateLimit("THROTTLE", {
62 * namespaceId: 1001,
63 * simple: { limit: 10, period: 60 },
64 * }),
65 * },
66 * });
67 *
68 * export type WorkerEnv = Cloudflare.InferEnv<typeof Worker>;
69 * // { THROTTLE: RateLimit } — the native Cloudflare binding
70 *
71 * // worker.ts
72 * export default {
73 * fetch: async (req: Request, env: WorkerEnv) => {
74 * const { success } = await env.THROTTLE.limit({ key: "ip" });
75 * return new Response(success ? "ok" : "rate limited");
76 * },
77 * };
78 * ```
79 *
80 * ### Binding inside an Effect-native Worker
81 * **Example:** yield* RateLimit does the binding
82 * ```typescript
83 * Cloudflare.Worker("Worker", { main: "./src/worker.ts" },
84 * Effect.gen(function* () {
85 * // Attaches the binding to this Worker AND returns the runtime client.
86 * const throttle = yield* Cloudflare.RateLimit("THROTTLE", {
87 * namespaceId: 1001,
88 * simple: { limit: 10, period: 60 },
89 * });
90 *
91 * return {
92 * fetch: Effect.gen(function* () {
93 * const { success } = yield* throttle.limit({ key: "ip" });
94 * return HttpServerResponse.text(success ? "ok" : "rate limited");
95 * }),
96 * };
97 * }).pipe(Effect.provide(Cloudflare.Workers.RateLimitBinding)),
98 * );
99 * ```
100 *
101 * @see https://developers.cloudflare.com/workers/runtime-apis/bindings/rate-limit/
102 *
103 * @binding
104 * @product Rate Limiting
105 * @category Application Security
106 */
107 export interface RateLimit extends Binding.Service<RateLimit, TypeId, RateLimitClient> {
108 /**
109 * @param name Binding name (logical id) — the `env` key it resolves to.
110 * @param props Rate limit namespace + simple config.
111 */
112 (name: string, props: RateLimitProps): RateLimitBinding;
113 }
114
115 export const RateLimit = Binding.Service<
116 RateLimit,
117 { namespaceId: string; simple: { limit: number; period: RateLimitPeriod } }
118 >({
119 id: TypeId,
120 defaultName: "RATE_LIMIT",
121 parse: (name: string, props: RateLimitProps) => ({
122 name,
123 namespaceId: String(props.namespaceId),
124 simple: props.simple,
125 }),
126 toWorkerBinding: (binding) => ({
127 type: "ratelimit",
128 name: binding.name,
129 namespaceId: binding.namespaceId,
130 simple: binding.simple,
131 }),
132 });
133
134 export const isRateLimit = (value: unknown): value is RateLimitBinding =>
135 Binding.isBinding(value) && value.kind === TypeId;