limit.ts

1.8 KB · raw

1import type { Hono } from "hono";2import { clientIp } from "../server/client.ts";34// The expensive public answers — a whole-repo bundle, a tarball, a highlighted file, a raw object,5// a save page's diff — carry a per-address budget, so one crawler can't hold the one request6// thread. A HEAD fetches nothing, and the rest of the site is not counted.7const RATE = 60; // requests a minute8const BURST = 20; // allowed at once9const MINUTE = 60_000;10const HEAVY = /^\/[^/]+\/(?:koh\/bundle$|archive\/|files\/|raw\/|saves\/)/;1112/** 429 with `Retry-After` past the budget; small and in memory, one bucket per address. */13export function registerHeavyLimit(app: Hono): void {14	const buckets = new Map<string, { tokens: number; at: number }>();15	// The whole seconds `ip` must wait for a token, or 0 for one now.16	const take = (ip: string, now: number): number => {17		const bucket = buckets.get(ip);18		// Bounded: an address full again after a quiet minute needs no entry.19		if (!bucket && buckets.size > 4096) {20			for (const [key, it] of buckets) {21				if (it.tokens + ((now - it.at) * RATE) / MINUTE >= BURST) buckets.delete(key);22			}23		}24		const held = (bucket?.tokens ?? BURST) + ((now - (bucket?.at ?? now)) * RATE) / MINUTE;25		const tokens = Math.min(BURST, held);26		buckets.set(ip, { tokens: Math.max(0, tokens - 1), at: now });27		if (tokens >= 1) return 0;28		return Math.max(1, Math.ceil(((1 - tokens) * MINUTE) / RATE / 1000));29	};30	app.use("*", async (c, next) => {31		const ip = clientIp(c);32		// An address no runtime gave can't tell clients apart, so it is not counted.33		if (ip !== "" && c.req.method !== "HEAD" && HEAVY.test(c.req.path)) {34			const wait = take(ip, Date.now());35			if (wait > 0) return c.text("too many requests\n", 429, { "Retry-After": String(wait) });36		}37		await next();38	});39}