Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/packages/shared-store/src/helpers/rate-limit-fixed.ts
T

97 lines
3.4 KiB
TypeScript

import { MemoryAdapter } from "../adapters/memory.js";
import type { SharedStore } from "../factory.js";
export interface FixedWindowRateLimiterOptions {
store: SharedStore;
/** Sub-namespace for this limiter (e.g. `"login-ip"`). */
prefix: string;
/** Window length in seconds. */
windowSeconds: number;
/** Allowed actions per window. */
max: number;
}
export interface FixedWindowDecision {
/** True when the request is below the cap. */
allowed: boolean;
/** How many actions are still permitted in the current window. */
remaining: number;
/** Wall-clock time when the current window resets. */
resetAt: Date;
}
export interface FixedWindowRateLimiter {
/** Atomically reserve one or more actions in the current window. */
consume(key: string, weight?: number): Promise<FixedWindowDecision>;
/** Test/admin helper: drop the counter for a key. */
reset(key: string): Promise<void>;
}
const FIXED_WINDOW_SCRIPT = `
local weight = tonumber(ARGV[2])
local current = redis.call('INCRBY', KEYS[1], weight)
if current == weight then
redis.call('EXPIRE', KEYS[1], tonumber(ARGV[1]))
end
local ttl = redis.call('TTL', KEYS[1])
return { current, ttl }
`;
// Register the memory-adapter equivalent so the same eval() call works
// against both backends. The memory adapter resolves scripts by exact
// string match.
MemoryAdapter.registerScript(FIXED_WINDOW_SCRIPT, async (adapter, keys, args) => {
const [key] = keys;
const window = Number.parseInt(args[0] ?? "0", 10);
const weight = Number.parseInt(args[1] ?? "1", 10);
const current = await adapter.incr(key, weight);
if (current === weight && window > 0) {
await adapter.expire(key, window);
}
// We do not implement TTL command on the adapter surface; the helper
// computes resetAt locally for the memory case.
return [current, window];
});
/**
* Create a Redis-style fixed-window rate limiter. The window starts on
* the first `consume()` call and resets after `windowSeconds`. The
* decision is computed atomically in Redis via Lua (and sequentially,
* race-free, in the memory adapter).
*/
export function createFixedWindowRateLimiter(options: FixedWindowRateLimiterOptions): FixedWindowRateLimiter {
if (options.windowSeconds <= 0) {
throw new Error("createFixedWindowRateLimiter: windowSeconds must be > 0");
}
if (options.max <= 0) {
throw new Error("createFixedWindowRateLimiter: max must be > 0");
}
const store = options.store;
const bucketKey = (key: string) => `rl:fixed:${options.prefix}:${key}`;
return {
async consume(key, weight = 1) {
if (!Number.isSafeInteger(weight) || weight <= 0) {
throw new Error("fixed-window rate-limit weight must be a positive safe integer");
}
const fullKey = store.key(bucketKey(key));
const result = (await store.adapter.eval(FIXED_WINDOW_SCRIPT, [fullKey], [String(options.windowSeconds), String(weight)])) as
| [number | string, number | string]
| undefined;
const current = Number(result?.[0] ?? 0);
const ttlReported = Number(result?.[1] ?? options.windowSeconds);
const ttl = ttlReported > 0 ? ttlReported : options.windowSeconds;
const remaining = Math.max(0, options.max - current);
return {
allowed: current <= options.max,
remaining,
resetAt: new Date(Date.now() + ttl * 1000),
};
},
async reset(key) {
await store.del(bucketKey(key));
},
};
}