UNPKG

logs-interceptor

Version:

High-performance, production-ready log interceptor for Node.js applications with Loki integration. Built with Clean Architecture principles. Supports Node.js, Browser, and Node-RED.

78 lines 2.21 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CircuitBreaker = void 0; class CircuitBreaker { constructor(config) { this.config = config; this.state = 'closed'; this.failures = 0; this.successCount = 0; } async execute(operation) { if (!this.config.enabled) { return operation(); } if (this.isOpen()) { throw new Error('Circuit breaker is open'); } try { const result = await operation(); this.recordSuccess(); return result; } catch (error) { this.recordFailure(); throw error; } } recordSuccess() { if (this.state === 'half-open') { this.successCount++; if (this.successCount >= this.config.halfOpenRequests) { this.state = 'closed'; this.failures = 0; this.successCount = 0; } } else if (this.state === 'closed') { this.failures = 0; } } recordFailure() { this.failures++; this.lastFailure = Date.now(); if (this.failures >= this.config.failureThreshold) { this.state = 'open'; this.nextAttempt = Date.now() + this.config.resetTimeout; } } getState() { return { state: this.state, failures: this.failures, successCount: this.successCount, lastFailure: this.lastFailure, nextAttempt: this.nextAttempt, }; } reset() { this.state = 'closed'; this.failures = 0; this.successCount = 0; this.lastFailure = undefined; this.nextAttempt = undefined; } isOpen() { if (this.state === 'open') { if (this.nextAttempt && Date.now() >= this.nextAttempt) { this.state = 'half-open'; this.successCount = 0; return false; } return true; } return false; } } exports.CircuitBreaker = CircuitBreaker; //# sourceMappingURL=CircuitBreaker.js.map