xypriss 1.2.3 → 1.3.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.
Files changed (103) hide show
  1. package/README.md +138 -3
  2. package/dist/cjs/mods/security/src/components/cache/index.js +1 -1
  3. package/dist/cjs/shared/logger/Logger.js +1 -0
  4. package/dist/cjs/shared/logger/Logger.js.map +1 -1
  5. package/dist/cjs/src/cluster/bun-cluster-manager.js +1567 -0
  6. package/dist/cjs/src/cluster/bun-cluster-manager.js.map +1 -0
  7. package/dist/cjs/src/cluster/cluster-manager.js +1 -1
  8. package/dist/cjs/src/cluster/cluster-manager.js.map +1 -1
  9. package/dist/cjs/src/cluster/index.js +25 -6
  10. package/dist/cjs/src/cluster/index.js.map +1 -1
  11. package/dist/cjs/src/cluster/memory-manager.js +463 -0
  12. package/dist/cjs/src/cluster/memory-manager.js.map +1 -0
  13. package/dist/cjs/src/cluster/modules/BunIPCManager.js +603 -0
  14. package/dist/cjs/src/cluster/modules/BunIPCManager.js.map +1 -0
  15. package/dist/cjs/src/cluster/modules/ClusterFactory.js +22 -1
  16. package/dist/cjs/src/cluster/modules/ClusterFactory.js.map +1 -1
  17. package/dist/cjs/src/cluster/modules/CpuMonitor.js +658 -0
  18. package/dist/cjs/src/cluster/modules/CpuMonitor.js.map +1 -0
  19. package/dist/cjs/src/cluster/modules/ProcessMonitor.js +513 -0
  20. package/dist/cjs/src/cluster/modules/ProcessMonitor.js.map +1 -0
  21. package/dist/cjs/src/plugins/server-maintenance-plugin.js +1 -1
  22. package/dist/cjs/src/server/FastServer.js +64 -43
  23. package/dist/cjs/src/server/FastServer.js.map +1 -1
  24. package/dist/cjs/src/server/components/fastapi/ClusterManagerComponent.js +226 -10
  25. package/dist/cjs/src/server/components/fastapi/ClusterManagerComponent.js.map +1 -1
  26. package/dist/cjs/src/server/const/Cluster.config.js +174 -31
  27. package/dist/cjs/src/server/const/Cluster.config.js.map +1 -1
  28. package/dist/cjs/src/server/const/default.js +11 -2
  29. package/dist/cjs/src/server/const/default.js.map +1 -1
  30. package/dist/cjs/src/server/utils/PortManager.js +26 -15
  31. package/dist/cjs/src/server/utils/PortManager.js.map +1 -1
  32. package/dist/esm/mods/security/src/components/cache/index.js +1 -1
  33. package/dist/esm/shared/logger/Logger.js +1 -0
  34. package/dist/esm/shared/logger/Logger.js.map +1 -1
  35. package/dist/esm/src/cluster/bun-cluster-manager.js +1565 -0
  36. package/dist/esm/src/cluster/bun-cluster-manager.js.map +1 -0
  37. package/dist/esm/src/cluster/cluster-manager.js +1 -1
  38. package/dist/esm/src/cluster/cluster-manager.js.map +1 -1
  39. package/dist/esm/src/cluster/index.js +25 -6
  40. package/dist/esm/src/cluster/index.js.map +1 -1
  41. package/dist/esm/src/cluster/memory-manager.js +461 -0
  42. package/dist/esm/src/cluster/memory-manager.js.map +1 -0
  43. package/dist/esm/src/cluster/modules/BunIPCManager.js +601 -0
  44. package/dist/esm/src/cluster/modules/BunIPCManager.js.map +1 -0
  45. package/dist/esm/src/cluster/modules/ClusterFactory.js +22 -1
  46. package/dist/esm/src/cluster/modules/ClusterFactory.js.map +1 -1
  47. package/dist/esm/src/cluster/modules/CpuMonitor.js +656 -0
  48. package/dist/esm/src/cluster/modules/CpuMonitor.js.map +1 -0
  49. package/dist/esm/src/cluster/modules/ProcessMonitor.js +511 -0
  50. package/dist/esm/src/cluster/modules/ProcessMonitor.js.map +1 -0
  51. package/dist/esm/src/plugins/server-maintenance-plugin.js +1 -1
  52. package/dist/esm/src/server/FastServer.js +64 -43
  53. package/dist/esm/src/server/FastServer.js.map +1 -1
  54. package/dist/esm/src/server/components/fastapi/ClusterManagerComponent.js +226 -10
  55. package/dist/esm/src/server/components/fastapi/ClusterManagerComponent.js.map +1 -1
  56. package/dist/esm/src/server/const/Cluster.config.js +174 -31
  57. package/dist/esm/src/server/const/Cluster.config.js.map +1 -1
  58. package/dist/esm/src/server/const/default.js +11 -2
  59. package/dist/esm/src/server/const/default.js.map +1 -1
  60. package/dist/esm/src/server/utils/PortManager.js +26 -15
  61. package/dist/esm/src/server/utils/PortManager.js.map +1 -1
  62. package/dist/index.d.ts +78 -1
  63. package/package.json +3 -1
  64. package/dist/cjs/src/plugins/modules/network/index.js +0 -120
  65. package/dist/cjs/src/plugins/modules/network/index.js.map +0 -1
  66. package/dist/cjs/src/server/plugins/PluginEngine.js +0 -378
  67. package/dist/cjs/src/server/plugins/PluginEngine.js.map +0 -1
  68. package/dist/cjs/src/server/plugins/PluginRegistry.js +0 -339
  69. package/dist/cjs/src/server/plugins/PluginRegistry.js.map +0 -1
  70. package/dist/cjs/src/server/plugins/builtin/JWTAuthPlugin.js +0 -591
  71. package/dist/cjs/src/server/plugins/builtin/JWTAuthPlugin.js.map +0 -1
  72. package/dist/cjs/src/server/plugins/builtin/ResponseTimePlugin.js +0 -413
  73. package/dist/cjs/src/server/plugins/builtin/ResponseTimePlugin.js.map +0 -1
  74. package/dist/cjs/src/server/plugins/builtin/SmartCachePlugin.js +0 -843
  75. package/dist/cjs/src/server/plugins/builtin/SmartCachePlugin.js.map +0 -1
  76. package/dist/cjs/src/server/plugins/core/CachePlugin.js +0 -1975
  77. package/dist/cjs/src/server/plugins/core/CachePlugin.js.map +0 -1
  78. package/dist/cjs/src/server/plugins/core/PerformancePlugin.js +0 -894
  79. package/dist/cjs/src/server/plugins/core/PerformancePlugin.js.map +0 -1
  80. package/dist/cjs/src/server/plugins/core/SecurityPlugin.js +0 -799
  81. package/dist/cjs/src/server/plugins/core/SecurityPlugin.js.map +0 -1
  82. package/dist/cjs/src/server/plugins/types/PluginTypes.js +0 -47
  83. package/dist/cjs/src/server/plugins/types/PluginTypes.js.map +0 -1
  84. package/dist/esm/src/plugins/modules/network/index.js +0 -109
  85. package/dist/esm/src/plugins/modules/network/index.js.map +0 -1
  86. package/dist/esm/src/server/plugins/PluginEngine.js +0 -376
  87. package/dist/esm/src/server/plugins/PluginEngine.js.map +0 -1
  88. package/dist/esm/src/server/plugins/PluginRegistry.js +0 -337
  89. package/dist/esm/src/server/plugins/PluginRegistry.js.map +0 -1
  90. package/dist/esm/src/server/plugins/builtin/JWTAuthPlugin.js +0 -589
  91. package/dist/esm/src/server/plugins/builtin/JWTAuthPlugin.js.map +0 -1
  92. package/dist/esm/src/server/plugins/builtin/ResponseTimePlugin.js +0 -411
  93. package/dist/esm/src/server/plugins/builtin/ResponseTimePlugin.js.map +0 -1
  94. package/dist/esm/src/server/plugins/builtin/SmartCachePlugin.js +0 -841
  95. package/dist/esm/src/server/plugins/builtin/SmartCachePlugin.js.map +0 -1
  96. package/dist/esm/src/server/plugins/core/CachePlugin.js +0 -1973
  97. package/dist/esm/src/server/plugins/core/CachePlugin.js.map +0 -1
  98. package/dist/esm/src/server/plugins/core/PerformancePlugin.js +0 -872
  99. package/dist/esm/src/server/plugins/core/PerformancePlugin.js.map +0 -1
  100. package/dist/esm/src/server/plugins/core/SecurityPlugin.js +0 -797
  101. package/dist/esm/src/server/plugins/core/SecurityPlugin.js.map +0 -1
  102. package/dist/esm/src/server/plugins/types/PluginTypes.js +0 -47
  103. package/dist/esm/src/server/plugins/types/PluginTypes.js.map +0 -1
@@ -1,872 +0,0 @@
1
- import { func } from '../../../../mods/security/src/components/fortified-function/index.js';
2
- import { PluginType, PluginPriority } from '../types/PluginTypes.js';
3
- import * as si from 'systeminformation';
4
- import pidusage from 'pidusage';
5
- import * as osUtils from 'node-os-utils';
6
- import { globalPerformanceMonitor } from '../../../../mods/security/src/utils/performanceMonitor.js';
7
-
8
- /**
9
- * Performance Plugin Base Class
10
- *
11
- * Foundation for performance monitoring plugins with <0.3ms execution overhead
12
- * and comprehensive metrics collection using XyPrissJS performance utilities.
13
- */
14
- /**
15
- * Abstract base class for performance monitoring plugins
16
- */
17
- class PerformancePlugin {
18
- constructor() {
19
- this.type = PluginType.PERFORMANCE;
20
- this.priority = PluginPriority.NORMAL;
21
- this.isAsync = false; // Performance plugins should be synchronous for minimal overhead
22
- this.isCacheable = true;
23
- this.maxExecutionTime = 300; // 0.3ms max for performance operations
24
- // Performance thresholds
25
- this.performanceThresholds = {
26
- responseTime: 100, // 100ms
27
- memoryUsage: 50 * 1024 * 1024, // 50MB
28
- cpuUsage: 80, // 80%
29
- };
30
- // Performance tracking
31
- this.timers = new Map();
32
- this.metrics = new Map();
33
- this.lastCpuCheck = 0;
34
- this.cachedCpuUsage = 0;
35
- this.performanceData = {
36
- totalExecutions: 0,
37
- averageExecutionTime: 0,
38
- minExecutionTime: Infinity,
39
- maxExecutionTime: 0,
40
- errorCount: 0,
41
- successRate: 100,
42
- memoryUsage: 0,
43
- cpuUsage: 0,
44
- lastExecuted: new Date(),
45
- };
46
- }
47
- /**
48
- * Initialize performance plugin with XyPrissJS utilities
49
- */
50
- async initialize(context) {
51
- // Create fortified metrics collector for ultra-fast performance tracking
52
- this.fortifiedMetrics = func((metricName, value) => {
53
- this.recordMetricInternal(metricName, value);
54
- }, {
55
- ultraFast: "maximum",
56
- auditLog: false, // Disable audit logging for performance metrics
57
- timeout: 100, // Very short timeout for metrics
58
- errorHandling: "graceful",
59
- });
60
- // Initialize system monitoring
61
- await this.initializeSystemMonitoring();
62
- // Initialize performance monitoring
63
- await this.initializePerformanceMonitoring(context);
64
- }
65
- /**
66
- * Execute performance plugin with minimal overhead
67
- */
68
- execute(context) {
69
- const startTime = performance.now();
70
- try {
71
- // Start request timing if not already started
72
- if (!context.metrics.requestStartTime) {
73
- context.metrics.requestStartTime = startTime;
74
- }
75
- // Collect performance metrics
76
- const metrics = this.collectPerformanceMetrics(context);
77
- // Execute plugin-specific performance logic
78
- const result = this.executePerformanceLogic(context, metrics);
79
- const executionTime = performance.now() - startTime;
80
- // Update performance statistics
81
- this.updatePerformanceStats(executionTime, true);
82
- // Store metrics in context
83
- context.metrics.pluginExecutionTimes.set(this.id, executionTime);
84
- return {
85
- success: true,
86
- executionTime,
87
- data: {
88
- metrics,
89
- result,
90
- },
91
- shouldContinue: true,
92
- };
93
- }
94
- catch (error) {
95
- const executionTime = performance.now() - startTime;
96
- // Update error statistics
97
- this.updatePerformanceStats(executionTime, false);
98
- return {
99
- success: false,
100
- executionTime,
101
- error,
102
- shouldContinue: true, // Performance errors shouldn't stop execution
103
- };
104
- }
105
- }
106
- /**
107
- * Start a named timer for performance measurement
108
- */
109
- startTimer(name) {
110
- this.timers.set(name, performance.now());
111
- }
112
- /**
113
- * End a named timer and return elapsed time
114
- */
115
- endTimer(name) {
116
- const startTime = this.timers.get(name);
117
- if (!startTime) {
118
- console.warn(`Timer '${name}' was not started`);
119
- return 0;
120
- }
121
- const elapsed = performance.now() - startTime;
122
- this.timers.delete(name);
123
- // Record the timing metric
124
- this.recordMetric(`timer.${name}`, elapsed);
125
- return elapsed;
126
- }
127
- /**
128
- * Record a performance metric
129
- */
130
- recordMetric(name, value) {
131
- if (this.fortifiedMetrics) {
132
- this.fortifiedMetrics(name, value);
133
- }
134
- else {
135
- this.recordMetricInternal(name, value);
136
- }
137
- }
138
- /**
139
- * Get current performance metrics
140
- */
141
- getMetrics() {
142
- return { ...this.performanceData };
143
- }
144
- /**
145
- * Precompile performance monitoring for optimal execution
146
- */
147
- async precompile() {
148
- // Pre-warm performance monitoring systems
149
- await this.precompilePerformanceMonitoring();
150
- }
151
- /**
152
- * Warm up performance plugin
153
- */
154
- async warmup(context) {
155
- // Perform initial metrics collection to warm up systems
156
- this.collectPerformanceMetrics(context);
157
- }
158
- // ===== PERFORMANCE IMPLEMENTATIONS =====
159
- /**
160
- * Initialize plugin-specific performance monitoring
161
- * implementation with comprehensive monitoring setup
162
- */
163
- async initializePerformanceMonitoring(context) {
164
- try {
165
- // Initialize performance thresholds from configuration
166
- if (context.config.customSettings.performanceThresholds) {
167
- this.updatePerformanceThresholds(context.config.customSettings.performanceThresholds);
168
- }
169
- // Setup metric collection intervals
170
- if (context.config.customSettings.metricsCollection) {
171
- this.setupMetricsCollection(context.config.customSettings.metricsCollection);
172
- }
173
- // Initialize performance alerting
174
- if (context.config.customSettings.performanceAlerting) {
175
- this.setupPerformanceAlerting(context.config.customSettings.performanceAlerting);
176
- }
177
- // Setup performance profiling
178
- if (context.config.enableProfiling) {
179
- await this.setupPerformanceProfiling(context);
180
- }
181
- context.logger.info(`Performance plugin ${this.constructor.name} initialized successfully`);
182
- }
183
- catch (error) {
184
- context.logger.error(`Error initializing performance plugin: ${error.message}`, error);
185
- throw error;
186
- }
187
- }
188
- /**
189
- * Execute plugin-specific performance logic
190
- * implementation with comprehensive performance analysis
191
- */
192
- executePerformanceLogic(context, metrics) {
193
- try {
194
- const performanceResults = {
195
- metrics,
196
- thresholdViolations: [],
197
- performanceScore: 0,
198
- recommendations: [],
199
- alerts: [],
200
- optimizations: [],
201
- };
202
- // Check performance thresholds
203
- performanceResults.thresholdViolations =
204
- this.checkPerformanceThresholds(metrics);
205
- // Calculate performance score
206
- performanceResults.performanceScore =
207
- this.calculatePerformanceScore(metrics, performanceResults.thresholdViolations);
208
- // Generate performance recommendations
209
- performanceResults.recommendations =
210
- this.generatePerformanceRecommendations(metrics);
211
- // Check for performance alerts
212
- performanceResults.alerts = this.checkPerformanceAlerts(metrics);
213
- // Suggest optimizations
214
- performanceResults.optimizations =
215
- this.suggestOptimizations(metrics);
216
- // Record performance metrics
217
- this.recordPerformanceMetrics(metrics);
218
- return performanceResults;
219
- }
220
- catch (error) {
221
- console.error(`Error executing performance logic: ${error.message}`);
222
- return {
223
- error: error.message,
224
- performanceScore: 0,
225
- alerts: ["Performance monitoring failed"],
226
- };
227
- }
228
- }
229
- /**
230
- * Precompile performance monitoring systems
231
- * implementation with comprehensive pre-warming using real system metrics
232
- */
233
- async precompilePerformanceMonitoring() {
234
- try {
235
- // Pre-warm CPU usage calculation
236
- const cpuUsage = this.getCpuUsage();
237
- // Pre-warm memory usage calculation
238
- const memoryUsage = this.getMemoryUsage();
239
- // Pre-warm advanced CPU metrics
240
- const advancedCpuMetrics = await this.getAdvancedCpuMetrics();
241
- // Pre-warm process CPU usage
242
- const processCpuUsage = await this.getProcessCpuUsage();
243
- // Pre-warm metric recording with real system data
244
- this.recordMetric("precompile.cpu", cpuUsage);
245
- this.recordMetric("precompile.memory", memoryUsage);
246
- this.recordMetric("precompile.advanced_cpu", advancedCpuMetrics.usage);
247
- // Pre-warm timer functionality
248
- this.startTimer("precompile.timer");
249
- await new Promise((resolve) => setTimeout(resolve, 1)); // Minimal delay for realistic timing
250
- this.endTimer("precompile.timer");
251
- // Pre-warm performance threshold checking with real system metrics
252
- const realSystemMetrics = {
253
- requestDuration: 1, // Minimal request duration for precompile
254
- memoryUsage: memoryUsage,
255
- cpuUsage: cpuUsage,
256
- advancedCpu: advancedCpuMetrics,
257
- processCpu: processCpuUsage,
258
- timestamp: Date.now(),
259
- };
260
- this.checkPerformanceThresholds(realSystemMetrics);
261
- // Pre-warm global performance monitor integration
262
- const operationId = `precompile_${Date.now()}`;
263
- globalPerformanceMonitor.startOperation(operationId, "precompile_warmup", {
264
- algorithm: "performance_monitoring",
265
- dataSize: memoryUsage,
266
- });
267
- globalPerformanceMonitor.endOperation(operationId, true);
268
- // Pre-warm system resource monitoring
269
- const systemResources = globalPerformanceMonitor.getSystemResourceUsage();
270
- this.recordMetric("precompile.system_memory", systemResources.memory.heapUsed);
271
- this.recordMetric("precompile.system_uptime", systemResources.uptime);
272
- console.debug("Performance monitoring systems precompiled successfully with real metrics", {
273
- cpuUsage,
274
- memoryUsage,
275
- advancedCpuCores: advancedCpuMetrics.cores,
276
- processPid: processCpuUsage.pid,
277
- systemUptime: systemResources.uptime,
278
- });
279
- }
280
- catch (error) {
281
- console.error("Error precompiling performance monitoring:", error);
282
- }
283
- }
284
- // ===== PROTECTED HELPER METHODS =====
285
- /**
286
- * Collect comprehensive performance metrics
287
- */
288
- collectPerformanceMetrics(context) {
289
- const now = performance.now();
290
- return {
291
- // Timing metrics
292
- requestDuration: now - context.metrics.requestStartTime,
293
- pluginExecutionTime: now - context.startTime,
294
- // Memory metrics
295
- memoryUsage: this.getMemoryUsage(),
296
- // CPU metrics (if available)
297
- cpuUsage: this.getCpuUsage(),
298
- // Request metrics
299
- requestSize: this.getRequestSize(context.req),
300
- responseSize: this.getResponseSize(context.res),
301
- // Cache metrics
302
- cacheHits: context.metrics.cacheHits,
303
- cacheMisses: context.metrics.cacheMisses,
304
- // Custom metrics
305
- customMetrics: this.collectCustomMetrics(context),
306
- };
307
- }
308
- /**
309
- * Get current memory usage
310
- */
311
- getMemoryUsage() {
312
- try {
313
- const memUsage = process.memoryUsage();
314
- return memUsage.heapUsed;
315
- }
316
- catch (error) {
317
- return 0;
318
- }
319
- }
320
- /**
321
- * CPU usage monitoring with multi-core support
322
- */
323
- getCpuUsage() {
324
- try {
325
- const now = Date.now();
326
- // Use cached value if checked recently (within 1 second)
327
- if (now - this.lastCpuCheck < 1000) {
328
- return this.cachedCpuUsage;
329
- }
330
- // Get current CPU usage
331
- const currentUsage = process.cpuUsage();
332
- if (this.lastCpuUsage) {
333
- // Calculate CPU usage percentage
334
- const userDiff = currentUsage.user - this.lastCpuUsage.user;
335
- const systemDiff = currentUsage.system - this.lastCpuUsage.system;
336
- const totalDiff = userDiff + systemDiff;
337
- // Convert to percentage (microseconds to percentage)
338
- const timeDiff = now - this.lastCpuCheck;
339
- const cpuPercent = (totalDiff / (timeDiff * 1000)) * 100;
340
- this.cachedCpuUsage = Math.min(Math.max(cpuPercent, 0), 100);
341
- }
342
- this.lastCpuUsage = currentUsage;
343
- this.lastCpuCheck = now;
344
- return this.cachedCpuUsage;
345
- }
346
- catch (error) {
347
- console.error("Error getting CPU usage:", error);
348
- return 0;
349
- }
350
- }
351
- /**
352
- * Get advanced CPU metrics using systeminformation
353
- */
354
- async getAdvancedCpuMetrics() {
355
- try {
356
- const [cpuLoad, cpuInfo] = await Promise.all([
357
- si.currentLoad(),
358
- si.cpu(),
359
- ]);
360
- return {
361
- usage: cpuLoad.currentLoad,
362
- cores: cpuInfo.cores,
363
- speed: cpuInfo.speed,
364
- temperature: undefined, // Temperature not available in current load data,
365
- };
366
- }
367
- catch (error) {
368
- console.error("Error getting advanced CPU metrics:", error);
369
- return {
370
- usage: this.getCpuUsage(),
371
- cores: require("os").cpus().length,
372
- speed: 0,
373
- };
374
- }
375
- }
376
- /**
377
- * Get process-specific CPU usage using pidusage
378
- */
379
- async getProcessCpuUsage(pid) {
380
- try {
381
- const targetPid = pid || process.pid;
382
- const stats = await pidusage(targetPid);
383
- return stats;
384
- }
385
- catch (error) {
386
- console.error("Error getting process CPU usage:", error);
387
- return {
388
- cpu: 0,
389
- memory: 0,
390
- ppid: 0,
391
- pid: process.pid,
392
- ctime: 0,
393
- elapsed: 0,
394
- timestamp: Date.now(),
395
- };
396
- }
397
- }
398
- /**
399
- * Get request size in bytes
400
- */
401
- getRequestSize(req) {
402
- try {
403
- let size = 0;
404
- // Add headers size
405
- if (req.headers) {
406
- size += JSON.stringify(req.headers).length;
407
- }
408
- // Add body size
409
- if (req.body) {
410
- size += JSON.stringify(req.body).length;
411
- }
412
- // Add query size
413
- if (req.query) {
414
- size += JSON.stringify(req.query).length;
415
- }
416
- return size;
417
- }
418
- catch (error) {
419
- return 0;
420
- }
421
- }
422
- /**
423
- * Get response size in bytes with actual tracking
424
- */
425
- getResponseSize(res) {
426
- try {
427
- // Check for Content-Length header first
428
- const contentLength = res.getHeader("content-length");
429
- if (contentLength) {
430
- return parseInt(contentLength, 10) || 0;
431
- }
432
- // Check for Transfer-Encoding: chunked
433
- const transferEncoding = res.getHeader("transfer-encoding");
434
- if (transferEncoding === "chunked") {
435
- // For chunked responses, we need to track the actual size
436
- return this.getChunkedResponseSize(res);
437
- }
438
- // Fallback: estimate from headers and any available data
439
- let size = 0;
440
- // Add headers size
441
- const headers = res.getHeaders();
442
- if (headers) {
443
- for (const [key, value] of Object.entries(headers)) {
444
- size += key.length + String(value).length + 4; // +4 for ": " and "\r\n"
445
- }
446
- }
447
- // Add status line size (approximate)
448
- size += 15; // "HTTP/1.1 200 OK\r\n"
449
- return size;
450
- }
451
- catch (error) {
452
- console.error("Error calculating response size:", error);
453
- return 0;
454
- }
455
- }
456
- /**
457
- * Track chunked response size using response interceptor
458
- */
459
- getChunkedResponseSize(res) {
460
- try {
461
- // Check if we've already set up size tracking for this response
462
- if (res._XyPrissResponseSize !== undefined) {
463
- return res._XyPrissResponseSize;
464
- }
465
- // Initialize size tracking
466
- res._XyPrissResponseSize = 0;
467
- // Intercept the write method to track chunk sizes
468
- const originalWrite = res.write;
469
- res.write = function (chunk, encoding, callback) {
470
- if (chunk) {
471
- const chunkSize = Buffer.isBuffer(chunk)
472
- ? chunk.length
473
- : Buffer.byteLength(chunk, encoding || "utf8");
474
- res._XyPrissResponseSize += chunkSize;
475
- }
476
- return originalWrite.call(this, chunk, encoding, callback);
477
- };
478
- // Intercept the end method to track final chunk
479
- const originalEnd = res.end;
480
- res.end = function (chunk, encoding, callback) {
481
- if (chunk) {
482
- const chunkSize = Buffer.isBuffer(chunk)
483
- ? chunk.length
484
- : Buffer.byteLength(chunk, encoding || "utf8");
485
- res._XyPrissResponseSize += chunkSize;
486
- }
487
- return originalEnd.call(this, chunk, encoding, callback);
488
- };
489
- return res._XyPrissResponseSize;
490
- }
491
- catch (error) {
492
- console.error("Error setting up chunked response size tracking:", error);
493
- return 0;
494
- }
495
- }
496
- /**
497
- * Setup response size tracking middleware
498
- */
499
- setupResponseSizeTracking(_req, res) {
500
- try {
501
- // Initialize response size tracking
502
- res._XyPrissResponseSize = 0;
503
- res._XyPrissStartTime = Date.now();
504
- // Track response headers size
505
- const originalSetHeader = res.setHeader;
506
- res.setHeader = function (name, value) {
507
- const headerSize = name.length + String(value).length + 4;
508
- res._XyPrissResponseSize += headerSize;
509
- return originalSetHeader.call(this, name, value);
510
- };
511
- // Track response body size
512
- const originalWrite = res.write;
513
- res.write = function (chunk, encoding, callback) {
514
- if (chunk) {
515
- const chunkSize = Buffer.isBuffer(chunk)
516
- ? chunk.length
517
- : Buffer.byteLength(chunk, encoding || "utf8");
518
- res._XyPrissResponseSize += chunkSize;
519
- }
520
- return originalWrite.call(this, chunk, encoding, callback);
521
- };
522
- const originalEnd = res.end;
523
- res.end = function (chunk, encoding, callback) {
524
- if (chunk) {
525
- const chunkSize = Buffer.isBuffer(chunk)
526
- ? chunk.length
527
- : Buffer.byteLength(chunk, encoding || "utf8");
528
- res._XyPrissResponseSize += chunkSize;
529
- }
530
- // Record final response metrics
531
- const responseTime = Date.now() - res._XyPrissStartTime;
532
- res.setHeader("X-Response-Size", res._XyPrissResponseSize);
533
- res.setHeader("X-Response-Time", responseTime);
534
- return originalEnd.call(this, chunk, encoding, callback);
535
- };
536
- }
537
- catch (error) {
538
- console.error("Error setting up response size tracking:", error);
539
- }
540
- }
541
- /**
542
- * Collect custom performance metrics (to be overridden by subclasses)
543
- */
544
- collectCustomMetrics(_context) {
545
- return {};
546
- }
547
- /**
548
- * Initialize system monitoring with libraries
549
- */
550
- async initializeSystemMonitoring() {
551
- try {
552
- // Initialize CPU monitoring with osUtils
553
- this.cpuMonitor = osUtils.cpu;
554
- // Initialize CPU usage tracking
555
- this.lastCpuUsage = process.cpuUsage();
556
- this.lastCpuCheck = Date.now();
557
- this.cachedCpuUsage = 0;
558
- // Pre-warm system information calls
559
- await this.preWarmSystemInfo();
560
- }
561
- catch (error) {
562
- console.error("Error initializing system monitoring:", error);
563
- // Fallback to basic monitoring
564
- this.lastCpuUsage = process.cpuUsage();
565
- this.lastCpuCheck = Date.now();
566
- this.cachedCpuUsage = 0;
567
- }
568
- }
569
- /**
570
- * Pre-warm system information calls for better performance
571
- */
572
- async preWarmSystemInfo() {
573
- try {
574
- // Pre-warm systeminformation calls
575
- await Promise.allSettled([si.cpu(), si.currentLoad(), si.mem()]);
576
- // Pre-warm pidusage
577
- await pidusage(process.pid);
578
- }
579
- catch (error) {
580
- // Ignore pre-warming errors
581
- console.debug("System info pre-warming completed with some errors:", error);
582
- }
583
- }
584
- /**
585
- * Record metric internally
586
- */
587
- recordMetricInternal(name, value) {
588
- const values = this.metrics.get(name) || [];
589
- values.push(value);
590
- // Keep only last 100 values for memory efficiency
591
- if (values.length > 100) {
592
- values.shift();
593
- }
594
- this.metrics.set(name, values);
595
- }
596
- /**
597
- * Update performance statistics
598
- */
599
- updatePerformanceStats(executionTime, success) {
600
- this.performanceData.totalExecutions++;
601
- this.performanceData.lastExecuted = new Date();
602
- if (success) {
603
- // Update timing statistics
604
- this.performanceData.minExecutionTime = Math.min(this.performanceData.minExecutionTime, executionTime);
605
- this.performanceData.maxExecutionTime = Math.max(this.performanceData.maxExecutionTime, executionTime);
606
- // Update average execution time
607
- const totalTime = this.performanceData.averageExecutionTime *
608
- (this.performanceData.totalExecutions - 1) +
609
- executionTime;
610
- this.performanceData.averageExecutionTime =
611
- totalTime / this.performanceData.totalExecutions;
612
- }
613
- else {
614
- this.performanceData.errorCount++;
615
- }
616
- // Update success rate
617
- this.performanceData.successRate =
618
- ((this.performanceData.totalExecutions -
619
- this.performanceData.errorCount) /
620
- this.performanceData.totalExecutions) *
621
- 100;
622
- // Update resource usage
623
- this.performanceData.memoryUsage = this.getMemoryUsage();
624
- this.performanceData.cpuUsage = this.getCpuUsage();
625
- }
626
- /**
627
- * Check if performance thresholds are exceeded
628
- */
629
- checkPerformanceThresholds(metrics) {
630
- const violations = [];
631
- if (metrics.requestDuration > this.performanceThresholds.responseTime) {
632
- violations.push(`Response time exceeded: ${metrics.requestDuration}ms > ${this.performanceThresholds.responseTime}ms`);
633
- }
634
- if (metrics.memoryUsage > this.performanceThresholds.memoryUsage) {
635
- violations.push(`Memory usage exceeded: ${metrics.memoryUsage} > ${this.performanceThresholds.memoryUsage}`);
636
- }
637
- if (metrics.cpuUsage > this.performanceThresholds.cpuUsage) {
638
- violations.push(`CPU usage exceeded: ${metrics.cpuUsage}% > ${this.performanceThresholds.cpuUsage}%`);
639
- }
640
- return violations;
641
- }
642
- /**
643
- * Get metric statistics
644
- */
645
- getMetricStats(metricName) {
646
- const values = this.metrics.get(metricName) || [];
647
- if (values.length === 0) {
648
- return { count: 0, average: 0, min: 0, max: 0 };
649
- }
650
- const sum = values.reduce((a, b) => a + b, 0);
651
- return {
652
- count: values.length,
653
- average: sum / values.length,
654
- min: Math.min(...values),
655
- max: Math.max(...values),
656
- };
657
- }
658
- // ===== PERFORMANCE HELPER METHODS =====
659
- /**
660
- * Update performance thresholds from configuration
661
- */
662
- updatePerformanceThresholds(thresholds) {
663
- try {
664
- if (thresholds.responseTime) {
665
- this.performanceThresholds.responseTime =
666
- thresholds.responseTime;
667
- }
668
- if (thresholds.memoryUsage) {
669
- this.performanceThresholds.memoryUsage =
670
- thresholds.memoryUsage;
671
- }
672
- if (thresholds.cpuUsage) {
673
- this.performanceThresholds.cpuUsage =
674
- thresholds.cpuUsage;
675
- }
676
- console.debug("Performance thresholds updated successfully");
677
- }
678
- catch (error) {
679
- console.error("Error updating performance thresholds:", error);
680
- }
681
- }
682
- /**
683
- * Setup metrics collection intervals
684
- */
685
- setupMetricsCollection(config) {
686
- try {
687
- const interval = config.interval || 60000; // 1 minute default
688
- setInterval(() => {
689
- this.collectSystemMetrics();
690
- }, interval);
691
- console.debug("Metrics collection setup completed");
692
- }
693
- catch (error) {
694
- console.error("Error setting up metrics collection:", error);
695
- }
696
- }
697
- /**
698
- * Setup performance alerting
699
- */
700
- setupPerformanceAlerting(config) {
701
- try {
702
- // Setup alerting thresholds and handlers
703
- console.debug("Performance alerting setup completed");
704
- }
705
- catch (error) {
706
- console.error("Error setting up performance alerting:", error);
707
- }
708
- }
709
- /**
710
- * Setup performance profiling
711
- */
712
- async setupPerformanceProfiling(context) {
713
- try {
714
- // Setup profiling tools and configurations
715
- console.debug("Performance profiling setup completed");
716
- }
717
- catch (error) {
718
- console.error("Error setting up performance profiling:", error);
719
- }
720
- }
721
- /**
722
- * Calculate performance score based on metrics and violations
723
- */
724
- calculatePerformanceScore(metrics, violations) {
725
- try {
726
- let score = 100;
727
- // Deduct points for threshold violations
728
- score -= violations.length * 15;
729
- // Deduct points based on metric values
730
- if (metrics.requestDuration >
731
- this.performanceThresholds.responseTime * 0.8) {
732
- score -= 10;
733
- }
734
- if (metrics.memoryUsage >
735
- this.performanceThresholds.memoryUsage * 0.8) {
736
- score -= 10;
737
- }
738
- if (metrics.cpuUsage > this.performanceThresholds.cpuUsage * 0.8) {
739
- score -= 10;
740
- }
741
- // Bonus points for good performance
742
- if (metrics.requestDuration <
743
- this.performanceThresholds.responseTime * 0.5) {
744
- score += 5;
745
- }
746
- return Math.max(0, Math.min(100, score));
747
- }
748
- catch (error) {
749
- console.error("Error calculating performance score:", error);
750
- return 0;
751
- }
752
- }
753
- /**
754
- * Generate performance recommendations
755
- */
756
- generatePerformanceRecommendations(metrics) {
757
- const recommendations = [];
758
- try {
759
- if (metrics.requestDuration >
760
- this.performanceThresholds.responseTime) {
761
- recommendations.push("Consider optimizing request processing time");
762
- recommendations.push("Review database queries and API calls");
763
- }
764
- if (metrics.memoryUsage > this.performanceThresholds.memoryUsage) {
765
- recommendations.push("Consider optimizing memory usage");
766
- recommendations.push("Review object creation and garbage collection");
767
- }
768
- if (metrics.cpuUsage > this.performanceThresholds.cpuUsage) {
769
- recommendations.push("Consider optimizing CPU-intensive operations");
770
- recommendations.push("Review algorithmic complexity");
771
- }
772
- if (metrics.cacheHits / (metrics.cacheHits + metrics.cacheMisses) <
773
- 0.8) {
774
- recommendations.push("Consider improving cache hit rate");
775
- }
776
- return recommendations;
777
- }
778
- catch (error) {
779
- console.error("Error generating performance recommendations:", error);
780
- return ["Error generating recommendations"];
781
- }
782
- }
783
- /**
784
- * Check for performance alerts
785
- */
786
- checkPerformanceAlerts(metrics) {
787
- const alerts = [];
788
- try {
789
- // Critical performance alerts
790
- if (metrics.requestDuration >
791
- this.performanceThresholds.responseTime * 2) {
792
- alerts.push("CRITICAL: Response time severely degraded");
793
- }
794
- if (metrics.memoryUsage >
795
- this.performanceThresholds.memoryUsage * 1.5) {
796
- alerts.push("CRITICAL: Memory usage critically high");
797
- }
798
- if (metrics.cpuUsage > this.performanceThresholds.cpuUsage * 1.2) {
799
- alerts.push("WARNING: CPU usage elevated");
800
- }
801
- return alerts;
802
- }
803
- catch (error) {
804
- console.error("Error checking performance alerts:", error);
805
- return ["Error checking alerts"];
806
- }
807
- }
808
- /**
809
- * Suggest optimizations based on metrics
810
- */
811
- suggestOptimizations(metrics) {
812
- const optimizations = [];
813
- try {
814
- if (metrics.requestDuration > 100) {
815
- optimizations.push("Enable response compression");
816
- optimizations.push("Implement request caching");
817
- }
818
- if (metrics.memoryUsage > 50 * 1024 * 1024) {
819
- optimizations.push("Implement object pooling");
820
- optimizations.push("Optimize data structures");
821
- }
822
- if (metrics.cpuUsage > 70) {
823
- optimizations.push("Implement CPU-intensive task queuing");
824
- optimizations.push("Consider worker threads for heavy operations");
825
- }
826
- return optimizations;
827
- }
828
- catch (error) {
829
- console.error("Error suggesting optimizations:", error);
830
- return ["Error suggesting optimizations"];
831
- }
832
- }
833
- /**
834
- * Record performance metrics for analysis
835
- */
836
- recordPerformanceMetrics(metrics) {
837
- try {
838
- // Record key metrics
839
- this.recordMetric("request.duration", metrics.requestDuration);
840
- this.recordMetric("memory.usage", metrics.memoryUsage);
841
- this.recordMetric("cpu.usage", metrics.cpuUsage);
842
- this.recordMetric("cache.hits", metrics.cacheHits);
843
- this.recordMetric("cache.misses", metrics.cacheMisses);
844
- // Update performance data
845
- this.performanceData.memoryUsage = metrics.memoryUsage;
846
- this.performanceData.cpuUsage = metrics.cpuUsage;
847
- }
848
- catch (error) {
849
- console.error("Error recording performance metrics:", error);
850
- }
851
- }
852
- /**
853
- * Collect system metrics periodically
854
- */
855
- collectSystemMetrics() {
856
- try {
857
- const metrics = {
858
- timestamp: Date.now(),
859
- memoryUsage: this.getMemoryUsage(),
860
- cpuUsage: this.getCpuUsage(),
861
- };
862
- this.recordMetric("system.memory", metrics.memoryUsage);
863
- this.recordMetric("system.cpu", metrics.cpuUsage);
864
- }
865
- catch (error) {
866
- console.error("Error collecting system metrics:", error);
867
- }
868
- }
869
- }
870
-
871
- export { PerformancePlugin };
872
- //# sourceMappingURL=PerformancePlugin.js.map