@@ -5,32 +5,35 @@ export enum CircuitState {
55}
66
77export interface CircuitBreakerOptions {
8- failureThreshold ?: number ;
9- resetTimeoutMs ?: number ;
8+ failureThreshold ?: number ; // Number of failures before opening
9+ cooldownPeriodMs ?: number ; // Time in ms before attempting half-open
1010}
1111
1212export class CircuitBreakerOpenError extends Error {
13- constructor ( message = 'Service temporarily unavailable due to open circuit breaker' ) {
13+ public statusCode : number = 503 ;
14+ constructor ( message : string = 'Service unavailable: Circuit breaker is OPEN' ) {
1415 super ( message ) ;
1516 this . name = 'CircuitBreakerOpenError' ;
1617 }
1718}
1819
1920export class CircuitBreaker {
2021 private state : CircuitState = CircuitState . CLOSED ;
21- private failureCount = 0 ;
22- private readonly failureThreshold : number ;
23- private readonly resetTimeoutMs : number ;
22+ private failureCount : number = 0 ;
2423 private lastStateChange : number = Date . now ( ) ;
24+ private readonly failureThreshold : number ;
25+ private readonly cooldownPeriodMs : number ;
2526
2627 constructor ( options : CircuitBreakerOptions = { } ) {
2728 this . failureThreshold = options . failureThreshold ?? 5 ;
28- this . resetTimeoutMs = options . resetTimeoutMs ?? 10000 ;
29+ this . cooldownPeriodMs = options . cooldownPeriodMs ?? 30000 ; // Default 30 seconds
2930 }
3031
3132 public getState ( ) : CircuitState {
32- if ( this . state === CircuitState . OPEN && Date . now ( ) - this . lastStateChange >= this . resetTimeoutMs ) {
33- this . state = CircuitState . HALF_OPEN ;
33+ if ( this . state === CircuitState . OPEN ) {
34+ if ( Date . now ( ) - this . lastStateChange >= this . cooldownPeriodMs ) {
35+ this . state = CircuitState . HALF_OPEN ;
36+ }
3437 }
3538 return this . state ;
3639 }
@@ -55,7 +58,6 @@ export class CircuitBreaker {
5558 private onSuccess ( ) : void {
5659 this . failureCount = 0 ;
5760 this . state = CircuitState . CLOSED ;
58- this . lastStateChange = Date . now ( ) ;
5961 }
6062
6163 private onFailure ( ) : void {
@@ -69,6 +71,11 @@ export class CircuitBreaker {
6971 public reset ( ) : void {
7072 this . state = CircuitState . CLOSED ;
7173 this . failureCount = 0 ;
72- this . lastStateChange = Date . now ( ) ;
7374 }
7475}
76+
77+ // Global/Per-endpoint instances
78+ export const fingerprintCircuitBreaker = new CircuitBreaker ( {
79+ failureThreshold : 3 ,
80+ cooldownPeriodMs : 15000 ,
81+ } ) ;
0 commit comments