mirror of
https://github.com/openclaw/openclaw.git
synced 2026-05-09 23:34:31 +00:00
refactor(acp): split session tests and share rate limiter
This commit is contained in:
48
src/infra/fixed-window-rate-limit.ts
Normal file
48
src/infra/fixed-window-rate-limit.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
export type FixedWindowRateLimiter = {
|
||||
consume: () => {
|
||||
allowed: boolean;
|
||||
retryAfterMs: number;
|
||||
remaining: number;
|
||||
};
|
||||
reset: () => void;
|
||||
};
|
||||
|
||||
export function createFixedWindowRateLimiter(params: {
|
||||
maxRequests: number;
|
||||
windowMs: number;
|
||||
now?: () => number;
|
||||
}): FixedWindowRateLimiter {
|
||||
const maxRequests = Math.max(1, Math.floor(params.maxRequests));
|
||||
const windowMs = Math.max(1, Math.floor(params.windowMs));
|
||||
const now = params.now ?? Date.now;
|
||||
|
||||
let count = 0;
|
||||
let windowStartMs = 0;
|
||||
|
||||
return {
|
||||
consume() {
|
||||
const nowMs = now();
|
||||
if (nowMs - windowStartMs >= windowMs) {
|
||||
windowStartMs = nowMs;
|
||||
count = 0;
|
||||
}
|
||||
if (count >= maxRequests) {
|
||||
return {
|
||||
allowed: false,
|
||||
retryAfterMs: Math.max(0, windowStartMs + windowMs - nowMs),
|
||||
remaining: 0,
|
||||
};
|
||||
}
|
||||
count += 1;
|
||||
return {
|
||||
allowed: true,
|
||||
retryAfterMs: 0,
|
||||
remaining: Math.max(0, maxRequests - count),
|
||||
};
|
||||
},
|
||||
reset() {
|
||||
count = 0;
|
||||
windowStartMs = 0;
|
||||
},
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user