import { HttpApp } from '../src/infra/http/base-http-app'; import { MemoryMonitoringPlugin, MemoryMonitoringPluginOptions } from '../src/infra/http/plugins/plugins/memory-monitoring-plugin'; import { HealthCheckPlugin } from '../src/infra/http/plugins/plugins/health-check-plugin'; import { MetricsPlugin } from '../src/infra/http/plugins/plugins/metrics-plugin'; // Example: Basic Memory Monitoring Plugin Usage async function basicMemoryMonitoringExample() { console.log('=== Basic Memory Monitoring Plugin Example ==='); const app = new HttpApp(); // Create memory monitoring plugin with default settings const memoryPlugin = new MemoryMonitoringPlugin(); // Install the plugin app.usePlugin(memoryPlugin); // Add some routes to generate memory activity app.get('/test', (req, res) => { // Simulate some memory usage const data = new Array(1000).fill(0).map((_, i) => ({ id: i, data: 'test' })); res.json({ message: 'Test route', dataLength: data.length }); }); app.get('/memory-intensive', (req, res) => { // Simulate memory intensive operation const largeArray = new Array(100000).fill(0).map((_, i) => ({ id: i, timestamp: Date.now(), data: `Large data item ${i}`, nested: { value: Math.random(), array: new Array(100).fill(Math.random()) } })); res.json({ message: 'Memory intensive operation completed', items: largeArray.length, memoryUsage: process.memoryUsage() }); }); // Start the application await app.start(3000); console.log('Application started on port 3000'); console.log('Available memory monitoring endpoints:'); console.log('- GET /memory/stats - Detailed memory statistics'); console.log('- GET /memory/summary - Memory summary with status'); console.log('- GET /memory/leaks - Detected memory leaks'); console.log('- GET /memory/history - Memory usage history'); console.log('- POST /memory/gc - Force garbage collection'); console.log('- GET /memory/health - Memory health check'); console.log('- GET /test - Test route'); console.log('- GET /memory-intensive - Memory intensive test route'); // Demonstrate plugin methods setTimeout(() => { console.log('\n=== Plugin Methods Demo ==='); const stats = memoryPlugin.getMemoryStats(); console.log('Current memory stats:', { used: `${(stats.current.used / 1024 / 1024).toFixed(2)} MB`, percentage: `${stats.current.percentage.toFixed(2)}%`, leaks: stats.leaks.length }); const summary = memoryPlugin.getMemorySummary(); console.log('Memory summary:', { status: summary.status, uptime: `${summary.uptime}s`, leaks: summary.leaks }); const config = memoryPlugin.getConfig(); console.log('Plugin configuration:', { basePath: config.basePath, exposeEndpoints: config.exposeEndpoints, autoGC: config.autoGC }); }, 2000); } // Example: Advanced Memory Monitoring with Custom Configuration async function advancedMemoryMonitoringExample() { console.log('\n=== Advanced Memory Monitoring Plugin Example ==='); const app = new HttpApp(); // Custom memory monitoring configuration const memoryOptions: MemoryMonitoringPluginOptions = { basePath: '/advanced-memory', exposeEndpoints: true, includeInRequest: true, autoGC: true, gcThreshold: 80, // Trigger GC at 80% memory usage interval: 15000, // Check every 15 seconds threshold: { used: 1024 * 1024 * 1024, // 1GB percentage: 75, // 75% heapUsed: 512 * 1024 * 1024, // 512MB rss: 1024 * 1024 * 1024 // 1GB }, leakDetection: { enabled: true, consecutiveGrowths: 2, // Detect leak after 2 consecutive growths growthThreshold: 5, // 5% growth threshold maxHistory: 30 // Keep 30 snapshots }, onLeak: (leakInfo) => { console.log('🚨 Memory leak detected!', { severity: leakInfo.severity, growth: `${leakInfo.growth.percentage.toFixed(2)}%`, current: `${(leakInfo.current.used / 1024 / 1024).toFixed(2)} MB` }); }, onThreshold: (memoryInfo) => { console.log('⚠️ Memory threshold exceeded!', { used: `${(memoryInfo.used / 1024 / 1024).toFixed(2)} MB`, percentage: `${memoryInfo.percentage.toFixed(2)}%` }); } }; // Create memory monitoring plugin with custom options const memoryPlugin = new MemoryMonitoringPlugin(memoryOptions); // Install the plugin app.usePlugin(memoryPlugin); // Add routes that will trigger memory events app.get('/leak-test', (req, res) => { // Simulate potential memory leak const leakyData = []; for (let i = 0; i < 10000; i++) { leakyData.push({ id: i, data: new Array(100).fill('leaky data'), timestamp: Date.now() }); } res.json({ message: 'Leak test completed', items: leakyData.length, note: 'This might trigger memory leak detection' }); }); app.get('/gc-test', (req, res) => { // Force garbage collection memoryPlugin.forceGC(); const beforeGC = memoryPlugin.getMemoryStats().current; res.json({ message: 'Garbage collection triggered', memoryBeforeGC: { used: `${(beforeGC.used / 1024 / 1024).toFixed(2)} MB`, percentage: `${beforeGC.percentage.toFixed(2)}%` } }); }); // Start the application await app.start(3001); console.log('Advanced memory monitoring application started on port 3001'); console.log('Available endpoints:'); console.log('- GET /advanced-memory/stats - Detailed memory statistics'); console.log('- GET /advanced-memory/summary - Memory summary'); console.log('- GET /advanced-memory/leaks - Memory leaks'); console.log('- GET /advanced-memory/history - Memory history'); console.log('- POST /advanced-memory/gc - Force GC'); console.log('- GET /advanced-memory/health - Health check'); console.log('- GET /leak-test - Trigger potential memory leak'); console.log('- GET /gc-test - Test garbage collection'); } // Example: Combining Multiple Monitoring Plugins async function combinedMonitoringExample() { console.log('\n=== Combined Monitoring Plugins Example ==='); const app = new HttpApp(); // Install multiple monitoring plugins const healthPlugin = new HealthCheckPlugin({ path: '/health', checks: [] }); const metricsPlugin = new MetricsPlugin({ metricsPath: '/metrics', metricsFormat: 'prometheus' }); const memoryPlugin = new MemoryMonitoringPlugin({ basePath: '/memory', autoGC: true }); // Add custom health checks that use memory monitoring healthPlugin.addHealthCheck({ name: 'memory', check: () => { const summary = memoryPlugin.getMemorySummary(); return { status: summary.status === 'healthy' ? 'healthy' : 'unhealthy', message: `Memory usage: ${summary.current.percentage.toFixed(2)}%`, data: summary }; }, critical: true }); healthPlugin.addHealthCheck({ name: 'memory-leaks', check: () => { const leaks = memoryPlugin.getMemoryLeaks(); return { status: leaks.length === 0 ? 'healthy' : 'unhealthy', message: `${leaks.length} memory leaks detected`, data: { leaks: leaks.length } }; } }); // Install all plugins app.usePlugin(healthPlugin); app.usePlugin(metricsPlugin); app.usePlugin(memoryPlugin); // Add a comprehensive monitoring dashboard route app.get('/monitoring/dashboard', (req, res) => { const healthStats = healthPlugin.getHealthChecks(); const memoryStats = memoryPlugin.getMemoryStats(); const memorySummary = memoryPlugin.getMemorySummary(); res.json({ timestamp: new Date().toISOString(), health: { checks: healthStats.length, status: 'ok' // Simplified for demo }, memory: { current: memoryStats.current, summary: memorySummary, leaks: memoryStats.leaks.length, history: memoryStats.history.length }, endpoints: { health: '/health', metrics: '/metrics', memory: { stats: '/memory/stats', summary: '/memory/summary', leaks: '/memory/leaks', history: '/memory/history', gc: 'POST /memory/gc', health: '/memory/health' } } }); }); // Start the application await app.start(3002); console.log('Combined monitoring application started on port 3002'); console.log('Available endpoints:'); console.log('- GET /health - Health checks (includes memory checks)'); console.log('- GET /metrics - Prometheus metrics'); console.log('- GET /memory/* - Memory monitoring endpoints'); console.log('- GET /monitoring/dashboard - Combined monitoring dashboard'); } // Run examples async function runExamples() { try { await basicMemoryMonitoringExample(); // Wait a bit before starting the next example await new Promise(resolve => setTimeout(resolve, 5000)); await advancedMemoryMonitoringExample(); // Wait a bit before starting the next example await new Promise(resolve => setTimeout(resolve, 5000)); await combinedMonitoringExample(); console.log('\n=== All Examples Completed ==='); console.log('You can now test the endpoints in different terminals:'); console.log('Terminal 1: curl http://localhost:3000/memory/stats'); console.log('Terminal 2: curl http://localhost:3001/advanced-memory/summary'); console.log('Terminal 3: curl http://localhost:3002/monitoring/dashboard'); } catch (error) { console.error('Error running examples:', error); } } // Export for use in other files export { basicMemoryMonitoringExample, advancedMemoryMonitoringExample, combinedMonitoringExample, runExamples }; // Run if this file is executed directly if (require.main === module) { runExamples(); }