UNPKG

bigbasealpha

Version:

Professional Grade Custom Database System - A sophisticated, dependency-free database with encryption, caching, indexing, and web dashboard

305 lines (253 loc) • 10.2 kB
import BigBaseAlpha from '../src/alpha.js'; /** * BigBaseAlpha Terminal UI Framework and Performance Analytics Demo * * This example demonstrates the new features added in v1.3.0: * - Terminal UI Framework with charts, tables, and monitors * - Performance Analytics and profiling capabilities */ async function demonstrateTerminalUI() { console.log('šŸŽØ BigBaseAlpha Terminal UI Framework Demo\n'.rainbow); const alpha = new BigBaseAlpha({ path: './demo_data', encryption: false, ui: { theme: 'default', colors: true, animation: true }, performance: { enableProfiling: true, sampleInterval: 500 } }); await alpha.init(); // 1. Bar Chart Demo console.log('šŸ“Š Creating Bar Chart...'.cyan); const barChart = alpha.createChart({ type: 'bar', values: [ { label: 'Users', value: 150 }, { label: 'Orders', value: 89 }, { label: 'Products', value: 200 }, { label: 'Reviews', value: 67 } ] }, { title: 'Database Collections Stats', color: 'green', width: 40 }); barChart.render(); await sleep(2000); // 2. Line Chart Demo console.log('\nšŸ“ˆ Creating Line Chart...'.cyan); const performanceData = Array.from({ length: 20 }, (_, i) => Math.sin(i * 0.3) * 50 + 50 + Math.random() * 10 ); const lineChart = alpha.createChart({ type: 'line', values: performanceData }, { title: 'Query Performance Over Time', color: 'blue', width: 50 }); lineChart.render(); await sleep(2000); // 3. Pie Chart Demo console.log('\nšŸ° Creating Pie Chart...'.cyan); const pieChart = alpha.createChart({ type: 'pie', values: [ { label: 'JSON Files', value: 45 }, { label: 'Binary Files', value: 30 }, { label: 'CSV Files', value: 15 }, { label: 'XML Files', value: 10 } ] }, { title: 'Storage Format Distribution', color: 'magenta' }); pieChart.render(); await sleep(2000); // 4. Table Demo console.log('\nšŸ“‹ Creating Data Table...'.cyan); const sampleData = [ { ID: 1, Name: 'John Doe', Role: 'Admin', Status: 'Active', LastLogin: '2025-08-02' }, { ID: 2, Name: 'Jane Smith', Role: 'User', Status: 'Active', LastLogin: '2025-08-01' }, { ID: 3, Name: 'Bob Johnson', Role: 'User', Status: 'Inactive', LastLogin: '2025-07-30' }, { ID: 4, Name: 'Alice Brown', Role: 'Moderator', Status: 'Active', LastLogin: '2025-08-02' } ]; const table = alpha.createTable(sampleData, { title: 'User Management Table', sortBy: 'Name' }); table.render(); await sleep(2000); // 5. Progress Bar Demo console.log('\nā³ Creating Progress Bar...'.cyan); const progressBar = alpha.createProgressBar(0, { total: 100, width: 50, color: 'yellow', showPercent: true }); for (let i = 0; i <= 100; i += 10) { const progress = alpha.createProgressBar(i, { total: 100, width: 50, color: i > 80 ? 'green' : i > 50 ? 'yellow' : 'red', showPercent: true }); progress.render(); await sleep(300); } console.log('\nāœ… Progress Complete!'.green); await sleep(1000); alpha.close(); } async function demonstratePerformanceAnalytics() { console.log('\nšŸ” BigBaseAlpha Performance Analytics Demo\n'.rainbow); const alpha = new BigBaseAlpha({ path: './demo_data', encryption: false, performance: { enableProfiling: true, sampleInterval: 500, maxSamples: 100 } }); await alpha.init(); // 1. CPU Monitoring Demo console.log('šŸ’» Starting CPU Monitoring (5 seconds)...'.cyan); const cpuMonitor = alpha.monitor('cpu', { duration: 5000, interval: 500 }); // Simulate some CPU work setTimeout(() => { for (let i = 0; i < 1000000; i++) { Math.sqrt(i); } }, 2000); await sleep(6000); cpuMonitor.stop(); // 2. Memory Monitoring Demo console.log('\n🧠 Starting Memory Monitoring (5 seconds)...'.cyan); const memoryMonitor = alpha.monitor('memory', { duration: 5000, interval: 500 }); // Simulate memory usage const bigArray = []; setTimeout(() => { for (let i = 0; i < 100000; i++) { bigArray.push(new Array(100).fill(Math.random())); } }, 2000); await sleep(6000); memoryMonitor.stop(); // 3. Query Profiling Demo console.log('\nšŸ“Š Query Profiling Demo...'.cyan); // Create some test data await alpha.createCollection('performance_test'); const testData = Array.from({ length: 1000 }, (_, i) => ({ id: i, name: `User ${i}`, email: `user${i}@example.com`, age: Math.floor(Math.random() * 80) + 18, status: Math.random() > 0.5 ? 'active' : 'inactive' })); for (const item of testData) { await alpha.insert('performance_test', item); } // Profile query execution console.log('Executing profiled query...'.yellow); const queryResult = await alpha.executeQueryWithProfiling('performance_test', { age: { $gte: 25, $lte: 35 }, status: 'active' }, { realtime: false }); console.log('\nšŸ“ˆ Query Performance Results:'.green); console.log(`Duration: ${queryResult.performance.duration.toFixed(2)}ms`); console.log(`Results: ${queryResult.data.length} records`); console.log(`Efficiency: ${queryResult.analysis.efficiency.toFixed(1)}%`); console.log(`Memory Delta: ${(queryResult.performance.memoryDelta.heapUsed / 1024).toFixed(2)} KB`); if (queryResult.analysis.recommendations.length > 0) { console.log('\nšŸ’” Recommendations:'.yellow); queryResult.analysis.recommendations.forEach(rec => { console.log(` • ${rec}`); }); } // 4. System Metrics Demo console.log('\nšŸ–„ļø Current System Metrics:'.cyan); const metrics = alpha.getSystemMetrics(); const metricsTable = alpha.createTable([ { Metric: 'CPU Cores', Value: metrics.cpu.cores.length }, { Metric: 'Avg CPU Usage', Value: `${metrics.cpu.average.toFixed(1)}%` }, { Metric: 'Total Memory', Value: `${(metrics.memory.system.total / 1024 / 1024 / 1024).toFixed(2)} GB` }, { Metric: 'Memory Usage', Value: `${metrics.memory.system.percentage.toFixed(1)}%` }, { Metric: 'Process Memory', Value: `${(metrics.memory.process.heapUsed / 1024 / 1024).toFixed(2)} MB` } ], { title: 'System Performance Metrics' }); metricsTable.render(); // 5. Performance Report console.log('\nšŸ“‹ Generating Performance Report...'.cyan); const report = alpha.generatePerformanceReport({ format: 'terminal', includeCharts: true }); await sleep(2000); // 6. Combined Dashboard Demo (if we have multiple components) console.log('\nšŸŽ›ļø Creating Performance Dashboard...'.cyan); const dashboardComponents = [ alpha.createChart({ type: 'bar', values: [ { label: 'Query Time', value: queryResult.performance.duration }, { label: 'Memory Used', value: queryResult.performance.memoryDelta.heapUsed / 1024 }, { label: 'CPU Time', value: queryResult.performance.cpuDelta.user / 1000 } ] }, { title: 'Performance Metrics', color: 'green' }), alpha.createTable([ { Component: 'Query Engine', Status: 'Healthy', Response: '< 50ms' }, { Component: 'Storage Engine', Status: 'Healthy', Response: '< 10ms' }, { Component: 'Cache System', Status: 'Healthy', Response: '< 5ms' }, { Component: 'Index Manager', Status: 'Healthy', Response: '< 15ms' } ], { title: 'Component Health Status' }) ]; alpha.createDashboard(dashboardComponents); await sleep(3000); alpha.close(); } async function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } // Run the demonstrations async function runDemos() { try { await demonstrateTerminalUI(); await sleep(2000); await demonstratePerformanceAnalytics(); console.log('\nšŸŽ‰ Demo completed successfully!'.rainbow); console.log('\nšŸ“š Available UI Components:'.cyan); console.log(' • alpha.createChart({ type: "bar|line|pie", data })'); console.log(' • alpha.createTable(data, options)'); console.log(' • alpha.createLogMonitor(source, options)'); console.log(' • alpha.createProgressBar(current, options)'); console.log(' • alpha.createDashboard(components)'); console.log('\nšŸ” Available Performance Methods:'.cyan); console.log(' • alpha.monitor("cpu|memory|disk|all", options)'); console.log(' • alpha.startProfile(name, options)'); console.log(' • alpha.endProfile(name)'); console.log(' • alpha.executeQueryWithProfiling(collection, query)'); console.log(' • alpha.generatePerformanceReport(options)'); console.log(' • alpha.getSystemMetrics()'); } catch (error) { console.error('Demo error:', error); } } // Check if this file is being run directly if (import.meta.url === `file://${process.argv[1]}`) { runDemos(); } export { demonstrateTerminalUI, demonstratePerformanceAnalytics };