You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
413 lines
14 KiB
413 lines
14 KiB
/**
|
|
* Phase 3.3 Performance Optimization Usage Example
|
|
*
|
|
* Demonstrates comprehensive performance optimization including database, memory, and battery
|
|
* Shows query optimization, memory management, object pooling, and performance monitoring
|
|
*
|
|
* @author Matthew Raymer
|
|
* @version 1.0.0
|
|
*/
|
|
|
|
import { DailyNotification } from '@timesafari/daily-notification-plugin';
|
|
|
|
/**
|
|
* Example: Configure performance optimization
|
|
*/
|
|
async function configurePerformanceOptimization() {
|
|
try {
|
|
console.log('Configuring performance optimization...');
|
|
|
|
// Configure with performance optimization
|
|
await DailyNotification.configure({
|
|
storage: 'shared',
|
|
ttlSeconds: 1800, // 30 minutes TTL
|
|
prefetchLeadMinutes: 15,
|
|
enablePerformanceOptimization: true,
|
|
enableDatabaseIndexes: true,
|
|
enableObjectPooling: true,
|
|
enableMemoryMonitoring: true,
|
|
enableBatteryOptimization: true,
|
|
memoryWarningThreshold: 50, // MB
|
|
memoryCriticalThreshold: 100, // MB
|
|
objectPoolSize: 10,
|
|
maxObjectPoolSize: 50
|
|
});
|
|
|
|
console.log('✅ Performance optimization configured');
|
|
|
|
// The plugin will now:
|
|
// - Add database indexes for query optimization
|
|
// - Implement object pooling for frequently used objects
|
|
// - Monitor memory usage with automatic cleanup
|
|
// - Optimize battery usage and background CPU
|
|
// - Track performance metrics and provide reports
|
|
|
|
} catch (error) {
|
|
console.error('❌ Performance optimization configuration failed:', error);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Example: Demonstrate database optimization
|
|
*/
|
|
async function demonstrateDatabaseOptimization() {
|
|
try {
|
|
console.log('Demonstrating database optimization...');
|
|
|
|
// Configure performance optimization
|
|
await configurePerformanceOptimization();
|
|
|
|
// Optimize database
|
|
console.log('🗄️ Optimizing database...');
|
|
await DailyNotification.optimizeDatabase();
|
|
|
|
// The plugin will:
|
|
// - Add indexes for common queries (slot_id, fetched_at, status, etc.)
|
|
// - Optimize query performance with PRAGMA settings
|
|
// - Implement connection pooling with cache optimization
|
|
// - Analyze database performance and update metrics
|
|
|
|
console.log('✅ Database optimization completed');
|
|
|
|
// Check database performance metrics
|
|
const dbMetrics = await DailyNotification.getDatabaseMetrics();
|
|
console.log('📊 Database Metrics:');
|
|
console.log(` Page Count: ${dbMetrics.pageCount}`);
|
|
console.log(` Page Size: ${dbMetrics.pageSize}`);
|
|
console.log(` Cache Size: ${dbMetrics.cacheSize}`);
|
|
console.log(` Query Performance: ${dbMetrics.queryPerformance}`);
|
|
|
|
} catch (error) {
|
|
console.error('❌ Database optimization demonstration failed:', error);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Example: Demonstrate memory optimization
|
|
*/
|
|
async function demonstrateMemoryOptimization() {
|
|
try {
|
|
console.log('Demonstrating memory optimization...');
|
|
|
|
// Configure performance optimization
|
|
await configurePerformanceOptimization();
|
|
|
|
// Check initial memory usage
|
|
const initialMemory = await DailyNotification.getMemoryUsage();
|
|
console.log(`📊 Initial Memory Usage: ${initialMemory.usage}MB`);
|
|
|
|
// Optimize memory
|
|
console.log('🧠 Optimizing memory...');
|
|
await DailyNotification.optimizeMemory();
|
|
|
|
// The plugin will:
|
|
// - Check current memory usage
|
|
// - Perform cleanup if thresholds exceeded
|
|
// - Optimize object pools
|
|
// - Clear old caches
|
|
// - Update memory metrics
|
|
|
|
console.log('✅ Memory optimization completed');
|
|
|
|
// Check memory after optimization
|
|
const optimizedMemory = await DailyNotification.getMemoryUsage();
|
|
console.log(`📊 Optimized Memory Usage: ${optimizedMemory.usage}MB`);
|
|
console.log(`📊 Memory Reduction: ${initialMemory.usage - optimizedMemory.usage}MB`);
|
|
|
|
// Check memory metrics
|
|
const memoryMetrics = await DailyNotification.getMemoryMetrics();
|
|
console.log('📊 Memory Metrics:');
|
|
console.log(` Average Usage: ${memoryMetrics.averageUsage}MB`);
|
|
console.log(` Peak Usage: ${memoryMetrics.peakUsage}MB`);
|
|
console.log(` Cleanup Count: ${memoryMetrics.cleanupCount}`);
|
|
console.log(` Critical Cleanups: ${memoryMetrics.criticalCleanupCount}`);
|
|
|
|
} catch (error) {
|
|
console.error('❌ Memory optimization demonstration failed:', error);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Example: Demonstrate object pooling
|
|
*/
|
|
async function demonstrateObjectPooling() {
|
|
try {
|
|
console.log('Demonstrating object pooling...');
|
|
|
|
// Configure performance optimization
|
|
await configurePerformanceOptimization();
|
|
|
|
// Get objects from pool
|
|
console.log('🔄 Using object pooling...');
|
|
|
|
const objects = [];
|
|
for (let i = 0; i < 5; i++) {
|
|
const obj = await DailyNotification.getPooledObject('String');
|
|
objects.push(obj);
|
|
console.log(` Got object ${i + 1} from pool`);
|
|
}
|
|
|
|
// Return objects to pool
|
|
for (let i = 0; i < objects.length; i++) {
|
|
await DailyNotification.returnPooledObject('String', objects[i]);
|
|
console.log(` Returned object ${i + 1} to pool`);
|
|
}
|
|
|
|
// The plugin will:
|
|
// - Reuse objects from pool instead of creating new ones
|
|
// - Reduce memory allocation and garbage collection
|
|
// - Track pool hits and misses
|
|
// - Optimize pool sizes based on usage patterns
|
|
|
|
console.log('✅ Object pooling demonstration completed');
|
|
|
|
// Check object pool metrics
|
|
const poolMetrics = await DailyNotification.getObjectPoolMetrics();
|
|
console.log('📊 Object Pool Metrics:');
|
|
console.log(` Pool Hits: ${poolMetrics.poolHits}`);
|
|
console.log(` Pool Misses: ${poolMetrics.poolMisses}`);
|
|
console.log(` Hit Ratio: ${(poolMetrics.hitRatio * 100).toFixed(1)}%`);
|
|
console.log(` Active Pools: ${poolMetrics.activePools}`);
|
|
|
|
} catch (error) {
|
|
console.error('❌ Object pooling demonstration failed:', error);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Example: Demonstrate battery optimization
|
|
*/
|
|
async function demonstrateBatteryOptimization() {
|
|
try {
|
|
console.log('Demonstrating battery optimization...');
|
|
|
|
// Configure performance optimization
|
|
await configurePerformanceOptimization();
|
|
|
|
// Optimize battery usage
|
|
console.log('🔋 Optimizing battery usage...');
|
|
await DailyNotification.optimizeBattery();
|
|
|
|
// The plugin will:
|
|
// - Minimize background CPU usage
|
|
// - Optimize network requests for efficiency
|
|
// - Track battery usage patterns
|
|
// - Adjust behavior based on battery level
|
|
// - Reduce task frequency during low battery
|
|
|
|
console.log('✅ Battery optimization completed');
|
|
|
|
// Check battery metrics
|
|
const batteryMetrics = await DailyNotification.getBatteryMetrics();
|
|
console.log('📊 Battery Metrics:');
|
|
console.log(` Background CPU Usage: ${batteryMetrics.backgroundCpuUsage}%`);
|
|
console.log(` Network Efficiency: ${batteryMetrics.networkEfficiency}%`);
|
|
console.log(` Battery Level: ${batteryMetrics.batteryLevel}%`);
|
|
console.log(` Power Saving Mode: ${batteryMetrics.powerSavingMode ? 'Enabled' : 'Disabled'}`);
|
|
|
|
} catch (error) {
|
|
console.error('❌ Battery optimization demonstration failed:', error);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Example: Monitor performance metrics
|
|
*/
|
|
async function monitorPerformanceMetrics() {
|
|
try {
|
|
console.log('Monitoring performance metrics...');
|
|
|
|
// Configure performance optimization
|
|
await configurePerformanceOptimization();
|
|
|
|
// Get comprehensive performance metrics
|
|
const performanceMetrics = await DailyNotification.getPerformanceMetrics();
|
|
|
|
console.log('📊 Performance Metrics:');
|
|
console.log(` Overall Score: ${performanceMetrics.overallScore}/100`);
|
|
console.log(` Database Performance: ${performanceMetrics.databasePerformance}/100`);
|
|
console.log(` Memory Efficiency: ${performanceMetrics.memoryEfficiency}/100`);
|
|
console.log(` Battery Efficiency: ${performanceMetrics.batteryEfficiency}/100`);
|
|
console.log(` Object Pool Efficiency: ${performanceMetrics.objectPoolEfficiency}/100`);
|
|
|
|
// Detailed metrics
|
|
console.log('📊 Detailed Metrics:');
|
|
console.log(` Database Queries: ${performanceMetrics.totalDatabaseQueries}`);
|
|
console.log(` Memory Usage: ${performanceMetrics.averageMemoryUsage}MB`);
|
|
console.log(` Object Pool Hits: ${performanceMetrics.objectPoolHits}`);
|
|
console.log(` Background CPU: ${performanceMetrics.backgroundCpuUsage}%`);
|
|
console.log(` Network Requests: ${performanceMetrics.totalNetworkRequests}`);
|
|
|
|
// Performance recommendations
|
|
if (performanceMetrics.recommendations.length > 0) {
|
|
console.log('💡 Performance Recommendations:');
|
|
performanceMetrics.recommendations.forEach((rec, index) => {
|
|
console.log(` ${index + 1}. ${rec}`);
|
|
});
|
|
}
|
|
|
|
} catch (error) {
|
|
console.error('❌ Performance metrics monitoring failed:', error);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Example: Performance optimization for production
|
|
*/
|
|
async function optimizeForProduction() {
|
|
try {
|
|
console.log('Optimizing for production...');
|
|
|
|
// Configure production-optimized settings
|
|
await DailyNotification.configure({
|
|
storage: 'shared',
|
|
ttlSeconds: 1800,
|
|
prefetchLeadMinutes: 15,
|
|
enablePerformanceOptimization: true,
|
|
enableDatabaseIndexes: true,
|
|
enableObjectPooling: true,
|
|
enableMemoryMonitoring: true,
|
|
enableBatteryOptimization: true,
|
|
memoryWarningThreshold: 30, // Lower threshold for production
|
|
memoryCriticalThreshold: 60, // Lower threshold for production
|
|
objectPoolSize: 20, // Larger pool for production
|
|
maxObjectPoolSize: 100, // Larger max pool for production
|
|
enablePerformanceReporting: true,
|
|
performanceReportInterval: 3600000 // 1 hour
|
|
});
|
|
|
|
console.log('✅ Production optimization configured');
|
|
|
|
// Run all optimizations
|
|
console.log('🚀 Running production optimizations...');
|
|
|
|
await DailyNotification.optimizeDatabase();
|
|
await DailyNotification.optimizeMemory();
|
|
await DailyNotification.optimizeBattery();
|
|
|
|
console.log('✅ Production optimizations completed');
|
|
|
|
// Schedule notifications with optimized performance
|
|
await DailyNotification.scheduleDailyNotification({
|
|
url: 'https://api.example.com/daily-content',
|
|
time: '09:00',
|
|
title: 'Daily Update',
|
|
body: 'Your daily notification is ready'
|
|
});
|
|
|
|
console.log('✅ Notification scheduled with production optimization');
|
|
|
|
// The plugin will now:
|
|
// - Use optimized database queries with indexes
|
|
// - Manage memory efficiently with automatic cleanup
|
|
// - Pool objects to reduce allocation overhead
|
|
// - Monitor battery usage and adjust behavior
|
|
// - Provide comprehensive performance reporting
|
|
// - Handle high load scenarios gracefully
|
|
|
|
} catch (error) {
|
|
console.error('❌ Production optimization failed:', error);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Example: Performance stress testing
|
|
*/
|
|
async function performanceStressTesting() {
|
|
try {
|
|
console.log('Running performance stress testing...');
|
|
|
|
// Configure performance optimization
|
|
await configurePerformanceOptimization();
|
|
|
|
// Stress test with multiple operations
|
|
const operations = [];
|
|
for (let i = 0; i < 10; i++) {
|
|
operations.push(
|
|
DailyNotification.scheduleDailyNotification({
|
|
url: 'https://api.example.com/daily-content',
|
|
time: `09:${i.toString().padStart(2, '0')}`,
|
|
title: `Daily Update ${i + 1}`,
|
|
body: 'Your daily notification is ready'
|
|
})
|
|
);
|
|
}
|
|
|
|
console.log('📡 Executing 10 concurrent operations...');
|
|
const startTime = Date.now();
|
|
|
|
await Promise.all(operations);
|
|
|
|
const endTime = Date.now();
|
|
const duration = endTime - startTime;
|
|
|
|
console.log(`✅ Stress test completed in ${duration}ms`);
|
|
|
|
// Check performance under load
|
|
const stressMetrics = await DailyNotification.getPerformanceMetrics();
|
|
console.log('📊 Stress Test Results:');
|
|
console.log(` Operations Completed: 10`);
|
|
console.log(` Total Duration: ${duration}ms`);
|
|
console.log(` Average per Operation: ${duration / 10}ms`);
|
|
console.log(` Performance Score: ${stressMetrics.overallScore}/100`);
|
|
console.log(` Memory Usage: ${stressMetrics.averageMemoryUsage}MB`);
|
|
|
|
// Performance should remain stable under load
|
|
if (stressMetrics.overallScore >= 80) {
|
|
console.log('✅ Excellent performance under load');
|
|
} else if (stressMetrics.overallScore >= 60) {
|
|
console.log('✅ Good performance under load');
|
|
} else {
|
|
console.log('⚠️ Performance degradation under load detected');
|
|
}
|
|
|
|
} catch (error) {
|
|
console.error('❌ Performance stress testing failed:', error);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Example: Reset performance metrics
|
|
*/
|
|
async function resetPerformanceMetrics() {
|
|
try {
|
|
console.log('Resetting performance metrics...');
|
|
|
|
// Configure performance optimization
|
|
await configurePerformanceOptimization();
|
|
|
|
// Get metrics before reset
|
|
const beforeMetrics = await DailyNotification.getPerformanceMetrics();
|
|
console.log('📊 Before Reset:');
|
|
console.log(` Overall Score: ${beforeMetrics.overallScore}/100`);
|
|
console.log(` Database Queries: ${beforeMetrics.totalDatabaseQueries}`);
|
|
console.log(` Memory Usage: ${beforeMetrics.averageMemoryUsage}MB`);
|
|
|
|
// Reset metrics
|
|
await DailyNotification.resetPerformanceMetrics();
|
|
console.log('✅ Performance metrics reset');
|
|
|
|
// Get metrics after reset
|
|
const afterMetrics = await DailyNotification.getPerformanceMetrics();
|
|
console.log('📊 After Reset:');
|
|
console.log(` Overall Score: ${afterMetrics.overallScore}/100`);
|
|
console.log(` Database Queries: ${afterMetrics.totalDatabaseQueries}`);
|
|
console.log(` Memory Usage: ${afterMetrics.averageMemoryUsage}MB`);
|
|
|
|
} catch (error) {
|
|
console.error('❌ Performance metrics reset failed:', error);
|
|
}
|
|
}
|
|
|
|
// Export examples for use
|
|
export {
|
|
configurePerformanceOptimization,
|
|
demonstrateDatabaseOptimization,
|
|
demonstrateMemoryOptimization,
|
|
demonstrateObjectPooling,
|
|
demonstrateBatteryOptimization,
|
|
monitorPerformanceMetrics,
|
|
optimizeForProduction,
|
|
performanceStressTesting,
|
|
resetPerformanceMetrics
|
|
};
|
|
|