feat(httpclient): add circuit breaker for CDN and RIPEstat
Per-host circuit breaker с retry для CDN fetch и RIPEstat; порог 5 ошибок, cooldown 30s. Co-authored-by: Cursor <[email protected]>
This commit is contained in:
@@ -24,9 +24,6 @@ func New(timeout time.Duration) *http.Client {
|
||||
|
||||
// DoWithRetry executes hc.Do(req) up to maxAttempts times with linear backoff.
|
||||
func DoWithRetry(ctx context.Context, hc *http.Client, req *http.Request, maxAttempts int) (*http.Response, error) {
|
||||
if hc == nil {
|
||||
hc = New(0)
|
||||
}
|
||||
if maxAttempts <= 0 {
|
||||
maxAttempts = 3
|
||||
}
|
||||
@@ -66,3 +63,25 @@ func DoWithRetry(ctx context.Context, hc *http.Client, req *http.Request, maxAtt
|
||||
}
|
||||
return nil, fmt.Errorf("httpclient: request failed after %d attempts", maxAttempts)
|
||||
}
|
||||
|
||||
// DoWithBreaker applies per-host circuit breaking then retries transient failures.
|
||||
func DoWithBreaker(ctx context.Context, hc *http.Client, req *http.Request, maxAttempts int) (*http.Response, error) {
|
||||
if req == nil || req.URL == nil {
|
||||
return nil, fmt.Errorf("httpclient: nil request")
|
||||
}
|
||||
br := breakerForHost(req.URL.Hostname())
|
||||
if !br.allow() {
|
||||
return nil, fmt.Errorf("httpclient: circuit open for %s", req.URL.Hostname())
|
||||
}
|
||||
resp, err := DoWithRetry(ctx, hc, req, maxAttempts)
|
||||
if err != nil {
|
||||
br.recordFailure()
|
||||
return nil, err
|
||||
}
|
||||
if resp.StatusCode >= 500 {
|
||||
br.recordFailure()
|
||||
return resp, nil
|
||||
}
|
||||
br.recordSuccess()
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user