Merge pull request #6 from alankernel67/claude/ecstatic-cannon-526cac
Rate limits without Cloudflare's bindings: a Durable Object fallback (RATE_LIMITS=durable)
altugank authored · GitHub committed 2 parents f5f0e3914d98b1commit ae5059ef9ec9e749eff2ce36656a1c5fcc49535cBrowse files
10 files changed+205−12
Files (10)
- apps/diffinery/docs/self-hosting/architecture.md+4−1
- apps/diffinery/docs/self-hosting/configuration.md+4−2
- apps/diffinery/docs/self-hosting/deploy.md+1−1
- apps/diffinery/src/env.ts+9−0
- apps/diffinery/src/index.ts+1−0
- apps/diffinery/src/lib/rate-limit.ts+48−4
- apps/diffinery/src/rate-limiter.ts+36−0
- apps/diffinery/test/e2e/entry.ts+1−0
- apps/diffinery/test/unit/rate-limit.test.ts+93−2
- apps/diffinery/wrangler.jsonc+8−2
modifiedapps/diffinery/docs/self-hosting/architecture.md+4−1View file
| @@ -24,6 +24,7 @@ | ||
| 24 | 24 | | The Git transfer of a GitHub import | Containers (`ImportContainer`, one container per transfer) | `IMPORTER` | |
| 25 | 25 | | Scheduled workflows | Durable Object alarm, every 5 minutes (`SchedulerDO`, one instance) | `SCHEDULER` | |
| 26 | 26 | | Joining large artifact and cache uploads | Durable Objects, one per step (`ComposeDO`) | `COMPOSE` | |
| 27 | +| Request rate limits | Workers rate limiting; where it doesn't exist (`RATE_LIMITS=durable`), Durable Objects (`RateLimiterDO`, 32 shards) | `RL_AUTH`, `RL_ANON`, `RL_ACCOUNT`, `RL_CREATE`, `RL_MODEL`; `RATE_LIMITER` | | |
| 27 | 28 | | Token expiry reminders, email log pruning, registry cleanup, expiry of draft imports and of account exports, a check that the scheduler's alarm is set, IndexNow submissions | Cron Triggers, every 5 minutes | `scheduled` handler | |
| 28 | 29 | | Live run logs and pull request updates in the browser | Durable Object WebSockets with hibernation | Through `REPO` | |
| 29 | 30 | | Outgoing email | Email Sending | `EMAIL` | |
| @@ -54,7 +55,7 @@ | ||
| 54 | 55 | |
| 55 | 56 | ## The Worker |
| 56 | 57 | |
| 57 | -`apps/diffinery/src/index.ts` exports the Worker's `fetch`, `queue` and `scheduled` handlers, and the classes Cloudflare instantiates: `RepoDO`, `SchedulerDO`, `ComposeDO`, `RunnerContainer`, `SandboxContainer`, `RunWorkflow`, `ImportWorkflow` and `ImportContainer`. | |
| 58 | +`apps/diffinery/src/index.ts` exports the Worker's `fetch`, `queue` and `scheduled` handlers, and the classes Cloudflare instantiates: `RepoDO`, `SchedulerDO`, `ComposeDO`, `RateLimiterDO`, `RunnerContainer`, `SandboxContainer`, `RunWorkflow`, `ImportWorkflow` and `ImportContainer`. | |
| 58 | 59 | |
| 59 | 60 | Every request goes through one middleware before it reaches a route: |
| 60 | 61 | |
| @@ -215,6 +216,8 @@ | ||
| 215 | 216 | |
| 216 | 217 | Every request passes the rate limiting bindings before it is handled (`src/lib/rate-limit.ts`). Sign-in, invitation and security report requests count per IP address in `RL_AUTH`, other anonymous requests per IP address in `RL_ANON`, and requests with a session or token per account in `RL_ACCOUNT`. Requests that create repositories, organizations, forks, issues, pull requests, releases, comments or reviews also count in `RL_CREATE`, as do MCP tool calls that change something. Job, sandbox, runner and import credentials, health checks and avatars aren't counted. Cloudflare keeps each count in the location that serves the request, so the limits stop bursts rather than meter use exactly. Past a limit the request answers `429` with `retry-after: 60`. See [Bindings](/docs/self-hosting/configuration#bindings). |
| 217 | 218 | |
| 219 | +A missing binding lets requests through, as in local development. Where the bindings don't exist at all, such as on celld, the open-source Workers runtime, set the `RATE_LIMITS` variable to `durable`: each limit without a binding is then counted by the `RateLimiterDO` Durable Object (`src/rate-limiter.ts`, binding `RATE_LIMITER`) with the same limits. Keys are spread over 32 objects by a hash of the key (`ip:<address>`, `acct:<id>` and so on), and each object counts its keys in fixed 60-second windows, in memory, without writing to storage. A request costs at most one call to one object, because the buckets a request counts against share a key. The fixed windows let up to twice a limit through around the start of a minute, and an object that restarts or moves starts its counts again. If the object fails, the request goes through, as with a failing binding. | |
| 220 | + | |
| 218 | 221 | ## Request flow: a git push |
| 219 | 222 | |
| 220 | 223 | 1. `git push` sends `POST /<owner>/<repo>.git/git-receive-pack` with a token in Basic authentication. |
modifiedapps/diffinery/docs/self-hosting/configuration.md+4−2View file
| @@ -48,6 +48,7 @@ | ||
| 48 | 48 | | `MCP_REGISTRY_AUTH` | Not set | No | The proof record served at `/.well-known/mcp-registry-auth`, such as `v=MCPv1; k=ed25519; p=<public key>`, so you can publish your instance's MCP server to the official MCP registry under your domain. Not set, that path is a 404. See [List your instance in the MCP registry](/docs/agents/mcp#list-your-instance-in-the-mcp-registry). | |
| 49 | 49 | | `INDEXNOW` | Not set | No | `off` stops telling search engines about new, changed and removed public pages through IndexNow. Not set, or anything else, it is on whenever `PUBLIC_URL` is a public `https` origin and `MASTER_KEY` is set. Turn it off for an instance search engines can't reach. See [Search engines](/docs/admin/site-administration#search-engines). | |
| 50 | 50 | | `TERMINALS` | Not set | No | `off` switches [terminals](/docs/agents/terminal) off: nobody can open one, and open ones end at their next check, within a minute. Anything else, or not set, leaves them on. | |
| 51 | +| `RATE_LIMITS` | Not set | Where the `ratelimits` bindings don't exist, such as celld, the open-source Workers runtime | `durable` counts requests in the `RATE_LIMITER` Durable Object for each rate limit whose binding (`RL_AUTH`, `RL_ANON`, `RL_ACCOUNT`, `RL_CREATE`, `RL_MODEL`) is missing, with the same limits. A limit that has its binding keeps using it. Anything else, or not set, lets requests through where a binding is missing. Leave it unset on Cloudflare and in local development. See [Rate limits](/docs/self-hosting/architecture#rate-limits). | | |
| 51 | 52 | |
| 52 | 53 | When either `ACCESS_TEAM_DOMAIN` or `ACCESS_AUD` is empty, email sign-in at `/auth/access` is off: the page answers "Account recovery by email is not set up on this instance. Ask an administrator for a sign-in link.", and the sign-in page doesn't offer **Recover your account by email**. Passkeys, invitations and admin sign-in links keep working, but the first administrator can't sign in, because email sign-in is how an account in `BOOTSTRAP_ADMINS` is created. |
| 53 | 54 | |
| @@ -237,10 +238,11 @@ | ||
| 237 | 238 | | `MAIL` | Queue producer, with a consumer on the same Worker | `diffinery-mail`, dead-letter queue `diffinery-mail-dlq` | Email jobs. Consumer: batches of up to 20, waiting up to 2 seconds, 8 retries. Optional: without it emails are dropped with a warning in the logs. | |
| 238 | 239 | | `EMAIL` | `send_email` (Email Sending) | Your onboarded domain | Sending email. Optional: without it every email is logged as `skipped`. | |
| 239 | 240 | | (none) | Queue consumer | `diffinery-mail-events` | Bounces and complaints from Email Sending's event subscriptions; the deploy subscribes this queue to your sending domain's events (see [Site administration](/docs/admin/site-administration#where-bounces-and-complaints-come-from)). Consumer: batches of up to 50, waiting up to 5 seconds, 8 retries. | |
| 240 | -| `RL_AUTH`, `RL_ANON`, `RL_ACCOUNT`, `RL_CREATE`, `RL_MODEL` | Rate limiting (`ratelimits`) | Namespaces `1001` to `1005`; 20, 300, 2,000, 60 and 600 requests per 60 seconds | [Request rate limits](/docs/reference/rest-api#rate-limits): sign-in and security reports per IP address, anonymous requests per IP address, signed-in requests per account, new content per account, and agents' model requests per paying person (`MODEL_RATE_LIMIT` in `src/lib/rate-limit.ts`). Optional: a missing binding (the `dev` environment declares none) or one that fails lets requests through. If you change a limit, change `RATE_LIMITS` (or `MODEL_RATE_LIMIT`) in `src/lib/rate-limit.ts` to match, since the 429 messages quote it. Namespace IDs are shared across your Cloudflare account, so pick others if another Worker already uses these. | | |
| 241 | +| `RL_AUTH`, `RL_ANON`, `RL_ACCOUNT`, `RL_CREATE`, `RL_MODEL` | Rate limiting (`ratelimits`) | Namespaces `1001` to `1005`; 20, 300, 2,000, 60 and 600 requests per 60 seconds | [Request rate limits](/docs/reference/rest-api#rate-limits): sign-in and security reports per IP address, anonymous requests per IP address, signed-in requests per account, new content per account, and agents' model requests per paying person (`MODEL_RATE_LIMIT` in `src/lib/rate-limit.ts`). Optional: a missing binding (the `dev` environment declares none) or one that fails lets requests through. If you change a limit, change `RATE_LIMITS` (or `MODEL_RATE_LIMIT`) in `src/lib/rate-limit.ts` to match, since the 429 messages quote it. Namespace IDs are shared across your Cloudflare account, so pick others if another Worker already uses these. Where these bindings don't exist, set `RATE_LIMITS` to `durable` to count in `RATE_LIMITER` instead. | | |
| 241 | 242 | | `REPO` | Durable Object namespace | Class `RepoDO` (SQLite) | One object per repository. | |
| 242 | 243 | | `SCHEDULER` | Durable Object namespace | Class `SchedulerDO` (SQLite) | One object that starts scheduled workflow runs on its own alarm. | |
| 243 | 244 | | `COMPOSE` | Durable Object namespace | Class `ComposeDO` (SQLite) | Joins the blocks of large artifact and cache uploads, one short-lived object per step, so the copying doesn't slow the repository's object. Without it, `RepoDO` does the joining. | |
| 245 | +| `RATE_LIMITER` | Durable Object namespace | Class `RateLimiterDO` (SQLite) | Request rate limits when `RATE_LIMITS` is `durable` and the `ratelimits` bindings are missing, such as on celld. 32 objects, each counting a share of the keys in memory. Unused otherwise. | | |
| 244 | 246 | | `RUNNER` | Durable Object namespace with a container | Class `RunnerContainer` (SQLite) | One container per hosted workflow job, and per runner of a [GitHub job](/docs/actions/github-runners). | |
| 245 | 247 | | `GITHUB_RUNNERS` | Durable Object namespace | Class `GitHubRunnersDO` (SQLite) | One object per account that pays for [GitHub runners](#github-runners): it starts runners for its GitHub jobs on its own alarm. | |
| 246 | 248 | | `SANDBOX` | Durable Object namespace with a container | Class `SandboxContainer` (SQLite) | One container per agent sandbox. | |
| @@ -248,7 +250,7 @@ | ||
| 248 | 250 | | `IMPORTER` | Durable Object namespace with a container | Class `ImportContainer` (SQLite) | One container per Git transfer of a GitHub import. | |
| 249 | 251 | | `IMPORT_WORKFLOW` | Workflow | `diffinery-import`, class `ImportWorkflow` | One durable instance per attempt of a GitHub import. | |
| 250 | 252 | |
| 251 | -The Durable Object classes are declared in seven migrations (`new_sqlite_classes`): tag `v1` for `RepoDO`, `RunnerContainer` and `SandboxContainer`, tag `v2` for `ImportContainer`, tag `v3` for `ProjectDO`, tag `v4` for `SchedulerDO`, tag `v5` for `RunnerContainerMedium`, `RunnerContainerSmall` and `RunnerContainerTiny`, tag `v6` for `ComposeDO`, and tag `v7` for `GitHubRunnersDO`. `wrangler deploy` applies a migration tag the account doesn't have yet. | |
| 253 | +The Durable Object classes are declared in eight migrations (`new_sqlite_classes`): tag `v1` for `RepoDO`, `RunnerContainer` and `SandboxContainer`, tag `v2` for `ImportContainer`, tag `v3` for `ProjectDO`, tag `v4` for `SchedulerDO`, tag `v5` for `RunnerContainerMedium`, `RunnerContainerSmall` and `RunnerContainerTiny`, tag `v6` for `ComposeDO`, tag `v7` for `GitHubRunnersDO`, and tag `v8` for `RateLimiterDO`. `wrangler deploy` applies a migration tag the account doesn't have yet. | |
| 252 | 254 | |
| 253 | 255 | ## Other Worker settings |
| 254 | 256 |
modifiedapps/diffinery/docs/self-hosting/deploy.md+1−1View file
| @@ -186,7 +186,7 @@ | ||
| 186 | 186 | |
| 187 | 187 | ### wrangler deploy |
| 188 | 188 | |
| 189 | -`pnpm exec wrangler deploy -c wrangler.deploy.jsonc` (run in `apps/diffinery`) deploys the Worker with all its bindings, and builds the runner image from `containers/runner/Dockerfile` (Ubuntu 24.04 with Node.js 22, git, git-lfs and the runner agent) for all three container classes: `RunnerContainer` (hosted jobs), `SandboxContainer` (agent sandboxes) and `ImportContainer` (the Git transfers of GitHub imports). It also applies Durable Object migrations the account doesn't have yet: tag `v1` creates `RepoDO`, `RunnerContainer` and `SandboxContainer`, tag `v2` creates `ImportContainer`, tag `v3` creates `ProjectDO`, tag `v4` creates `SchedulerDO`, tag `v5` creates the smaller runner classes, and tag `v6` creates `ComposeDO`. | |
| 189 | +`pnpm exec wrangler deploy -c wrangler.deploy.jsonc` (run in `apps/diffinery`) deploys the Worker with all its bindings, and builds the runner image from `containers/runner/Dockerfile` (Ubuntu 24.04 with Node.js 22, git, git-lfs and the runner agent) for all three container classes: `RunnerContainer` (hosted jobs), `SandboxContainer` (agent sandboxes) and `ImportContainer` (the Git transfers of GitHub imports). It also applies Durable Object migrations the account doesn't have yet: tag `v1` creates `RepoDO`, `RunnerContainer` and `SandboxContainer`, tag `v2` creates `ImportContainer`, tag `v3` creates `ProjectDO`, tag `v4` creates `SchedulerDO`, tag `v5` creates the smaller runner classes, tag `v6` creates `ComposeDO`, tag `v7` creates `GitHubRunnersDO`, and tag `v8` creates `RateLimiterDO`. | |
| 190 | 190 | |
| 191 | 191 | ### scripts/ensure-secrets.sh |
| 192 | 192 |
modifiedapps/diffinery/src/env.ts+9−0View file
| @@ -2,6 +2,7 @@ | ||
| 2 | 2 | import type { RepoDO } from "./repo/RepoDO.js"; |
| 3 | 3 | import type { SchedulerDO } from "./scheduler.js"; |
| 4 | 4 | import type { ComposeDO } from "./compose.js"; |
| 5 | +import type { RateLimiterDO } from "./rate-limiter.js"; | |
| 5 | 6 | import type { ImportContainer } from "./imports/container.js"; |
| 6 | 7 | import type { RunnerContainer, SandboxContainer } from "./runner/containers.js"; |
| 7 | 8 | import type { MailJob } from "./mail/types.js"; |
| @@ -59,6 +60,14 @@ | ||
| 59 | 60 | RL_CREATE?: RateLimit; |
| 60 | 61 | /** Model requests through the proxy, per paying person (agentic/proxy.ts). */ |
| 61 | 62 | RL_MODEL?: RateLimit; |
| 63 | + /** | |
| 64 | + * "durable": count the requests of each RL_* binding that isn't configured in RATE_LIMITER instead, | |
| 65 | + * for deployments without Cloudflare's rate limiting, such as celld (lib/rate-limit.ts). Unset, a | |
| 66 | + * missing binding lets requests through. | |
| 67 | + */ | |
| 68 | + RATE_LIMITS?: string; | |
| 69 | + /** The rate limiter RATE_LIMITS=durable uses, one object per shard of keys (rate-limiter.ts). */ | |
| 70 | + RATE_LIMITER?: DurableObjectNamespace<RateLimiterDO>; | |
| 62 | 71 | /** Email jobs, sent by the queue consumer in mail/send.ts. */ |
| 63 | 72 | MAIL?: Queue<MailJob>; |
| 64 | 73 | IMPORT_WORKFLOW: Workflow<{ importId: string }>; |
modifiedapps/diffinery/src/index.ts+1−0View file
| @@ -8,6 +8,7 @@ | ||
| 8 | 8 | export { RepoDO } from "./repo/RepoDO.js"; |
| 9 | 9 | export { SchedulerDO } from "./scheduler.js"; |
| 10 | 10 | export { ComposeDO } from "./compose.js"; |
| 11 | +export { RateLimiterDO } from "./rate-limiter.js"; | |
| 11 | 12 | export { RunnerContainer, RunnerContainerMedium, RunnerContainerSmall, RunnerContainerTiny, SandboxContainer, SandboxPoolDO } from "./runner/containers.js"; |
| 12 | 13 | export { RunWorkflow } from "./runner/workflow.js"; |
| 13 | 14 | export { ImportWorkflow } from "./imports/workflow.js"; |
modifiedapps/diffinery/src/lib/rate-limit.ts+48−4View file
| @@ -6,7 +6,9 @@ | ||
| 6 | 6 | * Request rate limits (Workers rate limiting bindings, configured in wrangler.jsonc). Each |
| 7 | 7 | * binding counts per key over 60 seconds in the Cloudflare location that serves the request, so |
| 8 | 8 | * the limits stop floods and scripted abuse rather than meter use exactly. A binding that isn't |
| 9 | - * configured (local development) or that fails lets the request through. | |
| 9 | + * configured (local development) or that fails lets the request through, unless RATE_LIMITS=durable: | |
| 10 | + * then the RATE_LIMITER Durable Object counts that bucket instead (rate-limiter.ts), for deployments | |
| 11 | + * without the bindings, such as celld. It fails open too. | |
| 10 | 12 | * |
| 11 | 13 | * - RL_AUTH: sign-in, passkey registration, invitation and sign-in links, open sign-up, private |
| 12 | 14 | * security reports (/security/report), early access requests and their confirmations |
| @@ -70,16 +72,20 @@ | ||
| 70 | 72 | |
| 71 | 73 | /** The bucket that's over its limit for this request, or null. */ |
| 72 | 74 | export async function overLimit(env: Env, buckets: Array<[Bucket, string]>): Promise<Bucket | null> { |
| 75 | + const unbound: Array<[Bucket, string]> = []; | |
| 73 | 76 | for (const [b, key] of buckets) { |
| 74 | 77 | const rl = (env as unknown as Record<string, RateLimiter | undefined>)[b]; |
| 75 | - if (!rl) continue; | |
| 78 | + if (!rl) { | |
| 79 | + unbound.push([b, key]); | |
| 80 | + continue; | |
| 81 | + } | |
| 76 | 82 | try { |
| 77 | 83 | if (!(await rl.limit({ key })).success) return b; |
| 78 | 84 | } catch (e) { |
| 79 | 85 | console.error("rate limiter failed", b, e); |
| 80 | 86 | } |
| 81 | 87 | } |
| 82 | - return null; | |
| 88 | + return durableOverLimit(env, unbound); | |
| 83 | 89 | } |
| 84 | 90 | |
| 85 | 91 | /** |
| @@ -91,7 +97,7 @@ | ||
| 91 | 97 | |
| 92 | 98 | /** Whether this person is over their model request rate. A missing (local) or failing binding lets it through. */ |
| 93 | 99 | export async function modelRateLimited(env: Env, personId: string): Promise<boolean> { |
| 94 | - if (!env.RL_MODEL) return false; | |
| 100 | + if (!env.RL_MODEL) return (await durableOverLimit(env, [["RL_MODEL", `model:${personId}`]])) !== null; | |
| 95 | 101 | try { |
| 96 | 102 | return !(await env.RL_MODEL.limit({ key: `model:${personId}` })).success; |
| 97 | 103 | } catch (e) { |
| @@ -100,6 +106,44 @@ | ||
| 100 | 106 | } |
| 101 | 107 | } |
| 102 | 108 | |
| 109 | +/** Limits per window for the Durable Object fallback: the same as the bindings'. */ | |
| 110 | +const DURABLE_LIMITS: Record<Bucket | "RL_MODEL", number> = { ...RATE_LIMITS, RL_MODEL: MODEL_RATE_LIMIT }; | |
| 111 | + | |
| 112 | +/** | |
| 113 | + * Objects the fallback spreads keys over. A key always lands on the same one; the requests of one | |
| 114 | + * key (one address, one account) can't be spread anyway, and a fixed set keeps the objects few and | |
| 115 | + * warm instead of one per address. | |
| 116 | + */ | |
| 117 | +export const RATE_LIMITER_SHARDS = 32; | |
| 118 | + | |
| 119 | +/** The RATE_LIMITER object that counts `key`: FNV-1a of the key, modulo the shards. */ | |
| 120 | +export function rateLimiterShard(key: string): string { | |
| 121 | + let h = 0x811c9dc5; | |
| 122 | + for (let i = 0; i < key.length; i++) h = Math.imul(h ^ key.charCodeAt(i), 0x01000193); | |
| 123 | + return `shard-${(h >>> 0) % RATE_LIMITER_SHARDS}`; | |
| 124 | +} | |
| 125 | + | |
| 126 | +/** | |
| 127 | + * Counts buckets that have no binding in the RATE_LIMITER Durable Object, when RATE_LIMITS=durable. | |
| 128 | + * One call per key, so a request costs one call: its buckets share a key (an account's requests | |
| 129 | + * and its new content). A failing object lets the request through, as a failing binding does. | |
| 130 | + */ | |
| 131 | +async function durableOverLimit<B extends Bucket | "RL_MODEL">(env: Env, buckets: Array<[B, string]>): Promise<B | null> { | |
| 132 | + const ns = env.RATE_LIMITS === "durable" ? env.RATE_LIMITER : undefined; | |
| 133 | + if (!ns || !buckets.length) return null; | |
| 134 | + const byKey = new Map<string, Array<[B, number]>>(); | |
| 135 | + for (const [b, key] of buckets) byKey.set(key, [...(byKey.get(key) ?? []), [b, DURABLE_LIMITS[b]]]); | |
| 136 | + for (const [key, limits] of byKey) { | |
| 137 | + try { | |
| 138 | + const over = await ns.get(ns.idFromName(rateLimiterShard(key))).hit(key, limits); | |
| 139 | + if (over) return over as B; | |
| 140 | + } catch (e) { | |
| 141 | + console.error("rate limiter object failed", e); | |
| 142 | + } | |
| 143 | + } | |
| 144 | + return null; | |
| 145 | +} | |
| 146 | + | |
| 103 | 147 | const WHAT: Record<Bucket, string> = { |
| 104 | 148 | RL_AUTH: "sign-in attempts, security reports, early access requests and contact messages from your network", |
| 105 | 149 | RL_ANON: "requests from your network without signing in", |
addedapps/diffinery/src/rate-limiter.ts+36−0View file
| @@ -1,0 +1,36 @@ | ||
| 1 | +import { DurableObject } from "cloudflare:workers"; | |
| 2 | +import type { Env } from "./env.js"; | |
| 3 | +import { RATE_PERIOD_S } from "./lib/rate-limit.js"; | |
| 4 | + | |
| 5 | +/** | |
| 6 | + * Request rate limits for deployments without Cloudflare's rate limiting bindings, such as celld | |
| 7 | + * (RATE_LIMITS=durable, lib/rate-limit.ts). Each object counts the keys of one shard in fixed | |
| 8 | + * windows of RATE_PERIOD_S, in memory only: nothing is written to storage, so counting costs no | |
| 9 | + * write per request, and an object that is evicted or moved starts its window again. Like the | |
| 10 | + * bindings, the limits stop floods and scripted abuse rather than meter use exactly. | |
| 11 | + */ | |
| 12 | +export class RateLimiterDO extends DurableObject<Env> { | |
| 13 | + private window = 0; | |
| 14 | + /** `<bucket>\n<key>` → requests in the current window. Cleared when the window rolls over, so it holds one window's keys. */ | |
| 15 | + private counts = new Map<string, number>(); | |
| 16 | + | |
| 17 | + /** | |
| 18 | + * Counts one request for `key` against each bucket in turn ([name, limit per window]), and | |
| 19 | + * returns the first bucket over its limit, or null. Buckets after that one aren't counted, as | |
| 20 | + * with the bindings. | |
| 21 | + */ | |
| 22 | + hit(key: string, limits: Array<[bucket: string, limit: number]>): string | null { | |
| 23 | + const w = Math.floor(Date.now() / 1000 / RATE_PERIOD_S); | |
| 24 | + if (w !== this.window) { | |
| 25 | + this.window = w; | |
| 26 | + this.counts.clear(); | |
| 27 | + } | |
| 28 | + for (const [bucket, limit] of limits) { | |
| 29 | + const k = `${bucket}\n${key}`; | |
| 30 | + const n = (this.counts.get(k) ?? 0) + 1; | |
| 31 | + this.counts.set(k, n); | |
| 32 | + if (n > limit) return bucket; | |
| 33 | + } | |
| 34 | + return null; | |
| 35 | + } | |
| 36 | +} |
modifiedapps/diffinery/test/e2e/entry.ts+1−0View file
| @@ -7,6 +7,7 @@ | ||
| 7 | 7 | export { RepoDO } from "../../src/repo/RepoDO.js"; |
| 8 | 8 | export { SchedulerDO } from "../../src/scheduler.js"; |
| 9 | 9 | export { ComposeDO } from "../../src/compose.js"; |
| 10 | +export { RateLimiterDO } from "../../src/rate-limiter.js"; | |
| 10 | 11 | export { RunnerContainer, RunnerContainerMedium, RunnerContainerSmall, RunnerContainerTiny, SandboxContainer } from "../../src/runner/containers.js"; |
| 11 | 12 | export { RunWorkflow } from "../../src/runner/workflow.js"; |
| 12 | 13 | export { ImportWorkflow } from "../../src/imports/workflow.js"; |
modifiedapps/diffinery/test/unit/rate-limit.test.ts+93−2View file
| @@ -1,8 +1,9 @@ | ||
| 1 | 1 | import { readFileSync } from "node:fs"; |
| 2 | -import { describe, expect, it } from "vitest"; | |
| 2 | +import { afterEach, describe, expect, it, vi } from "vitest"; | |
| 3 | 3 | import type { Env } from "../../src/env.js"; |
| 4 | 4 | import type { Principal } from "../../src/auth/principal.js"; |
| 5 | -import { bucketsFor, MODEL_RATE_LIMIT, modelRateLimited, overLimit, RATE_LIMITS, RATE_PERIOD_S, type RateLimiter } from "../../src/lib/rate-limit.js"; | |
| 5 | +import { bucketsFor, MODEL_RATE_LIMIT, modelRateLimited, overLimit, RATE_LIMITER_SHARDS, rateLimiterShard, RATE_LIMITS, RATE_PERIOD_S, type RateLimiter } from "../../src/lib/rate-limit.js"; | |
| 6 | +import { RateLimiterDO } from "../../src/rate-limiter.js"; | |
| 6 | 7 | |
| 7 | 8 | const anon: Principal = { type: "anonymous" }; |
| 8 | 9 | const person = { type: "account", account: { id: "u1" }, via: "token", scopes: ["write"], repoIds: null } as unknown as Principal; |
| @@ -140,3 +141,93 @@ | ||
| 140 | 141 | expect(bucketsFor("POST", "/-/model/anthropic/v1/messages", person, "203.0.113.9")).toEqual([]); |
| 141 | 142 | }); |
| 142 | 143 | }); |
| 144 | + | |
| 145 | +/** A RATE_LIMITER namespace of real RateLimiterDO objects, recording which object each call reached. */ | |
| 146 | +function limiterObjects(fail = false) { | |
| 147 | + const objects = new Map<string, RateLimiterDO>(); | |
| 148 | + const calls: string[] = []; | |
| 149 | + const ns = { | |
| 150 | + idFromName: (name: string) => name, | |
| 151 | + get: (name: string) => ({ | |
| 152 | + hit: async (key: string, limits: Array<[string, number]>) => { | |
| 153 | + calls.push(name); | |
| 154 | + if (fail) throw new Error("object unreachable"); | |
| 155 | + if (!objects.has(name)) objects.set(name, new RateLimiterDO({} as DurableObjectState, {} as Env)); | |
| 156 | + return objects.get(name)!.hit(key, limits); | |
| 157 | + }, | |
| 158 | + }), | |
| 159 | + }; | |
| 160 | + return { ns, calls }; | |
| 161 | +} | |
| 162 | + | |
| 163 | +describe("the Durable Object fallback (RATE_LIMITS=durable)", () => { | |
| 164 | + afterEach(() => vi.useRealTimers()); | |
| 165 | + | |
| 166 | + it("counts buckets without a binding at the production limits, one object call per request", async () => { | |
| 167 | + const { ns, calls } = limiterObjects(); | |
| 168 | + const env = { RATE_LIMITS: "durable", RATE_LIMITER: ns } as unknown as Env; | |
| 169 | + const sign = bucketsFor("POST", "/signup", anon, "203.0.113.9"); | |
| 170 | + for (let i = 0; i < RATE_LIMITS.RL_AUTH; i++) expect(await overLimit(env, sign)).toBeNull(); | |
| 171 | + expect(await overLimit(env, sign)).toBe("RL_AUTH"); | |
| 172 | + expect(await overLimit(env, bucketsFor("POST", "/signup", anon, "203.0.113.10"))).toBeNull(); | |
| 173 | + // An account's request and its new content share a key: one call counts both buckets. | |
| 174 | + calls.length = 0; | |
| 175 | + const create = bucketsFor("POST", "/api/v3/repos/acme/app/issues", person, "x"); | |
| 176 | + for (let i = 0; i < RATE_LIMITS.RL_CREATE; i++) expect(await overLimit(env, create)).toBeNull(); | |
| 177 | + expect(await overLimit(env, create)).toBe("RL_CREATE"); | |
| 178 | + expect(calls).toHaveLength(RATE_LIMITS.RL_CREATE + 1); | |
| 179 | + expect(new Set(calls)).toEqual(new Set([rateLimiterShard("acct:u1")])); | |
| 180 | + }); | |
| 181 | + | |
| 182 | + it("starts a new count every window", async () => { | |
| 183 | + vi.useFakeTimers({ toFake: ["Date"] }); | |
| 184 | + vi.setSystemTime(Date.UTC(2026, 9, 30, 12, 0, 0)); | |
| 185 | + const { ns } = limiterObjects(); | |
| 186 | + const env = { RATE_LIMITS: "durable", RATE_LIMITER: ns } as unknown as Env; | |
| 187 | + const b = bucketsFor("POST", "/signup", anon, "203.0.113.9"); | |
| 188 | + for (let i = 0; i < RATE_LIMITS.RL_AUTH; i++) await overLimit(env, b); | |
| 189 | + expect(await overLimit(env, b)).toBe("RL_AUTH"); | |
| 190 | + vi.setSystemTime(Date.UTC(2026, 9, 30, 12, 0, RATE_PERIOD_S - 1)); | |
| 191 | + expect(await overLimit(env, b)).toBe("RL_AUTH"); | |
| 192 | + vi.setSystemTime(Date.UTC(2026, 9, 30, 12, 0, RATE_PERIOD_S)); | |
| 193 | + expect(await overLimit(env, b)).toBeNull(); | |
| 194 | + }); | |
| 195 | + | |
| 196 | + it("limits model requests per paying person", async () => { | |
| 197 | + const { ns } = limiterObjects(); | |
| 198 | + const env = { RATE_LIMITS: "durable", RATE_LIMITER: ns } as unknown as Env; | |
| 199 | + for (let i = 0; i < MODEL_RATE_LIMIT; i++) expect(await modelRateLimited(env, "p1")).toBe(false); | |
| 200 | + expect(await modelRateLimited(env, "p1")).toBe(true); | |
| 201 | + expect(await modelRateLimited(env, "p2")).toBe(false); | |
| 202 | + }); | |
| 203 | + | |
| 204 | + it("uses a binding where there is one, and is off unless RATE_LIMITS is durable", async () => { | |
| 205 | + const { ns, calls } = limiterObjects(); | |
| 206 | + const bound = { RATE_LIMITS: "durable", RATE_LIMITER: ns, RL_ANON: limiter(1) } as unknown as Env; | |
| 207 | + expect(await overLimit(bound, [["RL_ANON", "ip:x"]])).toBeNull(); | |
| 208 | + expect(await overLimit(bound, [["RL_ANON", "ip:x"]])).toBe("RL_ANON"); | |
| 209 | + expect(await modelRateLimited({ RATE_LIMITER: ns } as unknown as Env, "p1")).toBe(false); | |
| 210 | + expect(await overLimit({ RATE_LIMITER: ns } as unknown as Env, [["RL_AUTH", "ip:x"]])).toBeNull(); | |
| 211 | + expect(calls).toEqual([]); | |
| 212 | + }); | |
| 213 | + | |
| 214 | + it("lets requests through when the object fails", async () => { | |
| 215 | + const { ns, calls } = limiterObjects(true); | |
| 216 | + const env = { RATE_LIMITS: "durable", RATE_LIMITER: ns } as unknown as Env; | |
| 217 | + expect(await overLimit(env, [["RL_AUTH", "ip:x"]])).toBeNull(); | |
| 218 | + expect(await modelRateLimited(env, "p1")).toBe(false); | |
| 219 | + expect(calls).toHaveLength(2); | |
| 220 | + }); | |
| 221 | + | |
| 222 | + it("spreads keys over a fixed set of objects", () => { | |
| 223 | + const shards = new Set(Array.from({ length: 2000 }, (_, i) => rateLimiterShard(`ip:198.51.${i >> 8}.${i & 255}`))); | |
| 224 | + expect(shards.size).toBe(RATE_LIMITER_SHARDS); | |
| 225 | + expect(rateLimiterShard("acct:u1")).toBe(rateLimiterShard("acct:u1")); | |
| 226 | + }); | |
| 227 | + | |
| 228 | + it("is bound in wrangler.jsonc, for production and local development", () => { | |
| 229 | + const text = readFileSync(new URL("../../wrangler.jsonc", import.meta.url), "utf8"); | |
| 230 | + expect(text.match(/\{ "name": "RATE_LIMITER", "class_name": "RateLimiterDO" \}/g)).toHaveLength(2); | |
| 231 | + expect(text).toMatch(/"new_sqlite_classes": \["RateLimiterDO"\]/); | |
| 232 | + }); | |
| 233 | +}); |
modifiedapps/diffinery/wrangler.jsonc+8−2View file
| @@ -49,7 +49,8 @@ | ||
| 49 | 49 | // domain is onboarded under Compute > Email Service > Email Sending (see scripts/email-sending.sh). |
| 50 | 50 | "send_email": [{ "name": "EMAIL" }], |
| 51 | 51 | // Request rate limits per minute (src/lib/rate-limit.ts; RATE_LIMITS there must match). Local |
| 52 | - // development declares none, so nothing is limited there. | |
| 52 | + // development declares none, so nothing is limited there. Where these bindings don't exist (celld), | |
| 53 | + // the RATE_LIMITER Durable Object counts instead when the RATE_LIMITS var is "durable". | |
| 53 | 54 | "ratelimits": [ |
| 54 | 55 | { "name": "RL_AUTH", "namespace_id": "1001", "simple": { "limit": 20, "period": 60 } }, |
| 55 | 56 | { "name": "RL_ANON", "namespace_id": "1002", "simple": { "limit": 300, "period": 60 } }, |
| @@ -63,6 +64,8 @@ | ||
| 63 | 64 | { "name": "REPO", "class_name": "RepoDO" }, |
| 64 | 65 | { "name": "SCHEDULER", "class_name": "SchedulerDO" }, |
| 65 | 66 | { "name": "COMPOSE", "class_name": "ComposeDO" }, |
| 67 | + // Request rate limits without the ratelimits bindings (RATE_LIMITS=durable, src/rate-limiter.ts). | |
| 68 | + { "name": "RATE_LIMITER", "class_name": "RateLimiterDO" }, | |
| 66 | 69 | { "name": "RUNNER", "class_name": "RunnerContainer" }, |
| 67 | 70 | // Smaller hosted runners (src/runner/sizes.ts), the same runner on smaller instance types. |
| 68 | 71 | { "name": "RUNNER_MEDIUM", "class_name": "RunnerContainerMedium" }, |
| @@ -87,7 +90,9 @@ | ||
| 87 | 90 | // Joining large uploads' blocks, a step per object (compose.ts). |
| 88 | 91 | { "tag": "v6", "new_sqlite_classes": ["ComposeDO"] }, |
| 89 | 92 | // GitHub jobs on Diffinery runners (src/github-runners/GitHubRunnersDO.ts). |
| 90 | - { "tag": "v7", "new_sqlite_classes": ["GitHubRunnersDO"] } | |
| 93 | + { "tag": "v7", "new_sqlite_classes": ["GitHubRunnersDO"] }, | |
| 94 | + // Request rate limits without the ratelimits bindings (rate-limiter.ts). | |
| 95 | + { "tag": "v8", "new_sqlite_classes": ["RateLimiterDO"] } | |
| 91 | 96 | ], |
| 92 | 97 | "workflows": [ |
| 93 | 98 | { "name": "diffinery-run", "binding": "RUN_WORKFLOW", "class_name": "RunWorkflow" }, |
| @@ -160,6 +165,7 @@ | ||
| 160 | 165 | { "name": "REPO", "class_name": "RepoDO" }, |
| 161 | 166 | { "name": "SCHEDULER", "class_name": "SchedulerDO" }, |
| 162 | 167 | { "name": "COMPOSE", "class_name": "ComposeDO" }, |
| 168 | + { "name": "RATE_LIMITER", "class_name": "RateLimiterDO" }, | |
| 163 | 169 | { "name": "RUNNER", "class_name": "RunnerContainer" }, |
| 164 | 170 | { "name": "RUNNER_MEDIUM", "class_name": "RunnerContainerMedium" }, |
| 165 | 171 | { "name": "RUNNER_SMALL", "class_name": "RunnerContainerSmall" }, |