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.
67 lines
1.5 KiB
Go
67 lines
1.5 KiB
Go
package circuitbreaker
|
|
|
|
import (
|
|
"time"
|
|
|
|
"git.codelab.vc/pkg/httpx/internal/clock"
|
|
)
|
|
|
|
type options struct {
|
|
failureThreshold int // consecutive failures to trip
|
|
openDuration time.Duration // how long to stay open before half-open
|
|
halfOpenMax int // max concurrent requests in half-open
|
|
clk clock.Clock // time source (real by default)
|
|
}
|
|
|
|
func defaults() options {
|
|
return options{
|
|
failureThreshold: 5,
|
|
openDuration: 30 * time.Second,
|
|
halfOpenMax: 1,
|
|
clk: clock.System(),
|
|
}
|
|
}
|
|
|
|
// Option configures a Breaker.
|
|
type Option func(*options)
|
|
|
|
// withClock sets the clock used for state-transition timing. Unexported; for
|
|
// deterministic tests.
|
|
func withClock(c clock.Clock) Option {
|
|
return func(o *options) {
|
|
if c != nil {
|
|
o.clk = c
|
|
}
|
|
}
|
|
}
|
|
|
|
// WithFailureThreshold sets the number of consecutive failures required to
|
|
// trip the breaker from Closed to Open. Default is 5.
|
|
func WithFailureThreshold(n int) Option {
|
|
return func(o *options) {
|
|
if n > 0 {
|
|
o.failureThreshold = n
|
|
}
|
|
}
|
|
}
|
|
|
|
// WithOpenDuration sets how long the breaker stays in the Open state before
|
|
// transitioning to HalfOpen. Default is 30s.
|
|
func WithOpenDuration(d time.Duration) Option {
|
|
return func(o *options) {
|
|
if d > 0 {
|
|
o.openDuration = d
|
|
}
|
|
}
|
|
}
|
|
|
|
// WithHalfOpenMax sets the maximum number of concurrent probe requests
|
|
// allowed while the breaker is in the HalfOpen state. Default is 1.
|
|
func WithHalfOpenMax(n int) Option {
|
|
return func(o *options) {
|
|
if n > 0 {
|
|
o.halfOpenMax = n
|
|
}
|
|
}
|
|
}
|