All files / src/resilience circuit-breaker.ts

0% Statements 0/326
0% Branches 0/1
0% Functions 0/1
0% Lines 0/326

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
/**
 * Circuit Breaker Pattern
 *
 * Prevents cascading failures by breaking the circuit after failures.
 *
 * @module v3/shared/resilience/circuit-breaker
 */

import { EventEmitter } from 'events';

/**
 * Circuit breaker states
 */
export enum CircuitBreakerState {
  /** Circuit is closed, requests flow normally */
  CLOSED = 'CLOSED',

  /** Circuit is open, requests are rejected immediately */
  OPEN = 'OPEN',

  /** Circuit is testing if service recovered */
  HALF_OPEN = 'HALF_OPEN',
}

/**
 * Circuit breaker options
 */
export interface CircuitBreakerOptions {
  /** Name for identification */
  name: string;

  /** Failure threshold before opening circuit (default: 5) */
  failureThreshold: number;

  /** Success threshold in half-open state to close circuit (default: 3) */
  successThreshold: number;

  /** Time to wait before testing again in ms (default: 30000) */
  timeout: number;

  /** Time window to track failures in ms (default: 60000) */
  rollingWindow: number;

  /** Volume threshold - minimum requests before tripping (default: 10) */
  volumeThreshold: number;

  /** Custom failure detection */
  isFailure?: (error: Error) => boolean;

  /** Fallback function when circuit is open */
  fallback?: <T>(error: Error) => T | Promise<T>;

  /** Callback when state changes */
  onStateChange?: (from: CircuitBreakerState, to: CircuitBreakerState) => void;
}

/**
 * Circuit breaker statistics
 */
export interface CircuitBreakerStats {
  state: CircuitBreakerState;
  failures: number;
  successes: number;
  totalRequests: number;
  rejectedRequests: number;
  lastFailure: Date | null;
  lastSuccess: Date | null;
  openSince: Date | null;
}

/**
 * Default options
 */
const DEFAULT_OPTIONS: Omit<CircuitBreakerOptions, 'name'> = {
  failureThreshold: 5,
  successThreshold: 3,
  timeout: 30000,
  rollingWindow: 60000,
  volumeThreshold: 10,
};

/**
 * Request tracking entry
 */
interface RequestEntry {
  timestamp: number;
  success: boolean;
}

/**
 * Circuit Breaker
 *
 * Implements the circuit breaker pattern to prevent cascading failures.
 *
 * @example
 * const breaker = new CircuitBreaker({
 *   name: 'external-api',
 *   failureThreshold: 5,
 *   timeout: 30000,
 * });
 *
 * try {
 *   const result = await breaker.execute(() => fetchExternalAPI());
 * } catch (error) {
 *   if (error.message === 'Circuit is open') {
 *     // Handle circuit open case
 *   }
 * }
 */
export class CircuitBreaker extends EventEmitter {
  private readonly options: CircuitBreakerOptions;
  private state: CircuitBreakerState = CircuitBreakerState.CLOSED;
  private requests: RequestEntry[] = [];
  private halfOpenSuccesses = 0;
  private openedAt: Date | null = null;
  private lastFailure: Date | null = null;
  private lastSuccess: Date | null = null;
  private rejectedCount = 0;
  private timeoutId?: ReturnType<typeof setTimeout>;

  constructor(options: CircuitBreakerOptions) {
    super();
    this.options = { ...DEFAULT_OPTIONS, ...options };
  }

  /**
   * Execute a function through the circuit breaker
   */
  async execute<T>(fn: () => Promise<T>): Promise<T> {
    // Clean up old requests
    this.cleanOldRequests();

    // Check if circuit should be tested
    this.checkState();

    // If open, reject immediately or use fallback
    if (this.state === CircuitBreakerState.OPEN) {
      this.rejectedCount++;
      const error = new Error(`Circuit breaker '${this.options.name}' is open`);

      if (this.options.fallback) {
        return this.options.fallback(error);
      }

      throw error;
    }

    try {
      const result = await fn();
      this.onSuccess();
      return result;
    } catch (error) {
      const err = error instanceof Error ? error : new Error(String(error));

      // Check if this should be counted as failure
      const isFailure = this.options.isFailure?.(err) ?? true;

      if (isFailure) {
        this.onFailure(err);
      }

      throw error;
    }
  }

  /**
   * Get current state
   */
  getState(): CircuitBreakerState {
    this.checkState();
    return this.state;
  }

  /**
   * Get statistics
   */
  getStats(): CircuitBreakerStats {
    this.cleanOldRequests();

    return {
      state: this.state,
      failures: this.requests.filter((r) => !r.success).length,
      successes: this.requests.filter((r) => r.success).length,
      totalRequests: this.requests.length,
      rejectedRequests: this.rejectedCount,
      lastFailure: this.lastFailure,
      lastSuccess: this.lastSuccess,
      openSince: this.openedAt,
    };
  }

  /**
   * Force reset the circuit breaker
   */
  reset(): void {
    const previousState = this.state;
    this.state = CircuitBreakerState.CLOSED;
    this.requests = [];
    this.halfOpenSuccesses = 0;
    this.openedAt = null;

    if (this.timeoutId) {
      clearTimeout(this.timeoutId);
      this.timeoutId = undefined;
    }

    if (previousState !== this.state) {
      this.notifyStateChange(previousState, this.state);
    }
  }

  /**
   * Handle successful request
   */
  private onSuccess(): void {
    this.lastSuccess = new Date();
    this.requests.push({ timestamp: Date.now(), success: true });

    if (this.state === CircuitBreakerState.HALF_OPEN) {
      this.halfOpenSuccesses++;

      if (this.halfOpenSuccesses >= this.options.successThreshold) {
        this.transitionTo(CircuitBreakerState.CLOSED);
        this.halfOpenSuccesses = 0;
      }
    }
  }

  /**
   * Handle failed request
   */
  private onFailure(error: Error): void {
    this.lastFailure = new Date();
    this.requests.push({ timestamp: Date.now(), success: false });

    if (this.state === CircuitBreakerState.HALF_OPEN) {
      // Failed during half-open, go back to open
      this.transitionTo(CircuitBreakerState.OPEN);
      this.halfOpenSuccesses = 0;
      return;
    }

    // Check if we should open the circuit
    const failures = this.requests.filter((r) => !r.success).length;
    const totalRequests = this.requests.length;

    if (
      totalRequests >= this.options.volumeThreshold &&
      failures >= this.options.failureThreshold
    ) {
      this.transitionTo(CircuitBreakerState.OPEN);
    }
  }

  /**
   * Check if state should change based on timeout
   */
  private checkState(): void {
    if (this.state === CircuitBreakerState.OPEN && this.openedAt) {
      const elapsed = Date.now() - this.openedAt.getTime();

      if (elapsed >= this.options.timeout) {
        this.transitionTo(CircuitBreakerState.HALF_OPEN);
      }
    }
  }

  /**
   * Transition to new state
   */
  private transitionTo(newState: CircuitBreakerState): void {
    const previousState = this.state;

    if (previousState === newState) {
      return;
    }

    this.state = newState;

    if (newState === CircuitBreakerState.OPEN) {
      this.openedAt = new Date();
      this.scheduleHalfOpen();
    } else if (newState === CircuitBreakerState.CLOSED) {
      this.openedAt = null;
      this.requests = [];

      if (this.timeoutId) {
        clearTimeout(this.timeoutId);
        this.timeoutId = undefined;
      }
    }

    this.notifyStateChange(previousState, newState);
  }

  /**
   * Schedule transition to half-open
   */
  private scheduleHalfOpen(): void {
    if (this.timeoutId) {
      clearTimeout(this.timeoutId);
    }

    this.timeoutId = setTimeout(() => {
      if (this.state === CircuitBreakerState.OPEN) {
        this.transitionTo(CircuitBreakerState.HALF_OPEN);
      }
    }, this.options.timeout);
  }

  /**
   * Notify state change
   */
  private notifyStateChange(from: CircuitBreakerState, to: CircuitBreakerState): void {
    this.emit('stateChange', { from, to });
    this.options.onStateChange?.(from, to);
  }

  /**
   * Clean old requests outside rolling window
   */
  private cleanOldRequests(): void {
    const cutoff = Date.now() - this.options.rollingWindow;
    this.requests = this.requests.filter((r) => r.timestamp >= cutoff);
  }
}