Skip to main content

apps/gateway/src/middleware/rate-limit.ts

Metadata

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;
}