Skip to content
Open
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
14 changes: 3 additions & 11 deletions circuit_breaker.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ type CircuitBreaker struct {
state atomic.Value // circuitBreakerState
failureCount atomic.Uint32
successCount atomic.Uint32
lastFailureAt time.Time
lastFailureAt atomic.Value // time.Time
}

// NewCircuitBreaker method creates a new [CircuitBreaker] with default settings.
Expand Down Expand Up @@ -117,10 +117,6 @@ func (cb *CircuitBreaker) getState() circuitBreakerState {
}

func (cb *CircuitBreaker) allow() error {
if cb == nil {
return nil
}

if cb.getState() == circuitBreakerStateOpen {
return ErrCircuitBreakerOpen
}
Expand All @@ -129,10 +125,6 @@ func (cb *CircuitBreaker) allow() error {
}

func (cb *CircuitBreaker) applyPolicies(resp *http.Response) {
if cb == nil {
return
}

failed := false
for _, policy := range cb.policies {
if policy(resp) {
Expand All @@ -142,7 +134,7 @@ func (cb *CircuitBreaker) applyPolicies(resp *http.Response) {
}

if failed {
if cb.failureCount.Load() > 0 && time.Since(cb.lastFailureAt) > cb.timeout {
if cb.failureCount.Load() > 0 && time.Since(cb.lastFailureAt.Load().(time.Time)) > cb.timeout {
cb.failureCount.Store(0)
}

Expand All @@ -152,7 +144,7 @@ func (cb *CircuitBreaker) applyPolicies(resp *http.Response) {
if failCount >= cb.failureThreshold {
cb.open()
} else {
cb.lastFailureAt = time.Now()
cb.lastFailureAt.Store(time.Now())
}
case circuitBreakerStateHalfOpen:
cb.open()
Expand Down
10 changes: 7 additions & 3 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -2240,8 +2240,10 @@ func (c *Client) executeRequestMiddlewares(req *Request) (err error) {
// Executes method executes the given `Request` object and returns
// response or error.
func (c *Client) execute(req *Request) (*Response, error) {
if err := c.circuitBreaker.allow(); err != nil {
return nil, err
if c.circuitBreaker != nil {
if err := c.circuitBreaker.allow(); err != nil {
return nil, err
}
}

if err := c.executeRequestMiddlewares(req); err != nil {
Expand All @@ -2268,7 +2270,9 @@ func (c *Client) execute(req *Request) (*Response, error) {
}
}
if resp != nil {
c.circuitBreaker.applyPolicies(resp)
if c.circuitBreaker != nil {
c.circuitBreaker.applyPolicies(resp)
}

response.Body = resp.Body
if err = response.wrapContentDecompresser(); err != nil {
Expand Down