-
Notifications
You must be signed in to change notification settings - Fork 3
feat: add circuit breaker for upstream provider overload protection #75
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
base: main
Are you sure you want to change the base?
Changes from 5 commits
7700a8f
aad288c
47253f1
8cf2d18
8e44145
7af3bc1
521df9b
c85b836
e446954
1d2315e
6994f89
6a7d578
b0ff0eb
bee7a4d
98c7b7a
7733266
7c7c85b
8943ef0
7d2dcb1
e3438f4
a32f246
e929098
ab08de4
161db92
33ea4ae
dbfab23
2af2875
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,131 @@ | ||
| package aibridge | ||
kacpersaw marked this conversation as resolved.
Show resolved
Hide resolved
kacpersaw marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| import ( | ||
| "fmt" | ||
| "net/http" | ||
| "sync" | ||
| "time" | ||
|
|
||
| "github.com/sony/gobreaker/v2" | ||
| ) | ||
|
|
||
| // CircuitBreakerConfig holds configuration for circuit breakers. | ||
| // Fields match gobreaker.Settings for clarity. | ||
| type CircuitBreakerConfig struct { | ||
| // Enabled controls whether circuit breakers are active. | ||
| Enabled bool | ||
| // MaxRequests is the maximum number of requests allowed in half-open state. | ||
| MaxRequests uint32 | ||
| // Interval is the cyclic period of the closed state for clearing internal counts. | ||
| Interval time.Duration | ||
| // Timeout is how long the circuit stays open before transitioning to half-open. | ||
| Timeout time.Duration | ||
| // FailureThreshold is the number of consecutive failures that triggers the circuit to open. | ||
| FailureThreshold uint32 | ||
| } | ||
|
|
||
| // DefaultCircuitBreakerConfig returns sensible defaults for circuit breaker configuration. | ||
| func DefaultCircuitBreakerConfig() CircuitBreakerConfig { | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Not used, right?
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. It may be used like: |
||
| return CircuitBreakerConfig{ | ||
| Enabled: false, // Disabled by default for backward compatibility | ||
| FailureThreshold: 5, | ||
| Interval: 10 * time.Second, | ||
| Timeout: 30 * time.Second, | ||
| MaxRequests: 3, | ||
| } | ||
| } | ||
|
|
||
| // isCircuitBreakerFailure returns true if the given HTTP status code | ||
| // should count as a failure for circuit breaker purposes. | ||
| func isCircuitBreakerFailure(statusCode int) bool { | ||
| switch statusCode { | ||
| case http.StatusTooManyRequests, // 429 | ||
| http.StatusServiceUnavailable, // 503 | ||
| 529: // Anthropic "Overloaded" | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I had a comment here before about this not being provider-specific; not sure what happened to it.
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
| return true | ||
| default: | ||
| return false | ||
| } | ||
| } | ||
|
|
||
| // CircuitBreakers manages per-endpoint circuit breakers using sony/gobreaker. | ||
| // Circuit breakers are keyed by "provider:endpoint" for per-endpoint isolation. | ||
| type CircuitBreakers struct { | ||
kacpersaw marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| breakers sync.Map // map[string]*gobreaker.CircuitBreaker[any] | ||
| config CircuitBreakerConfig | ||
| onChange func(name string, from, to gobreaker.State) | ||
| } | ||
|
|
||
| // NewCircuitBreakers creates a new circuit breaker manager. | ||
| func NewCircuitBreakers(config CircuitBreakerConfig, onChange func(name string, from, to gobreaker.State)) *CircuitBreakers { | ||
| return &CircuitBreakers{ | ||
| config: config, | ||
| onChange: onChange, | ||
| } | ||
| } | ||
|
|
||
| // Allow checks if a request to provider/endpoint should be allowed. | ||
| func (c *CircuitBreakers) Allow(provider, endpoint string) bool { | ||
| if !c.config.Enabled { | ||
kacpersaw marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| return true | ||
| } | ||
| cb := c.getOrCreate(provider, endpoint) | ||
| return cb.State() != gobreaker.StateOpen | ||
| } | ||
|
|
||
| // RecordSuccess records a successful request. | ||
| func (c *CircuitBreakers) RecordSuccess(provider, endpoint string) { | ||
| if !c.config.Enabled { | ||
| return | ||
| } | ||
| cb := c.getOrCreate(provider, endpoint) | ||
| _, _ = cb.Execute(func() (any, error) { return nil, nil }) | ||
| } | ||
|
|
||
| // RecordFailure records a failed request. Returns true if this caused the circuit to open. | ||
| func (c *CircuitBreakers) RecordFailure(provider, endpoint string, statusCode int) bool { | ||
| if !c.config.Enabled || !isCircuitBreakerFailure(statusCode) { | ||
| return false | ||
| } | ||
| cb := c.getOrCreate(provider, endpoint) | ||
| before := cb.State() | ||
| _, _ = cb.Execute(func() (any, error) { | ||
| return nil, fmt.Errorf("upstream error: %d", statusCode) | ||
| }) | ||
| return before != gobreaker.StateOpen && cb.State() == gobreaker.StateOpen | ||
| } | ||
|
|
||
| // State returns the current state for a provider/endpoint. | ||
| func (c *CircuitBreakers) State(provider, endpoint string) gobreaker.State { | ||
| if !c.config.Enabled { | ||
| return gobreaker.StateClosed | ||
| } | ||
| cb := c.getOrCreate(provider, endpoint) | ||
| return cb.State() | ||
| } | ||
|
|
||
| func (c *CircuitBreakers) getOrCreate(provider, endpoint string) *gobreaker.CircuitBreaker[any] { | ||
| key := provider + ":" + endpoint | ||
| if v, ok := c.breakers.Load(key); ok { | ||
| return v.(*gobreaker.CircuitBreaker[any]) | ||
| } | ||
|
|
||
| settings := gobreaker.Settings{ | ||
| Name: key, | ||
| MaxRequests: c.config.MaxRequests, | ||
| Interval: c.config.Interval, | ||
| Timeout: c.config.Timeout, | ||
| ReadyToTrip: func(counts gobreaker.Counts) bool { | ||
| return counts.ConsecutiveFailures >= c.config.FailureThreshold | ||
| }, | ||
| OnStateChange: func(name string, from, to gobreaker.State) { | ||
| if c.onChange != nil { | ||
| c.onChange(name, from, to) | ||
| } | ||
| }, | ||
| } | ||
|
|
||
| cb := gobreaker.NewCircuitBreaker[any](settings) | ||
| actual, _ := c.breakers.LoadOrStore(key, cb) | ||
| return actual.(*gobreaker.CircuitBreaker[any]) | ||
| } | ||
Uh oh!
There was an error while loading. Please reload this page.