Drive circuit breaker state transitions via internal/clock

The Open->HalfOpen promotion used time.Now/time.Since directly, forcing tests
to use real time.Sleep and diverging from the project's clock convention. Add
an unexported withClock option (default clock.System) and replace the real
sleeps in tests with mock-clock Advance, making the transitions deterministic
and the package faster.
This commit is contained in:
2026-05-23 13:47:26 +03:00
parent 43d3ecfba1
commit b07d487e63
3 changed files with 32 additions and 9 deletions

View File

@@ -72,7 +72,7 @@ func (b *Breaker) State() State {
// stateLocked returns the effective state, promoting Open → HalfOpen when the
// open duration has elapsed. Caller must hold b.mu.
func (b *Breaker) stateLocked() State {
if b.state == StateOpen && time.Since(b.openedAt) >= b.opts.openDuration {
if b.state == StateOpen && b.opts.clk.Since(b.openedAt) >= b.opts.openDuration {
b.state = StateHalfOpen
b.halfOpenCur = 0
}
@@ -142,7 +142,7 @@ func (b *Breaker) record(success bool) {
// tripLocked transitions to the Open state and records the timestamp.
func (b *Breaker) tripLocked() {
b.state = StateOpen
b.openedAt = time.Now()
b.openedAt = b.opts.clk.Now()
b.halfOpenCur = 0
}