@codai/cbd
Version:
Codai Better Database - High-Performance Vector Memory System with HPKV-inspired architecture and MCP server
274 lines ⢠12 kB
JavaScript
/**
* CBD Universal Database Phase 2 Startup Script
* Production-ready service with all advanced features enabled
*/
import { CBDUniversalServicePhase2 } from './CBDUniversalServicePhase2';
import dotenv from 'dotenv';
// Load environment variables
dotenv.config();
/**
* Main startup function
*/
async function startCBDPhase2() {
console.log('š CBD Universal Database Phase 2 - Starting Production Service...\n');
try {
// Create service instance with production configuration
const cbdService = new CBDUniversalServicePhase2({
server: {
port: parseInt(process.env.CBD_PORT || '4180'),
host: process.env.CBD_HOST || '0.0.0.0',
enableHttps: false,
maxRequestSize: '50mb',
requestTimeout: 60000
},
vectorSearch: {
enabled: true,
openaiApiKey: process.env.OPENAI_API_KEY || '',
maxResults: 20,
similarityThreshold: 0.85
},
machineLearning: {
enabled: true,
openaiApiKey: process.env.OPENAI_API_KEY || '',
autoML: true,
predictiveAnalytics: true
},
realtimeSync: {
enabled: true,
port: parseInt(process.env.CBD_WEBSOCKET_PORT || '4181'),
maxConnections: 2000,
heartbeatInterval: 25000
},
security: {
enabled: true,
jwtSecret: process.env.JWT_SECRET || 'cbd-phase2-production-secret',
jwtExpirationTime: '7d',
rbacEnabled: true,
auditLogging: true
},
performance: {
connectionPoolSize: 50,
cacheSize: 5000,
enableOptimization: true,
metricsInterval: 15000
},
ecosystem: {
enabled: true,
serviceDiscovery: true,
crossServiceSync: true
}
});
// Setup event listeners
setupEventListeners(cbdService);
// Start the service
await cbdService.start();
// Display service information
displayServiceInfo(cbdService);
// Setup graceful shutdown
setupGracefulShutdown(cbdService);
console.log('\nā
CBD Universal Database Phase 2 is now running!');
console.log('š Monitor the service at: http://localhost:4180/stats');
console.log('ā¤ļø Health check at: http://localhost:4180/health\n');
}
catch (error) {
console.error('ā Failed to start CBD Phase 2 service:', error);
process.exit(1);
}
}
/**
* Setup event listeners for the service
*/
function setupEventListeners(service) {
service.on('service-started', (data) => {
console.log('š Service started successfully:', data);
});
service.on('service-error', (error) => {
console.error('ā Service error:', error);
});
service.on('service-stopped', () => {
console.log('š½ Service stopped gracefully');
});
service.on('metrics-updated', (metrics) => {
if (process.env.DEBUG_METRICS === 'true') {
console.log('š Metrics updated:', JSON.stringify(metrics, null, 2));
}
});
}
/**
* Display service information
*/
function displayServiceInfo(service) {
const status = service.getStatus();
const config = service.getConfig();
console.log('\nš Service Configuration:');
console.log('='.repeat(50));
console.log(`š Server: ${config.server.host}:${config.server.port}`);
console.log(`š Vector Search: ${config.vectorSearch.enabled ? 'Enabled' : 'Disabled'}`);
console.log(`š¤ Machine Learning: ${config.machineLearning.enabled ? 'Enabled' : 'Disabled'}`);
console.log(`ā” Real-time Sync: ${config.realtimeSync.enabled ? 'Enabled' : 'Disabled'}`);
console.log(`š Enhanced Security: ${config.security.enabled ? 'Enabled' : 'Disabled'}`);
console.log(`š Ecosystem Integration: ${config.ecosystem.enabled ? 'Enabled' : 'Disabled'}`);
console.log(`š Performance Optimization: ${config.performance.enableOptimization ? 'Enabled' : 'Disabled'}`);
console.log('\nšÆ Available Endpoints:');
console.log('='.repeat(50));
console.log('š GET /health - Health check');
console.log('š GET /stats - Service statistics');
console.log('š GET /api/performance/metrics - Performance metrics');
console.log('ā” POST /api/performance/optimize - Trigger optimization');
if (config.vectorSearch.enabled) {
console.log('š POST /api/vector/search - Hybrid vector search');
console.log('š POST /api/vector/cluster - Vector clustering');
}
if (config.machineLearning.enabled) {
console.log('š¤ POST /api/ml/embedding - Generate embeddings');
console.log('š¤ POST /api/ml/predict - Predictive analytics');
console.log('š¤ POST /api/ml/automl - AutoML operations');
}
if (config.security.enabled) {
console.log('š POST /api/auth/login - User authentication');
console.log('š POST /api/auth/api-key - Generate API key');
console.log('š GET /api/security/audit - Audit logs');
}
if (config.realtimeSync.enabled) {
console.log('ā” POST /api/realtime/subscribe - Create live subscription');
console.log('ā” POST /api/realtime/broadcast - Broadcast data changes');
}
if (config.ecosystem.enabled) {
console.log('š GET /api/ecosystem/services - Connected services');
console.log('š POST /api/ecosystem/operation - Distributed operations');
}
console.log('\nš§ Phase 2 Advanced Features:');
console.log('='.repeat(50));
console.log('ā
Advanced Vector Search Engine - Hybrid search, clustering, optimization');
console.log('ā
Machine Learning Integration - Custom models, AutoML, predictive analytics');
console.log('ā
Real-time Data Synchronization - WebSocket streaming, live queries, conflict resolution');
console.log('ā
Enhanced Security Framework - JWT auth, RBAC, API keys, encryption, audit logging');
console.log('ā
Performance Optimization - Connection pooling, caching, auto-optimization');
console.log('ā
Ecosystem Integration - Service mesh, cross-service sync, monitoring');
}
/**
* Setup graceful shutdown handling
*/
function setupGracefulShutdown(service) {
const gracefulShutdown = async (signal) => {
console.log(`\nš½ Received ${signal}, shutting down gracefully...`);
try {
await service.stop();
console.log('ā
CBD Phase 2 service stopped successfully');
process.exit(0);
}
catch (error) {
console.error('ā Error during shutdown:', error);
process.exit(1);
}
};
// Handle different shutdown signals
process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));
process.on('SIGINT', () => gracefulShutdown('SIGINT'));
process.on('SIGUSR2', () => gracefulShutdown('SIGUSR2')); // nodemon restart
// Handle uncaught exceptions
process.on('uncaughtException', (error) => {
console.error('ā Uncaught Exception:', error);
gracefulShutdown('uncaughtException');
});
// Handle unhandled promise rejections
process.on('unhandledRejection', (reason, promise) => {
console.error('ā Unhandled Rejection at:', promise, 'reason:', reason);
gracefulShutdown('unhandledRejection');
});
}
/**
* Health check function for external monitoring
*/
async function healthCheck() {
try {
const response = await fetch('http://localhost:4180/health');
const data = await response.json();
if (data.status === 'healthy') {
console.log('ā
Health check passed:', data);
return true;
}
else {
console.error('ā Health check failed:', data);
return false;
}
}
catch (error) {
console.error('ā Health check error:', error);
return false;
}
}
/**
* Production readiness check
*/
function checkProductionReadiness() {
const requiredEnvVars = [
'OPENAI_API_KEY',
'JWT_SECRET'
];
const missingVars = requiredEnvVars.filter(varName => !process.env[varName]);
if (missingVars.length > 0) {
console.warn('ā ļø Missing environment variables for production:', missingVars.join(', '));
console.warn('ā ļø Service will run but some features may be limited');
}
if (process.env.NODE_ENV === 'production') {
console.log('š Running in PRODUCTION mode');
// Additional production checks
if (!process.env.JWT_SECRET || process.env.JWT_SECRET.includes('default')) {
console.error('ā CRITICAL: JWT_SECRET must be set to a secure value in production!');
process.exit(1);
}
}
else {
console.log('š§ Running in DEVELOPMENT mode');
}
}
/**
* Display Phase 2 implementation status
*/
function displayPhase2Status() {
console.log('\nšÆ CBD Universal Database - Phase 2 Implementation Status:');
console.log('='.repeat(60));
console.log('ā
Phase 2.1: Feature Enhancement - COMPLETED');
console.log(' āāā Advanced Vector Search Engine - ā
Implemented');
console.log(' āāā Machine Learning Integration - ā
Implemented');
console.log(' āāā Real-time Data Synchronization - ā
Implemented');
console.log(' āāā Enhanced Security Framework - ā
Implemented');
console.log('');
console.log('ā
Phase 2.2: Performance Optimization - COMPLETED');
console.log(' āāā Connection Pooling & Management - ā
Implemented');
console.log(' āāā Intelligent Caching System - ā
Implemented');
console.log(' āāā Query Performance Optimization - ā
Implemented');
console.log(' āāā Memory & CPU Optimization - ā
Implemented');
console.log('');
console.log('ā
Phase 2.3: Integration Testing - COMPLETED');
console.log(' āāā Unit Testing Suite - ā
Implemented');
console.log(' āāā Integration Testing Framework - ā
Implemented');
console.log(' āāā Performance & Load Testing - ā
Implemented');
console.log(' āāā End-to-End Testing - ā
Implemented');
console.log('');
console.log('ā
Phase 2.4: Ecosystem Integration - COMPLETED');
console.log(' āāā Gateway Integration - ā
Implemented');
console.log(' āāā Service Mesh Implementation - ā
Implemented');
console.log(' āāā Cross-Service Data Sync - ā
Implemented');
console.log(' āāā Unified Monitoring & Observability- ā
Implemented');
console.log('');
console.log('š Phase 2: FULLY IMPLEMENTED - PRODUCTION READY!');
console.log('='.repeat(60));
}
// Check if this script is being run directly
if (import.meta.url === `file://${process.argv[1]}`) {
// Display Phase 2 status
displayPhase2Status();
// Check production readiness
checkProductionReadiness();
// Start the service
startCBDPhase2().catch((error) => {
console.error('ā Startup failed:', error);
process.exit(1);
});
}
// Export functions for testing and external use
export { startCBDPhase2, healthCheck, checkProductionReadiness, displayPhase2Status };
//# sourceMappingURL=start-phase2-production.js.map