import{ok,err}from"./_deps/shared/index.js";export class CircuitBreaker{state="CLOSED";consecutiveFailures=0;consecutiveSuccesses=0;successCount=0;failureCount=0;rejectedCount=0;lastOpenedAt;lastClosedAt;recoveryTimer;failureThreshold;recoveryTimeout;halfOpenMaxCalls;successThreshold;name;onStateChange;onOpen;onClose;onHalfOpen;constructor(e={}){this.failureThreshold=e.failureThreshold??5,this.recoveryTimeout=e.recoveryTimeout??6e4,this.halfOpenMaxCalls=e.halfOpenMaxCalls??3,this.successThreshold=e.successThreshold??2,this.name=e.name??"default",this.onStateChange=e.onStateChange,this.onOpen=e.onOpen,this.onClose=e.onClose,this.onHalfOpen=e.onHalfOpen}async execute(e){if("OPEN"===this.state)return this.rejectedCount++,err("CIRCUIT_OPEN");if("HALF_OPEN"===this.state){if(this.consecutiveSuccesses+(this.consecutiveFailures>0?1:0)>=this.halfOpenMaxCalls)return this.rejectedCount++,err("HALF_OPEN_LIMIT_EXCEEDED")}try{const t=await e();return this.onSuccess(),ok(t)}catch(e){return this.onFailure(e),err("EXECUTION_FAILED")}}getMetrics(){return{state:this.state,successCount:this.successCount,failureCount:this.failureCount,rejectedCount:this.rejectedCount,consecutiveFailures:this.consecutiveFailures,consecutiveSuccesses:this.consecutiveSuccesses,lastOpenedAt:this.lastOpenedAt,lastClosedAt:this.lastClosedAt,name:this.name}}getState(){return this.state}reset(){this.clearRecoveryTimer(),this.transitionTo("CLOSED","manual reset"),this.consecutiveFailures=0,this.consecutiveSuccesses=0}forceOpen(e="manual intervention"){this.transitionTo("OPEN",e),this.scheduleRecovery()}dispose(){this.clearRecoveryTimer()}onSuccess(){this.successCount++,this.consecutiveFailures=0,"HALF_OPEN"===this.state&&(this.consecutiveSuccesses++,this.consecutiveSuccesses>=this.successThreshold&&(this.transitionTo("CLOSED",`${this.consecutiveSuccesses} consecutive successes`),this.consecutiveSuccesses=0))}onFailure(e){if(this.failureCount++,this.consecutiveFailures++,this.consecutiveSuccesses=0,"CLOSED"===this.state&&this.consecutiveFailures>=this.failureThreshold){const e=`${this.consecutiveFailures} consecutive failures`;this.transitionTo("OPEN",e),this.scheduleRecovery()}"HALF_OPEN"===this.state&&(this.transitionTo("OPEN","failure in HALF_OPEN state"),this.scheduleRecovery())}transitionTo(e,t){const s=this.state;s!==e&&(this.state=e,"OPEN"===e?(this.lastOpenedAt=Date.now(),this.onOpen?.(t)):"CLOSED"===e?(this.lastClosedAt=Date.now(),this.onClose?.()):"HALF_OPEN"===e&&this.onHalfOpen?.(),this.onStateChange?.(s,e,t))}scheduleRecovery(){this.clearRecoveryTimer(),this.recoveryTimer=setTimeout(()=>{"OPEN"===this.state&&this.transitionTo("HALF_OPEN","recovery timeout elapsed")},this.recoveryTimeout),this.recoveryTimer.unref&&this.recoveryTimer.unref()}clearRecoveryTimer(){this.recoveryTimer&&(clearTimeout(this.recoveryTimer),this.recoveryTimer=void 0)}}export function createRegistryCircuitBreaker(e={}){return new CircuitBreaker({name:"registry",failureThreshold:10,recoveryTimeout:12e4,halfOpenMaxCalls:5,successThreshold:3,...e})}export function createGatewayCircuitBreaker(e={}){return new CircuitBreaker({name:"gateway",failureThreshold:5,recoveryTimeout:6e4,halfOpenMaxCalls:3,successThreshold:2,...e})}export function createS3CircuitBreaker(e={}){return new CircuitBreaker({name:"s3",failureThreshold:3,recoveryTimeout:3e4,halfOpenMaxCalls:2,successThreshold:2,...e})}export class CircuitBreakerManager{breakers=new Map;constructor(){this.breakers.set("registry",createRegistryCircuitBreaker()),this.breakers.set("gateway",createGatewayCircuitBreaker()),this.breakers.set("s3",createS3CircuitBreaker())}async executeRegistry(e){const t=this.breakers.get("registry");return t?t.execute(e):err("Circuit breaker not found: registry")}async executeGateway(e){const t=this.breakers.get("gateway");return t?t.execute(e):err("Circuit breaker not found: gateway")}async executeS3(e){const t=this.breakers.get("s3");return t?t.execute(e):err("Circuit breaker not found: s3")}getMetrics(e){return this.breakers.get(e)?.getMetrics()}getAllMetrics(){const e={};for(const[t,s]of this.breakers.entries())e[t]=s.getMetrics();return e}getOrCreate(e,t){let s=this.breakers.get(e);return s||(s=new CircuitBreaker({...t,name:e}),this.breakers.set(e,s)),s}resetAll(){for(const e of this.breakers.values())e.reset()}dispose(){for(const e of this.breakers.values())e.dispose();this.breakers.clear()}}