// SPEC-094 AC-5: Circuit breaker for storage operations
const DEFAULT_CONFIG = {
    maxFailures: 3,
    resetTimeoutMs: 60_000,
    halfOpenMax: 1,
};
export class CircuitBreaker {
    name;
    state = 'closed';
    failureCount = 0;
    lastFailureTime = 0;
    config;
    constructor(name, config) {
        this.name = name;
        this.config = { ...DEFAULT_CONFIG, ...config };
    }
    async execute(fn, fallback) {
        if (this.state === 'open') {
            const elapsed = Date.now() - this.lastFailureTime;
            if (elapsed >= this.config.resetTimeoutMs) {
                this.state = 'half-open';
            }
            else {
                if (fallback !== undefined) {
                    return fallback;
                }
                throw new Error(`Circuit open for ${this.name}`);
            }
        }
        const wasHalfOpen = this.state === 'half-open';
        try {
            const result = await fn();
            this.state = 'closed';
            this.failureCount = 0;
            return result;
        }
        catch (error) {
            this.failureCount++;
            this.lastFailureTime = Date.now();
            if (wasHalfOpen) {
                this.state = 'open';
            }
            else if (this.failureCount >= this.config.maxFailures) {
                this.state = 'open';
            }
            if (fallback !== undefined) {
                return fallback;
            }
            throw error;
        }
    }
    getState() {
        return this.state;
    }
    reset() {
        this.state = 'closed';
        this.failureCount = 0;
    }
    getFailureCount() {
        return this.failureCount;
    }
}
//# sourceMappingURL=circuit-breaker.js.map