adpa-enterprise-framework-automation
Version:
Modular, standards-compliant Node.js/TypeScript automation framework for enterprise requirements, project, and data management. Provides CLI and API for BABOK v3, PMBOK 7th Edition, and DMBOK 2.0 (in progress). Production-ready Express.js API with TypeSpe
68 lines • 1.8 kB
JavaScript
/**
* Circuit Breaker Pattern Implementation
* Provides fault tolerance and resilience for external service calls
*/
export class CircuitBreaker {
state = 'CLOSED';
failureCount = 0;
lastFailureTime = null;
config;
constructor(config) {
this.config = config;
}
async execute(operation) {
if (this.state === 'OPEN') {
if (this.shouldAttemptReset()) {
this.state = 'HALF_OPEN';
this.notifyStateChange();
}
else {
throw new Error('Circuit breaker is OPEN');
}
}
try {
const result = await operation();
this.onSuccess();
return result;
}
catch (error) {
this.onFailure();
throw error;
}
}
onSuccess() {
this.failureCount = 0;
this.lastFailureTime = null;
this.state = 'CLOSED';
this.notifyStateChange();
}
onFailure() {
this.failureCount++;
this.lastFailureTime = Date.now();
if (this.failureCount >= this.config.failureThreshold) {
this.state = 'OPEN';
this.notifyStateChange();
}
}
shouldAttemptReset() {
return this.lastFailureTime !== null &&
(Date.now() - this.lastFailureTime) >= this.config.resetTimeout;
}
notifyStateChange() {
if (this.config.monitor) {
this.config.monitor(this.state);
}
}
getState() {
return this.state;
}
getFailureCount() {
return this.failureCount;
}
}
// Legacy compatibility export
export const circuitBreaker = new CircuitBreaker({
failureThreshold: 5,
resetTimeout: 60000
});
//# sourceMappingURL=circuit-breaker.js.map