- Implement WebSocket augmentation for real-time communication - Implement WebRTC augmentation for peer-to-peer connections - Implement HTTP augmentation as minimal REST fallback - Add auto-discovery augmentation for data pattern analysis - Add adaptive storage augmentation for intelligent resource management - Add environment adapter augmentation for universal compatibility - Template auto-detects environment (browser, Node.js, serverless, containers) - Intelligent transport selection (WebRTC → WebSocket → HTTP) - Automatic storage optimization (memory → filesystem → S3) - Zero configuration required - just npm start - Includes intelligent verb scoring by default - Works in any environment without configuration - Full documentation and examples included
4 lines
No EOL
14 KiB
JavaScript
4 lines
No EOL
14 KiB
JavaScript
import { logger } from '../utils/logger.js'
|
|
|
|
/**
|
|
* Environment Adapter Augmentation - Adapts Brainy to any runtime environment\n * Automatically configures optimal settings for browser, Node.js, serverless, containers, etc.\n */\nexport class EnvironmentAdapterAugmentation {\n constructor(capabilities) {\n this.type = 'CONDUIT'\n this.priority = 1 // Highest priority - runs first\n this.capabilities = capabilities\n this.adaptations = []\n this.environmentOptimizations = []\n \n this.db = null\n }\n\n async augment(brainyData, context) {\n this.db = brainyData\n \n try {\n // Apply environment-specific optimizations\n await this.applyEnvironmentOptimizations()\n \n // Setup environment-specific monitoring\n this.setupEnvironmentMonitoring()\n \n // Configure runtime adaptations\n this.configureRuntimeAdaptations()\n \n logger.info('Environment Adapter augmentation initialized', {\n environment: this.capabilities.environment,\n platform: this.capabilities.platform,\n optimizations: this.environmentOptimizations.length,\n adaptations: this.adaptations.length\n })\n \n } catch (error) {\n logger.error('Failed to initialize Environment Adapter augmentation:', error)\n throw error\n }\n }\n\n async applyEnvironmentOptimizations() {\n const { environment, platform, runtime, network } = this.capabilities\n \n // Browser environment optimizations\n if (platform.isBrowser) {\n await this.applyBrowserOptimizations()\n }\n \n // Node.js environment optimizations\n if (platform.isNode) {\n await this.applyNodeOptimizations()\n }\n \n // Serverless environment optimizations\n if (platform.isServerless) {\n await this.applyServerlessOptimizations()\n }\n \n // Container environment optimizations\n if (platform.isContainer) {\n await this.applyContainerOptimizations()\n }\n \n // Edge environment optimizations\n if (platform.isEdge) {\n await this.applyEdgeOptimizations()\n }\n \n // Kubernetes-specific optimizations\n if (environment === 'kubernetes') {\n await this.applyKubernetesOptimizations()\n }\n }\n\n async applyBrowserOptimizations() {\n this.environmentOptimizations.push({\n type: 'browser',\n description: 'Browser environment detected',\n optimizations: [\n 'Using OPFS storage when available',\n 'Web Workers for background processing',\n 'IndexedDB fallback for persistence',\n 'WebRTC peer-to-peer communication',\n 'Service Worker for offline capability'\n ]\n })\n \n // Configure browser-specific settings\n if (this.db.updateConfiguration) {\n await this.db.updateConfiguration({\n storage: {\n preferOPFS: true,\n fallbackToIndexedDB: true\n },\n performance: {\n useWebWorkers: true,\n backgroundProcessing: true\n },\n network: {\n enableWebRTC: true,\n preferPeerToPeer: true\n }\n })\n }\n \n logger.info('Applied browser optimizations')\n }\n\n async applyNodeOptimizations() {\n this.environmentOptimizations.push({\n type: 'node',\n description: 'Node.js environment detected',\n optimizations: [\n 'Worker threads for parallel processing',\n 'Filesystem storage with async I/O',\n 'Clustering for multi-core utilization',\n 'Memory-mapped files for large datasets',\n 'Native module optimizations'\n ]\n })\n \n // Configure Node.js-specific settings\n if (this.db.updateConfiguration) {\n await this.db.updateConfiguration({\n performance: {\n useWorkerThreads: this.capabilities.runtime.supportsWorkers,\n enableClustering: this.capabilities.memory.isHighMemory,\n memoryMapping: true\n },\n storage: {\n asyncIO: true,\n bufferSize: this.capabilities.memory.isHighMemory ? 64 * 1024 : 16 * 1024\n }\n })\n }\n \n logger.info('Applied Node.js optimizations')\n }\n\n async applyServerlessOptimizations() {\n this.environmentOptimizations.push({\n type: 'serverless',\n description: 'Serverless environment detected',\n optimizations: [\n 'Memory-only storage for fast cold starts',\n 'Minimal initialization overhead',\n 'Stateless operation mode',\n 'Aggressive caching strategies',\n 'Connection pooling disabled'\n ]\n })\n \n // Configure serverless-specific settings\n if (this.db.updateConfiguration) {\n await this.db.updateConfiguration({\n storage: {\n forceMemoryStorage: true,\n skipPersistence: true\n },\n performance: {\n fastStartup: true,\n minimalInitialization: true,\n statelessMode: true\n },\n cache: {\n aggressiveCaching: true,\n preloadFrequentQueries: true\n },\n network: {\n disableConnectionPooling: true,\n shortTimeouts: true\n }\n })\n }\n \n logger.info('Applied serverless optimizations')\n }\n\n async applyContainerOptimizations() {\n this.environmentOptimizations.push({\n type: 'container',\n description: 'Container environment detected',\n optimizations: [\n 'Volume-based persistent storage',\n 'Resource-aware scaling',\n 'Health check endpoints',\n 'Graceful shutdown handling',\n 'Logging to stdout/stderr'\n ]\n })\n \n // Configure container-specific settings\n if (this.db.updateConfiguration) {\n await this.db.updateConfiguration({\n storage: {\n useVolumes: true,\n persistentPath: '/app/data'\n },\n monitoring: {\n healthChecks: true,\n metricsEndpoint: true\n },\n lifecycle: {\n gracefulShutdown: true,\n shutdownTimeout: 30000\n },\n logging: {\n outputToStdout: true,\n structuredLogging: true\n }\n })\n }\n \n logger.info('Applied container optimizations')\n }\n\n async applyEdgeOptimizations() {\n this.environmentOptimizations.push({\n type: 'edge',\n description: 'Edge computing environment detected',\n optimizations: [\n 'Ultra-low latency configuration',\n 'Minimal resource usage',\n 'Edge-specific storage adapters',\n 'Geographic load balancing',\n 'CDN integration'\n ]\n })\n \n // Configure edge-specific settings\n if (this.db.updateConfiguration) {\n await this.db.updateConfiguration({\n performance: {\n ultraLowLatency: true,\n minimalFootprint: true,\n edgeOptimized: true\n },\n storage: {\n edgeStorage: true,\n replicationStrategy: 'geographic'\n },\n cache: {\n edgeCaching: true,\n cdnIntegration: true\n }\n })\n }\n \n logger.info('Applied edge computing optimizations')\n }\n\n async applyKubernetesOptimizations() {\n this.environmentOptimizations.push({\n type: 'kubernetes',\n description: 'Kubernetes environment detected',\n optimizations: [\n 'Pod-aware resource management',\n 'ConfigMap and Secret integration',\n 'Horizontal pod autoscaling support',\n 'Service mesh compatibility',\n 'Distributed storage coordination'\n ]\n })\n \n // Configure Kubernetes-specific settings\n if (this.db.updateConfiguration) {\n await this.db.updateConfiguration({\n kubernetes: {\n podAware: true,\n useConfigMaps: true,\n useSecrets: true\n },\n scaling: {\n horizontalPodAutoscaling: true,\n resourceRequests: this.calculateResourceRequests()\n },\n storage: {\n distributedCoordination: true,\n persistentVolumeClaims: true\n },\n networking: {\n serviceMesh: true,\n inClusterService: true\n }\n })\n }\n \n logger.info('Applied Kubernetes optimizations')\n }\n\n setupEnvironmentMonitoring() {\n const { environment, platform } = this.capabilities\n \n // Setup platform-specific monitoring\n if (platform.isNode) {\n this.setupNodeMonitoring()\n }\n \n if (platform.isBrowser) {\n this.setupBrowserMonitoring()\n }\n \n if (platform.isServerless) {\n this.setupServerlessMonitoring()\n }\n \n logger.debug('Environment monitoring configured', { environment, platform })\n }\n\n setupNodeMonitoring() {\n // Monitor Node.js specific metrics\n setInterval(() => {\n const usage = process.memoryUsage()\n const cpuUsage = process.cpuUsage()\n \n // Check for memory leaks\n if (usage.heapUsed > usage.heapTotal * 0.9) {\n this.recordAdaptation({\n type: 'memory-warning',\n description: 'High memory usage detected in Node.js environment',\n action: 'Consider enabling garbage collection or reducing cache size'\n })\n }\n \n }, 60000) // Check every minute\n }\n\n setupBrowserMonitoring() {\n // Monitor browser-specific metrics\n if (typeof window !== 'undefined') {\n // Monitor connection status\n window.addEventListener('online', () => {\n this.recordAdaptation({\n type: 'connectivity-restored',\n description: 'Browser connectivity restored',\n action: 'Resume network operations'\n })\n })\n \n window.addEventListener('offline', () => {\n this.recordAdaptation({\n type: 'connectivity-lost',\n description: 'Browser went offline',\n action: 'Switch to offline mode'\n })\n })\n }\n }\n\n setupServerlessMonitoring() {\n // Monitor serverless-specific metrics\n const startTime = Date.now()\n \n // Monitor cold start time\n setTimeout(() => {\n const warmupTime = Date.now() - startTime\n \n this.recordAdaptation({\n type: 'cold-start-measurement',\n description: `Serverless cold start completed in ${warmupTime}ms`,\n action: warmupTime > 5000 ? 'Consider optimizing initialization' : 'Cold start performance acceptable'\n })\n }, 100)\n }\n\n configureRuntimeAdaptations() {\n // Configure adaptations based on runtime characteristics\n if (this.capabilities.runtime.isLongRunning) {\n this.adaptations.push({\n type: 'long-running',\n description: 'Long-running process detected',\n configuration: {\n enableBackgroundOptimization: true,\n periodicMaintenance: true,\n statisticsCollection: true\n }\n })\n } else {\n this.adaptations.push({\n type: 'short-lived',\n description: 'Short-lived process detected',\n configuration: {\n fastStartup: true,\n minimalInitialization: true,\n skipPeriodicTasks: true\n }\n })\n }\n \n if (this.capabilities.network.supportsPeerToPeer) {\n this.adaptations.push({\n type: 'peer-to-peer',\n description: 'Peer-to-peer networking supported',\n configuration: {\n enableWebRTC: true,\n enablePeerDiscovery: true,\n preferDirectConnections: true\n }\n })\n }\n }\n\n calculateResourceRequests() {\n // Calculate optimal resource requests for Kubernetes\n const memoryMB = this.capabilities.memory.available\n const isHighPerformance = this.capabilities.memory.isHighMemory\n \n return {\n memory: `${Math.max(128, Math.min(memoryMB, 1024))}Mi`,\n cpu: isHighPerformance ? '500m' : '250m'\n }\n }\n\n recordAdaptation(adaptation) {\n const record = {\n ...adaptation,\n timestamp: new Date().toISOString(),\n environment: this.capabilities.environment,\n platform: this.capabilities.platform\n }\n \n this.adaptations.push(record)\n \n // Keep only recent adaptations\n if (this.adaptations.length > 100) {\n this.adaptations = this.adaptations.slice(-100)\n }\n \n logger.debug('Environment adaptation recorded', {\n type: adaptation.type,\n description: adaptation.description\n })\n }\n\n // Public API methods\n getEnvironmentInfo() {\n return {\n capabilities: this.capabilities,\n optimizations: this.environmentOptimizations,\n adaptations: this.adaptations.slice(-10), // Last 10 adaptations\n recommendations: this.getEnvironmentRecommendations()\n }\n }\n\n getEnvironmentRecommendations() {\n const recommendations = []\n \n // Environment-specific recommendations\n if (this.capabilities.platform.isServerless && this.capabilities.storage.filesystem) {\n recommendations.push({\n type: 'storage',\n priority: 'high',\n title: 'Serverless with persistent storage detected',\n description: 'Filesystem storage may not persist across function invocations',\n action: 'Consider using memory storage or external storage service'\n })\n }\n \n if (this.capabilities.environment === 'production' && this.capabilities.storage.memory) {\n recommendations.push({\n type: 'production',\n priority: 'high',\n title: 'Production environment using memory storage',\n description: 'Data will not persist across restarts',\n action: 'Configure persistent storage (filesystem or S3)'\n })\n }\n \n if (this.capabilities.memory.available < 512 && this.capabilities.platform.isNode) {\n recommendations.push({\n type: 'performance',\n priority: 'medium',\n title: 'Low memory environment detected',\n description: `Only ${this.capabilities.memory.available}MB available`,\n action: 'Consider increasing memory limits or using memory-optimized configuration'\n })\n }\n \n return recommendations\n }\n\n async cleanup() {\n // Cleanup environment-specific resources\n logger.info('Environment Adapter augmentation cleaned up')\n }\n}
|