@oxog/spark 1.1.0 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +632 -293
- package/LICENSE +20 -20
- package/README.md +288 -241
- package/package.json +83 -89
- package/src/core/application.js +1070 -956
- package/src/core/context.js +1100 -830
- package/src/core/middleware.js +305 -217
- package/src/index.js +183 -278
- package/src/middleware/body-parser.js +484 -526
- package/src/middleware/cache.js +179 -170
- package/src/middleware/compression.js +179 -182
- package/src/middleware/cors.js +178 -95
- package/src/middleware/health.js +221 -218
- package/src/middleware/logger.js +197 -194
- package/src/middleware/metrics.js +341 -327
- package/src/middleware/rate-limit.js +369 -319
- package/src/middleware/security.js +444 -332
- package/src/middleware/session.js +649 -529
- package/src/middleware/static.js +406 -299
- package/src/router/layer.js +199 -117
- package/src/router/route.js +151 -123
- package/src/router/router.js +705 -755
- package/src/utils/async-handler.js +147 -144
- package/src/utils/context-pool.js +85 -82
- package/src/utils/regex-validator.js +189 -176
- package/src/utils/safe-json.js +110 -0
- package/types/index.d.ts +536 -291
- package/dist/LICENSE +0 -21
- package/dist/README.md +0 -242
- package/dist/core/application.js +0 -957
- package/dist/core/context.js +0 -831
- package/dist/core/middleware.js +0 -218
- package/dist/core/request.js +0 -333
- package/dist/core/response.js +0 -375
- package/dist/index.js +0 -278
- package/dist/middleware/body-parser.js +0 -526
- package/dist/middleware/cache.js +0 -171
- package/dist/middleware/compression.js +0 -183
- package/dist/middleware/cors.js +0 -95
- package/dist/middleware/health.js +0 -219
- package/dist/middleware/index.js +0 -21
- package/dist/middleware/logger.js +0 -195
- package/dist/middleware/metrics.js +0 -328
- package/dist/middleware/rate-limit.js +0 -320
- package/dist/middleware/security.js +0 -333
- package/dist/middleware/session.js +0 -530
- package/dist/middleware/static.js +0 -299
- package/dist/package.json +0 -62
- package/dist/router/layer.js +0 -117
- package/dist/router/route.js +0 -123
- package/dist/router/router.js +0 -756
- package/dist/types/index.d.ts +0 -291
- package/dist/utils/async-handler.js +0 -145
- package/dist/utils/cache.js +0 -441
- package/dist/utils/context-pool.js +0 -83
- package/dist/utils/error-types.js +0 -132
- package/dist/utils/http.js +0 -413
- package/dist/utils/regex-validator.js +0 -177
- package/src/core/request.js +0 -333
- package/src/core/response.js +0 -375
- package/src/middleware/index.js +0 -21
- package/src/utils/cache.js +0 -441
- package/src/utils/error-types.js +0 -132
- package/src/utils/http.js +0 -413
|
@@ -1,328 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Metrics collection middleware for performance monitoring
|
|
3
|
-
*/
|
|
4
|
-
|
|
5
|
-
class MetricsCollector {
|
|
6
|
-
constructor() {
|
|
7
|
-
this.metrics = {
|
|
8
|
-
requests: {
|
|
9
|
-
total: 0,
|
|
10
|
-
byMethod: {},
|
|
11
|
-
byStatus: {},
|
|
12
|
-
byPath: {}
|
|
13
|
-
},
|
|
14
|
-
responseTime: {
|
|
15
|
-
total: 0,
|
|
16
|
-
count: 0,
|
|
17
|
-
min: Infinity,
|
|
18
|
-
max: 0,
|
|
19
|
-
buckets: {
|
|
20
|
-
'<100ms': 0,
|
|
21
|
-
'100-500ms': 0,
|
|
22
|
-
'500ms-1s': 0,
|
|
23
|
-
'1s-5s': 0,
|
|
24
|
-
'>5s': 0
|
|
25
|
-
}
|
|
26
|
-
},
|
|
27
|
-
errors: {
|
|
28
|
-
total: 0,
|
|
29
|
-
byType: {},
|
|
30
|
-
byStatus: {}
|
|
31
|
-
},
|
|
32
|
-
activeConnections: 0,
|
|
33
|
-
memory: {
|
|
34
|
-
samples: [],
|
|
35
|
-
maxSamples: 100
|
|
36
|
-
}
|
|
37
|
-
};
|
|
38
|
-
|
|
39
|
-
this.startTime = Date.now();
|
|
40
|
-
this.memoryInterval = null;
|
|
41
|
-
this.setupMemoryTracking();
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
setupMemoryTracking() {
|
|
45
|
-
this.memoryInterval = setInterval(() => {
|
|
46
|
-
const memUsage = process.memoryUsage();
|
|
47
|
-
this.metrics.memory.samples.push({
|
|
48
|
-
timestamp: Date.now(),
|
|
49
|
-
...memUsage
|
|
50
|
-
});
|
|
51
|
-
|
|
52
|
-
// Keep only last 100 samples
|
|
53
|
-
if (this.metrics.memory.samples.length > this.metrics.memory.maxSamples) {
|
|
54
|
-
this.metrics.memory.samples.shift();
|
|
55
|
-
}
|
|
56
|
-
}, 30000); // Every 30 seconds
|
|
57
|
-
|
|
58
|
-
// Don't keep process alive
|
|
59
|
-
this.memoryInterval.unref();
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
recordRequest(method, path, status, duration, error = null) {
|
|
63
|
-
// Total requests
|
|
64
|
-
this.metrics.requests.total++;
|
|
65
|
-
|
|
66
|
-
// By method
|
|
67
|
-
this.metrics.requests.byMethod[method] = (this.metrics.requests.byMethod[method] || 0) + 1;
|
|
68
|
-
|
|
69
|
-
// By status
|
|
70
|
-
this.metrics.requests.byStatus[status] = (this.metrics.requests.byStatus[status] || 0) + 1;
|
|
71
|
-
|
|
72
|
-
// By path (sanitized)
|
|
73
|
-
const sanitizedPath = this.sanitizePath(path);
|
|
74
|
-
this.metrics.requests.byPath[sanitizedPath] = (this.metrics.requests.byPath[sanitizedPath] || 0) + 1;
|
|
75
|
-
|
|
76
|
-
// Response time
|
|
77
|
-
this.metrics.responseTime.total += duration;
|
|
78
|
-
this.metrics.responseTime.count++;
|
|
79
|
-
this.metrics.responseTime.min = Math.min(this.metrics.responseTime.min, duration);
|
|
80
|
-
this.metrics.responseTime.max = Math.max(this.metrics.responseTime.max, duration);
|
|
81
|
-
|
|
82
|
-
// Response time buckets
|
|
83
|
-
if (duration < 100) {
|
|
84
|
-
this.metrics.responseTime.buckets['<100ms']++;
|
|
85
|
-
} else if (duration < 500) {
|
|
86
|
-
this.metrics.responseTime.buckets['100-500ms']++;
|
|
87
|
-
} else if (duration < 1000) {
|
|
88
|
-
this.metrics.responseTime.buckets['500ms-1s']++;
|
|
89
|
-
} else if (duration < 5000) {
|
|
90
|
-
this.metrics.responseTime.buckets['1s-5s']++;
|
|
91
|
-
} else {
|
|
92
|
-
this.metrics.responseTime.buckets['>5s']++;
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
// Errors
|
|
96
|
-
if (error || status >= 400) {
|
|
97
|
-
this.metrics.errors.total++;
|
|
98
|
-
this.metrics.errors.byStatus[status] = (this.metrics.errors.byStatus[status] || 0) + 1;
|
|
99
|
-
|
|
100
|
-
if (error) {
|
|
101
|
-
const errorType = error.constructor.name;
|
|
102
|
-
this.metrics.errors.byType[errorType] = (this.metrics.errors.byType[errorType] || 0) + 1;
|
|
103
|
-
}
|
|
104
|
-
}
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
sanitizePath(path) {
|
|
108
|
-
// Replace IDs and numbers with placeholders
|
|
109
|
-
return path
|
|
110
|
-
.replace(/\/\d+/g, '/:id')
|
|
111
|
-
.replace(/\/[a-f0-9]{24}/g, '/:id') // MongoDB ObjectIds
|
|
112
|
-
.replace(/\/[a-f0-9-]{36}/g, '/:uuid'); // UUIDs
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
incrementActiveConnections() {
|
|
116
|
-
this.metrics.activeConnections++;
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
decrementActiveConnections() {
|
|
120
|
-
this.metrics.activeConnections = Math.max(0, this.metrics.activeConnections - 1);
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
getMetrics() {
|
|
124
|
-
const now = Date.now();
|
|
125
|
-
const uptime = now - this.startTime;
|
|
126
|
-
|
|
127
|
-
const avgResponseTime = this.metrics.responseTime.count > 0
|
|
128
|
-
? this.metrics.responseTime.total / this.metrics.responseTime.count
|
|
129
|
-
: 0;
|
|
130
|
-
|
|
131
|
-
return {
|
|
132
|
-
timestamp: now,
|
|
133
|
-
uptime: uptime,
|
|
134
|
-
requests: {
|
|
135
|
-
...this.metrics.requests,
|
|
136
|
-
rps: this.metrics.requests.total / (uptime / 1000) // requests per second
|
|
137
|
-
},
|
|
138
|
-
responseTime: {
|
|
139
|
-
...this.metrics.responseTime,
|
|
140
|
-
average: avgResponseTime,
|
|
141
|
-
min: this.metrics.responseTime.min === Infinity ? 0 : this.metrics.responseTime.min
|
|
142
|
-
},
|
|
143
|
-
errors: {
|
|
144
|
-
...this.metrics.errors,
|
|
145
|
-
errorRate: this.metrics.requests.total > 0
|
|
146
|
-
? (this.metrics.errors.total / this.metrics.requests.total * 100).toFixed(2) + '%'
|
|
147
|
-
: '0%'
|
|
148
|
-
},
|
|
149
|
-
activeConnections: this.metrics.activeConnections,
|
|
150
|
-
memory: this.getMemoryStats()
|
|
151
|
-
};
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
getMemoryStats() {
|
|
155
|
-
if (this.metrics.memory.samples.length === 0) {
|
|
156
|
-
return { current: process.memoryUsage() };
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
const latest = this.metrics.memory.samples[this.metrics.memory.samples.length - 1];
|
|
160
|
-
const samples = this.metrics.memory.samples;
|
|
161
|
-
|
|
162
|
-
const heapUsedSamples = samples.map(s => s.heapUsed);
|
|
163
|
-
const avg = heapUsedSamples.reduce((a, b) => a + b, 0) / heapUsedSamples.length;
|
|
164
|
-
const max = Math.max(...heapUsedSamples);
|
|
165
|
-
const min = Math.min(...heapUsedSamples);
|
|
166
|
-
|
|
167
|
-
return {
|
|
168
|
-
current: {
|
|
169
|
-
heapUsed: latest.heapUsed,
|
|
170
|
-
heapTotal: latest.heapTotal,
|
|
171
|
-
external: latest.external,
|
|
172
|
-
rss: latest.rss
|
|
173
|
-
},
|
|
174
|
-
stats: {
|
|
175
|
-
average: avg,
|
|
176
|
-
max: max,
|
|
177
|
-
min: min,
|
|
178
|
-
samples: samples.length
|
|
179
|
-
}
|
|
180
|
-
};
|
|
181
|
-
}
|
|
182
|
-
|
|
183
|
-
reset() {
|
|
184
|
-
this.metrics = {
|
|
185
|
-
requests: {
|
|
186
|
-
total: 0,
|
|
187
|
-
byMethod: {},
|
|
188
|
-
byStatus: {},
|
|
189
|
-
byPath: {}
|
|
190
|
-
},
|
|
191
|
-
responseTime: {
|
|
192
|
-
total: 0,
|
|
193
|
-
count: 0,
|
|
194
|
-
min: Infinity,
|
|
195
|
-
max: 0,
|
|
196
|
-
buckets: {
|
|
197
|
-
'<100ms': 0,
|
|
198
|
-
'100-500ms': 0,
|
|
199
|
-
'500ms-1s': 0,
|
|
200
|
-
'1s-5s': 0,
|
|
201
|
-
'>5s': 0
|
|
202
|
-
}
|
|
203
|
-
},
|
|
204
|
-
errors: {
|
|
205
|
-
total: 0,
|
|
206
|
-
byType: {},
|
|
207
|
-
byStatus: {}
|
|
208
|
-
},
|
|
209
|
-
activeConnections: 0,
|
|
210
|
-
memory: {
|
|
211
|
-
samples: [],
|
|
212
|
-
maxSamples: 100
|
|
213
|
-
}
|
|
214
|
-
};
|
|
215
|
-
|
|
216
|
-
this.startTime = Date.now();
|
|
217
|
-
}
|
|
218
|
-
|
|
219
|
-
stop() {
|
|
220
|
-
if (this.memoryInterval) {
|
|
221
|
-
clearInterval(this.memoryInterval);
|
|
222
|
-
this.memoryInterval = null;
|
|
223
|
-
}
|
|
224
|
-
}
|
|
225
|
-
}
|
|
226
|
-
|
|
227
|
-
// Global metrics collector instance
|
|
228
|
-
const globalCollector = new MetricsCollector();
|
|
229
|
-
|
|
230
|
-
/**
|
|
231
|
-
* Metrics middleware
|
|
232
|
-
* @param {Object} options - Metrics options
|
|
233
|
-
* @returns {Function} Middleware function
|
|
234
|
-
*/
|
|
235
|
-
function metrics(options = {}) {
|
|
236
|
-
const opts = {
|
|
237
|
-
path: '/_metrics',
|
|
238
|
-
collectResponseTime: true,
|
|
239
|
-
collectMemory: true,
|
|
240
|
-
excludePaths: ['/favicon.ico'],
|
|
241
|
-
customCollector: null,
|
|
242
|
-
...options
|
|
243
|
-
};
|
|
244
|
-
|
|
245
|
-
const collector = opts.customCollector || globalCollector;
|
|
246
|
-
|
|
247
|
-
const middleware = async (ctx, next) => {
|
|
248
|
-
// Serve metrics endpoint
|
|
249
|
-
if (ctx.path === opts.path) {
|
|
250
|
-
if (ctx.method !== 'GET') {
|
|
251
|
-
ctx.status(405).json({ error: 'Method Not Allowed' });
|
|
252
|
-
return;
|
|
253
|
-
}
|
|
254
|
-
|
|
255
|
-
const metricsData = collector.getMetrics();
|
|
256
|
-
ctx.json(metricsData);
|
|
257
|
-
return;
|
|
258
|
-
}
|
|
259
|
-
|
|
260
|
-
// Skip excluded paths
|
|
261
|
-
if (opts.excludePaths.includes(ctx.path)) {
|
|
262
|
-
return next();
|
|
263
|
-
}
|
|
264
|
-
|
|
265
|
-
// Track active connections
|
|
266
|
-
collector.incrementActiveConnections();
|
|
267
|
-
|
|
268
|
-
const startTime = Date.now();
|
|
269
|
-
let error = null;
|
|
270
|
-
|
|
271
|
-
try {
|
|
272
|
-
await next();
|
|
273
|
-
} catch (err) {
|
|
274
|
-
error = err;
|
|
275
|
-
throw err;
|
|
276
|
-
} finally {
|
|
277
|
-
const duration = Date.now() - startTime;
|
|
278
|
-
|
|
279
|
-
// Record metrics
|
|
280
|
-
collector.recordRequest(
|
|
281
|
-
ctx.method,
|
|
282
|
-
ctx.path,
|
|
283
|
-
ctx.statusCode,
|
|
284
|
-
duration,
|
|
285
|
-
error
|
|
286
|
-
);
|
|
287
|
-
|
|
288
|
-
// Add response time header
|
|
289
|
-
if (opts.collectResponseTime) {
|
|
290
|
-
ctx.set('X-Response-Time', `${duration}ms`);
|
|
291
|
-
}
|
|
292
|
-
|
|
293
|
-
// Decrement active connections
|
|
294
|
-
collector.decrementActiveConnections();
|
|
295
|
-
}
|
|
296
|
-
};
|
|
297
|
-
|
|
298
|
-
// Add cleanup method to middleware
|
|
299
|
-
middleware.cleanup = () => {
|
|
300
|
-
collector.stop();
|
|
301
|
-
};
|
|
302
|
-
|
|
303
|
-
// Add collector access
|
|
304
|
-
middleware.collector = collector;
|
|
305
|
-
|
|
306
|
-
return middleware;
|
|
307
|
-
}
|
|
308
|
-
|
|
309
|
-
/**
|
|
310
|
-
* Create a custom metrics collector
|
|
311
|
-
* @returns {MetricsCollector} New metrics collector instance
|
|
312
|
-
*/
|
|
313
|
-
function createCollector() {
|
|
314
|
-
return new MetricsCollector();
|
|
315
|
-
}
|
|
316
|
-
|
|
317
|
-
/**
|
|
318
|
-
* Get global metrics collector
|
|
319
|
-
* @returns {MetricsCollector} Global collector instance
|
|
320
|
-
*/
|
|
321
|
-
function getGlobalCollector() {
|
|
322
|
-
return globalCollector;
|
|
323
|
-
}
|
|
324
|
-
|
|
325
|
-
module.exports = metrics;
|
|
326
|
-
module.exports.createCollector = createCollector;
|
|
327
|
-
module.exports.getGlobalCollector = getGlobalCollector;
|
|
328
|
-
module.exports.MetricsCollector = MetricsCollector;
|
|
@@ -1,320 +0,0 @@
|
|
|
1
|
-
const DEFAULT_WINDOW_MS = 15 * 60 * 1000; // 15 minutes
|
|
2
|
-
const DEFAULT_MAX_REQUESTS = 100;
|
|
3
|
-
const DEFAULT_MESSAGE = 'Too many requests, please try again later.';
|
|
4
|
-
|
|
5
|
-
class MemoryStore {
|
|
6
|
-
constructor() {
|
|
7
|
-
this.store = new Map();
|
|
8
|
-
this.resetTimes = new Map();
|
|
9
|
-
}
|
|
10
|
-
|
|
11
|
-
async incr(key, windowMs) {
|
|
12
|
-
const now = Date.now();
|
|
13
|
-
const resetTime = this.resetTimes.get(key) || now;
|
|
14
|
-
|
|
15
|
-
if (now > resetTime) {
|
|
16
|
-
this.store.set(key, 1);
|
|
17
|
-
this.resetTimes.set(key, now + windowMs);
|
|
18
|
-
return { totalHits: 1, resetTime: now + windowMs };
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
const current = this.store.get(key) || 0;
|
|
22
|
-
const newCount = current + 1;
|
|
23
|
-
this.store.set(key, newCount);
|
|
24
|
-
|
|
25
|
-
return { totalHits: newCount, resetTime };
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
async decrement(key) {
|
|
29
|
-
const current = this.store.get(key) || 0;
|
|
30
|
-
if (current > 0) {
|
|
31
|
-
this.store.set(key, current - 1);
|
|
32
|
-
}
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
async reset(key) {
|
|
36
|
-
this.store.delete(key);
|
|
37
|
-
this.resetTimes.delete(key);
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
cleanup() {
|
|
41
|
-
const now = Date.now();
|
|
42
|
-
for (const [key, resetTime] of this.resetTimes) {
|
|
43
|
-
if (now > resetTime) {
|
|
44
|
-
this.store.delete(key);
|
|
45
|
-
this.resetTimes.delete(key);
|
|
46
|
-
}
|
|
47
|
-
}
|
|
48
|
-
}
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
function rateLimit(options = {}) {
|
|
52
|
-
const opts = {
|
|
53
|
-
windowMs: options.windowMs || DEFAULT_WINDOW_MS,
|
|
54
|
-
max: options.max || DEFAULT_MAX_REQUESTS,
|
|
55
|
-
message: options.message || DEFAULT_MESSAGE,
|
|
56
|
-
statusCode: options.statusCode || 429,
|
|
57
|
-
headers: options.headers !== false,
|
|
58
|
-
keyGenerator: options.keyGenerator || defaultKeyGenerator,
|
|
59
|
-
handler: options.handler || defaultHandler,
|
|
60
|
-
onLimitReached: options.onLimitReached,
|
|
61
|
-
skipSuccessfulRequests: options.skipSuccessfulRequests || false,
|
|
62
|
-
skipFailedRequests: options.skipFailedRequests || false,
|
|
63
|
-
store: options.store || new MemoryStore(),
|
|
64
|
-
...options
|
|
65
|
-
};
|
|
66
|
-
|
|
67
|
-
// Start cleanup interval
|
|
68
|
-
let cleanupInterval;
|
|
69
|
-
if (opts.store.cleanup) {
|
|
70
|
-
// Use smaller interval for cleanup (1/4 of window)
|
|
71
|
-
const cleanupPeriod = Math.max(60000, Math.floor(opts.windowMs / 4));
|
|
72
|
-
cleanupInterval = setInterval(() => {
|
|
73
|
-
opts.store.cleanup();
|
|
74
|
-
}, cleanupPeriod);
|
|
75
|
-
|
|
76
|
-
// Allow cleanup interval to be stopped when server shuts down
|
|
77
|
-
if (cleanupInterval.unref) {
|
|
78
|
-
cleanupInterval.unref();
|
|
79
|
-
}
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
const middleware = async (ctx, next) => {
|
|
83
|
-
const key = opts.keyGenerator(ctx);
|
|
84
|
-
const { totalHits, resetTime } = await opts.store.incr(key, opts.windowMs);
|
|
85
|
-
|
|
86
|
-
if (opts.headers) {
|
|
87
|
-
ctx.set('X-RateLimit-Limit', opts.max);
|
|
88
|
-
ctx.set('X-RateLimit-Remaining', Math.max(0, opts.max - totalHits));
|
|
89
|
-
ctx.set('X-RateLimit-Reset', new Date(resetTime).toISOString());
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
if (totalHits <= opts.max) {
|
|
93
|
-
await next();
|
|
94
|
-
|
|
95
|
-
if (opts.skipSuccessfulRequests && ctx.statusCode >= 200 && ctx.statusCode < 300) {
|
|
96
|
-
await opts.store.decrement(key);
|
|
97
|
-
}
|
|
98
|
-
} else {
|
|
99
|
-
if (opts.onLimitReached) {
|
|
100
|
-
opts.onLimitReached(ctx, opts);
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
return opts.handler(ctx, opts);
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
if (opts.skipFailedRequests && ctx.statusCode >= 400) {
|
|
107
|
-
await opts.store.decrement(key);
|
|
108
|
-
}
|
|
109
|
-
};
|
|
110
|
-
|
|
111
|
-
// Attach cleanup method to middleware for manual cleanup
|
|
112
|
-
middleware.cleanup = () => {
|
|
113
|
-
if (cleanupInterval) {
|
|
114
|
-
clearInterval(cleanupInterval);
|
|
115
|
-
cleanupInterval = null;
|
|
116
|
-
}
|
|
117
|
-
if (opts.store.cleanup) {
|
|
118
|
-
opts.store.cleanup();
|
|
119
|
-
}
|
|
120
|
-
};
|
|
121
|
-
|
|
122
|
-
// Attach store for external access if needed
|
|
123
|
-
middleware.store = opts.store;
|
|
124
|
-
|
|
125
|
-
return middleware;
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
function defaultKeyGenerator(ctx) {
|
|
129
|
-
return ctx.ip();
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
function defaultHandler(ctx, opts) {
|
|
133
|
-
ctx.set('Retry-After', Math.round(opts.windowMs / 1000));
|
|
134
|
-
ctx.status(opts.statusCode).json({
|
|
135
|
-
error: 'Too Many Requests',
|
|
136
|
-
message: opts.message
|
|
137
|
-
});
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
function slowDown(options = {}) {
|
|
141
|
-
const opts = {
|
|
142
|
-
windowMs: options.windowMs || DEFAULT_WINDOW_MS,
|
|
143
|
-
delayAfter: options.delayAfter || 1,
|
|
144
|
-
delayMs: options.delayMs || 1000,
|
|
145
|
-
maxDelayMs: options.maxDelayMs || 60000,
|
|
146
|
-
skipSuccessfulRequests: options.skipSuccessfulRequests || false,
|
|
147
|
-
skipFailedRequests: options.skipFailedRequests || false,
|
|
148
|
-
keyGenerator: options.keyGenerator || defaultKeyGenerator,
|
|
149
|
-
store: options.store || new MemoryStore(),
|
|
150
|
-
...options
|
|
151
|
-
};
|
|
152
|
-
|
|
153
|
-
// Start cleanup interval for slowDown store
|
|
154
|
-
let cleanupInterval;
|
|
155
|
-
if (opts.store.cleanup) {
|
|
156
|
-
const cleanupPeriod = Math.max(60000, Math.floor(opts.windowMs / 4));
|
|
157
|
-
cleanupInterval = setInterval(() => {
|
|
158
|
-
opts.store.cleanup();
|
|
159
|
-
}, cleanupPeriod);
|
|
160
|
-
|
|
161
|
-
if (cleanupInterval.unref) {
|
|
162
|
-
cleanupInterval.unref();
|
|
163
|
-
}
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
const middleware = async (ctx, next) => {
|
|
167
|
-
const key = opts.keyGenerator(ctx);
|
|
168
|
-
const { totalHits } = await opts.store.incr(key, opts.windowMs);
|
|
169
|
-
|
|
170
|
-
if (totalHits > opts.delayAfter) {
|
|
171
|
-
const delay = Math.min(
|
|
172
|
-
(totalHits - opts.delayAfter) * opts.delayMs,
|
|
173
|
-
opts.maxDelayMs
|
|
174
|
-
);
|
|
175
|
-
|
|
176
|
-
await new Promise(resolve => setTimeout(resolve, delay));
|
|
177
|
-
}
|
|
178
|
-
|
|
179
|
-
await next();
|
|
180
|
-
|
|
181
|
-
if (opts.skipSuccessfulRequests && ctx.statusCode >= 200 && ctx.statusCode < 300) {
|
|
182
|
-
await opts.store.decrement(key);
|
|
183
|
-
}
|
|
184
|
-
|
|
185
|
-
if (opts.skipFailedRequests && ctx.statusCode >= 400) {
|
|
186
|
-
await opts.store.decrement(key);
|
|
187
|
-
}
|
|
188
|
-
};
|
|
189
|
-
|
|
190
|
-
// Attach cleanup method
|
|
191
|
-
middleware.cleanup = () => {
|
|
192
|
-
if (cleanupInterval) {
|
|
193
|
-
clearInterval(cleanupInterval);
|
|
194
|
-
cleanupInterval = null;
|
|
195
|
-
}
|
|
196
|
-
if (opts.store.cleanup) {
|
|
197
|
-
opts.store.cleanup();
|
|
198
|
-
}
|
|
199
|
-
};
|
|
200
|
-
|
|
201
|
-
middleware.store = opts.store;
|
|
202
|
-
|
|
203
|
-
return middleware;
|
|
204
|
-
}
|
|
205
|
-
|
|
206
|
-
class TokenBucket {
|
|
207
|
-
constructor(capacity, refillRate, refillPeriod = 1000) {
|
|
208
|
-
this.capacity = capacity;
|
|
209
|
-
this.tokens = capacity;
|
|
210
|
-
this.refillRate = refillRate;
|
|
211
|
-
this.refillPeriod = refillPeriod;
|
|
212
|
-
this.lastRefill = Date.now();
|
|
213
|
-
}
|
|
214
|
-
|
|
215
|
-
consume(tokens = 1) {
|
|
216
|
-
this.refill();
|
|
217
|
-
|
|
218
|
-
if (this.tokens >= tokens) {
|
|
219
|
-
this.tokens -= tokens;
|
|
220
|
-
return true;
|
|
221
|
-
}
|
|
222
|
-
|
|
223
|
-
return false;
|
|
224
|
-
}
|
|
225
|
-
|
|
226
|
-
refill() {
|
|
227
|
-
const now = Date.now();
|
|
228
|
-
const timePassed = now - this.lastRefill;
|
|
229
|
-
const tokensToAdd = Math.floor(timePassed / this.refillPeriod * this.refillRate);
|
|
230
|
-
|
|
231
|
-
if (tokensToAdd > 0) {
|
|
232
|
-
this.tokens = Math.min(this.capacity, this.tokens + tokensToAdd);
|
|
233
|
-
this.lastRefill = now;
|
|
234
|
-
}
|
|
235
|
-
}
|
|
236
|
-
}
|
|
237
|
-
|
|
238
|
-
function tokenBucket(options = {}) {
|
|
239
|
-
const opts = {
|
|
240
|
-
capacity: options.capacity || 10,
|
|
241
|
-
refillRate: options.refillRate || 1,
|
|
242
|
-
refillPeriod: options.refillPeriod || 1000,
|
|
243
|
-
keyGenerator: options.keyGenerator || defaultKeyGenerator,
|
|
244
|
-
message: options.message || DEFAULT_MESSAGE,
|
|
245
|
-
statusCode: options.statusCode || 429,
|
|
246
|
-
cleanupPeriod: options.cleanupPeriod || 300000, // 5 minutes
|
|
247
|
-
maxBuckets: options.maxBuckets || 10000, // Maximum number of buckets to prevent memory leak
|
|
248
|
-
...options
|
|
249
|
-
};
|
|
250
|
-
|
|
251
|
-
const buckets = new Map();
|
|
252
|
-
const lastActivity = new Map();
|
|
253
|
-
|
|
254
|
-
// Cleanup old buckets
|
|
255
|
-
const cleanupInterval = setInterval(() => {
|
|
256
|
-
const now = Date.now();
|
|
257
|
-
const keysToDelete = [];
|
|
258
|
-
|
|
259
|
-
for (const [key, timestamp] of lastActivity) {
|
|
260
|
-
if (now - timestamp > opts.cleanupPeriod) {
|
|
261
|
-
keysToDelete.push(key);
|
|
262
|
-
}
|
|
263
|
-
}
|
|
264
|
-
|
|
265
|
-
for (const key of keysToDelete) {
|
|
266
|
-
buckets.delete(key);
|
|
267
|
-
lastActivity.delete(key);
|
|
268
|
-
}
|
|
269
|
-
}, Math.max(60000, opts.cleanupPeriod / 4));
|
|
270
|
-
|
|
271
|
-
if (cleanupInterval.unref) {
|
|
272
|
-
cleanupInterval.unref();
|
|
273
|
-
}
|
|
274
|
-
|
|
275
|
-
const middleware = async (ctx, next) => {
|
|
276
|
-
const key = opts.keyGenerator(ctx);
|
|
277
|
-
|
|
278
|
-
// Prevent unlimited growth
|
|
279
|
-
if (!buckets.has(key) && buckets.size >= opts.maxBuckets) {
|
|
280
|
-
// Remove oldest bucket
|
|
281
|
-
const oldestKey = lastActivity.entries().next().value?.[0];
|
|
282
|
-
if (oldestKey) {
|
|
283
|
-
buckets.delete(oldestKey);
|
|
284
|
-
lastActivity.delete(oldestKey);
|
|
285
|
-
}
|
|
286
|
-
}
|
|
287
|
-
|
|
288
|
-
if (!buckets.has(key)) {
|
|
289
|
-
buckets.set(key, new TokenBucket(opts.capacity, opts.refillRate, opts.refillPeriod));
|
|
290
|
-
}
|
|
291
|
-
|
|
292
|
-
const bucket = buckets.get(key);
|
|
293
|
-
lastActivity.set(key, Date.now());
|
|
294
|
-
|
|
295
|
-
if (bucket.consume()) {
|
|
296
|
-
await next();
|
|
297
|
-
} else {
|
|
298
|
-
ctx.status(opts.statusCode).json({
|
|
299
|
-
error: 'Too Many Requests',
|
|
300
|
-
message: opts.message
|
|
301
|
-
});
|
|
302
|
-
}
|
|
303
|
-
};
|
|
304
|
-
|
|
305
|
-
// Attach cleanup method
|
|
306
|
-
middleware.cleanup = () => {
|
|
307
|
-
if (cleanupInterval) {
|
|
308
|
-
clearInterval(cleanupInterval);
|
|
309
|
-
}
|
|
310
|
-
buckets.clear();
|
|
311
|
-
lastActivity.clear();
|
|
312
|
-
};
|
|
313
|
-
|
|
314
|
-
return middleware;
|
|
315
|
-
}
|
|
316
|
-
|
|
317
|
-
module.exports = rateLimit;
|
|
318
|
-
module.exports.slowDown = slowDown;
|
|
319
|
-
module.exports.tokenBucket = tokenBucket;
|
|
320
|
-
module.exports.MemoryStore = MemoryStore;
|