@oxog/spark 1.1.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 +294 -0
- package/LICENSE +21 -0
- package/README.md +242 -0
- package/dist/LICENSE +21 -0
- package/dist/README.md +242 -0
- package/dist/core/application.js +957 -0
- package/dist/core/context.js +831 -0
- package/dist/core/middleware.js +218 -0
- package/dist/core/request.js +333 -0
- package/dist/core/response.js +375 -0
- package/dist/index.js +278 -0
- package/dist/middleware/body-parser.js +526 -0
- package/dist/middleware/cache.js +171 -0
- package/dist/middleware/compression.js +183 -0
- package/dist/middleware/cors.js +95 -0
- package/dist/middleware/health.js +219 -0
- package/dist/middleware/index.js +21 -0
- package/dist/middleware/logger.js +195 -0
- package/dist/middleware/metrics.js +328 -0
- package/dist/middleware/rate-limit.js +320 -0
- package/dist/middleware/security.js +333 -0
- package/dist/middleware/session.js +530 -0
- package/dist/middleware/static.js +299 -0
- package/dist/package.json +62 -0
- package/dist/router/layer.js +117 -0
- package/dist/router/route.js +123 -0
- package/dist/router/router.js +756 -0
- package/dist/types/index.d.ts +291 -0
- package/dist/utils/async-handler.js +145 -0
- package/dist/utils/cache.js +441 -0
- package/dist/utils/context-pool.js +83 -0
- package/dist/utils/error-types.js +132 -0
- package/dist/utils/http.js +413 -0
- package/dist/utils/regex-validator.js +177 -0
- package/package.json +89 -0
- package/src/core/application.js +957 -0
- package/src/core/context.js +831 -0
- package/src/core/middleware.js +218 -0
- package/src/core/request.js +333 -0
- package/src/core/response.js +375 -0
- package/src/index.js +278 -0
- package/src/middleware/body-parser.js +526 -0
- package/src/middleware/cache.js +171 -0
- package/src/middleware/compression.js +183 -0
- package/src/middleware/cors.js +95 -0
- package/src/middleware/health.js +219 -0
- package/src/middleware/index.js +21 -0
- package/src/middleware/logger.js +195 -0
- package/src/middleware/metrics.js +328 -0
- package/src/middleware/rate-limit.js +320 -0
- package/src/middleware/security.js +333 -0
- package/src/middleware/session.js +530 -0
- package/src/middleware/static.js +299 -0
- package/src/router/layer.js +117 -0
- package/src/router/route.js +123 -0
- package/src/router/router.js +756 -0
- package/src/utils/async-handler.js +145 -0
- package/src/utils/cache.js +441 -0
- package/src/utils/context-pool.js +83 -0
- package/src/utils/error-types.js +132 -0
- package/src/utils/http.js +413 -0
- package/src/utils/regex-validator.js +177 -0
- package/types/index.d.ts +291 -0
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Wraps async route handlers to properly catch errors
|
|
3
|
+
* @param {Function} fn - Async function to wrap
|
|
4
|
+
* @returns {Function} Wrapped function that catches errors
|
|
5
|
+
*/
|
|
6
|
+
function asyncHandler(fn) {
|
|
7
|
+
return (ctx, next) => {
|
|
8
|
+
const result = fn(ctx, next);
|
|
9
|
+
|
|
10
|
+
// If it's a promise, catch any errors
|
|
11
|
+
if (result && typeof result.then === 'function') {
|
|
12
|
+
return result.catch((error) => {
|
|
13
|
+
// Pass error to the next middleware
|
|
14
|
+
return next(error);
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
return result;
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Wraps all methods of a router or controller
|
|
24
|
+
* @param {Object} target - Object with methods to wrap
|
|
25
|
+
* @returns {Object} Object with wrapped methods
|
|
26
|
+
*/
|
|
27
|
+
function wrapAsync(target) {
|
|
28
|
+
const wrapped = {};
|
|
29
|
+
|
|
30
|
+
for (const key in target) {
|
|
31
|
+
if (typeof target[key] === 'function') {
|
|
32
|
+
wrapped[key] = asyncHandler(target[key]);
|
|
33
|
+
} else {
|
|
34
|
+
wrapped[key] = target[key];
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
return wrapped;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Error handler middleware that can work as both regular middleware and error handler
|
|
43
|
+
* @param {Error|Context} errOrCtx - Error object or Context (when used as regular middleware)
|
|
44
|
+
* @param {Context|Function} ctxOrNext - Context or next function
|
|
45
|
+
* @param {Function} [next] - Next middleware function
|
|
46
|
+
*/
|
|
47
|
+
function errorHandler(errOrCtx, ctxOrNext, next) {
|
|
48
|
+
// Check if this is being used as error handler (3 args) or regular middleware (2 args)
|
|
49
|
+
if (next && typeof next === 'function') {
|
|
50
|
+
// This is an error handler (err, ctx, next)
|
|
51
|
+
const err = errOrCtx;
|
|
52
|
+
const ctx = ctxOrNext;
|
|
53
|
+
|
|
54
|
+
// Skip if response already sent
|
|
55
|
+
if (ctx.responded) {
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// Log error for debugging
|
|
60
|
+
console.error('Error handler caught:', err);
|
|
61
|
+
|
|
62
|
+
// Set status code
|
|
63
|
+
const status = err.status || err.statusCode || 500;
|
|
64
|
+
ctx.status(status);
|
|
65
|
+
|
|
66
|
+
handleErrorResponse(err, ctx, status);
|
|
67
|
+
} else {
|
|
68
|
+
// This is regular middleware (ctx, next)
|
|
69
|
+
const ctx = errOrCtx;
|
|
70
|
+
const nextFn = ctxOrNext;
|
|
71
|
+
|
|
72
|
+
// Just pass through - this shouldn't normally happen
|
|
73
|
+
return nextFn();
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function handleErrorResponse(err, ctx, status) {
|
|
78
|
+
// Prepare error response
|
|
79
|
+
const isDevelopment = process.env.NODE_ENV !== 'production';
|
|
80
|
+
const errorResponse = {
|
|
81
|
+
error: err.message || 'Internal Server Error',
|
|
82
|
+
status: status
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
// Add stack trace in development
|
|
86
|
+
if (isDevelopment) {
|
|
87
|
+
errorResponse.stack = err.stack;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// Add any additional error properties
|
|
91
|
+
if (err.code) {
|
|
92
|
+
errorResponse.code = err.code;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
if (err.details) {
|
|
96
|
+
errorResponse.details = err.details;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// Send error response
|
|
100
|
+
ctx.json(errorResponse);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Creates a custom error with status code
|
|
105
|
+
* @param {string} message - Error message
|
|
106
|
+
* @param {number} status - HTTP status code
|
|
107
|
+
* @param {string} code - Error code
|
|
108
|
+
* @returns {Error} Custom error object
|
|
109
|
+
*/
|
|
110
|
+
function createError(message, status = 500, code = null) {
|
|
111
|
+
const error = new Error(message);
|
|
112
|
+
error.status = status;
|
|
113
|
+
if (code) {
|
|
114
|
+
error.code = code;
|
|
115
|
+
}
|
|
116
|
+
return error;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Common HTTP errors
|
|
121
|
+
*/
|
|
122
|
+
const errors = {
|
|
123
|
+
badRequest: (message = 'Bad Request') => createError(message, 400, 'BAD_REQUEST'),
|
|
124
|
+
unauthorized: (message = 'Unauthorized') => createError(message, 401, 'UNAUTHORIZED'),
|
|
125
|
+
forbidden: (message = 'Forbidden') => createError(message, 403, 'FORBIDDEN'),
|
|
126
|
+
notFound: (message = 'Not Found') => createError(message, 404, 'NOT_FOUND'),
|
|
127
|
+
methodNotAllowed: (message = 'Method Not Allowed') => createError(message, 405, 'METHOD_NOT_ALLOWED'),
|
|
128
|
+
conflict: (message = 'Conflict') => createError(message, 409, 'CONFLICT'),
|
|
129
|
+
gone: (message = 'Gone') => createError(message, 410, 'GONE'),
|
|
130
|
+
unprocessableEntity: (message = 'Unprocessable Entity') => createError(message, 422, 'UNPROCESSABLE_ENTITY'),
|
|
131
|
+
tooManyRequests: (message = 'Too Many Requests') => createError(message, 429, 'TOO_MANY_REQUESTS'),
|
|
132
|
+
internalServerError: (message = 'Internal Server Error') => createError(message, 500, 'INTERNAL_SERVER_ERROR'),
|
|
133
|
+
notImplemented: (message = 'Not Implemented') => createError(message, 501, 'NOT_IMPLEMENTED'),
|
|
134
|
+
badGateway: (message = 'Bad Gateway') => createError(message, 502, 'BAD_GATEWAY'),
|
|
135
|
+
serviceUnavailable: (message = 'Service Unavailable') => createError(message, 503, 'SERVICE_UNAVAILABLE'),
|
|
136
|
+
gatewayTimeout: (message = 'Gateway Timeout') => createError(message, 504, 'GATEWAY_TIMEOUT')
|
|
137
|
+
};
|
|
138
|
+
|
|
139
|
+
module.exports = {
|
|
140
|
+
asyncHandler,
|
|
141
|
+
wrapAsync,
|
|
142
|
+
errorHandler,
|
|
143
|
+
createError,
|
|
144
|
+
errors
|
|
145
|
+
};
|
|
@@ -0,0 +1,441 @@
|
|
|
1
|
+
const { EventEmitter } = require('events');
|
|
2
|
+
|
|
3
|
+
const DEFAULT_TTL = 300000; // 5 minutes
|
|
4
|
+
const DEFAULT_MAX_SIZE = 1000;
|
|
5
|
+
|
|
6
|
+
class MemoryCache extends EventEmitter {
|
|
7
|
+
constructor(options = {}) {
|
|
8
|
+
super();
|
|
9
|
+
this.options = {
|
|
10
|
+
ttl: options.ttl || DEFAULT_TTL,
|
|
11
|
+
maxSize: options.maxSize || DEFAULT_MAX_SIZE,
|
|
12
|
+
checkPeriod: options.checkPeriod || 60000, // 1 minute
|
|
13
|
+
maxEventListeners: options.maxEventListeners || 100,
|
|
14
|
+
...options
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
// Set max event listeners to prevent warning
|
|
18
|
+
this.setMaxListeners(this.options.maxEventListeners);
|
|
19
|
+
|
|
20
|
+
this.cache = new Map();
|
|
21
|
+
this.timers = new Map();
|
|
22
|
+
this.stats = {
|
|
23
|
+
hits: 0,
|
|
24
|
+
misses: 0,
|
|
25
|
+
keys: 0,
|
|
26
|
+
ksize: 0,
|
|
27
|
+
vsize: 0
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
this.cleanupInterval = null;
|
|
31
|
+
this.startCleanup();
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
get(key) {
|
|
35
|
+
const entry = this.cache.get(key);
|
|
36
|
+
|
|
37
|
+
if (!entry) {
|
|
38
|
+
this.stats.misses++;
|
|
39
|
+
return undefined;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
if (Date.now() > entry.expires) {
|
|
43
|
+
this.del(key);
|
|
44
|
+
this.stats.misses++;
|
|
45
|
+
return undefined;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
this.stats.hits++;
|
|
49
|
+
entry.accessed = Date.now();
|
|
50
|
+
return entry.value;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
set(key, value, ttl) {
|
|
54
|
+
const expiresAt = Date.now() + (ttl || this.options.ttl);
|
|
55
|
+
|
|
56
|
+
if (this.cache.has(key)) {
|
|
57
|
+
this.del(key);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
if (this.cache.size >= this.options.maxSize) {
|
|
61
|
+
this.evictLRU();
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const entry = {
|
|
65
|
+
value,
|
|
66
|
+
expires: expiresAt,
|
|
67
|
+
created: Date.now(),
|
|
68
|
+
accessed: Date.now()
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
this.cache.set(key, entry);
|
|
72
|
+
this.stats.keys++;
|
|
73
|
+
this.stats.ksize += key.length;
|
|
74
|
+
this.stats.vsize += this.getSize(value);
|
|
75
|
+
|
|
76
|
+
this.scheduleExpiration(key, expiresAt);
|
|
77
|
+
this.emit('set', key, value);
|
|
78
|
+
|
|
79
|
+
return true;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
del(key) {
|
|
83
|
+
const entry = this.cache.get(key);
|
|
84
|
+
|
|
85
|
+
if (!entry) {
|
|
86
|
+
return false;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
this.cache.delete(key);
|
|
90
|
+
this.stats.keys--;
|
|
91
|
+
this.stats.ksize -= key.length;
|
|
92
|
+
this.stats.vsize -= this.getSize(entry.value);
|
|
93
|
+
|
|
94
|
+
if (this.timers.has(key)) {
|
|
95
|
+
clearTimeout(this.timers.get(key));
|
|
96
|
+
this.timers.delete(key);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
this.emit('del', key);
|
|
100
|
+
return true;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
has(key) {
|
|
104
|
+
const entry = this.cache.get(key);
|
|
105
|
+
|
|
106
|
+
if (!entry) {
|
|
107
|
+
return false;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
if (Date.now() > entry.expires) {
|
|
111
|
+
this.del(key);
|
|
112
|
+
return false;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
return true;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
clear() {
|
|
119
|
+
for (const timer of this.timers.values()) {
|
|
120
|
+
clearTimeout(timer);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
this.cache.clear();
|
|
124
|
+
this.timers.clear();
|
|
125
|
+
this.stats = {
|
|
126
|
+
hits: 0,
|
|
127
|
+
misses: 0,
|
|
128
|
+
keys: 0,
|
|
129
|
+
ksize: 0,
|
|
130
|
+
vsize: 0
|
|
131
|
+
};
|
|
132
|
+
|
|
133
|
+
this.emit('flush');
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
keys() {
|
|
137
|
+
const keys = [];
|
|
138
|
+
const now = Date.now();
|
|
139
|
+
|
|
140
|
+
for (const [key, entry] of this.cache) {
|
|
141
|
+
if (now <= entry.expires) {
|
|
142
|
+
keys.push(key);
|
|
143
|
+
} else {
|
|
144
|
+
this.del(key);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
return keys;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
values() {
|
|
152
|
+
const values = [];
|
|
153
|
+
const now = Date.now();
|
|
154
|
+
|
|
155
|
+
for (const [key, entry] of this.cache) {
|
|
156
|
+
if (now <= entry.expires) {
|
|
157
|
+
values.push(entry.value);
|
|
158
|
+
} else {
|
|
159
|
+
this.del(key);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
return values;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
entries() {
|
|
167
|
+
const entries = [];
|
|
168
|
+
const now = Date.now();
|
|
169
|
+
|
|
170
|
+
for (const [key, entry] of this.cache) {
|
|
171
|
+
if (now <= entry.expires) {
|
|
172
|
+
entries.push([key, entry.value]);
|
|
173
|
+
} else {
|
|
174
|
+
this.del(key);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
return entries;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
size() {
|
|
182
|
+
return this.cache.size;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
getStats() {
|
|
186
|
+
return {
|
|
187
|
+
...this.stats,
|
|
188
|
+
hitRate: this.stats.hits / (this.stats.hits + this.stats.misses) || 0,
|
|
189
|
+
memoryUsage: this.stats.ksize + this.stats.vsize
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
getTTL(key) {
|
|
194
|
+
const entry = this.cache.get(key);
|
|
195
|
+
|
|
196
|
+
if (!entry) {
|
|
197
|
+
return -1;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
const remaining = entry.expires - Date.now();
|
|
201
|
+
return remaining > 0 ? remaining : -1;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
touch(key, ttl) {
|
|
205
|
+
const entry = this.cache.get(key);
|
|
206
|
+
|
|
207
|
+
if (!entry) {
|
|
208
|
+
return false;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
const newExpires = Date.now() + (ttl || this.options.ttl);
|
|
212
|
+
entry.expires = newExpires;
|
|
213
|
+
entry.accessed = Date.now();
|
|
214
|
+
|
|
215
|
+
this.scheduleExpiration(key, newExpires);
|
|
216
|
+
return true;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
scheduleExpiration(key, expiresAt) {
|
|
220
|
+
if (this.timers.has(key)) {
|
|
221
|
+
clearTimeout(this.timers.get(key));
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
const delay = expiresAt - Date.now();
|
|
225
|
+
|
|
226
|
+
// Only set timer if delay is positive and reasonable
|
|
227
|
+
if (delay > 0 && delay < 2147483647) { // Max 32-bit signed integer for setTimeout
|
|
228
|
+
const timeout = setTimeout(() => {
|
|
229
|
+
this.del(key);
|
|
230
|
+
}, delay);
|
|
231
|
+
|
|
232
|
+
// Allow timer to be garbage collected if process exits
|
|
233
|
+
if (timeout.unref) {
|
|
234
|
+
timeout.unref();
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
this.timers.set(key, timeout);
|
|
238
|
+
} else if (delay <= 0) {
|
|
239
|
+
// If already expired, delete immediately
|
|
240
|
+
setImmediate(() => this.del(key));
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
evictLRU() {
|
|
245
|
+
let oldestKey = null;
|
|
246
|
+
let oldestTime = Infinity;
|
|
247
|
+
|
|
248
|
+
for (const [key, entry] of this.cache) {
|
|
249
|
+
if (entry.accessed < oldestTime) {
|
|
250
|
+
oldestTime = entry.accessed;
|
|
251
|
+
oldestKey = key;
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
if (oldestKey) {
|
|
256
|
+
this.del(oldestKey);
|
|
257
|
+
this.emit('evict', oldestKey);
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
getSize(value) {
|
|
262
|
+
if (typeof value === 'string') {
|
|
263
|
+
return value.length;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
if (Buffer.isBuffer(value)) {
|
|
267
|
+
return value.length;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
if (typeof value === 'object') {
|
|
271
|
+
return JSON.stringify(value).length;
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
return 0;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
startCleanup() {
|
|
278
|
+
if (this.cleanupInterval) {
|
|
279
|
+
clearInterval(this.cleanupInterval);
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
this.cleanupInterval = setInterval(() => {
|
|
283
|
+
this.cleanup();
|
|
284
|
+
}, this.options.checkPeriod);
|
|
285
|
+
|
|
286
|
+
// Allow cleanup interval to be garbage collected if process exits
|
|
287
|
+
if (this.cleanupInterval.unref) {
|
|
288
|
+
this.cleanupInterval.unref();
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
cleanup() {
|
|
293
|
+
const now = Date.now();
|
|
294
|
+
const expiredKeys = [];
|
|
295
|
+
|
|
296
|
+
for (const [key, entry] of this.cache) {
|
|
297
|
+
if (now > entry.expires) {
|
|
298
|
+
expiredKeys.push(key);
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
for (const key of expiredKeys) {
|
|
303
|
+
this.del(key);
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
this.emit('cleanup', expiredKeys.length);
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
stop() {
|
|
310
|
+
if (this.cleanupInterval) {
|
|
311
|
+
clearInterval(this.cleanupInterval);
|
|
312
|
+
this.cleanupInterval = null;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
this.clear();
|
|
316
|
+
|
|
317
|
+
// Remove all event listeners to prevent memory leaks
|
|
318
|
+
this.removeAllListeners();
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
class LRUCache extends MemoryCache {
|
|
323
|
+
constructor(options = {}) {
|
|
324
|
+
super(options);
|
|
325
|
+
this.maxSize = options.maxSize || DEFAULT_MAX_SIZE;
|
|
326
|
+
|
|
327
|
+
// Override parent's max size to ensure consistency
|
|
328
|
+
this.options.maxSize = this.maxSize;
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
get(key) {
|
|
332
|
+
const value = super.get(key);
|
|
333
|
+
|
|
334
|
+
if (value !== undefined) {
|
|
335
|
+
this.moveToFront(key);
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
return value;
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
set(key, value, ttl) {
|
|
342
|
+
const result = super.set(key, value, ttl);
|
|
343
|
+
this.moveToFront(key);
|
|
344
|
+
return result;
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
moveToFront(key) {
|
|
348
|
+
const entry = this.cache.get(key);
|
|
349
|
+
if (entry) {
|
|
350
|
+
this.cache.delete(key);
|
|
351
|
+
this.cache.set(key, entry);
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
function createCache(options = {}) {
|
|
357
|
+
const type = options.type || 'memory';
|
|
358
|
+
|
|
359
|
+
switch (type) {
|
|
360
|
+
case 'memory':
|
|
361
|
+
return new MemoryCache(options);
|
|
362
|
+
case 'lru':
|
|
363
|
+
return new LRUCache(options);
|
|
364
|
+
default:
|
|
365
|
+
throw new Error(`Unknown cache type: ${type}`);
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
function memoize(fn, options = {}) {
|
|
370
|
+
const cache = createCache(options);
|
|
371
|
+
|
|
372
|
+
const memoized = function(...args) {
|
|
373
|
+
const key = options.keyGenerator ?
|
|
374
|
+
options.keyGenerator(...args) :
|
|
375
|
+
JSON.stringify(args);
|
|
376
|
+
|
|
377
|
+
if (cache.has(key)) {
|
|
378
|
+
return cache.get(key);
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
const result = fn.apply(this, args);
|
|
382
|
+
cache.set(key, result, options.ttl);
|
|
383
|
+
|
|
384
|
+
return result;
|
|
385
|
+
};
|
|
386
|
+
|
|
387
|
+
// Attach cache cleanup method
|
|
388
|
+
memoized.clear = () => cache.clear();
|
|
389
|
+
memoized.stop = () => cache.stop();
|
|
390
|
+
|
|
391
|
+
return memoized;
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
function asyncMemoize(fn, options = {}) {
|
|
395
|
+
const cache = createCache(options);
|
|
396
|
+
const pending = new Map();
|
|
397
|
+
|
|
398
|
+
const memoized = async function(...args) {
|
|
399
|
+
const key = options.keyGenerator ?
|
|
400
|
+
options.keyGenerator(...args) :
|
|
401
|
+
JSON.stringify(args);
|
|
402
|
+
|
|
403
|
+
if (cache.has(key)) {
|
|
404
|
+
return cache.get(key);
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
if (pending.has(key)) {
|
|
408
|
+
return pending.get(key);
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
const promise = fn.apply(this, args);
|
|
412
|
+
pending.set(key, promise);
|
|
413
|
+
|
|
414
|
+
try {
|
|
415
|
+
const result = await promise;
|
|
416
|
+
cache.set(key, result, options.ttl);
|
|
417
|
+
pending.delete(key);
|
|
418
|
+
return result;
|
|
419
|
+
} catch (error) {
|
|
420
|
+
pending.delete(key);
|
|
421
|
+
throw error;
|
|
422
|
+
}
|
|
423
|
+
};
|
|
424
|
+
|
|
425
|
+
// Attach cache cleanup method
|
|
426
|
+
memoized.clear = () => {
|
|
427
|
+
cache.clear();
|
|
428
|
+
pending.clear();
|
|
429
|
+
};
|
|
430
|
+
memoized.stop = () => cache.stop();
|
|
431
|
+
|
|
432
|
+
return memoized;
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
module.exports = {
|
|
436
|
+
MemoryCache,
|
|
437
|
+
LRUCache,
|
|
438
|
+
createCache,
|
|
439
|
+
memoize,
|
|
440
|
+
asyncMemoize
|
|
441
|
+
};
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
const Context = require('../core/context');
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Context Object Pool for performance optimization
|
|
5
|
+
* Reuses Context objects to reduce garbage collection pressure
|
|
6
|
+
*/
|
|
7
|
+
class ContextPool {
|
|
8
|
+
constructor(maxSize = 100) {
|
|
9
|
+
this.pool = [];
|
|
10
|
+
this.maxSize = maxSize;
|
|
11
|
+
this.created = 0;
|
|
12
|
+
this.reused = 0;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Acquire a Context object from the pool or create new one
|
|
17
|
+
* @param {IncomingMessage} req - HTTP request object
|
|
18
|
+
* @param {ServerResponse} res - HTTP response object
|
|
19
|
+
* @param {Application} app - Spark application instance
|
|
20
|
+
* @returns {Context} Context instance
|
|
21
|
+
*/
|
|
22
|
+
acquire(req, res, app) {
|
|
23
|
+
let ctx;
|
|
24
|
+
|
|
25
|
+
if (this.pool.length > 0) {
|
|
26
|
+
ctx = this.pool.pop();
|
|
27
|
+
ctx.init(req, res, app);
|
|
28
|
+
this.reused++;
|
|
29
|
+
} else {
|
|
30
|
+
ctx = new Context(req, res, app);
|
|
31
|
+
this.created++;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
return ctx;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Release a Context object back to the pool
|
|
39
|
+
* @param {Context} ctx - Context to release
|
|
40
|
+
*/
|
|
41
|
+
release(ctx) {
|
|
42
|
+
if (this.pool.length < this.maxSize) {
|
|
43
|
+
ctx.reset();
|
|
44
|
+
this.pool.push(ctx);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Get pool statistics
|
|
50
|
+
* @returns {Object} Pool stats
|
|
51
|
+
*/
|
|
52
|
+
getStats() {
|
|
53
|
+
return {
|
|
54
|
+
poolSize: this.pool.length,
|
|
55
|
+
maxSize: this.maxSize,
|
|
56
|
+
created: this.created,
|
|
57
|
+
reused: this.reused,
|
|
58
|
+
reuseRatio: this.created > 0 ? (this.reused / this.created * 100).toFixed(2) + '%' : '0%'
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Clear the pool
|
|
64
|
+
*/
|
|
65
|
+
clear() {
|
|
66
|
+
this.pool.length = 0;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Resize the pool
|
|
71
|
+
* @param {number} newSize - New maximum pool size
|
|
72
|
+
*/
|
|
73
|
+
resize(newSize) {
|
|
74
|
+
this.maxSize = newSize;
|
|
75
|
+
|
|
76
|
+
// Trim pool if new size is smaller
|
|
77
|
+
if (this.pool.length > newSize) {
|
|
78
|
+
this.pool.length = newSize;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
module.exports = ContextPool;
|