All files / framework/pubsub PubSubManager.ts

0% Statements 0/228
0% Branches 0/110
0% Functions 0/37
0% Lines 0/220

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 
/**
 * PubSubManager - Automatic Event Publishing and Subscription
 *
 * This class handles automatic publishing of model changes and database events
 * to IPFS PubSub topics, enabling real-time synchronization across nodes:
 * - Model-level events (create, update, delete)
 * - Database-level events (replication, sync)
 * - Custom application events
 * - Topic management and subscription handling
 * - Event filtering and routing
 */
 
import { BaseModel } from '../models/BaseModel';
 
// Node.js types for compatibility
declare global {
  namespace NodeJS {
    interface Timeout {}
  }
}
 
export interface PubSubConfig {
  enabled: boolean;
  autoPublishModelEvents: boolean;
  autoPublishDatabaseEvents: boolean;
  topicPrefix: string;
  maxRetries: number;
  retryDelay: number;
  eventBuffer: {
    enabled: boolean;
    maxSize: number;
    flushInterval: number;
  };
  compression: {
    enabled: boolean;
    threshold: number; // bytes
  };
  encryption: {
    enabled: boolean;
    publicKey?: string;
    privateKey?: string;
  };
}
 
export interface PubSubEvent {
  id: string;
  type: string;
  topic: string;
  data: any;
  timestamp: number;
  source: string;
  metadata?: any;
}
 
export interface TopicSubscription {
  topic: string;
  handler: (event: PubSubEvent) => void | Promise<void>;
  filter?: (event: PubSubEvent) => boolean;
  options: {
    autoAck: boolean;
    maxRetries: number;
    deadLetterTopic?: string;
  };
}
 
export interface PubSubStats {
  totalPublished: number;
  totalReceived: number;
  totalSubscriptions: number;
  publishErrors: number;
  receiveErrors: number;
  averageLatency: number;
  topicStats: Map<
    string,
    {
      published: number;
      received: number;
      subscribers: number;
      lastActivity: number;
    }
  >;
}
 
export class PubSubManager {
  private ipfsService: any;
  private config: PubSubConfig;
  private subscriptions: Map<string, TopicSubscription[]> = new Map();
  private eventBuffer: PubSubEvent[] = [];
  private bufferFlushInterval: any = null;
  private stats: PubSubStats;
  private latencyMeasurements: number[] = [];
  private nodeId: string;
  private isInitialized: boolean = false;
  private eventListeners: Map<string, Function[]> = new Map();
 
  constructor(ipfsService: any, config: Partial<PubSubConfig> = {}) {
    this.ipfsService = ipfsService;
    this.nodeId = `node-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
 
    this.config = {
      enabled: true,
      autoPublishModelEvents: true,
      autoPublishDatabaseEvents: true,
      topicPrefix: 'debros',
      maxRetries: 3,
      retryDelay: 1000,
      eventBuffer: {
        enabled: true,
        maxSize: 100,
        flushInterval: 5000,
      },
      compression: {
        enabled: true,
        threshold: 1024,
      },
      encryption: {
        enabled: false,
      },
      ...config,
    };
 
    this.stats = {
      totalPublished: 0,
      totalReceived: 0,
      totalSubscriptions: 0,
      publishErrors: 0,
      receiveErrors: 0,
      averageLatency: 0,
      topicStats: new Map(),
    };
  }
 
  // Simple event emitter functionality
  emit(event: string, ...args: any[]): boolean {
    const listeners = this.eventListeners.get(event) || [];
    listeners.forEach((listener) => {
      try {
        listener(...args);
      } catch (error) {
        console.error(`Error in event listener for ${event}:`, error);
      }
    });
    return listeners.length > 0;
  }
 
  on(event: string, listener: Function): this {
    if (!this.eventListeners.has(event)) {
      this.eventListeners.set(event, []);
    }
    this.eventListeners.get(event)!.push(listener);
    return this;
  }
 
  off(event: string, listener?: Function): this {
    if (!listener) {
      this.eventListeners.delete(event);
    } else {
      const listeners = this.eventListeners.get(event) || [];
      const index = listeners.indexOf(listener);
      if (index >= 0) {
        listeners.splice(index, 1);
      }
    }
    return this;
  }
 
  // Initialize PubSub system
  async initialize(): Promise<void> {
    if (!this.config.enabled) {
      console.log('📡 PubSub disabled in configuration');
      return;
    }
 
    try {
      console.log('📡 Initializing PubSubManager...');
 
      // Start event buffer flushing if enabled
      if (this.config.eventBuffer.enabled) {
        this.startEventBuffering();
      }
 
      // Subscribe to model events if auto-publishing is enabled
      if (this.config.autoPublishModelEvents) {
        this.setupModelEventPublishing();
      }
 
      // Subscribe to database events if auto-publishing is enabled
      if (this.config.autoPublishDatabaseEvents) {
        this.setupDatabaseEventPublishing();
      }
 
      this.isInitialized = true;
      console.log('✅ PubSubManager initialized successfully');
    } catch (error) {
      console.error('❌ Failed to initialize PubSubManager:', error);
      throw error;
    }
  }
 
  // Publish event to a topic
  async publish(
    topic: string,
    data: any,
    options: {
      priority?: 'low' | 'normal' | 'high';
      retries?: number;
      compress?: boolean;
      encrypt?: boolean;
      metadata?: any;
    } = {},
  ): Promise<boolean> {
    if (!this.config.enabled || !this.isInitialized) {
      return false;
    }
 
    const event: PubSubEvent = {
      id: this.generateEventId(),
      type: this.extractEventType(topic),
      topic: this.prefixTopic(topic),
      data,
      timestamp: Date.now(),
      source: this.nodeId,
      metadata: options.metadata,
    };
 
    try {
      // Process event (compression, encryption, etc.)
      const processedData = await this.processEventForPublishing(event, options);
 
      // Publish with buffering or directly
      if (this.config.eventBuffer.enabled && options.priority !== 'high') {
        return this.bufferEvent(event, processedData);
      } else {
        return await this.publishDirect(event.topic, processedData, options.retries);
      }
    } catch (error) {
      this.stats.publishErrors++;
      console.error(`❌ Failed to publish to ${topic}:`, error);
      this.emit('publishError', { topic, error, event });
      return false;
    }
  }
 
  // Subscribe to a topic
  async subscribe(
    topic: string,
    handler: (event: PubSubEvent) => void | Promise<void>,
    options: {
      filter?: (event: PubSubEvent) => boolean;
      autoAck?: boolean;
      maxRetries?: number;
      deadLetterTopic?: string;
    } = {},
  ): Promise<boolean> {
    if (!this.config.enabled || !this.isInitialized) {
      return false;
    }
 
    const fullTopic = this.prefixTopic(topic);
 
    try {
      const subscription: TopicSubscription = {
        topic: fullTopic,
        handler,
        filter: options.filter,
        options: {
          autoAck: options.autoAck !== false,
          maxRetries: options.maxRetries || this.config.maxRetries,
          deadLetterTopic: options.deadLetterTopic,
        },
      };
 
      // Add to subscriptions map
      if (!this.subscriptions.has(fullTopic)) {
        this.subscriptions.set(fullTopic, []);
 
        // Subscribe to IPFS PubSub topic
        await this.ipfsService.pubsub.subscribe(fullTopic, (message: any) => {
          this.handleIncomingMessage(fullTopic, message);
        });
      }
 
      this.subscriptions.get(fullTopic)!.push(subscription);
      this.stats.totalSubscriptions++;
 
      // Update topic stats
      this.updateTopicStats(fullTopic, 'subscribers', 1);
 
      console.log(`📡 Subscribed to topic: ${fullTopic}`);
      this.emit('subscribed', { topic: fullTopic, subscription });
 
      return true;
    } catch (error) {
      console.error(`❌ Failed to subscribe to ${topic}:`, error);
      this.emit('subscribeError', { topic, error });
      return false;
    }
  }
 
  // Unsubscribe from a topic
  async unsubscribe(topic: string, handler?: Function): Promise<boolean> {
    const fullTopic = this.prefixTopic(topic);
    const subscriptions = this.subscriptions.get(fullTopic);
 
    if (!subscriptions) {
      return false;
    }
 
    try {
      if (handler) {
        // Remove specific handler
        const index = subscriptions.findIndex((sub) => sub.handler === handler);
        if (index >= 0) {
          subscriptions.splice(index, 1);
          this.stats.totalSubscriptions--;
        }
      } else {
        // Remove all handlers for this topic
        this.stats.totalSubscriptions -= subscriptions.length;
        subscriptions.length = 0;
      }
 
      // If no more subscriptions, unsubscribe from IPFS
      if (subscriptions.length === 0) {
        await this.ipfsService.pubsub.unsubscribe(fullTopic);
        this.subscriptions.delete(fullTopic);
        this.stats.topicStats.delete(fullTopic);
      }
 
      console.log(`📡 Unsubscribed from topic: ${fullTopic}`);
      this.emit('unsubscribed', { topic: fullTopic });
 
      return true;
    } catch (error) {
      console.error(`❌ Failed to unsubscribe from ${topic}:`, error);
      return false;
    }
  }
 
  // Setup automatic model event publishing
  private setupModelEventPublishing(): void {
    const topics = {
      create: 'model.created',
      update: 'model.updated',
      delete: 'model.deleted',
      save: 'model.saved',
    };
 
    // Listen for model events on the global framework instance
    this.on('modelEvent', async (eventType: string, model: BaseModel, changes?: any) => {
      const topic = topics[eventType as keyof typeof topics];
      if (!topic) return;
 
      const eventData = {
        modelName: model.constructor.name,
        modelId: model.id,
        userId: (model as any).userId,
        changes,
        timestamp: Date.now(),
      };
 
      await this.publish(topic, eventData, {
        priority: eventType === 'delete' ? 'high' : 'normal',
        metadata: {
          modelType: model.constructor.name,
          scope: (model.constructor as any).scope,
        },
      });
    });
  }
 
  // Setup automatic database event publishing
  private setupDatabaseEventPublishing(): void {
    const databaseTopics = {
      replication: 'database.replicated',
      sync: 'database.synced',
      conflict: 'database.conflict',
      error: 'database.error',
    };
 
    // Listen for database events
    this.on('databaseEvent', async (eventType: string, data: any) => {
      const topic = databaseTopics[eventType as keyof typeof databaseTopics];
      if (!topic) return;
 
      await this.publish(topic, data, {
        priority: eventType === 'error' ? 'high' : 'normal',
        metadata: {
          eventType,
          source: 'database',
        },
      });
    });
  }
 
  // Handle incoming PubSub messages
  private async handleIncomingMessage(topic: string, message: any): Promise<void> {
    try {
      const startTime = Date.now();
 
      // Parse and validate message
      const event = await this.processIncomingMessage(message);
      if (!event) return;
 
      // Update stats
      this.stats.totalReceived++;
      this.updateTopicStats(topic, 'received', 1);
 
      // Calculate latency
      const latency = Date.now() - event.timestamp;
      this.latencyMeasurements.push(latency);
      if (this.latencyMeasurements.length > 100) {
        this.latencyMeasurements.shift();
      }
      this.stats.averageLatency =
        this.latencyMeasurements.reduce((a, b) => a + b, 0) / this.latencyMeasurements.length;
 
      // Route to subscribers
      const subscriptions = this.subscriptions.get(topic) || [];
 
      for (const subscription of subscriptions) {
        try {
          // Apply filter if present
          if (subscription.filter && !subscription.filter(event)) {
            continue;
          }
 
          // Call handler
          await this.callHandlerWithRetry(subscription, event);
        } catch (error: any) {
          this.stats.receiveErrors++;
          console.error(`❌ Handler error for ${topic}:`, error);
 
          // Send to dead letter topic if configured
          if (subscription.options.deadLetterTopic) {
            await this.publish(subscription.options.deadLetterTopic, {
              originalTopic: topic,
              originalEvent: event,
              error: error?.message || String(error),
              timestamp: Date.now(),
            });
          }
        }
      }
 
      this.emit('messageReceived', { topic, event, processingTime: Date.now() - startTime });
    } catch (error) {
      this.stats.receiveErrors++;
      console.error(`❌ Failed to handle message from ${topic}:`, error);
      this.emit('messageError', { topic, error });
    }
  }
 
  // Call handler with retry logic
  private async callHandlerWithRetry(
    subscription: TopicSubscription,
    event: PubSubEvent,
    attempt: number = 1,
  ): Promise<void> {
    try {
      await subscription.handler(event);
    } catch (error) {
      if (attempt < subscription.options.maxRetries) {
        console.warn(
          `🔄 Retrying handler (attempt ${attempt + 1}/${subscription.options.maxRetries})`,
        );
        await new Promise((resolve) => setTimeout(resolve, this.config.retryDelay * attempt));
        return this.callHandlerWithRetry(subscription, event, attempt + 1);
      }
      throw error;
    }
  }
 
  // Process event for publishing (compression, encryption, etc.)
  private async processEventForPublishing(event: PubSubEvent, options: any): Promise<string> {
    let data = JSON.stringify(event);
 
    // Compression
    if (
      options.compress !== false &&
      this.config.compression.enabled &&
      data.length > this.config.compression.threshold
    ) {
      // In a real implementation, you'd use a compression library like zlib
      // data = await compress(data);
    }
 
    // Encryption
    if (
      options.encrypt !== false &&
      this.config.encryption.enabled &&
      this.config.encryption.publicKey
    ) {
      // In a real implementation, you'd encrypt with the public key
      // data = await encrypt(data, this.config.encryption.publicKey);
    }
 
    return data;
  }
 
  // Process incoming message
  private async processIncomingMessage(message: any): Promise<PubSubEvent | null> {
    try {
      let data = message.data.toString();
 
      // Decryption
      if (this.config.encryption.enabled && this.config.encryption.privateKey) {
        // In a real implementation, you'd decrypt with the private key
        // data = await decrypt(data, this.config.encryption.privateKey);
      }
 
      // Decompression
      if (this.config.compression.enabled) {
        // In a real implementation, you'd detect and decompress
        // data = await decompress(data);
      }
 
      const event = JSON.parse(data) as PubSubEvent;
 
      // Validate event structure
      if (!event.id || !event.topic || !event.timestamp) {
        console.warn('❌ Invalid event structure received');
        return null;
      }
 
      // Ignore our own messages
      if (event.source === this.nodeId) {
        return null;
      }
 
      return event;
    } catch (error) {
      console.error('❌ Failed to process incoming message:', error);
      return null;
    }
  }
 
  // Direct publish without buffering
  private async publishDirect(
    topic: string,
    data: string,
    retries: number = this.config.maxRetries,
  ): Promise<boolean> {
    for (let attempt = 1; attempt <= retries; attempt++) {
      try {
        await this.ipfsService.pubsub.publish(topic, data);
 
        this.stats.totalPublished++;
        this.updateTopicStats(topic, 'published', 1);
 
        return true;
      } catch (error) {
        if (attempt === retries) {
          throw error;
        }
 
        console.warn(`🔄 Retrying publish (attempt ${attempt + 1}/${retries})`);
        await new Promise((resolve) => setTimeout(resolve, this.config.retryDelay * attempt));
      }
    }
 
    return false;
  }
 
  // Buffer event for batch publishing
  private bufferEvent(event: PubSubEvent, _data: string): boolean {
    if (this.eventBuffer.length >= this.config.eventBuffer.maxSize) {
      // Buffer is full, flush immediately
      this.flushEventBuffer();
    }
 
    this.eventBuffer.push(event);
    return true;
  }
 
  // Start event buffering
  private startEventBuffering(): void {
    this.bufferFlushInterval = setInterval(() => {
      this.flushEventBuffer();
    }, this.config.eventBuffer.flushInterval);
  }
 
  // Flush event buffer
  private async flushEventBuffer(): Promise<void> {
    if (this.eventBuffer.length === 0) return;
 
    const events = [...this.eventBuffer];
    this.eventBuffer.length = 0;
 
    console.log(`📡 Flushing ${events.length} buffered events`);
 
    // Group events by topic for efficiency
    const eventsByTopic = new Map<string, PubSubEvent[]>();
    for (const event of events) {
      if (!eventsByTopic.has(event.topic)) {
        eventsByTopic.set(event.topic, []);
      }
      eventsByTopic.get(event.topic)!.push(event);
    }
 
    // Publish batches
    for (const [topic, topicEvents] of eventsByTopic) {
      try {
        for (const event of topicEvents) {
          const data = await this.processEventForPublishing(event, {});
          await this.publishDirect(topic, data);
        }
      } catch (error) {
        console.error(`❌ Failed to flush events for ${topic}:`, error);
        this.stats.publishErrors += topicEvents.length;
      }
    }
  }
 
  // Update topic statistics
  private updateTopicStats(
    topic: string,
    metric: 'published' | 'received' | 'subscribers',
    delta: number,
  ): void {
    if (!this.stats.topicStats.has(topic)) {
      this.stats.topicStats.set(topic, {
        published: 0,
        received: 0,
        subscribers: 0,
        lastActivity: Date.now(),
      });
    }
 
    const stats = this.stats.topicStats.get(topic)!;
    stats[metric] += delta;
    stats.lastActivity = Date.now();
  }
 
  // Utility methods
  private generateEventId(): string {
    return `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
  }
 
  private extractEventType(topic: string): string {
    const parts = topic.split('.');
    return parts[parts.length - 1];
  }
 
  private prefixTopic(topic: string): string {
    return `${this.config.topicPrefix}.${topic}`;
  }
 
  // Get PubSub statistics
  getStats(): PubSubStats {
    return { ...this.stats };
  }
 
  // Get list of active topics
  getActiveTopics(): string[] {
    return Array.from(this.subscriptions.keys());
  }
 
  // Get subscribers for a topic
  getTopicSubscribers(topic: string): number {
    const fullTopic = this.prefixTopic(topic);
    return this.subscriptions.get(fullTopic)?.length || 0;
  }
 
  // Check if topic exists
  hasSubscriptions(topic: string): boolean {
    const fullTopic = this.prefixTopic(topic);
    return this.subscriptions.has(fullTopic) && this.subscriptions.get(fullTopic)!.length > 0;
  }
 
  // Clear all subscriptions
  async clearAllSubscriptions(): Promise<void> {
    const topics = Array.from(this.subscriptions.keys());
 
    for (const topic of topics) {
      try {
        await this.ipfsService.pubsub.unsubscribe(topic);
      } catch (error) {
        console.error(`Failed to unsubscribe from ${topic}:`, error);
      }
    }
 
    this.subscriptions.clear();
    this.stats.topicStats.clear();
    this.stats.totalSubscriptions = 0;
 
    console.log(`📡 Cleared all ${topics.length} subscriptions`);
  }
 
  // Shutdown
  async shutdown(): Promise<void> {
    console.log('📡 Shutting down PubSubManager...');
 
    // Stop event buffering
    if (this.bufferFlushInterval) {
      clearInterval(this.bufferFlushInterval as any);
      this.bufferFlushInterval = null;
    }
 
    // Flush remaining events
    await this.flushEventBuffer();
 
    // Clear all subscriptions
    await this.clearAllSubscriptions();
 
    // Clear event listeners
    this.eventListeners.clear();
 
    this.isInitialized = false;
    console.log('✅ PubSubManager shut down successfully');
  }
}