Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added predicate fn to switch "Half Open" to "Open" #75

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
16 changes: 15 additions & 1 deletion v2/gobreaker.go
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ type Settings struct {
ReadyToTrip func(counts Counts) bool
OnStateChange func(name string, from State, to State)
IsSuccessful func(err error) bool
ReadyToOpen func(counts Counts) bool
}

// CircuitBreaker is a state machine to prevent sending requests that are likely to fail.
Expand All @@ -122,6 +123,7 @@ type CircuitBreaker[T any] struct {
readyToTrip func(counts Counts) bool
isSuccessful func(err error) bool
onStateChange func(name string, from State, to State)
readyToOpen func(counts Counts) bool

mutex sync.Mutex
state State
Expand Down Expand Up @@ -174,6 +176,12 @@ func NewCircuitBreaker[T any](st Settings) *CircuitBreaker[T] {
cb.isSuccessful = st.IsSuccessful
}

if st.ReadyToOpen == nil {
cb.readyToOpen = defaultReadyToOpen
} else {
cb.readyToOpen = st.ReadyToOpen
}

cb.toNewGeneration(time.Now())

return cb
Expand All @@ -197,6 +205,10 @@ func defaultIsSuccessful(err error) bool {
return err == nil
}

func defaultReadyToOpen(counts Counts) bool {
return counts.Requests > 0
}

// Name returns the name of the CircuitBreaker.
func (cb *CircuitBreaker[T]) Name() string {
return cb.name
Expand Down Expand Up @@ -328,7 +340,9 @@ func (cb *CircuitBreaker[T]) onFailure(state State, now time.Time) {
cb.setState(StateOpen, now)
}
case StateHalfOpen:
cb.setState(StateOpen, now)
if cb.readyToOpen(cb.counts) {
cb.setState(StateOpen, now)
}
}
}

Expand Down