Repository navigation
fix: pause upstream requests after HTTP 429 #430
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
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
cd5e0c6
fix: pause upstream requests after HTTP 429
worstell 7781f67
fix: pause all upstream requests of a strategy after HTTP 429
worstell a4c14c5
fix: include transform requests in the handler 429 cooldown
worstell f1cc2f1
fix: mark the triggering upstream 429 as no-store
worstell 258027f
fix: keep the cache client pool tuning when the default transport is …
worstell File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,136 @@ | ||
| package httputil | ||
|
|
||
| import ( | ||
| "context" | ||
| "io" | ||
| "math" | ||
| "net" | ||
| "net/http" | ||
| "strconv" | ||
| "strings" | ||
| "sync" | ||
| "time" | ||
|
|
||
| "github.com/alecthomas/errors" | ||
| ) | ||
|
|
||
| // BackoffTransport shares upstream cooldowns across requests and redirect hops. | ||
| // Requests in a [BackoffScope] share one cooldown; other requests share one | ||
| // per origin. | ||
| type BackoffTransport struct { | ||
| base http.RoundTripper | ||
| delay time.Duration | ||
| mu sync.Mutex | ||
| until map[any]time.Time | ||
| } | ||
|
|
||
| // NewBackoffTransport uses delay when a 429 has no valid Retry-After header. | ||
| func NewBackoffTransport(base http.RoundTripper, delay time.Duration) *BackoffTransport { | ||
| return &BackoffTransport{base: base, delay: delay, until: map[any]time.Time{}} | ||
| } | ||
|
|
||
| // RoundTrip rejects requests in a cooling scope or origin without retrying them. | ||
| func (t *BackoffTransport) RoundTrip(r *http.Request) (*http.Response, error) { | ||
| var cooldown any | ||
| if scope, ok := r.Context().Value(backoffScopeKey{}).(*BackoffScope); ok { | ||
| cooldown = scope | ||
| } else { | ||
| port := r.URL.Port() | ||
| if port == "" { | ||
| if r.URL.Scheme == "https" { | ||
| port = "443" | ||
| } else { | ||
| port = "80" | ||
| } | ||
| } | ||
| cooldown = strings.ToLower(r.URL.Scheme + "://" + net.JoinHostPort(r.URL.Hostname(), port)) | ||
| } | ||
| now := time.Now() | ||
| t.mu.Lock() | ||
| for k, until := range t.until { | ||
| if !until.After(now) { | ||
| delete(t.until, k) | ||
| } | ||
| } | ||
| until := t.until[cooldown] | ||
| t.mu.Unlock() | ||
| if until.After(now) { | ||
| if r.Body != nil { | ||
| _ = r.Body.Close() | ||
| } | ||
| body := "upstream rate limited; retry later\n" | ||
| return &http.Response{ | ||
| StatusCode: http.StatusTooManyRequests, | ||
| Status: "429 Too Many Requests", | ||
| Header: http.Header{ | ||
| "Retry-After": {strconv.FormatInt(int64(math.Ceil(until.Sub(now).Seconds())), 10)}, | ||
| "Cache-Control": {"no-store"}, | ||
| "Content-Type": {"text/plain; charset=utf-8"}, | ||
| }, | ||
| Body: io.NopCloser(strings.NewReader(body)), ContentLength: int64(len(body)), Request: r, | ||
| }, nil | ||
| } | ||
| resp, err := t.base.RoundTrip(r) | ||
| if err != nil { | ||
| return nil, errors.WithStack(err) | ||
| } | ||
| if resp.StatusCode == http.StatusTooManyRequests { | ||
| now = time.Now() | ||
| var valid bool | ||
| until, valid = retryAfter(resp.Header.Get("Retry-After"), now, t.delay) | ||
| t.mu.Lock() | ||
| if until.After(t.until[cooldown]) { | ||
| t.until[cooldown] = until | ||
| } | ||
| t.mu.Unlock() | ||
| // The cooldown ends the 429; a downstream cache must not keep it longer. | ||
| resp.Header.Set("Cache-Control", "no-store") | ||
| if !valid { | ||
| resp.Header.Set("Retry-After", strconv.FormatInt(int64(math.Ceil(until.Sub(now).Seconds())), 10)) | ||
| } | ||
| } | ||
| return resp, nil | ||
| } | ||
|
|
||
| type backoffScopeKey struct{} | ||
|
|
||
| // BackoffScope sends every request through it in one [BackoffTransport] | ||
| // cooldown, whatever origin the request reaches. | ||
| type BackoffScope struct { | ||
| base http.RoundTripper | ||
| } | ||
|
|
||
| // NewBackoffScope sends requests to base, or to http.DefaultTransport when base is nil. | ||
| func NewBackoffScope(base http.RoundTripper) *BackoffScope { | ||
| return &BackoffScope{base: base} | ||
| } | ||
|
|
||
| // WithContext puts requests made with ctx in this scope, including requests | ||
| // sent by other clients through a [BackoffTransport]. | ||
| func (s *BackoffScope) WithContext(ctx context.Context) context.Context { | ||
| return context.WithValue(ctx, backoffScopeKey{}, s) | ||
| } | ||
|
|
||
| // RoundTrip sends r in this scope. | ||
| func (s *BackoffScope) RoundTrip(r *http.Request) (*http.Response, error) { | ||
| base := s.base | ||
| if base == nil { | ||
| base = http.DefaultTransport | ||
| } | ||
| resp, err := base.RoundTrip(r.WithContext(s.WithContext(r.Context()))) | ||
| if err != nil { | ||
| return nil, errors.WithStack(err) | ||
| } | ||
| return resp, nil | ||
| } | ||
|
|
||
| func retryAfter(value string, now time.Time, fallback time.Duration) (time.Time, bool) { | ||
| value = strings.TrimSpace(value) | ||
| if seconds, err := strconv.ParseUint(value, 10, 63); err == nil && seconds <= uint64(math.MaxInt64/int64(time.Second)) { | ||
| return now.Add(time.Duration(seconds) * time.Second), true | ||
| } | ||
| if date, err := http.ParseTime(value); err == nil { | ||
| return date, true | ||
| } | ||
| return now.Add(fallback), false | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,122 @@ | ||
| package httputil_test | ||
|
|
||
| import ( | ||
| "io" | ||
| "net/http" | ||
| "strconv" | ||
| "strings" | ||
| "testing" | ||
| "testing/synctest" | ||
| "time" | ||
|
|
||
| "github.com/alecthomas/assert/v2" | ||
|
|
||
| "github.com/block/cachew/internal/httputil" | ||
| ) | ||
|
|
||
| type roundTripFunc func(*http.Request) (*http.Response, error) | ||
|
|
||
| func (f roundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } | ||
|
|
||
| func TestBackoffTransport(t *testing.T) { | ||
| for _, tt := range []struct { | ||
| name string | ||
| retryAfter string | ||
| delay time.Duration | ||
| }{ | ||
| {name: "Missing", delay: 7 * time.Second}, | ||
| {name: "Invalid", retryAfter: "later", delay: 7 * time.Second}, | ||
| {name: "Negative", retryAfter: "-3", delay: 7 * time.Second}, | ||
| {name: "Overflow", retryAfter: "9223372036854775807", delay: 7 * time.Second}, | ||
| {name: "Seconds", retryAfter: "2", delay: 2 * time.Second}, | ||
| {name: "Date", delay: 3 * time.Second}, | ||
| {name: "Zero", retryAfter: "0"}, | ||
| {name: "PastDate"}, | ||
| } { | ||
| t.Run(tt.name, func(t *testing.T) { | ||
| synctest.Test(t, func(t *testing.T) { | ||
| value := tt.retryAfter | ||
| if tt.name == "Date" || tt.name == "PastDate" { | ||
| value = time.Now().Add(tt.delay).UTC().Format(http.TimeFormat) | ||
| } | ||
| calls := 0 | ||
| base := roundTripFunc(func(r *http.Request) (*http.Response, error) { | ||
| calls++ | ||
| return &http.Response{StatusCode: http.StatusTooManyRequests, Header: http.Header{"Retry-After": {value}, "Cache-Control": {"public, max-age=3600"}}, | ||
| Body: io.NopCloser(strings.NewReader("origin limit")), Request: r}, nil | ||
| }) | ||
| transport := httputil.NewBackoffTransport(base, 7*time.Second) | ||
| client := &http.Client{Transport: transport} | ||
| get := func(url string) *http.Response { | ||
| req, err := http.NewRequestWithContext(t.Context(), http.MethodGet, url, nil) | ||
| assert.NoError(t, err) | ||
| resp, err := client.Do(req) | ||
| assert.NoError(t, err) | ||
| assert.NoError(t, resp.Body.Close()) | ||
| return resp | ||
| } | ||
| initial := get("https://example.com/limited") | ||
| wantHeader := value | ||
| switch tt.name { | ||
| case "Missing", "Invalid", "Negative", "Overflow": | ||
| wantHeader = "7" | ||
| } | ||
| assert.Equal(t, wantHeader, initial.Header.Get("Retry-After")) | ||
| assert.Equal(t, "no-store", initial.Header.Get("Cache-Control")) | ||
| if tt.delay > 0 { | ||
| resp := get("https://EXAMPLE.com:443/another-path") | ||
| assert.Equal(t, http.StatusTooManyRequests, resp.StatusCode) | ||
| assert.Equal(t, "no-store", resp.Header.Get("Cache-Control")) | ||
| assert.Equal(t, int(tt.delay.Seconds()), mustSeconds(t, resp.Header.Get("Retry-After"))) | ||
| assert.Equal(t, 1, calls) | ||
| get("https://other.example/ok") | ||
| get("http://example.com/ok") | ||
| get("https://example.com:444/ok") | ||
| assert.Equal(t, 4, calls) | ||
| time.Sleep(tt.delay - time.Nanosecond) | ||
| assert.Equal(t, "1", get("https://example.com/near-expiry").Header.Get("Retry-After")) | ||
| assert.Equal(t, 4, calls) | ||
| time.Sleep(time.Nanosecond) | ||
| } | ||
| before := calls | ||
| get("https://example.com/after-expiry") | ||
| assert.Equal(t, before+1, calls) | ||
| }) | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| func mustSeconds(t *testing.T, value string) int { | ||
| t.Helper() | ||
| seconds, err := strconv.Atoi(value) | ||
| assert.NoError(t, err) | ||
| return seconds | ||
| } | ||
|
|
||
| func TestBackoffRedirectDestination(t *testing.T) { | ||
| synctest.Test(t, func(t *testing.T) { | ||
| calls := make(map[string]int) | ||
| base := roundTripFunc(func(r *http.Request) (*http.Response, error) { | ||
| calls[r.URL.Host]++ | ||
| resp := &http.Response{StatusCode: http.StatusTooManyRequests, Header: make(http.Header), Body: http.NoBody, Request: r} | ||
| if r.URL.Host == "redirect.example" { | ||
| resp.StatusCode = http.StatusFound | ||
| resp.Header.Set("Location", "https://limited.example/file") | ||
| } | ||
| return resp, nil | ||
| }) | ||
| transport := httputil.NewBackoffTransport(base, time.Minute) | ||
| for range 2 { | ||
| client := &http.Client{Transport: transport} | ||
| req, err := http.NewRequestWithContext(t.Context(), http.MethodGet, "https://redirect.example/file", nil) | ||
| assert.NoError(t, err) | ||
| resp, err := client.Do(req) | ||
| assert.NoError(t, err) | ||
| assert.NoError(t, resp.Body.Close()) | ||
| assert.Equal(t, http.StatusTooManyRequests, resp.StatusCode) | ||
| assert.Equal(t, "60", resp.Header.Get("Retry-After")) | ||
| } | ||
| assert.Equal(t, 2, calls["redirect.example"]) | ||
| assert.Equal(t, 1, calls["limited.example"]) | ||
| }) | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.