Press n or j to go to the next uncovered block, b, p or k for the previous block.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 | /** * DebrosFramework - Main Framework Class * * This is the primary entry point for the DebrosFramework, providing a unified * API that integrates all framework components: * - Model system with decorators and validation * - Database management and sharding * - Query system with optimization * - Relationship management with lazy/eager loading * - Automatic pinning and PubSub features * - Migration system for schema evolution * - Configuration and lifecycle management */ import { BaseModel } from './models/BaseModel'; import { ModelRegistry } from './core/ModelRegistry'; import { DatabaseManager } from './core/DatabaseManager'; import { ShardManager } from './sharding/ShardManager'; import { ConfigManager } from './core/ConfigManager'; import { FrameworkOrbitDBService, FrameworkIPFSService } from './services/OrbitDBService'; import { QueryCache } from './query/QueryCache'; import { RelationshipManager } from './relationships/RelationshipManager'; import { PinningManager } from './pinning/PinningManager'; import { PubSubManager } from './pubsub/PubSubManager'; import { MigrationManager } from './migrations/MigrationManager'; import { FrameworkConfig } from './types/framework'; export interface DebrosFrameworkConfig extends FrameworkConfig { // Environment settings environment?: 'development' | 'production' | 'test'; // Service configurations orbitdb?: { directory?: string; options?: any; }; ipfs?: { config?: any; options?: any; }; // Feature toggles features?: { autoMigration?: boolean; automaticPinning?: boolean; pubsub?: boolean; queryCache?: boolean; relationshipCache?: boolean; }; // Performance settings performance?: { queryTimeout?: number; migrationTimeout?: number; maxConcurrentOperations?: number; batchSize?: number; }; // Monitoring and logging monitoring?: { enableMetrics?: boolean; logLevel?: 'error' | 'warn' | 'info' | 'debug'; metricsInterval?: number; }; } export interface FrameworkMetrics { uptime: number; totalModels: number; totalDatabases: number; totalShards: number; queriesExecuted: number; migrationsRun: number; cacheHitRate: number; averageQueryTime: number; memoryUsage: { queryCache: number; relationshipCache: number; total: number; }; performance: { slowQueries: number; failedOperations: number; averageResponseTime: number; }; } export interface FrameworkStatus { initialized: boolean; healthy: boolean; version: string; environment: string; services: { orbitdb: 'connected' | 'disconnected' | 'error'; ipfs: 'connected' | 'disconnected' | 'error'; pinning: 'active' | 'inactive' | 'error'; pubsub: 'active' | 'inactive' | 'error'; }; lastHealthCheck: number; } export class DebrosFramework { private config: DebrosFrameworkConfig; private configManager: ConfigManager; // Core services private orbitDBService: FrameworkOrbitDBService | null = null; private ipfsService: FrameworkIPFSService | null = null; // Framework components private databaseManager: DatabaseManager | null = null; private shardManager: ShardManager | null = null; private queryCache: QueryCache | null = null; private relationshipManager: RelationshipManager | null = null; private pinningManager: PinningManager | null = null; private pubsubManager: PubSubManager | null = null; private migrationManager: MigrationManager | null = null; // Framework state private initialized: boolean = false; private startTime: number = 0; private healthCheckInterval: any = null; private metricsCollector: any = null; private status: FrameworkStatus; private metrics: FrameworkMetrics; constructor(config: DebrosFrameworkConfig = {}) { this.config = this.mergeDefaultConfig(config); this.configManager = new ConfigManager(this.config); this.status = { initialized: false, healthy: false, version: '1.0.0', // This would come from package.json environment: this.config.environment || 'development', services: { orbitdb: 'disconnected', ipfs: 'disconnected', pinning: 'inactive', pubsub: 'inactive', }, lastHealthCheck: 0, }; this.metrics = { uptime: 0, totalModels: 0, totalDatabases: 0, totalShards: 0, queriesExecuted: 0, migrationsRun: 0, cacheHitRate: 0, averageQueryTime: 0, memoryUsage: { queryCache: 0, relationshipCache: 0, total: 0, }, performance: { slowQueries: 0, failedOperations: 0, averageResponseTime: 0, }, }; } // Main initialization method async initialize( existingOrbitDBService?: any, existingIPFSService?: any, overrideConfig?: Partial<DebrosFrameworkConfig>, ): Promise<void> { if (this.initialized) { throw new Error('Framework is already initialized'); } try { this.startTime = Date.now(); console.log('š Initializing DebrosFramework...'); // Apply config overrides if (overrideConfig) { this.config = { ...this.config, ...overrideConfig }; this.configManager = new ConfigManager(this.config); } // Initialize services await this.initializeServices(existingOrbitDBService, existingIPFSService); // Initialize core components await this.initializeCoreComponents(); // Initialize feature components await this.initializeFeatureComponents(); // Setup global framework access this.setupGlobalAccess(); // Start background processes await this.startBackgroundProcesses(); // Run automatic migrations if enabled if (this.config.features?.autoMigration && this.migrationManager) { await this.runAutomaticMigrations(); } this.initialized = true; this.status.initialized = true; this.status.healthy = true; console.log('ā DebrosFramework initialized successfully'); this.logFrameworkInfo(); } catch (error) { console.error('ā Framework initialization failed:', error); await this.cleanup(); throw error; } } // Service initialization private async initializeServices( existingOrbitDBService?: any, existingIPFSService?: any, ): Promise<void> { console.log('š” Initializing core services...'); try { // Initialize IPFS service if (existingIPFSService) { this.ipfsService = new FrameworkIPFSService(existingIPFSService); } else { // In a real implementation, create IPFS instance throw new Error('IPFS service is required. Please provide an existing IPFS instance.'); } await this.ipfsService.init(); this.status.services.ipfs = 'connected'; console.log('ā IPFS service initialized'); // Initialize OrbitDB service if (existingOrbitDBService) { this.orbitDBService = new FrameworkOrbitDBService(existingOrbitDBService); } else { // In a real implementation, create OrbitDB instance throw new Error( 'OrbitDB service is required. Please provide an existing OrbitDB instance.', ); } await this.orbitDBService.init(); this.status.services.orbitdb = 'connected'; console.log('ā OrbitDB service initialized'); } catch (error) { this.status.services.ipfs = 'error'; this.status.services.orbitdb = 'error'; throw new Error(`Service initialization failed: ${error}`); } } // Core component initialization private async initializeCoreComponents(): Promise<void> { console.log('š§ Initializing core components...'); // Database Manager this.databaseManager = new DatabaseManager(this.orbitDBService!); await this.databaseManager.initializeAllDatabases(); console.log('ā DatabaseManager initialized'); // Shard Manager this.shardManager = new ShardManager(); this.shardManager.setOrbitDBService(this.orbitDBService!); // Initialize shards for registered models const globalModels = ModelRegistry.getGlobalModels(); for (const model of globalModels) { if (model.sharding) { await this.shardManager.createShards(model.modelName, model.sharding, model.dbType); } } console.log('ā ShardManager initialized'); // Query Cache if (this.config.features?.queryCache !== false) { const cacheConfig = this.configManager.cacheConfig; this.queryCache = new QueryCache(cacheConfig?.maxSize || 1000, cacheConfig?.ttl || 300000); console.log('ā QueryCache initialized'); } // Relationship Manager this.relationshipManager = new RelationshipManager({ databaseManager: this.databaseManager, shardManager: this.shardManager, queryCache: this.queryCache, }); console.log('ā RelationshipManager initialized'); } // Feature component initialization private async initializeFeatureComponents(): Promise<void> { console.log('šļø Initializing feature components...'); // Pinning Manager if (this.config.features?.automaticPinning !== false) { this.pinningManager = new PinningManager(this.ipfsService!.getHelia(), { maxTotalPins: this.config.performance?.maxConcurrentOperations || 10000, cleanupIntervalMs: 60000, }); // Setup default pinning rules based on config if (this.config.defaultPinning) { const globalModels = ModelRegistry.getGlobalModels(); for (const model of globalModels) { this.pinningManager.setPinningRule(model.modelName, this.config.defaultPinning); } } this.status.services.pinning = 'active'; console.log('ā PinningManager initialized'); } // PubSub Manager if (this.config.features?.pubsub !== false) { this.pubsubManager = new PubSubManager(this.ipfsService!.getHelia(), { enabled: true, autoPublishModelEvents: true, autoPublishDatabaseEvents: true, topicPrefix: `debros-${this.config.environment || 'dev'}`, }); await this.pubsubManager.initialize(); this.status.services.pubsub = 'active'; console.log('ā PubSubManager initialized'); } // Migration Manager this.migrationManager = new MigrationManager( this.databaseManager, this.shardManager, this.createMigrationLogger(), ); console.log('ā MigrationManager initialized'); } // Setup global framework access for models private setupGlobalAccess(): void { (globalThis as any).__debrosFramework = { databaseManager: this.databaseManager, shardManager: this.shardManager, configManager: this.configManager, queryCache: this.queryCache, relationshipManager: this.relationshipManager, pinningManager: this.pinningManager, pubsubManager: this.pubsubManager, migrationManager: this.migrationManager, framework: this, }; } // Start background processes private async startBackgroundProcesses(): Promise<void> { console.log('āļø Starting background processes...'); // Health check interval this.healthCheckInterval = setInterval(() => { this.performHealthCheck(); }, 30000); // Every 30 seconds // Metrics collection if (this.config.monitoring?.enableMetrics !== false) { this.metricsCollector = setInterval(() => { this.collectMetrics(); }, this.config.monitoring?.metricsInterval || 60000); // Every minute } console.log('ā Background processes started'); } // Automatic migration execution private async runAutomaticMigrations(): Promise<void> { if (!this.migrationManager) return; try { console.log('š Running automatic migrations...'); const pendingMigrations = this.migrationManager.getPendingMigrations(); if (pendingMigrations.length > 0) { console.log(`Found ${pendingMigrations.length} pending migrations`); const results = await this.migrationManager.runPendingMigrations({ stopOnError: true, batchSize: this.config.performance?.batchSize || 100, }); const successful = results.filter((r) => r.success).length; console.log(`ā Completed ${successful}/${results.length} migrations`); this.metrics.migrationsRun += successful; } else { console.log('No pending migrations found'); } } catch (error) { console.error('ā Automatic migration failed:', error); if (this.config.environment === 'production') { // In production, don't fail initialization due to migration errors console.warn('Continuing initialization despite migration failure'); } else { throw error; } } } // Public API methods // Model registration registerModel(modelClass: typeof BaseModel, config?: any): void { ModelRegistry.register(modelClass.name, modelClass, config || {}); console.log(`š Registered model: ${modelClass.name}`); this.metrics.totalModels = ModelRegistry.getModelNames().length; } // Get model instance getModel(modelName: string): typeof BaseModel | null { return ModelRegistry.get(modelName) || null; } // Database operations async createUserDatabase(userId: string): Promise<void> { if (!this.databaseManager) { throw new Error('Framework not initialized'); } await this.databaseManager.createUserDatabases(userId); this.metrics.totalDatabases++; } async getUserDatabase(userId: string, modelName: string): Promise<any> { if (!this.databaseManager) { throw new Error('Framework not initialized'); } return await this.databaseManager.getUserDatabase(userId, modelName); } async getGlobalDatabase(modelName: string): Promise<any> { if (!this.databaseManager) { throw new Error('Framework not initialized'); } return await this.databaseManager.getGlobalDatabase(modelName); } // Migration operations async runMigration(migrationId: string, options?: any): Promise<any> { if (!this.migrationManager) { throw new Error('MigrationManager not initialized'); } const result = await this.migrationManager.runMigration(migrationId, options); this.metrics.migrationsRun++; return result; } async registerMigration(migration: any): Promise<void> { if (!this.migrationManager) { throw new Error('MigrationManager not initialized'); } this.migrationManager.registerMigration(migration); } getPendingMigrations(modelName?: string): any[] { if (!this.migrationManager) { return []; } return this.migrationManager.getPendingMigrations(modelName); } // Cache management clearQueryCache(): void { if (this.queryCache) { this.queryCache.clear(); } } clearRelationshipCache(): void { if (this.relationshipManager) { this.relationshipManager.clearRelationshipCache(); } } async warmupCaches(): Promise<void> { console.log('š„ Warming up caches...'); if (this.queryCache) { // Warm up common queries const commonQueries: any[] = []; // Would be populated with actual queries await this.queryCache.warmup(commonQueries); } if (this.relationshipManager && this.pinningManager) { // Warm up relationship cache for popular content // Implementation would depend on actual models } console.log('ā Cache warmup completed'); } // Health and monitoring performHealthCheck(): void { try { this.status.lastHealthCheck = Date.now(); // Check service health this.status.services.orbitdb = this.orbitDBService ? 'connected' : 'disconnected'; this.status.services.ipfs = this.ipfsService ? 'connected' : 'disconnected'; this.status.services.pinning = this.pinningManager ? 'active' : 'inactive'; this.status.services.pubsub = this.pubsubManager ? 'active' : 'inactive'; // Overall health check const allServicesHealthy = Object.values(this.status.services).every( (status) => status === 'connected' || status === 'active', ); this.status.healthy = this.initialized && allServicesHealthy; } catch (error) { console.error('Health check failed:', error); this.status.healthy = false; } } collectMetrics(): void { try { this.metrics.uptime = Date.now() - this.startTime; this.metrics.totalModels = ModelRegistry.getModelNames().length; if (this.queryCache) { const cacheStats = this.queryCache.getStats(); this.metrics.cacheHitRate = cacheStats.hitRate; this.metrics.averageQueryTime = 0; // Would need to be calculated from cache stats this.metrics.memoryUsage.queryCache = cacheStats.size * 1024; // Estimate } if (this.relationshipManager) { const relStats = this.relationshipManager.getRelationshipCacheStats(); this.metrics.memoryUsage.relationshipCache = relStats.cache.memoryUsage; } this.metrics.memoryUsage.total = this.metrics.memoryUsage.queryCache + this.metrics.memoryUsage.relationshipCache; } catch (error) { console.error('Metrics collection failed:', error); } } getStatus(): FrameworkStatus { return { ...this.status }; } getMetrics(): FrameworkMetrics { this.collectMetrics(); // Ensure fresh metrics return { ...this.metrics }; } getConfig(): DebrosFrameworkConfig { return { ...this.config }; } // Component access getDatabaseManager(): DatabaseManager | null { return this.databaseManager; } getShardManager(): ShardManager | null { return this.shardManager; } getRelationshipManager(): RelationshipManager | null { return this.relationshipManager; } getPinningManager(): PinningManager | null { return this.pinningManager; } getPubSubManager(): PubSubManager | null { return this.pubsubManager; } getMigrationManager(): MigrationManager | null { return this.migrationManager; } // Framework lifecycle async stop(): Promise<void> { if (!this.initialized) { return; } console.log('š Stopping DebrosFramework...'); try { await this.cleanup(); this.initialized = false; this.status.initialized = false; this.status.healthy = false; console.log('ā DebrosFramework stopped successfully'); } catch (error) { console.error('ā Error during framework shutdown:', error); throw error; } } async restart(newConfig?: Partial<DebrosFrameworkConfig>): Promise<void> { console.log('š Restarting DebrosFramework...'); const orbitDB = this.orbitDBService?.getOrbitDB(); const ipfs = this.ipfsService?.getHelia(); await this.stop(); if (newConfig) { this.config = { ...this.config, ...newConfig }; } await this.initialize(orbitDB, ipfs); } // Cleanup method private async cleanup(): Promise<void> { // Stop background processes if (this.healthCheckInterval) { clearInterval(this.healthCheckInterval); this.healthCheckInterval = null; } if (this.metricsCollector) { clearInterval(this.metricsCollector); this.metricsCollector = null; } // Cleanup components if (this.pubsubManager) { await this.pubsubManager.shutdown(); } if (this.pinningManager) { await this.pinningManager.shutdown(); } if (this.migrationManager) { await this.migrationManager.cleanup(); } if (this.queryCache) { this.queryCache.clear(); } if (this.relationshipManager) { this.relationshipManager.clearRelationshipCache(); } if (this.databaseManager) { await this.databaseManager.stop(); } if (this.shardManager) { await this.shardManager.stop(); } // Clear global access delete (globalThis as any).__debrosFramework; } // Utility methods private mergeDefaultConfig(config: DebrosFrameworkConfig): DebrosFrameworkConfig { return { environment: 'development', features: { autoMigration: true, automaticPinning: true, pubsub: true, queryCache: true, relationshipCache: true, }, performance: { queryTimeout: 30000, migrationTimeout: 300000, maxConcurrentOperations: 100, batchSize: 100, }, monitoring: { enableMetrics: true, logLevel: 'info', metricsInterval: 60000, }, ...config, }; } private createMigrationLogger(): any { const logLevel = this.config.monitoring?.logLevel || 'info'; return { info: (message: string, meta?: any) => { if (['info', 'debug'].includes(logLevel)) { console.log(`[MIGRATION INFO] ${message}`, meta || ''); } }, warn: (message: string, meta?: any) => { if (['warn', 'info', 'debug'].includes(logLevel)) { console.warn(`[MIGRATION WARN] ${message}`, meta || ''); } }, error: (message: string, meta?: any) => { console.error(`[MIGRATION ERROR] ${message}`, meta || ''); }, debug: (message: string, meta?: any) => { if (logLevel === 'debug') { console.log(`[MIGRATION DEBUG] ${message}`, meta || ''); } }, }; } private logFrameworkInfo(): void { console.log('\nš DebrosFramework Information:'); console.log('=============================='); console.log(`Version: ${this.status.version}`); console.log(`Environment: ${this.status.environment}`); console.log(`Models registered: ${this.metrics.totalModels}`); console.log( `Services: ${Object.entries(this.status.services) .map(([name, status]) => `${name}:${status}`) .join(', ')}`, ); console.log( `Features enabled: ${Object.entries(this.config.features || {}) .filter(([, enabled]) => enabled) .map(([feature]) => feature) .join(', ')}`, ); console.log(''); } // Static factory methods static async create(config: DebrosFrameworkConfig = {}): Promise<DebrosFramework> { const framework = new DebrosFramework(config); return framework; } static async createWithServices( orbitDBService: any, ipfsService: any, config: DebrosFrameworkConfig = {}, ): Promise<DebrosFramework> { const framework = new DebrosFramework(config); await framework.initialize(orbitDBService, ipfsService); return framework; } } // Export the main framework class as default export default DebrosFramework; |