Circuit Breaker State Machine Typed
Implement a typed circuit breaker state machine with closed open half-open transitions and metrics.
Code
type State='closed'|'open'|'half-open';export class CircuitBreaker{private state:State='closed';private failures=0;private lastFailure=0;constructor(private fn:Function,private opts:{threshold:number;resetMs:number}){}async call<T>(...args:any[]):Promise<T>{if(this.state==='open'&&Date.now()-this.lastFailure<this.opts.resetMs)throw new Error('open');if(this.state==='open')this.state='half-open';try{const r=await this.fn(...args);if(this.state==='half-open'){this.state='closed';this.failures=0;}return r;}catch(e){this.failures++;this.lastFailure=Date.now();if(this.state==='half-open'||this.failures>=this.opts.threshold)this.state='open';throw e;}}getState():State{return this.state;}}Report a problem with this exampleOpens a pre-filled issue on GitHub.