From d352bfffc308b633c8707eeed67447beb9f9c182 Mon Sep 17 00:00:00 2001 From: Rex57 <203883624+Rex57@users.noreply.github.com> Date: Thu, 8 Oct 2026 14:52:12 +0800 Subject: [PATCH] fix(providers): report the circuit breaker as half-open once recovery is due The breaker moves from open to half-open only inside isAllowed, on the next provider call. getState returned the stored field, so an idle worker kept reporting "open" after the recovery timeout, and status kept raising the error-level provider-circuit-open problem for an outage that was over. getState now reports half-open once the timeout has passed, without changing the breaker's state or counters. Signed-off-by: Rex57 <203883624+Rex57@users.noreply.github.com> --- src/providers/circuit-breaker.ts | 8 +++++++- test/circuit-breaker.test.ts | 23 +++++++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/src/providers/circuit-breaker.ts b/src/providers/circuit-breaker.ts index e7f1f85d23..bcb27e416f 100644 --- a/src/providers/circuit-breaker.ts +++ b/src/providers/circuit-breaker.ts @@ -72,8 +72,14 @@ export class CircuitBreaker { } getState(): CircuitBreakerState { + // isAllowed only moves open → half-open on the next call; an idle breaker + // must not keep reporting an outage that its recovery timeout has ended. + const recoveryDue = + this.state === "open" && + this.openedAt !== null && + Date.now() - this.openedAt >= this.recoveryTimeoutMs; return { - state: this.state, + state: recoveryDue ? "half-open" : this.state, failures: this.failures, lastFailureAt: this.lastFailureAt, openedAt: this.openedAt, diff --git a/test/circuit-breaker.test.ts b/test/circuit-breaker.test.ts index a4e32a30a2..be7489d9b7 100644 --- a/test/circuit-breaker.test.ts +++ b/test/circuit-breaker.test.ts @@ -54,6 +54,29 @@ describe("CircuitBreaker", () => { expect(cb.getState().state).toBe("half-open"); }); + it("reports half-open once the recovery timeout passed, before any call", () => { + const cb = new CircuitBreaker(); + cb.recordFailure(); + cb.recordFailure(); + cb.recordFailure(); + vi.advanceTimersByTime(29_999); + expect(cb.getState().state).toBe("open"); + vi.advanceTimersByTime(1); + expect(cb.getState().state).toBe("half-open"); + }); + + it("reading the state does not change the breaker", () => { + const cb = new CircuitBreaker(); + cb.recordFailure(); + cb.recordFailure(); + cb.recordFailure(); + vi.advanceTimersByTime(30_000); + expect(cb.getState().state).toBe("half-open"); + cb.recordFailure(); + expect(cb.getState().state).toBe("open"); + expect(cb.isAllowed).toBe(false); + }); + it("closes on success in half-open state", () => { const cb = new CircuitBreaker(); cb.recordFailure();