export class CircuitBreaker {
    threshold;
    resetMs;
    failures = 0;
    openedAt = 0;
    constructor(threshold = 5, resetMs = 10_000) {
        this.threshold = threshold;
        this.resetMs = resetMs;
    }
    async run(fn) {
        if (this.isOpen())
            throw new Error("Circuit breaker is open");
        try {
            const value = await fn();
            this.failures = 0;
            return value;
        }
        catch (error) {
            this.failures += 1;
            if (this.failures >= this.threshold)
                this.openedAt = Date.now();
            throw error;
        }
    }
    isOpen() {
        if (this.openedAt === 0)
            return false;
        if (Date.now() - this.openedAt > this.resetMs) {
            this.failures = 0;
            this.openedAt = 0;
            return false;
        }
        return true;
    }
}
