fix: 限流分桶按路由模式归一并统一清理过期计数

- 分桶键用路由模式(如 /health/escort-record/:id)而非真实 path,
  防止换订单 ID 绕开额度
- 计数桶统一登记、单定时器清理,windowMs 写入记录供过期判断
This commit is contained in:
lik
2026-11-08 12:00:26 +08:00
parent b0b706a1c4
commit 9a1242ffbc
2 changed files with 174 additions and 10 deletions
+52 -10
View File
@@ -10,16 +10,57 @@ import ResponseUtil from "../utils/responseUtil.js";
* 说明:单进程内存计数,多实例部署时每个实例各自计数(当前为单机部署,
* 若后续横向扩容需换成 Redis 之类的共享计数)。
*/
const store = new Map();
const cleanupInterval = 60_000;
const cleanupTimer = setInterval(() => {
const now = Date.now();
for (const [key, record] of store.entries()) {
if (now - record.resetAt > record.windowMs) store.delete(key);
// 所有计数桶统一登记,由一个定时器清理,避免为每个 limiter 各起一个 timer
const stores = new Set();
function registerStore(buckets) {
stores.add(buckets);
return buckets;
}
/**
* 清理所有过期计数(社区版只做内存回收,不影响限流语义:
* 访问时本身也会按窗口重置)
* @param {number} [now] 当前时间(测试可注入)
* @returns {number} 清理的条目数
*/
function sweepRateLimitStores(now = Date.now()) {
let removed = 0;
for (const buckets of stores) {
for (const [key, record] of buckets) {
if (now - record.resetAt > record.windowMs) {
buckets.delete(key);
removed += 1;
}
}
}
}, 60_000);
return removed;
}
const cleanupTimer = setInterval(() => sweepRateLimitStores(), cleanupInterval);
cleanupTimer.unref();
// 路径里可能带订单 ID;路由没匹配到模式时(理论上不该发生)兜底归一
const OBJECT_ID_SEGMENT = /\/[0-9a-fA-F]{24}(?=\/|$)/g;
function normalizeDynamicPath(path) {
return String(path || "").replace(OBJECT_ID_SEGMENT, "/:id");
}
/**
* 限流分桶键
*
* 用路由模式(如 /health/escort-record/:id)而不是真实 path:
* 否则同一用户在不同订单上各有一份额度,换个 ID 就能绕过限流。
*/
function resolveBucketPath(ctx) {
return ctx.routerPath || ctx._matchedRoute || normalizeDynamicPath(ctx.path);
}
const store = registerStore(new Map());
/**
* 创建限流中间件
* @param {number} max 窗口内最大请求数
@@ -28,7 +69,7 @@ cleanupTimer.unref();
function rateLimit(max, windowMs = 60_000) {
return async (ctx, next) => {
const identity = ctx.state.user?._id ? `u:${ctx.state.user._id}` : `ip:${ctx.ip}`;
const key = `${identity}:${ctx.method}:${ctx.path}`;
const key = `${identity}:${ctx.method}:${resolveBucketPath(ctx)}`;
const now = Date.now();
let record = store.get(key);
@@ -58,13 +99,14 @@ function rateLimit(max, windowMs = 60_000) {
* @returns {(identity: string) => {allowed: boolean, retryAfter: number}}
*/
function createUserLimiter(max, windowMs = 60_000) {
const buckets = new Map();
// windowMs 写进记录,供统一清理逻辑判断过期
const buckets = registerStore(new Map());
return (identity) => {
const now = Date.now();
let record = buckets.get(identity);
if (!record || now - record.resetAt > windowMs) {
record = { count: 0, resetAt: now };
record = { count: 0, resetAt: now, windowMs };
buckets.set(identity, record);
}
record.count++;
@@ -78,4 +120,4 @@ function createUserLimiter(max, windowMs = 60_000) {
};
}
export { rateLimit, createUserLimiter };
export { rateLimit, createUserLimiter, sweepRateLimitStores, normalizeDynamicPath };