Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion src/providers/circuit-breaker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
23 changes: 23 additions & 0 deletions test/circuit-breaker.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
Loading