All files middleware-chain.js

96.87% Statements 62/64
88.57% Branches 31/35
100% Functions 15/15
96.72% Lines 59/61

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                        19x 19x       2x             2x   1x 1x   1x 1x             2x                 4x       3x 3x 2x 1x   1x   1x 1x                   5x 5x       2x   2x 1x 1x     1x           2x 4x 4x   3x 3x 3x       1x       3x                 18x 18x 18x       5x 5x     5x 6x 3x     3x         5x 5x 1x 1x       4x 2x   4x   4x                 4x       7x       3x 6x 6x       5x 1x     1x       2x       2x              
/**
 * Middleware Chain - 中间件链实现
 * 
 * 设计模式:Middleware 链模式
 * 来源:2026-04-09 13:00 小时学习(DeerFlow 架构)
 */
 
/**
 * 日志中间件
 */
class LoggingMiddleware {
  constructor(options = {}) {
    this.logLevel = options.logLevel || 'info';
    this.logger = options.logger || console;
  }
 
  async handle(event) {
    const logEntry = {
      timestamp: new Date(event.timestamp).toISOString(),
      eventId: event.id,
      eventName: event.name,
      correlationId: event.metadata.correlationId
    };
 
    switch (this.logLevel) {
      case 'debug':
        this.logger.debug('[EVENT]', JSON.stringify(logEntry), 'Payload:', event.payload);
        break;
      case 'info':
        this.logger.info('[EVENT]', event.name, '→', event.id);
        break;
      case 'warn':
      case 'error':
        // 只记录警告和错误
        break;
    }
 
    return true; // 继续处理
  }
}
 
/**
 * 验证中间件
 */
class ValidationMiddleware {
  constructor(validatorFn) {
    this.validatorFn = validatorFn;
  }
 
  async handle(event) {
    try {
      const isValid = await this.validatorFn(event);
      if (!isValid) {
        return false; // 阻止事件处理
      }
      return true;
    } catch (error) {
      console.error('Validation error:', error.message);
      return false;
    }
  }
}
 
/**
 * 重试中间件
 */
class RetryMiddleware {
  constructor(options = {}) {
    this.maxRetries = options.maxRetries || 3;
    this.retryDelay = options.retryDelay || 1000;
  }
 
  async handle(event) {
    const { retryCount } = event.metadata;
    
    if (retryCount >= this.maxRetries) {
      console.warn(`Event ${event.name} exceeded max retries (${this.maxRetries})`);
      return false;
    }
 
    return true;
  }
 
  async retry(event, handler) {
    let lastError;
    
    for (let i = 0; i < this.maxRetries; i++) {
      try {
        return await handler(event);
      } catch (error) {
        lastError = error;
        console.warn(`Retry ${i + 1}/${this.maxRetries} for event ${event.name}`);
        await this._delay(this.retryDelay * (i + 1)); // 指数退避
      }
    }
 
    throw lastError;
  }
 
  _delay(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
  }
}
 
/**
 * 速率限制中间件
 */
class RateLimitMiddleware {
  constructor(options = {}) {
    this.maxEvents = options.maxEvents || 100;
    this.windowMs = options.windowMs || 60000; // 1 分钟
    this.eventCounts = new Map();
  }
 
  async handle(event) {
    const now = Date.now();
    const windowStart = now - this.windowMs;
    
    // 清理过期计数
    for (const [key, timestamps] of this.eventCounts.entries()) {
      const validTimestamps = timestamps.filter(t => t > windowStart);
      Iif (validTimestamps.length === 0) {
        this.eventCounts.delete(key);
      } else {
        this.eventCounts.set(key, validTimestamps);
      }
    }
 
    // 检查速率限制
    const currentCount = (this.eventCounts.get(event.name) || []).length;
    if (currentCount >= this.maxEvents) {
      console.warn(`Rate limit exceeded for event ${event.name}`);
      return false;
    }
 
    // 记录事件
    if (!this.eventCounts.has(event.name)) {
      this.eventCounts.set(event.name, []);
    }
    this.eventCounts.get(event.name).push(now);
 
    return true;
  }
}
 
/**
 * 中间件链执行器
 */
class MiddlewareChainExecutor {
  constructor() {
    this.middlewares = [];
  }
 
  use(middleware) {
    this.middlewares.push(middleware);
  }
 
  async execute(event) {
    for (const middleware of this.middlewares) {
      try {
        const result = typeof middleware.handle === 'function'
          ? await middleware.handle(event)
          : await middleware(event);
        
        if (result === false) {
          return { stopped: true, at: middleware.constructor.name };
        }
      } catch (error) {
        console.error(`Middleware ${middleware.constructor.name} error:`, error.message);
        // 继续执行下一个中间件
      }
    }
    return { stopped: false };
  }
}
 
module.exports = {
  LoggingMiddleware,
  ValidationMiddleware,
  RetryMiddleware,
  RateLimitMiddleware,
  MiddlewareChainExecutor
};