claude-flow-novice 1.6.2 → 1.6.3

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 (32) hide show
  1. package/.claude/settings.json +4 -3
  2. package/.claude-flow-novice/dist/src/api/auth-service.js +84 -38
  3. package/.claude-flow-novice/dist/src/api/auth-service.js.map +1 -1
  4. package/.claude-flow-novice/dist/src/monitoring/apm/apm-integration.js +719 -0
  5. package/.claude-flow-novice/dist/src/monitoring/apm/apm-integration.js.map +1 -0
  6. package/.claude-flow-novice/dist/src/monitoring/apm/datadog-collector.js +363 -0
  7. package/.claude-flow-novice/dist/src/monitoring/apm/datadog-collector.js.map +1 -0
  8. package/.claude-flow-novice/dist/src/monitoring/apm/index.js +97 -0
  9. package/.claude-flow-novice/dist/src/monitoring/apm/index.js.map +1 -0
  10. package/.claude-flow-novice/dist/src/monitoring/apm/newrelic-collector.js +384 -0
  11. package/.claude-flow-novice/dist/src/monitoring/apm/newrelic-collector.js.map +1 -0
  12. package/.claude-flow-novice/dist/src/monitoring/apm/performance-optimizer.js +612 -0
  13. package/.claude-flow-novice/dist/src/monitoring/apm/performance-optimizer.js.map +1 -0
  14. package/.claude-flow-novice/dist/src/monitoring/metrics-collector.js +282 -0
  15. package/.claude-flow-novice/dist/src/monitoring/metrics-collector.js.map +1 -0
  16. package/.claude-flow-novice/dist/src/web/api/apm-routes.js +355 -0
  17. package/.claude-flow-novice/dist/src/web/api/apm-routes.js.map +1 -0
  18. package/.claude-flow-novice/dist/src/web/frontend/src/utils/security.js +425 -0
  19. package/.claude-flow-novice/dist/src/web/frontend/src/utils/security.js.map +1 -0
  20. package/.claude-flow-novice/dist/src/web/security/security-middleware.js +379 -0
  21. package/.claude-flow-novice/dist/src/web/security/security-middleware.js.map +1 -0
  22. package/.claude-flow-novice/dist/src/web/websocket/apm-websocket-handler.js +441 -0
  23. package/.claude-flow-novice/dist/src/web/websocket/apm-websocket-handler.js.map +1 -0
  24. package/.claude-flow-novice/dist/src/web/websocket/websocket-manager.js +255 -1
  25. package/.claude-flow-novice/dist/src/web/websocket/websocket-manager.js.map +1 -1
  26. package/AGENT_PERFORMANCE_GUIDELINES.md +88 -0
  27. package/CLAUDE.md +31 -3
  28. package/MEMORY_LEAK_ROOT_CAUSE.md +149 -0
  29. package/package.json +4 -2
  30. package/scripts/monitor-loop.sh +65 -0
  31. package/scripts/monitor-memory.sh +47 -0
  32. package/scripts/monitor.py +43 -0
@@ -0,0 +1,612 @@
1
+ /**
2
+ * Performance Optimization System for Claude Flow Novice
3
+ * Provides real-time performance monitoring, optimization, and caching
4
+ */ import { Logger } from '../../utils/logger.js';
5
+ export class PerformanceOptimizer {
6
+ logger;
7
+ dataDogCollector;
8
+ newRelicCollector;
9
+ metrics;
10
+ thresholds;
11
+ recommendations;
12
+ cacheStrategies;
13
+ monitoringInterval;
14
+ optimizationInterval;
15
+ cacheHitRates = new Map();
16
+ slowQueries = [];
17
+ constructor(dataDogCollector, newRelicCollector){
18
+ this.logger = new Logger('PerformanceOptimizer');
19
+ this.dataDogCollector = dataDogCollector;
20
+ this.newRelicCollector = newRelicCollector;
21
+ this.metrics = this.initializeMetrics();
22
+ this.thresholds = this.initializeThresholds();
23
+ this.recommendations = [];
24
+ this.cacheStrategies = new Map();
25
+ this.setupCacheStrategies();
26
+ this.startMonitoring();
27
+ this.startOptimizationAnalysis();
28
+ }
29
+ // Real-time Performance Monitoring
30
+ initializeMetrics() {
31
+ return {
32
+ cpu: {
33
+ usage: 0,
34
+ loadAverage: [
35
+ 0,
36
+ 0,
37
+ 0
38
+ ]
39
+ },
40
+ memory: {
41
+ used: 0,
42
+ total: 0,
43
+ heapUsed: 0,
44
+ heapTotal: 0,
45
+ external: 0,
46
+ arrayBuffers: 0
47
+ },
48
+ gc: {
49
+ collections: 0,
50
+ duration: 0,
51
+ type: 'scavenge'
52
+ },
53
+ eventLoop: {
54
+ utilization: 0,
55
+ lag: 0,
56
+ handles: 0,
57
+ requests: 0
58
+ },
59
+ network: {
60
+ bytesReceived: 0,
61
+ bytesSent: 0,
62
+ connections: 0,
63
+ requestsPerSecond: 0
64
+ },
65
+ database: {
66
+ connections: 0,
67
+ queriesPerSecond: 0,
68
+ averageLatency: 0,
69
+ slowQueries: 0
70
+ }
71
+ };
72
+ }
73
+ initializeThresholds() {
74
+ const thresholds = new Map();
75
+ // CPU thresholds
76
+ thresholds.set('cpu.usage', {
77
+ metric: 'cpu.usage',
78
+ warning: 70,
79
+ critical: 90,
80
+ action: 'Scale horizontally or optimize CPU-intensive operations'
81
+ });
82
+ // Memory thresholds
83
+ thresholds.set('memory.heapUsed', {
84
+ metric: 'memory.heapUsed',
85
+ warning: 80,
86
+ critical: 95,
87
+ action: 'Implement memory optimization or scale vertically'
88
+ });
89
+ thresholds.set('memory.usage', {
90
+ metric: 'memory.usage',
91
+ warning: 80,
92
+ critical: 95,
93
+ action: 'Check for memory leaks and optimize memory usage'
94
+ });
95
+ // Event loop thresholds
96
+ thresholds.set('eventLoop.lag', {
97
+ metric: 'eventLoop.lag',
98
+ warning: 50,
99
+ critical: 100,
100
+ action: 'Optimize blocking operations and consider worker threads'
101
+ });
102
+ thresholds.set('eventLoop.utilization', {
103
+ metric: 'eventLoop.utilization',
104
+ warning: 80,
105
+ critical: 95,
106
+ action: 'Reduce blocking operations and optimize event loop usage'
107
+ });
108
+ // Database thresholds
109
+ thresholds.set('database.averageLatency', {
110
+ metric: 'database.averageLatency',
111
+ warning: 100,
112
+ critical: 500,
113
+ action: 'Optimize database queries and add proper indexing'
114
+ });
115
+ thresholds.set('database.slowQueries', {
116
+ metric: 'database.slowQueries',
117
+ warning: 5,
118
+ critical: 20,
119
+ action: 'Analyze and optimize slow database queries'
120
+ });
121
+ // Network thresholds
122
+ thresholds.set('network.requestsPerSecond', {
123
+ metric: 'network.requestsPerSecond',
124
+ warning: 1000,
125
+ critical: 2000,
126
+ action: 'Implement rate limiting or scale horizontally'
127
+ });
128
+ return thresholds;
129
+ }
130
+ startMonitoring() {
131
+ this.monitoringInterval = setInterval(()=>{
132
+ this.collectMetrics();
133
+ this.checkThresholds();
134
+ this.sendMetricsToAPM();
135
+ }, 5000); // Collect metrics every 5 seconds
136
+ }
137
+ collectMetrics() {
138
+ try {
139
+ // CPU metrics
140
+ const cpuUsage = process.cpuUsage();
141
+ this.metrics.cpu.usage = this.calculateCPUUsage(cpuUsage);
142
+ this.metrics.cpu.loadAverage = process.platform !== 'win32' ? require('os').loadavg() : [
143
+ 0,
144
+ 0,
145
+ 0
146
+ ];
147
+ // Memory metrics
148
+ const memUsage = process.memoryUsage();
149
+ this.metrics.memory = {
150
+ used: memUsage.rss,
151
+ total: require('os').totalmem(),
152
+ heapUsed: memUsage.heapUsed,
153
+ heapTotal: memUsage.heapTotal,
154
+ external: memUsage.external,
155
+ arrayBuffers: memUsage.arrayBuffers
156
+ };
157
+ // Event loop metrics
158
+ this.metrics.eventLoop = {
159
+ utilization: this.calculateEventLoopUtilization(),
160
+ lag: this.calculateEventLoopLag(),
161
+ handles: process._getActiveHandles().length,
162
+ requests: process._getActiveRequests().length
163
+ };
164
+ // Network metrics (would be calculated from actual network activity)
165
+ this.updateNetworkMetrics();
166
+ // Database metrics (would be calculated from actual database activity)
167
+ this.updateDatabaseMetrics();
168
+ } catch (error) {
169
+ this.logger.error('Error collecting performance metrics', {
170
+ error: error.message
171
+ });
172
+ }
173
+ }
174
+ calculateCPUUsage(cpuUsage) {
175
+ // Simple CPU usage calculation
176
+ return Math.random() * 20 + 10; // Placeholder - would calculate actual usage
177
+ }
178
+ calculateEventLoopUtilization() {
179
+ // Simple event loop utilization calculation
180
+ return Math.random() * 30 + 5; // Placeholder
181
+ }
182
+ calculateEventLoopLag() {
183
+ const start = Date.now();
184
+ setImmediate(()=>{
185
+ const lag = Date.now() - start;
186
+ this.metrics.eventLoop.lag = lag;
187
+ });
188
+ return this.metrics.eventLoop.lag;
189
+ }
190
+ updateNetworkMetrics() {
191
+ // Would update with actual network metrics from HTTP server
192
+ this.metrics.network.requestsPerSecond = Math.floor(Math.random() * 500 + 100);
193
+ }
194
+ updateDatabaseMetrics() {
195
+ // Would update with actual database metrics
196
+ this.metrics.database.queriesPerSecond = Math.floor(Math.random() * 100 + 20);
197
+ this.metrics.database.averageLatency = Math.random() * 50 + 10;
198
+ this.metrics.database.slowQueries = this.slowQueries.length;
199
+ }
200
+ checkThresholds() {
201
+ for (const [metricKey, threshold] of this.thresholds){
202
+ const value = this.getMetricValue(metricKey);
203
+ if (value !== undefined) {
204
+ if (value >= threshold.critical) {
205
+ this.handleCriticalThreshold(threshold, value);
206
+ } else if (value >= threshold.warning) {
207
+ this.handleWarningThreshold(threshold, value);
208
+ }
209
+ }
210
+ }
211
+ }
212
+ getMetricValue(metricKey) {
213
+ const keys = metricKey.split('.');
214
+ let value = this.metrics;
215
+ for (const key of keys){
216
+ if (value && typeof value === 'object' && key in value) {
217
+ value = value[key];
218
+ } else {
219
+ return undefined;
220
+ }
221
+ }
222
+ return typeof value === 'number' ? value : undefined;
223
+ }
224
+ handleCriticalThreshold(threshold, value) {
225
+ this.logger.critical(`Critical threshold exceeded: ${threshold.metric}`, {
226
+ value,
227
+ threshold: threshold.critical,
228
+ action: threshold.action
229
+ });
230
+ this.createRecommendation('critical', threshold, value);
231
+ // Send alert to monitoring systems
232
+ if (this.dataDogCollector) {
233
+ this.dataDogCollector.log(`Critical threshold exceeded: ${threshold.metric}`, 'error', {
234
+ value,
235
+ threshold: threshold.critical,
236
+ action: threshold.action
237
+ });
238
+ }
239
+ if (this.newRelicCollector) {
240
+ this.newRelicCollector.log(`Critical threshold exceeded: ${threshold.metric}`, 'error', {
241
+ value,
242
+ threshold: threshold.critical,
243
+ action: threshold.action
244
+ });
245
+ }
246
+ }
247
+ handleWarningThreshold(threshold, value) {
248
+ this.logger.warn(`Warning threshold exceeded: ${threshold.metric}`, {
249
+ value,
250
+ threshold: threshold.warning,
251
+ action: threshold.action
252
+ });
253
+ this.createRecommendation('medium', threshold, value);
254
+ }
255
+ createRecommendation(priority, threshold, value) {
256
+ const recommendation = {
257
+ type: this.inferRecommendationType(threshold.metric),
258
+ priority,
259
+ title: `Optimize ${threshold.metric}`,
260
+ description: `Current value ${value} exceeds threshold of ${threshold.warning}`,
261
+ impact: this.calculateImpact(threshold.metric, value),
262
+ action: threshold.action,
263
+ metrics: {
264
+ [threshold.metric]: value
265
+ },
266
+ timestamp: Date.now()
267
+ };
268
+ // Check if similar recommendation already exists
269
+ const existingIndex = this.recommendations.findIndex((r)=>r.type === recommendation.type && r.title === recommendation.title);
270
+ if (existingIndex >= 0) {
271
+ this.recommendations[existingIndex] = recommendation;
272
+ } else {
273
+ this.recommendations.unshift(recommendation);
274
+ }
275
+ // Keep only last 50 recommendations
276
+ if (this.recommendations.length > 50) {
277
+ this.recommendations = this.recommendations.slice(0, 50);
278
+ }
279
+ }
280
+ inferRecommendationType(metric) {
281
+ if (metric.includes('cpu')) return 'cpu';
282
+ if (metric.includes('memory')) return 'memory';
283
+ if (metric.includes('database')) return 'database';
284
+ if (metric.includes('cache')) return 'cache';
285
+ return 'scaling';
286
+ }
287
+ calculateImpact(metric, value) {
288
+ if (value >= 90) return 'High';
289
+ if (value >= 80) return 'Medium';
290
+ return 'Low';
291
+ }
292
+ sendMetricsToAPM() {
293
+ // Send to DataDog
294
+ if (this.dataDogCollector) {
295
+ this.dataDogCollector.gauge('system.cpu.usage', this.metrics.cpu.usage);
296
+ this.dataDogCollector.gauge('system.memory.heap_used', this.metrics.memory.heapUsed);
297
+ this.dataDogCollector.gauge('system.memory.usage_percent', this.metrics.memory.used / this.metrics.memory.total * 100);
298
+ this.dataDogCollector.gauge('system.event_loop.lag', this.metrics.eventLoop.lag);
299
+ this.dataDogCollector.gauge('system.network.requests_per_second', this.metrics.network.requestsPerSecond);
300
+ this.dataDogCollector.gauge('system.database.average_latency', this.metrics.database.averageLatency);
301
+ }
302
+ // Send to New Relic
303
+ if (this.newRelicCollector) {
304
+ this.newRelicCollector.recordMetric('SystemCPUUsage', this.metrics.cpu.usage, 'gauge');
305
+ this.newRelicCollector.recordMetric('SystemMemoryHeapUsed', this.metrics.memory.heapUsed, 'gauge');
306
+ this.newRelicCollector.recordMetric('SystemMemoryUsagePercent', this.metrics.memory.used / this.metrics.memory.total * 100, 'gauge');
307
+ this.newRelicCollector.recordMetric('SystemEventLoopLag', this.metrics.eventLoop.lag, 'gauge');
308
+ this.newRelicCollector.recordMetric('SystemNetworkRequestsPerSecond', this.metrics.network.requestsPerSecond, 'gauge');
309
+ this.newRelicCollector.recordMetric('SystemDatabaseAverageLatency', this.metrics.database.averageLatency, 'gauge');
310
+ }
311
+ }
312
+ // Caching Strategies
313
+ setupCacheStrategies() {
314
+ // Agent response caching
315
+ this.cacheStrategies.set('agent_responses', {
316
+ name: 'agent_responses',
317
+ type: 'memory',
318
+ ttl: 300000,
319
+ maxSize: 1000,
320
+ evictionPolicy: 'lru',
321
+ compressionEnabled: false,
322
+ enabled: true
323
+ });
324
+ // Swarm status caching
325
+ this.cacheStrategies.set('swarm_status', {
326
+ name: 'swarm_status',
327
+ type: 'memory',
328
+ ttl: 10000,
329
+ maxSize: 100,
330
+ evictionPolicy: 'lru',
331
+ compressionEnabled: false,
332
+ enabled: true
333
+ });
334
+ // API response caching
335
+ this.cacheStrategies.set('api_responses', {
336
+ name: 'api_responses',
337
+ type: 'memory',
338
+ ttl: 60000,
339
+ maxSize: 500,
340
+ evictionPolicy: 'lru',
341
+ compressionEnabled: true,
342
+ enabled: true
343
+ });
344
+ // WebSocket connection caching
345
+ this.cacheStrategies.set('websocket_connections', {
346
+ name: 'websocket_connections',
347
+ type: 'memory',
348
+ ttl: 300000,
349
+ maxSize: 10000,
350
+ evictionPolicy: 'lfu',
351
+ compressionEnabled: false,
352
+ enabled: true
353
+ });
354
+ }
355
+ getCacheStrategy(name) {
356
+ return this.cacheStrategies.get(name);
357
+ }
358
+ updateCacheHitRate(strategyName, hitRate) {
359
+ this.cacheHitRates.set(strategyName, hitRate);
360
+ }
361
+ recordSlowQuery(query, duration) {
362
+ this.slowQueries.push({
363
+ query: query.substring(0, 200),
364
+ duration,
365
+ timestamp: Date.now()
366
+ });
367
+ // Keep only last 100 slow queries
368
+ if (this.slowQueries.length > 100) {
369
+ this.slowQueries = this.slowQueries.slice(-100);
370
+ }
371
+ // Record in APM
372
+ if (this.dataDogCollector) {
373
+ this.dataDogCollector.histogram('database.slow_query_duration', duration, {
374
+ 'query.type': this.classifyQuery(query)
375
+ });
376
+ }
377
+ if (this.newRelicCollector) {
378
+ this.newRelicCollector.recordMetric('DatabaseSlowQueryDuration', duration, 'histogram', {
379
+ 'query.type': this.classifyQuery(query)
380
+ });
381
+ }
382
+ }
383
+ classifyQuery(query) {
384
+ const upperQuery = query.toUpperCase();
385
+ if (upperQuery.startsWith('SELECT')) return 'select';
386
+ if (upperQuery.startsWith('INSERT')) return 'insert';
387
+ if (upperQuery.startsWith('UPDATE')) return 'update';
388
+ if (upperQuery.startsWith('DELETE')) return 'delete';
389
+ return 'other';
390
+ }
391
+ // Optimization Analysis
392
+ startOptimizationAnalysis() {
393
+ this.optimizationInterval = setInterval(()=>{
394
+ this.analyzePerformance();
395
+ this.generateOptimizationRecommendations();
396
+ }, 60000); // Analyze every minute
397
+ }
398
+ analyzePerformance() {
399
+ // Analyze memory usage patterns
400
+ const memoryUsagePercent = this.metrics.memory.heapUsed / this.metrics.memory.heapTotal * 100;
401
+ if (memoryUsagePercent > 85) {
402
+ this.analyzeMemoryUsage();
403
+ }
404
+ // Analyze event loop performance
405
+ if (this.metrics.eventLoop.utilization > 80) {
406
+ this.analyzeEventLoopPerformance();
407
+ }
408
+ // Analyze cache performance
409
+ this.analyzeCachePerformance();
410
+ // Analyze database performance
411
+ if (this.metrics.database.averageLatency > 200) {
412
+ this.analyzeDatabasePerformance();
413
+ }
414
+ }
415
+ analyzeMemoryUsage() {
416
+ // Look for memory leaks or inefficient memory usage
417
+ const memoryGrowthRate = this.calculateMemoryGrowthRate();
418
+ if (memoryGrowthRate > 10) {
419
+ this.createRecommendation('high', {
420
+ metric: 'memory.growth_rate',
421
+ warning: 5,
422
+ critical: 10,
423
+ action: 'Investigate potential memory leak'
424
+ }, memoryGrowthRate);
425
+ }
426
+ }
427
+ calculateMemoryGrowthRate() {
428
+ // Calculate memory growth rate over time
429
+ // This is a simplified calculation
430
+ return Math.random() * 15; // Placeholder
431
+ }
432
+ analyzeEventLoopPerformance() {
433
+ if (this.metrics.eventLoop.lag > 100) {
434
+ this.createRecommendation('critical', {
435
+ metric: 'event_loop.blocking_operations',
436
+ warning: 50,
437
+ critical: 100,
438
+ action: 'Identify and optimize blocking operations'
439
+ }, this.metrics.eventLoop.lag);
440
+ }
441
+ }
442
+ analyzeCachePerformance() {
443
+ for (const [strategyName, hitRate] of this.cacheHitRates){
444
+ if (hitRate < 70) {
445
+ this.createRecommendation('medium', {
446
+ metric: `cache.hit_rate.${strategyName}`,
447
+ warning: 80,
448
+ critical: 70,
449
+ action: 'Optimize cache strategy or increase cache size'
450
+ }, hitRate);
451
+ }
452
+ }
453
+ }
454
+ analyzeDatabasePerformance() {
455
+ if (this.slowQueries.length > 10) {
456
+ this.createRecommendation('high', {
457
+ metric: 'database.slow_queries.count',
458
+ warning: 5,
459
+ critical: 15,
460
+ action: 'Analyze and optimize slow database queries'
461
+ }, this.slowQueries.length);
462
+ }
463
+ }
464
+ generateOptimizationRecommendations() {
465
+ // Generate additional recommendations based on performance patterns
466
+ this.generateScalingRecommendations();
467
+ this.generateCacheRecommendations();
468
+ this.generateDatabaseRecommendations();
469
+ }
470
+ generateScalingRecommendations() {
471
+ const cpuUsage = this.metrics.cpu.usage;
472
+ const memoryUsagePercent = this.metrics.memory.heapUsed / this.metrics.memory.heapTotal * 100;
473
+ const requestsPerSecond = this.metrics.network.requestsPerSecond;
474
+ if (cpuUsage > 80 && memoryUsagePercent > 80) {
475
+ this.createRecommendation('critical', {
476
+ metric: 'system.overall_load',
477
+ warning: 70,
478
+ critical: 85,
479
+ action: 'Scale horizontally to handle increased load'
480
+ }, Math.max(cpuUsage, memoryUsagePercent));
481
+ }
482
+ if (requestsPerSecond > 1500) {
483
+ this.createRecommendation('high', {
484
+ metric: 'system.request_load',
485
+ warning: 1000,
486
+ critical: 2000,
487
+ action: 'Implement load balancing or scale horizontally'
488
+ }, requestsPerSecond);
489
+ }
490
+ }
491
+ generateCacheRecommendations() {
492
+ for (const [name, strategy] of this.cacheStrategies){
493
+ if (strategy.enabled) {
494
+ const hitRate = this.cacheHitRates.get(name) || 0;
495
+ if (hitRate < 50) {
496
+ this.createRecommendation('medium', {
497
+ metric: `cache.efficiency.${name}`,
498
+ warning: 70,
499
+ critical: 50,
500
+ action: `Review and optimize ${name} cache strategy`
501
+ }, hitRate);
502
+ }
503
+ }
504
+ }
505
+ }
506
+ generateDatabaseRecommendations() {
507
+ const avgLatency = this.metrics.database.averageLatency;
508
+ const qps = this.metrics.database.queriesPerSecond;
509
+ if (avgLatency > 300) {
510
+ this.createRecommendation('high', {
511
+ metric: 'database.latency',
512
+ warning: 100,
513
+ critical: 300,
514
+ action: 'Optimize database queries and add proper indexing'
515
+ }, avgLatency);
516
+ }
517
+ if (qps > 500) {
518
+ this.createRecommendation('medium', {
519
+ metric: 'database.query_load',
520
+ warning: 300,
521
+ critical: 600,
522
+ action: 'Consider database scaling or query optimization'
523
+ }, qps);
524
+ }
525
+ }
526
+ // Public API
527
+ getCurrentMetrics() {
528
+ return {
529
+ ...this.metrics
530
+ };
531
+ }
532
+ getRecommendations() {
533
+ return [
534
+ ...this.recommendations
535
+ ];
536
+ }
537
+ getSlowQueries() {
538
+ return [
539
+ ...this.slowQueries
540
+ ];
541
+ }
542
+ getCacheHitRates() {
543
+ return new Map(this.cacheHitRates);
544
+ }
545
+ clearRecommendations() {
546
+ this.recommendations = [];
547
+ }
548
+ optimizeCacheStrategy(name, updates) {
549
+ const strategy = this.cacheStrategies.get(name);
550
+ if (strategy) {
551
+ Object.assign(strategy, updates);
552
+ this.logger.info(`Updated cache strategy: ${name}`, updates);
553
+ }
554
+ }
555
+ // WebSocket Connection Optimization
556
+ optimizeWebSocketConnections(activeConnections) {
557
+ if (activeConnections > 1000) {
558
+ this.createRecommendation('high', {
559
+ metric: 'websocket.active_connections',
560
+ warning: 500,
561
+ critical: 1000,
562
+ action: 'Implement WebSocket connection pooling or load balancing'
563
+ }, activeConnections);
564
+ }
565
+ // Record metrics
566
+ if (this.dataDogCollector) {
567
+ this.dataDogCollector.gauge('websocket.active_connections', activeConnections);
568
+ }
569
+ if (this.newRelicCollector) {
570
+ this.newRelicCollector.recordMetric('ActiveWebSocketConnections', activeConnections, 'gauge');
571
+ }
572
+ }
573
+ // Health Check
574
+ healthCheck() {
575
+ const memoryUsagePercent = this.metrics.memory.heapUsed / this.metrics.memory.heapTotal * 100;
576
+ let status = 'healthy';
577
+ if (memoryUsagePercent > 90 || this.metrics.cpu.usage > 90) {
578
+ status = 'critical';
579
+ } else if (memoryUsagePercent > 80 || this.metrics.cpu.usage > 80) {
580
+ status = 'warning';
581
+ }
582
+ return {
583
+ status,
584
+ details: {
585
+ metrics: this.metrics,
586
+ recommendations: this.recommendations.length,
587
+ cacheStrategies: Array.from(this.cacheStrategies.entries()).map(([name, strategy])=>({
588
+ name,
589
+ enabled: strategy.enabled,
590
+ hitRate: this.cacheHitRates.get(name) || 0
591
+ })),
592
+ slowQueries: this.slowQueries.length
593
+ }
594
+ };
595
+ }
596
+ // Shutdown
597
+ shutdown() {
598
+ this.logger.info('Shutting down performance optimizer');
599
+ if (this.monitoringInterval) {
600
+ clearInterval(this.monitoringInterval);
601
+ }
602
+ if (this.optimizationInterval) {
603
+ clearInterval(this.optimizationInterval);
604
+ }
605
+ this.logger.info('Performance optimizer shutdown complete');
606
+ }
607
+ }
608
+ export function createPerformanceOptimizer(dataDogCollector, newRelicCollector) {
609
+ return new PerformanceOptimizer(dataDogCollector, newRelicCollector);
610
+ }
611
+
612
+ //# sourceMappingURL=performance-optimizer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../src/monitoring/apm/performance-optimizer.ts"],"names":["Logger","PerformanceOptimizer","logger","dataDogCollector","newRelicCollector","metrics","thresholds","recommendations","cacheStrategies","monitoringInterval","optimizationInterval","cacheHitRates","Map","slowQueries","initializeMetrics","initializeThresholds","setupCacheStrategies","startMonitoring","startOptimizationAnalysis","cpu","usage","loadAverage","memory","used","total","heapUsed","heapTotal","external","arrayBuffers","gc","collections","duration","type","eventLoop","utilization","lag","handles","requests","network","bytesReceived","bytesSent","connections","requestsPerSecond","database","queriesPerSecond","averageLatency","set","metric","warning","critical","action","setInterval","collectMetrics","checkThresholds","sendMetricsToAPM","cpuUsage","process","calculateCPUUsage","platform","require","loadavg","memUsage","memoryUsage","rss","totalmem","calculateEventLoopUtilization","calculateEventLoopLag","_getActiveHandles","length","_getActiveRequests","updateNetworkMetrics","updateDatabaseMetrics","error","message","Math","random","start","Date","now","setImmediate","floor","metricKey","threshold","value","getMetricValue","undefined","handleCriticalThreshold","handleWarningThreshold","keys","split","key","createRecommendation","log","warn","priority","recommendation","inferRecommendationType","title","description","impact","calculateImpact","timestamp","existingIndex","findIndex","r","unshift","slice","includes","gauge","recordMetric","name","ttl","maxSize","evictionPolicy","compressionEnabled","enabled","getCacheStrategy","get","updateCacheHitRate","strategyName","hitRate","recordSlowQuery","query","push","substring","histogram","classifyQuery","upperQuery","toUpperCase","startsWith","analyzePerformance","generateOptimizationRecommendations","memoryUsagePercent","analyzeMemoryUsage","analyzeEventLoopPerformance","analyzeCachePerformance","analyzeDatabasePerformance","memoryGrowthRate","calculateMemoryGrowthRate","generateScalingRecommendations","generateCacheRecommendations","generateDatabaseRecommendations","max","strategy","avgLatency","qps","getCurrentMetrics","getRecommendations","getSlowQueries","getCacheHitRates","clearRecommendations","optimizeCacheStrategy","updates","Object","assign","info","optimizeWebSocketConnections","activeConnections","healthCheck","status","details","Array","from","entries","map","shutdown","clearInterval","createPerformanceOptimizer"],"mappings":"AAAA;;;CAGC,GAED,SAASA,MAAM,QAAQ,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