All files event-bus.js

91.46% Statements 75/82
84.9% Branches 45/53
100% Functions 16/16
92.2% Lines 71/77

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              2x 2x             28x       3x       37x 37x     5x 8x 2x   6x 1x     2x                 26x 26x 26x 26x 26x 26x             2x             31x             16x 16x               16x 13x   16x     16x   16x             3x   3x 3x   3x 3x 3x                 35x 35x   35x                           35x 35x   2x       33x 33x 18x 18x           18x       33x         33x     33x 33x   33x   9x 1x     8x 8x 8x     8x 1x               33x   33x                       33x 33x 5x               6x 6x 3x   6x             26x             3x 3x 4x   3x       2x  
/**
 * EventBus - 事件总线核心实现
 * 
 * 设计模式:事件驱动架构 (EDA)
 * 来源:2026-04-09 23:00 小时学习
 */
 
const EventEmitter = require('events');
const crypto = require('crypto');
 
/**
 * 事件 Schema 验证器
 */
class EventValidator {
  constructor(schemaRegistry = {}) {
    this.schemaRegistry = schemaRegistry;
  }
 
  registerSchema(eventName, schema) {
    this.schemaRegistry[eventName] = schema;
  }
 
  validate(eventName, payload) {
    const schema = this.schemaRegistry[eventName];
    if (!schema) return true; // 无 schema 则跳过验证
 
    // 简单类型检查
    for (const [key, type] of Object.entries(schema)) {
      if (payload[key] === undefined && schema.required?.includes(key)) {
        throw new Error(`Missing required field: ${key}`);
      }
      if (payload[key] !== undefined && typeof payload[key] !== type) {
        throw new Error(`Invalid type for ${key}: expected ${type}, got ${typeof payload[key]}`);
      }
    }
    return true;
  }
}
 
/**
 * 事件总线
 */
class EventBus extends EventEmitter {
  constructor(options = {}) {
    super();
    this.eventHistory = [];
    this.maxHistorySize = options.maxHistorySize || 1000;
    this.validator = new EventValidator();
    this.middlewareChain = [];
    this.subscribers = new Map();
  }
 
  /**
   * 注册事件 Schema
   */
  registerSchema(eventName, schema) {
    this.validator.registerSchema(eventName, schema);
  }
 
  /**
   * 注册中间件
   */
  use(middleware) {
    this.middlewareChain.push(middleware);
  }
 
  /**
   * 订阅事件
   */
  subscribe(eventName, handler, options = {}) {
    const subscriberId = crypto.randomBytes(8).toString('hex');
    const subscriber = {
      id: subscriberId,
      handler,
      priority: options.priority || 0,
      filter: options.filter || null,
      once: options.once || false
    };
 
    if (!this.subscribers.has(eventName)) {
      this.subscribers.set(eventName, []);
    }
    this.subscribers.get(eventName).push(subscriber);
    
    // 按优先级排序
    this.subscribers.get(eventName).sort((a, b) => b.priority - a.priority);
 
    return subscriberId;
  }
 
  /**
   * 取消订阅
   */
  unsubscribe(eventName, subscriberId) {
    Iif (!this.subscribers.has(eventName)) return false;
    
    const subscribers = this.subscribers.get(eventName);
    const index = subscribers.findIndex(s => s.id === subscriberId);
    
    Eif (index !== -1) {
      subscribers.splice(index, 1);
      return true;
    }
    return false;
  }
 
  /**
   * 发布事件
   */
  async publish(eventName, payload = {}, metadata = {}) {
    const eventId = crypto.randomBytes(16).toString('hex');
    const timestamp = Date.now();
    
    const event = {
      id: eventId,
      name: eventName,
      payload,
      metadata: {
        timestamp,
        correlationId: metadata.correlationId || eventId,
        causationId: metadata.causationId || null,
        retryCount: metadata.retryCount || 0
      },
      timestamp
    };
 
    // 验证事件
    try {
      this.validator.validate(eventName, payload);
    } catch (error) {
      throw new Error(`Event validation failed: ${error.message}`);
    }
 
    // 执行中间件链
    let shouldContinue = true;
    for (const middleware of this.middlewareChain) {
      try {
        const result = await middleware(event);
        if (result === false) {
          shouldContinue = false;
          break;
        }
      } catch (error) {
        console.error(`Middleware error: ${error.message}`);
      }
    }
 
    Iif (!shouldContinue) {
      return { eventId, status: 'skipped', reason: 'middleware_blocked' };
    }
 
    // 记录到历史
    this._addToHistory(event);
 
    // 通知订阅者
    const subscribers = this.subscribers.get(eventName) || [];
    const results = [];
    
    for (const subscriber of subscribers) {
      // 应用过滤器
      if (subscriber.filter && !subscriber.filter(payload)) {
        continue;
      }
 
      try {
        const result = await subscriber.handler(event);
        results.push({ subscriberId: subscriber.id, result, status: 'success' });
        
        // 处理 once 订阅
        if (subscriber.once) {
          this.unsubscribe(eventName, subscriber.id);
        }
      } catch (error) {
        results.push({ subscriberId: subscriber.id, error: error.message, status: 'failed' });
      }
    }
 
    // 发出原生事件(兼容 Node.js EventEmitter)
    super.emit(eventName, event);
 
    return {
      eventId,
      status: 'published',
      timestamp,
      subscriberResults: results
    };
  }
 
  /**
   * 添加到历史记录
   */
  _addToHistory(event) {
    this.eventHistory.push(event);
    if (this.eventHistory.length > this.maxHistorySize) {
      this.eventHistory.shift();
    }
  }
 
  /**
   * 获取事件历史
   */
  getHistory(limit = 100, eventName = null) {
    let history = this.eventHistory;
    if (eventName) {
      history = history.filter(e => e.name === eventName);
    }
    return history.slice(-limit);
  }
 
  /**
   * 清空历史
   */
  clearHistory() {
    this.eventHistory = [];
  }
 
  /**
   * 获取订阅者统计
   */
  getSubscriberStats() {
    const stats = {};
    for (const [eventName, subscribers] of this.subscribers.entries()) {
      stats[eventName] = subscribers.length;
    }
    return stats;
  }
}
 
module.exports = { EventBus, EventValidator };