apps/gateway/src/middleware/rate-limit.ts
Metadata
- Purpose: Gateway middleware for cross-cutting concerns.
- Domain:
applications - Language:
ts - Bytes: 2574
- Lines: 74
- Content hash (short):
0746e688 - Source (start): apps/gateway/src/middleware/rate-limit.ts:1
- Source (end): apps/gateway/src/middleware/rate-limit.ts:74
Indexed Symbols
getKey(line 13, function) - Implements get key for module behavior.getCounter(line 19, function) - Implements get counter for module behavior.cleanupCounters(line 29, function) - Implements cleanup counters for module behavior.
Markdown Headings (if applicable)
No markdown headings detected.
Source Preview
import type { FastifyPluginAsync } from "fastify";
import { env } from "../config/env.js";
import { getEffectivePlatformSettings } from "../services/runtime-config.js";
type Counter = {
count: number;
resetAt: number;
};
const counters = new Map<string, Counter>();
let requestCounter = 0;
function getKey(request: import("fastify").FastifyRequest): string {
const subject = request.auth?.subject ?? request.ip;
const workspaceId = request.headers[env.workspaceHeader];
return `${subject}:${typeof workspaceId === "string" ? workspaceId : "*"}`;
}
function getCounter(key: string, now: number, windowMs: number): Counter {
const existing = counters.get(key);
if (!existing || existing.resetAt <= now) {
const next = { count: 0, resetAt: now + windowMs };
counters.set(key, next);
return next;
}