Files
lik 9a1242ffbc fix: 限流分桶按路由模式归一并统一清理过期计数
- 分桶键用路由模式(如 /health/escort-record/:id)而非真实 path,
  防止换订单 ID 绕开额度
- 计数桶统一登记、单定时器清理,windowMs 写入记录供过期判断
2026-11-08 12:00:26 +08:00

124 lines
4.0 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import ResponseUtil from "../utils/responseUtil.js";
/**
* 进程内速率限制(health 服务的写接口)
*
* 与 user 服务的限流同构,但有两点差异:
* - 键优先用登录 token(已通过 requireAuth),避免多个用户共用同一 NAT 出口 IP 时互相挤占;
* - 无 token 时回退到 IP,保证匿名请求也受限。
*
* 说明:单进程内存计数,多实例部署时每个实例各自计数(当前为单机部署,
* 若后续横向扩容需换成 Redis 之类的共享计数)。
*/
const cleanupInterval = 60_000;
// 所有计数桶统一登记,由一个定时器清理,避免为每个 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;
}
}
}
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 窗口内最大请求数
* @param {number} windowMs 窗口时长(毫秒)
*/
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}:${resolveBucketPath(ctx)}`;
const now = Date.now();
let record = store.get(key);
if (!record || now - record.resetAt > windowMs) {
record = { count: 0, resetAt: now, windowMs };
store.set(key, record);
}
record.count++;
if (record.count > max) {
const retryAfter = Math.ceil((record.resetAt + windowMs - now) / 1000);
ctx.set("Retry-After", String(retryAfter));
return ResponseUtil.error(ctx, "操作过于频繁,请稍后再试", null, 429);
}
ctx.set("X-RateLimit-Limit", String(max));
ctx.set("X-RateLimit-Remaining", String(Math.max(0, max - record.count)));
await next();
};
}
/**
* 按用户维度的限流(供 WebSocket 等无 ctx 的场景复用)
* @param {string} identity 身份键(通常是 userId)
* @param {number} max 窗口内最大次数
* @param {number} windowMs 窗口时长(毫秒)
* @returns {(identity: string) => {allowed: boolean, retryAfter: number}}
*/
function createUserLimiter(max, windowMs = 60_000) {
// 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, windowMs };
buckets.set(identity, record);
}
record.count++;
if (record.count > max) {
return {
allowed: false,
retryAfter: Math.ceil((record.resetAt + windowMs - now) / 1000),
};
}
return { allowed: true, retryAfter: 0 };
};
}
export { rateLimit, createUserLimiter, sweepRateLimitStores, normalizeDynamicPath };