forked from nathydre21/wata-board
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrateLimiter.ts
More file actions
407 lines (352 loc) · 12.4 KB
/
Copy pathrateLimiter.ts
File metadata and controls
407 lines (352 loc) · 12.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
/**
* Tiered Rate Limiter Middleware (#85)
*
* Sliding-window rate limiter that respects user tiers.
* Exposes both an Express middleware and a programmatic API
* (checkLimit / getStatus) so the monitoring service (#99)
* can query rate-limit state without consuming a slot.
*/
import { Request, Response, NextFunction } from 'express';
import { UserTier, TierRateLimitStatus, EndpointType } from '../types/userTier';
import { getRateLimitForTier, getEndpointTypeMultiplier } from '../config/rateLimits';
import { userTierService } from '../services/userTierService';
import logger from '../utils/logger';
import { getPublisher, isRedisEnabled } from '../utils/redis';
interface WindowEntry {
timestamps: number[];
queueCount: number;
}
/** Options for the rate limiter middleware */
export interface RateLimiterMiddlewareOptions {
/** Explicit endpoint type override. If omitted, auto-detected from HTTP method. */
endpointType?: EndpointType;
}
export class TieredRateLimiter {
private windows: Map<string, WindowEntry> = new Map();
private cleanupInterval: NodeJS.Timeout;
private redisEnabled: boolean;
constructor() {
this.redisEnabled = isRedisEnabled();
// Prune stale entries every 2 minutes
this.cleanupInterval = setInterval(() => this.cleanup(), 2 * 60 * 1000);
}
// ── Core logic ─────────────────────────────────────────────
/**
* Check (and consume) one request slot for a user.
* @param userId - The user identifier
* @param endpointType - Optional endpoint type for differentiated rate limits
*/
async checkLimit(userId: string, endpointType?: EndpointType): Promise<TierRateLimitStatus> {
const tier = userTierService.getUserTier(userId);
const config = getRateLimitForTier(tier);
const now = Date.now();
const windowStart = now - config.windowMs;
// Apply endpoint-type multiplier for differentiated rate limits
const multiplier = getEndpointTypeMultiplier(endpointType);
const effectiveMaxRequests = Math.floor(config.maxRequests * multiplier);
const effectiveConfig = { ...config, maxRequests: effectiveMaxRequests };
if (this.redisEnabled) {
return this.checkLimitRedis(userId, tier, effectiveConfig, now);
}
let entry = this.windows.get(userId);
if (!entry) {
entry = { timestamps: [], queueCount: 0 };
this.windows.set(userId, entry);
}
// Slide the window
entry.timestamps = entry.timestamps.filter((t) => t > windowStart);
const remaining = effectiveMaxRequests - entry.timestamps.length;
const resetTime = new Date(
entry.timestamps.length > 0
? entry.timestamps[0] + config.windowMs
: now + config.windowMs,
);
if (remaining > 0) {
entry.timestamps.push(now);
return {
tier,
allowed: true,
remainingRequests: remaining - 1,
resetTime: resetTime.toISOString(),
queued: false,
limit: effectiveMaxRequests,
};
}
// Try to queue the request
if (entry.queueCount < config.queueSize) {
entry.queueCount++;
return {
tier,
allowed: false,
remainingRequests: 0,
resetTime: resetTime.toISOString(),
queued: true,
queuePosition: entry.queueCount,
limit: effectiveMaxRequests,
};
}
// Rejected entirely
return {
tier,
allowed: false,
remainingRequests: 0,
resetTime: resetTime.toISOString(),
queued: false,
limit: effectiveMaxRequests,
};
}
/**
* Read-only status check (does NOT consume a request slot).
* @param userId - The user identifier
* @param endpointType - Optional endpoint type for differentiated rate limits
*/
async getStatus(userId: string, endpointType?: EndpointType): Promise<TierRateLimitStatus> {
const tier = userTierService.getUserTier(userId);
const config = getRateLimitForTier(tier);
const now = Date.now();
// Apply endpoint-type multiplier for differentiated rate limits
const multiplier = getEndpointTypeMultiplier(endpointType);
const effectiveMaxRequests = Math.floor(config.maxRequests * multiplier);
const effectiveConfig = { ...config, maxRequests: effectiveMaxRequests };
if (this.redisEnabled) {
return this.getStatusRedis(userId, tier, effectiveConfig, now);
}
const windowStart = now - config.windowMs;
const entry = this.windows.get(userId);
const timestamps = entry
? entry.timestamps.filter((t) => t > windowStart)
: [];
const remaining = Math.max(0, effectiveMaxRequests - timestamps.length);
const resetTime = new Date(
timestamps.length > 0
? timestamps[0] + config.windowMs
: now + config.windowMs,
);
return {
tier,
allowed: remaining > 0,
remainingRequests: remaining,
resetTime: resetTime.toISOString(),
queued: false,
limit: effectiveMaxRequests,
};
}
// ── Express middleware factory ─────────────────────────────
/**
* Create Express middleware for rate limiting.
* @param options - Optional configuration
* @param options.endpointType - Explicit endpoint type. If omitted, auto-detected
* from HTTP method: GET/HEAD/OPTIONS → READ, everything else → WRITE.
*/
middleware(options?: RateLimiterMiddlewareOptions) {
return async (req: Request, res: Response, next: NextFunction) => {
if (process.env.NODE_ENV === 'test') {
return next();
}
try {
// Auto-detect endpoint type from HTTP method if not explicitly set
const endpointType = options?.endpointType
?? ((req.method === 'GET' || req.method === 'HEAD' || req.method === 'OPTIONS')
? EndpointType.READ
: EndpointType.WRITE);
const userId =
(req.headers['x-user-id'] as string) || req.ip || 'unknown';
const status = await this.checkLimit(userId, endpointType);
const resetAtMs = Date.parse(status.resetTime);
res.set('X-RateLimit-Limit', String(status.limit));
res.set('X-RateLimit-Remaining', String(status.remainingRequests));
res.set('X-RateLimit-Reset', String(Math.ceil(resetAtMs / 1000)));
res.set('X-RateLimit-Tier', status.tier);
res.set('X-RateLimit-Type', endpointType);
if (!status.allowed && !status.queued) {
logger.warn('Rate limit exceeded', { userId, tier: status.tier, endpointType });
return res.status(429).json({
error: 'Rate limit exceeded',
tier: status.tier,
retryAfter: Math.ceil((resetAtMs - Date.now()) / 1000),
limit: status.limit,
});
}
if (status.queued) {
logger.info('Request queued', {
userId,
tier: status.tier,
position: status.queuePosition,
endpointType,
});
return res.status(202).json({
message: 'Request queued',
queuePosition: status.queuePosition,
tier: status.tier,
});
}
return next();
} catch (error) {
logger.error('Rate limiter middleware failure', { error });
return next(error);
}
};
}
// ── Helpers ────────────────────────────────────────────────
private cleanup() {
if (this.redisEnabled) {
// Redis key expiry handles cleanup in distributed mode.
return;
}
const now = Date.now();
for (const [userId, entry] of this.windows.entries()) {
entry.timestamps = entry.timestamps.filter(
(t) => t > now - 5 * 60 * 1000,
);
if (entry.timestamps.length === 0 && entry.queueCount === 0) {
this.windows.delete(userId);
}
}
}
destroy() {
clearInterval(this.cleanupInterval);
}
/** Reset in-memory rate-limit windows (for tests). */
reset(): void {
this.windows.clear();
}
private buildRedisKeys(userId: string): { requestsKey: string; queueKey: string } {
return {
requestsKey: `rl:tier:requests:${userId}`,
queueKey: `rl:tier:queue:${userId}`,
};
}
private toStatus(
tier: UserTier,
allowed: number,
remainingRequests: number,
resetTimeMs: number,
queued: number,
queuePosition: number,
limit: number,
): TierRateLimitStatus {
return {
tier,
allowed: allowed === 1,
remainingRequests,
resetTime: new Date(resetTimeMs).toISOString(),
queued: queued === 1,
queuePosition: queuePosition > 0 ? queuePosition : undefined,
limit,
};
}
private async checkLimitRedis(
userId: string,
tier: UserTier,
config: { windowMs: number; maxRequests: number; queueSize: number },
now: number,
): Promise<TierRateLimitStatus> {
const client = getPublisher();
const { requestsKey, queueKey } = this.buildRedisKeys(userId);
const member = `${now}-${Math.random().toString(36).slice(2, 10)}`;
const script = `
local requestsKey = KEYS[1]
local queueKey = KEYS[2]
local now = tonumber(ARGV[1])
local windowMs = tonumber(ARGV[2])
local maxRequests = tonumber(ARGV[3])
local queueSize = tonumber(ARGV[4])
local member = ARGV[5]
local windowStart = now - windowMs
redis.call('ZREMRANGEBYSCORE', requestsKey, '-inf', windowStart)
local count = redis.call('ZCARD', requestsKey)
if count < maxRequests then
redis.call('ZADD', requestsKey, now, member)
redis.call('PEXPIRE', requestsKey, windowMs)
local minData = redis.call('ZRANGE', requestsKey, 0, 0, 'WITHSCORES')
local reset = now + windowMs
if minData[2] then
reset = tonumber(minData[2]) + windowMs
end
local remaining = maxRequests - count - 1
return {1, remaining, reset, 0, 0, maxRequests}
end
local queueCount = redis.call('INCR', queueKey)
if queueCount == 1 then
redis.call('PEXPIRE', queueKey, windowMs)
end
local minData = redis.call('ZRANGE', requestsKey, 0, 0, 'WITHSCORES')
local reset = now + windowMs
if minData[2] then
reset = tonumber(minData[2]) + windowMs
end
if queueCount <= queueSize then
return {0, 0, reset, 1, queueCount, maxRequests}
end
redis.call('DECR', queueKey)
return {0, 0, reset, 0, 0, maxRequests}
`;
const result = (await client.eval(
script,
2,
requestsKey,
queueKey,
String(now),
String(config.windowMs),
String(config.maxRequests),
String(config.queueSize),
member,
)) as [number, number, number, number, number, number];
return this.toStatus(
tier,
Number(result[0]),
Number(result[1]),
Number(result[2]),
Number(result[3]),
Number(result[4]),
Number(result[5]),
);
}
private async getStatusRedis(
userId: string,
tier: UserTier,
config: { windowMs: number; maxRequests: number; queueSize: number },
now: number,
): Promise<TierRateLimitStatus> {
const client = getPublisher();
const { requestsKey } = this.buildRedisKeys(userId);
const script = `
local requestsKey = KEYS[1]
local now = tonumber(ARGV[1])
local windowMs = tonumber(ARGV[2])
local maxRequests = tonumber(ARGV[3])
local windowStart = now - windowMs
redis.call('ZREMRANGEBYSCORE', requestsKey, '-inf', windowStart)
local count = redis.call('ZCARD', requestsKey)
local minData = redis.call('ZRANGE', requestsKey, 0, 0, 'WITHSCORES')
local reset = now + windowMs
if minData[2] then
reset = tonumber(minData[2]) + windowMs
end
local remaining = maxRequests - count
if remaining < 0 then remaining = 0 end
local allowed = 0
if remaining > 0 then allowed = 1 end
return {allowed, remaining, reset, maxRequests}
`;
const result = (await client.eval(
script,
1,
requestsKey,
String(now),
String(config.windowMs),
String(config.maxRequests),
)) as [number, number, number, number];
return this.toStatus(
tier,
Number(result[0]),
Number(result[1]),
Number(result[2]),
0,
0,
Number(result[3]),
);
}
}
/** Singleton instance */
export const tieredRateLimiter = new TieredRateLimiter();