From cd5e0c615e1444b0d4ab13f9feb10e4c1a06fdbf Mon Sep 17 00:00:00 2001 From: worstell Date: Mon, 9 Nov 2026 18:36:41 +0000 Subject: [PATCH 1/5] fix: pause upstream requests after HTTP 429 During load testing an upstream Maven repository rate limited cachew, and cachew kept forwarding misses to it, extending the block on the shared egress IP. The daemon's default HTTP transport now tracks a cooldown per origin (scheme, host and port) after a 429. During the cooldown, requests to that origin get a synthetic 429 with Retry-After and Cache-Control: no-store without contacting it. Cache hits and other origins are unaffected, and nothing is retried automatically. The cooldown uses a valid Retry-After (seconds or HTTP date) and falls back to the new global upstream-backoff setting (default 1m). NewHTTPClient now accepts a non-*http.Transport DefaultTransport, since the daemon wraps it. Co-authored-by: Cement --- README.md | 10 ++ client/client.go | 10 +- client/client_test.go | 16 +++ cmd/cachewd/main.go | 23 +++- internal/httputil/backoff.go | 94 +++++++++++++++++ internal/httputil/backoff_test.go | 121 ++++++++++++++++++++++ internal/strategy/handler/handler_test.go | 44 ++++++++ 7 files changed, 310 insertions(+), 8 deletions(-) create mode 100644 internal/httputil/backoff.go create mode 100644 internal/httputil/backoff_test.go diff --git a/README.md b/README.md index 767ba24e..25cdfbe7 100644 --- a/README.md +++ b/README.md @@ -217,6 +217,16 @@ spool { } ``` +## Upstream Rate Limits + +After an upstream returns 429, cachewd stops sending requests to that origin (scheme, host and port) until a cooldown ends. During the cooldown, misses for that origin get 429 with `Retry-After` and `Cache-Control: no-store` without contacting it. Cache hits and other origins are unaffected. Nothing is retried automatically. + +The cooldown uses the upstream's `Retry-After` (seconds or HTTP date) when it is valid, and `upstream-backoff` otherwise. Cooldowns are held in memory per process. + +```hcl +upstream-backoff = "1m" # Must be positive +``` + ## Authorization (OPA) Cachew uses [Open Policy Agent](https://www.openpolicyagent.org/) for request authorization. The default policy allows all requests from localhost and restricts remote access to non-admin paths (`/api/*`, `/admin/*`). diff --git a/client/client.go b/client/client.go index eab8f62b..8f5066c7 100644 --- a/client/client.go +++ b/client/client.go @@ -77,9 +77,13 @@ type HeaderFunc func() http.Header // tracer provider is configured, otelhttp falls back to a no-op tracer, so // this is cost-free for callers that have not opted in to tracing. func NewHTTPClient(headerFunc HeaderFunc) *http.Client { - transport := http.DefaultTransport.(*http.Transport).Clone() //nolint:errcheck - transport.MaxIdleConns = 100 - transport.MaxIdleConnsPerHost = 100 + transport := http.DefaultTransport + if base, ok := transport.(*http.Transport); ok { + cloned := base.Clone() + cloned.MaxIdleConns = 100 + cloned.MaxIdleConnsPerHost = 100 + transport = cloned + } var rt http.RoundTripper = otelhttp.NewTransport(transport) if headerFunc != nil { diff --git a/client/client_test.go b/client/client_test.go index 2bd08497..1794a48c 100644 --- a/client/client_test.go +++ b/client/client_test.go @@ -25,6 +25,22 @@ import ( "github.com/block/cachew/client" ) +func TestHTTPClientWithWrappedDefaultTransport(t *testing.T) { + original := http.DefaultTransport + t.Cleanup(func() { http.DefaultTransport = original }) //nolint:reassign + http.DefaultTransport = roundTripperFunc(func(r *http.Request) (*http.Response, error) { //nolint:reassign + assert.Equal(t, "token", r.Header.Get("Authorization")) + return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: http.NoBody, Request: r}, nil + }) + c := client.NewHTTPClient(func() http.Header { return http.Header{"Authorization": {"token"}} }) + r, err := http.NewRequestWithContext(t.Context(), http.MethodGet, "http://example.com", nil) + assert.NoError(t, err) + resp, err := c.Do(r) + assert.NoError(t, err) + assert.NoError(t, resp.Body.Close()) + assert.Equal(t, http.StatusOK, resp.StatusCode) +} + // fakeServer is a minimal /api/v1 backend for exercising the client over HTTP. type fakeServer struct { mu sync.Mutex diff --git a/cmd/cachewd/main.go b/cmd/cachewd/main.go index b8d20ee3..2e8b23e9 100644 --- a/cmd/cachewd/main.go +++ b/cmd/cachewd/main.go @@ -47,6 +47,7 @@ type GlobalConfig struct { State string `hcl:"state" default:"./state" help:"Base directory for all state (git mirrors, cache, etc.)."` Bind string `hcl:"bind" default:"127.0.0.1:8080" help:"Bind address for the server."` URL string `hcl:"url" default:"http://127.0.0.1:8080/" help:"Base URL for cachewd."` + UpstreamBackoff time.Duration `hcl:"upstream-backoff,optional" default:"1m" help:"Cooldown after an upstream 429 with missing or invalid Retry-After; must be positive."` ShutdownReadinessDelay time.Duration `hcl:"shutdown-readiness-delay,optional" default:"5s" help:"Delay between flipping readiness to 503 on SIGTERM and starting graceful shutdown."` // ShutdownTimeout must be less than the pod's terminationGracePeriodSeconds // (minus ShutdownReadinessDelay) or the kubelet will SIGKILL before Shutdown returns. @@ -104,11 +105,7 @@ func main() { // Flipped on SIGTERM so /_readiness fails before the listener closes. var shuttingDown atomic.Bool - // Enable mutex contention sampling so /admin/pprof/mutex returns - // useful data. The pprof endpoints themselves are mounted on the - // main HTTP listener under /admin/pprof/* via the net/http/pprof - // side-effect import; OPA gates external access. - runtime.SetMutexProfileFraction(cli.MutexProfileFraction) + configureProcess(cli.MutexProfileFraction, globalConfig.UpstreamBackoff) // Register the OpenTelemetry tracer provider. tracing.New is a // no-op when OTEL_EXPORTER_OTLP_ENDPOINT is unset, so deployments @@ -451,6 +448,19 @@ func newServer( }, nil } +// configureProcess applies process-wide runtime and HTTP transport settings. +func configureProcess(mutexProfileFraction int, upstreamBackoff time.Duration) { + // Enable mutex contention sampling so /admin/pprof/mutex returns + // useful data. The pprof endpoints themselves are mounted on the + // main HTTP listener under /admin/pprof/* via the net/http/pprof + // side-effect import; OPA gates external access. + runtime.SetMutexProfileFraction(mutexProfileFraction) + + // Every strategy that uses http.DefaultTransport shares one set of + // per-origin 429 cooldowns. + http.DefaultTransport = httputil.NewBackoffTransport(http.DefaultTransport, upstreamBackoff) //nolint:reassign +} + // loadGlobalConfig unmarshals the global config from HCL, using a two-pass // approach so that the "state" field is resolved first and then injected as // CACHEW_STATE for expansion in other defaults (e.g. mirror-root, disk root). @@ -491,6 +501,9 @@ func loadGlobalConfig(ast *hcl.AST) (GlobalConfig, map[string]string, error) { if err := hcl.UnmarshalAST(ast, &cfg, hcl.HydratedImplicitBlocks(true), expanding); err != nil { return cfg, nil, errors.Errorf("load global config: %w", err) } + if cfg.UpstreamBackoff <= 0 { + return cfg, nil, errors.New("upstream-backoff must be positive") + } return cfg, envars, nil } diff --git a/internal/httputil/backoff.go b/internal/httputil/backoff.go new file mode 100644 index 00000000..c2b96965 --- /dev/null +++ b/internal/httputil/backoff.go @@ -0,0 +1,94 @@ +package httputil + +import ( + "io" + "math" + "net" + "net/http" + "strconv" + "strings" + "sync" + "time" + + "github.com/alecthomas/errors" +) + +// BackoffTransport shares upstream cooldowns across requests and redirect hops. +type BackoffTransport struct { + base http.RoundTripper + delay time.Duration + mu sync.Mutex + until map[string]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[string]time.Time{}} +} + +// RoundTrip rejects requests to cooling origins without retrying them. +func (t *BackoffTransport) RoundTrip(r *http.Request) (*http.Response, error) { + port := r.URL.Port() + if port == "" { + if r.URL.Scheme == "https" { + port = "443" + } else { + port = "80" + } + } + origin := strings.ToLower(r.URL.Scheme + "://" + net.JoinHostPort(r.URL.Hostname(), port)) + now := time.Now() + t.mu.Lock() + for host, until := range t.until { + if !until.After(now) { + delete(t.until, host) + } + } + until := t.until[origin] + 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[origin]) { + t.until[origin] = until + } + t.mu.Unlock() + if !valid { + resp.Header.Set("Retry-After", strconv.FormatInt(int64(math.Ceil(until.Sub(now).Seconds())), 10)) + } + } + 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 +} diff --git a/internal/httputil/backoff_test.go b/internal/httputil/backoff_test.go new file mode 100644 index 00000000..e32439b2 --- /dev/null +++ b/internal/httputil/backoff_test.go @@ -0,0 +1,121 @@ +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}}, + 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")) + 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"]) + }) +} diff --git a/internal/strategy/handler/handler_test.go b/internal/strategy/handler/handler_test.go index bd51e79a..279059dd 100644 --- a/internal/strategy/handler/handler_test.go +++ b/internal/strategy/handler/handler_test.go @@ -999,3 +999,47 @@ func TestCacheResultLabelsServerMetrics(t *testing.T) { } assert.Equal(t, map[string]int64{handler.CacheHit: 1, handler.CacheMiss: 3, handler.CacheCoalesced: 1}, got) } + +func TestBackoffStillServesHits(t *testing.T) { + var calls atomic.Int32 + newUpstream := func() *httptest.Server { + return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + calls.Add(1) + if r.URL.Path == "/limited" { + w.WriteHeader(http.StatusTooManyRequests) + return + } + _, _ = io.WriteString(w, "body") + })) + } + limited := newUpstream() + defer limited.Close() + other := newUpstream() + defer other.Close() + client := &http.Client{Transport: httputil.NewBackoffTransport(http.DefaultTransport, time.Minute)} + c := mustNewMemoryCache() + defer c.Close() + h := handler.New(client, c, newTestSpools(t)).Transform(func(r *http.Request) (*http.Request, error) { + return http.NewRequestWithContext(r.Context(), http.MethodGet, r.URL.Query().Get("upstream")+r.URL.Path, nil) + }) + get := func(upstream, path string) *httptest.ResponseRecorder { + return serve(t, h, http.MethodGet, "http://example.com"+path+"?upstream="+upstream, nil) + } + + for _, path := range []string{"/cached", "/limited", "/cached", "/miss"} { + w := get(limited.URL, path) + if path == "/cached" { + assert.Equal(t, http.StatusOK, w.Code) + assert.Equal(t, "body", w.Body.String()) + } else { + assert.Equal(t, http.StatusTooManyRequests, w.Code) + assert.Equal(t, "60", w.Header().Get("Retry-After")) + } + } + assert.Equal(t, int32(2), calls.Load()) + + w := get(other.URL, "/miss") + assert.Equal(t, http.StatusOK, w.Code) + assert.Equal(t, "body", w.Body.String()) + assert.Equal(t, int32(3), calls.Load()) +} From 7781f679e38094888f594f275d7309e950840bb6 Mon Sep 17 00:00:00 2001 From: Elizabeth Worstell Date: Mon, 9 Nov 2026 11:29:39 -0800 Subject: [PATCH 2/5] fix: pause all upstream requests of a strategy after HTTP 429 A 429 from one upstream of a handler now pauses every upstream request of that handler, including fallbacks, redirect targets and parallel chunks. Before, only the origin that returned 429 paused, and host fallbacks received the requests during the cooldown. Requests made outside the strategy handlers, such as Git, still pause per origin. Co-authored-by: Chain <492cad42391b4a5c84d831885f468e6f1699c0a8c39241f1c002235ece37ee69@buzz> Co-Authored-By: Claude Opus 5.5 Signed-off-by: Elizabeth Worstell --- README.md | 2 +- internal/httputil/backoff.go | 64 +++++++++++++++++------ internal/strategy/handler/handler.go | 6 ++- internal/strategy/handler/handler_test.go | 23 ++++---- internal/strategy/host_test.go | 37 +++++++++++++ 5 files changed, 106 insertions(+), 26 deletions(-) diff --git a/README.md b/README.md index 25cdfbe7..bdf2273c 100644 --- a/README.md +++ b/README.md @@ -219,7 +219,7 @@ spool { ## Upstream Rate Limits -After an upstream returns 429, cachewd stops sending requests to that origin (scheme, host and port) until a cooldown ends. During the cooldown, misses for that origin get 429 with `Retry-After` and `Cache-Control: no-store` without contacting it. Cache hits and other origins are unaffected. Nothing is retried automatically. +After an upstream returns 429, cachewd stops sending upstream requests for that strategy until a cooldown ends. This includes its fallbacks and redirect targets. During the cooldown, misses get 429 with `Retry-After` and `Cache-Control: no-store` without contacting any upstream. Cache hits and other strategies are unaffected. Requests made outside the strategy handlers, such as Git, pause per origin (scheme, host and port). Nothing is retried automatically. The cooldown uses the upstream's `Retry-After` (seconds or HTTP date) when it is valid, and `upstream-backoff` otherwise. Cooldowns are held in memory per process. diff --git a/internal/httputil/backoff.go b/internal/httputil/backoff.go index c2b96965..c2093eb8 100644 --- a/internal/httputil/backoff.go +++ b/internal/httputil/backoff.go @@ -1,6 +1,7 @@ package httputil import ( + "context" "io" "math" "net" @@ -14,37 +15,44 @@ import ( ) // 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[string]time.Time + 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[string]time.Time{}} + return &BackoffTransport{base: base, delay: delay, until: map[any]time.Time{}} } -// RoundTrip rejects requests to cooling origins without retrying them. +// RoundTrip rejects requests in a cooling scope or origin without retrying them. func (t *BackoffTransport) RoundTrip(r *http.Request) (*http.Response, error) { - port := r.URL.Port() - if port == "" { - if r.URL.Scheme == "https" { - port = "443" - } else { - port = "80" + 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)) } - origin := strings.ToLower(r.URL.Scheme + "://" + net.JoinHostPort(r.URL.Hostname(), port)) now := time.Now() t.mu.Lock() - for host, until := range t.until { + for k, until := range t.until { if !until.After(now) { - delete(t.until, host) + delete(t.until, k) } } - until := t.until[origin] + until := t.until[cooldown] t.mu.Unlock() if until.After(now) { if r.Body != nil { @@ -71,8 +79,8 @@ func (t *BackoffTransport) RoundTrip(r *http.Request) (*http.Response, error) { var valid bool until, valid = retryAfter(resp.Header.Get("Retry-After"), now, t.delay) t.mu.Lock() - if until.After(t.until[origin]) { - t.until[origin] = until + if until.After(t.until[cooldown]) { + t.until[cooldown] = until } t.mu.Unlock() if !valid { @@ -82,6 +90,32 @@ func (t *BackoffTransport) RoundTrip(r *http.Request) (*http.Response, error) { 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} +} + +// 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(context.WithValue(r.Context(), backoffScopeKey{}, s))) + 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)) { diff --git a/internal/strategy/handler/handler.go b/internal/strategy/handler/handler.go index 86aef9c0..b025c800 100644 --- a/internal/strategy/handler/handler.go +++ b/internal/strategy/handler/handler.go @@ -94,13 +94,17 @@ const checkedAtHeader = "X-Cachew-Checked-At" // New creates a new Handler with the given HTTP client and cache. Concurrent // cache misses for the same key share one upstream fetch through a spool group. +// All upstream requests of the handler, including fallbacks, redirects and +// parallel chunks, share one 429 cooldown. // By default: // - Cache key is derived from the request URL // - No request transformation is performed // - Standard error handling is used. func New(client *http.Client, c cache.Cache, spools *spool.Registry) *Handler { + scoped := *client + scoped.Transport = httputil.NewBackoffScope(client.Transport) return &Handler{ - client: client, + client: &scoped, cache: c, spools: spools.NewGroup(spool.ReleaseCompleted), cacheKeyFunc: func(r *http.Request) CacheKeyParts { diff --git a/internal/strategy/handler/handler_test.go b/internal/strategy/handler/handler_test.go index 279059dd..a9e92d30 100644 --- a/internal/strategy/handler/handler_test.go +++ b/internal/strategy/handler/handler_test.go @@ -1000,7 +1000,7 @@ func TestCacheResultLabelsServerMetrics(t *testing.T) { assert.Equal(t, map[string]int64{handler.CacheHit: 1, handler.CacheMiss: 3, handler.CacheCoalesced: 1}, got) } -func TestBackoffStillServesHits(t *testing.T) { +func TestBackoffPausesHandler(t *testing.T) { var calls atomic.Int32 newUpstream := func() *httptest.Server { return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -1019,16 +1019,21 @@ func TestBackoffStillServesHits(t *testing.T) { client := &http.Client{Transport: httputil.NewBackoffTransport(http.DefaultTransport, time.Minute)} c := mustNewMemoryCache() defer c.Close() - h := handler.New(client, c, newTestSpools(t)).Transform(func(r *http.Request) (*http.Request, error) { - return http.NewRequestWithContext(r.Context(), http.MethodGet, r.URL.Query().Get("upstream")+r.URL.Path, nil) - }) - get := func(upstream, path string) *httptest.ResponseRecorder { + newHandler := func() *handler.Handler { + return handler.New(client, c, newTestSpools(t)).Transform(func(r *http.Request) (*http.Request, error) { + return http.NewRequestWithContext(r.Context(), http.MethodGet, r.URL.Query().Get("upstream")+r.URL.Path, nil) + }) + } + h := newHandler() + get := func(h http.Handler, upstream, path string) *httptest.ResponseRecorder { return serve(t, h, http.MethodGet, "http://example.com"+path+"?upstream="+upstream, nil) } - for _, path := range []string{"/cached", "/limited", "/cached", "/miss"} { - w := get(limited.URL, path) - if path == "/cached" { + for _, req := range []struct{ upstream, path string }{ + {limited.URL, "/cached"}, {limited.URL, "/limited"}, {limited.URL, "/cached"}, {limited.URL, "/miss"}, {other.URL, "/miss"}, + } { + w := get(h, req.upstream, req.path) + if req.path == "/cached" { assert.Equal(t, http.StatusOK, w.Code) assert.Equal(t, "body", w.Body.String()) } else { @@ -1038,7 +1043,7 @@ func TestBackoffStillServesHits(t *testing.T) { } assert.Equal(t, int32(2), calls.Load()) - w := get(other.URL, "/miss") + w := get(newHandler(), other.URL, "/miss") assert.Equal(t, http.StatusOK, w.Code) assert.Equal(t, "body", w.Body.String()) assert.Equal(t, int32(3), calls.Load()) diff --git a/internal/strategy/host_test.go b/internal/strategy/host_test.go index bfcd89bc..ca14cb69 100644 --- a/internal/strategy/host_test.go +++ b/internal/strategy/host_test.go @@ -17,6 +17,7 @@ import ( "github.com/alecthomas/hcl/v2" "github.com/block/cachew/internal/cache" + "github.com/block/cachew/internal/httputil" "github.com/block/cachew/internal/logging" "github.com/block/cachew/internal/spool" "github.com/block/cachew/internal/strategy" @@ -301,6 +302,42 @@ func TestHostFallbackOrder(t *testing.T) { assert.Equal(t, []int{0, 1, 2}, order) } +func TestHostBackoffPausesFallbacks(t *testing.T) { + defaultTransport := http.DefaultTransport + http.DefaultTransport = httputil.NewBackoffTransport(defaultTransport, time.Minute) //nolint:reassign + t.Cleanup(func() { http.DefaultTransport = defaultTransport }) //nolint:reassign + _, ctx := logging.Configure(context.Background(), logging.Config{Level: slog.LevelError}) + c, err := cache.NewMemory(ctx, cache.MemoryConfig{MaxTTL: time.Hour}) + assert.NoError(t, err) + defer c.Close() + calls := map[string]int{} + newServer := func(name string, status int) *httptest.Server { + return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + calls[name]++ + w.WriteHeader(status) + })) + } + primary := newServer("primary", http.StatusTooManyRequests) + defer primary.Close() + mirror := newServer("mirror", http.StatusOK) + defer mirror.Close() + mux := http.NewServeMux() + _, err = strategy.NewHost(ctx, strategy.HostConfig{ + Target: primary.URL, + Fallbacks: []strategy.HostFallbackConfig{{Target: mirror.URL}}, + }, c, mux, newTestSpools(t)) + assert.NoError(t, err) + u, err := url.Parse(primary.URL) + assert.NoError(t, err) + for _, path := range []string{"/a.jar", "/b.jar"} { + w := httptest.NewRecorder() + mux.ServeHTTP(w, httptest.NewRequestWithContext(ctx, http.MethodGet, "/"+u.Host+path, nil)) + assert.Equal(t, http.StatusTooManyRequests, w.Code) + assert.Equal(t, "60", w.Header().Get("Retry-After")) + } + assert.Equal(t, map[string]int{"primary": 1}, calls) +} + func TestHostFallbackIncompleteResponse(t *testing.T) { for _, cancelRequest := range []bool{false, true} { t.Run(strconv.FormatBool(cancelRequest), func(t *testing.T) { From a4c14c5bf3dec8361cd1237c941a23a8048afe53 Mon Sep 17 00:00:00 2001 From: Elizabeth Worstell Date: Mon, 9 Nov 2026 11:52:36 -0800 Subject: [PATCH 3/5] fix: include transform requests in the handler 429 cooldown Requests that a handler transform makes, such as the GitHub release metadata lookup, now share the handler's cooldown. A 429 from that lookup keeps Retry-After and is marked no-store. Co-authored-by: Chain <492cad42391b4a5c84d831885f468e6f1699c0a8c39241f1c002235ece37ee69@buzz> Co-Authored-By: Claude Opus 5.5 Signed-off-by: Elizabeth Worstell --- internal/httputil/backoff.go | 8 ++++++- internal/httputil/error.go | 16 +++++++++++++ internal/strategy/github_releases.go | 2 +- internal/strategy/github_releases_test.go | 29 ++++++++++++++++++++--- internal/strategy/handler/handler.go | 11 +++++---- 5 files changed, 57 insertions(+), 9 deletions(-) diff --git a/internal/httputil/backoff.go b/internal/httputil/backoff.go index c2093eb8..93fb5513 100644 --- a/internal/httputil/backoff.go +++ b/internal/httputil/backoff.go @@ -103,13 +103,19 @@ 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(context.WithValue(r.Context(), backoffScopeKey{}, s))) + resp, err := base.RoundTrip(r.WithContext(s.WithContext(r.Context()))) if err != nil { return nil, errors.WithStack(err) } diff --git a/internal/httputil/error.go b/internal/httputil/error.go index f21c01c0..ddb24764 100644 --- a/internal/httputil/error.go +++ b/internal/httputil/error.go @@ -3,6 +3,7 @@ package httputil import ( "fmt" + "maps" "net/http" "github.com/alecthomas/errors" @@ -26,6 +27,7 @@ type HTTPResponder interface { type HTTPError struct { status int err error + header http.Header } func (h HTTPError) Error() string { return fmt.Sprintf("%d: %s", h.status, h.err) } @@ -33,6 +35,7 @@ func (h HTTPError) Unwrap() error { return h.err } // WriteHTTP writes this error as an HTTP response. func (h HTTPError) WriteHTTP(w http.ResponseWriter, r *http.Request) { + maps.Copy(w.Header(), h.header) ErrorResponse(w, r, h.status, h.err.Error()) } @@ -42,3 +45,16 @@ func Errorf(status int, format string, args ...any) error { err: errors.Errorf(format, args...), } } + +// UpstreamErrorf is [Errorf] with the status of resp. For a 429 it keeps +// Retry-After and marks the response no-store. +func UpstreamErrorf(resp *http.Response, format string, args ...any) error { + err := HTTPError{status: resp.StatusCode, err: errors.Errorf(format, args...)} + if resp.StatusCode == http.StatusTooManyRequests { + err.header = http.Header{"Cache-Control": {"no-store"}} + if retryAfter := resp.Header.Get("Retry-After"); retryAfter != "" { + err.header.Set("Retry-After", retryAfter) + } + } + return err +} diff --git a/internal/strategy/github_releases.go b/internal/strategy/github_releases.go index ba090134..b6f469de 100644 --- a/internal/strategy/github_releases.go +++ b/internal/strategy/github_releases.go @@ -184,7 +184,7 @@ func (g *GitHubReleases) downloadRelease(ctx context.Context, org, repo, release defer resp.Body.Close() if resp.StatusCode != http.StatusOK { - return nil, httputil.Errorf(resp.StatusCode, "GitHub API returned %d", resp.StatusCode) + return nil, httputil.UpstreamErrorf(resp, "GitHub API returned %d", resp.StatusCode) } var releaseInfo struct { diff --git a/internal/strategy/github_releases_test.go b/internal/strategy/github_releases_test.go index b804e062..3a526f06 100644 --- a/internal/strategy/github_releases_test.go +++ b/internal/strategy/github_releases_test.go @@ -15,6 +15,7 @@ import ( "github.com/block/cachew/internal/cache" "github.com/block/cachew/internal/githubapp" + "github.com/block/cachew/internal/httputil" "github.com/block/cachew/internal/logging" "github.com/block/cachew/internal/strategy" ) @@ -53,6 +54,12 @@ func (m *mockGitHubServer) handleAPIRequest(w http.ResponseWriter, r *http.Reque repo := r.PathValue("repo") tag := r.PathValue("tag") + if tag == "limited" { + w.Header().Set("Retry-After", "30") + w.WriteHeader(http.StatusTooManyRequests) + return + } + if strings.Contains(r.URL.Path, "missing.tar.gz") { releaseInfo := map[string]any{ "tag_name": tag, @@ -115,11 +122,11 @@ func setupTest(t *testing.T, config strategy.GitHubReleasesConfig) (*mockGitHubS t.Cleanup(mock.close) originalTransport := http.DefaultTransport - t.Cleanup(func() { http.DefaultTransport = originalTransport }) //nolint:reassign // Required for testing - http.DefaultTransport = &testTransport{ //nolint:reassign // Required for testing + t.Cleanup(func() { http.DefaultTransport = originalTransport }) //nolint:reassign // Required for testing + http.DefaultTransport = httputil.NewBackoffTransport(&testTransport{ //nolint:reassign // Required for testing backend: mock.server, originalTransport: originalTransport, - } + }, time.Minute) _, ctx := logging.Configure(context.Background(), logging.Config{Level: slog.LevelError}) memCache, err := cache.NewMemory(ctx, cache.MemoryConfig{MaxTTL: time.Hour}) @@ -227,6 +234,22 @@ func TestGitHubReleasesPrivateRepoAPIError(t *testing.T) { assert.Equal(t, 0, mock.downloadCallCount) } +func TestGitHubReleasesRateLimitPausesStrategy(t *testing.T) { + mock, mux, ctx := setupTest(t, strategy.GitHubReleasesConfig{ + Token: "test-token", + PrivateOrgs: []string{"privateorg"}, + }) + for _, path := range []string{"privateorg/repo/releases/download/limited/binary.tar.gz", "publicorg/repo/releases/download/v1.0.0/binary.tar.gz"} { + w := httptest.NewRecorder() + mux.ServeHTTP(w, httptest.NewRequestWithContext(ctx, http.MethodGet, "/github.com/"+path, nil)) + assert.Equal(t, http.StatusTooManyRequests, w.Code) + assert.Equal(t, "no-store", w.Header().Get("Cache-Control")) + assert.Equal(t, "30", w.Header().Get("Retry-After")) + } + assert.Equal(t, 1, mock.apiCallCount) + assert.Equal(t, 0, mock.publicCallCount) +} + func TestGitHubReleasesPublicRepoNotFound(t *testing.T) { mock, mux, ctx := setupTest(t, strategy.GitHubReleasesConfig{}) diff --git a/internal/strategy/handler/handler.go b/internal/strategy/handler/handler.go index b025c800..dd3b53c0 100644 --- a/internal/strategy/handler/handler.go +++ b/internal/strategy/handler/handler.go @@ -71,6 +71,7 @@ func (p CacheKeyParts) Key() cache.Key { // }) type Handler struct { client *http.Client + scope *httputil.BackoffScope cache cache.Cache cacheKeyFunc func(*http.Request) CacheKeyParts transformFunc func(*http.Request) (*http.Request, error) @@ -94,17 +95,19 @@ const checkedAtHeader = "X-Cachew-Checked-At" // New creates a new Handler with the given HTTP client and cache. Concurrent // cache misses for the same key share one upstream fetch through a spool group. -// All upstream requests of the handler, including fallbacks, redirects and -// parallel chunks, share one 429 cooldown. +// All upstream requests of the handler, including requests its transform makes, +// fallbacks, redirects and parallel chunks, share one 429 cooldown. // By default: // - Cache key is derived from the request URL // - No request transformation is performed // - Standard error handling is used. func New(client *http.Client, c cache.Cache, spools *spool.Registry) *Handler { + scope := httputil.NewBackoffScope(client.Transport) scoped := *client - scoped.Transport = httputil.NewBackoffScope(client.Transport) + scoped.Transport = scope return &Handler{ client: &scoped, + scope: scope, cache: c, spools: spools.NewGroup(spool.ReleaseCompleted), cacheKeyFunc: func(r *http.Request) CacheKeyParts { @@ -420,7 +423,7 @@ func (h *Handler) revalidate(r *http.Request, key cache.Key, headers http.Header // If-Range are never forwarded: whole objects are cached and ranges are cut // locally. func (h *Handler) upstreamRequest(r *http.Request) (*http.Request, error) { - req, err := h.transformFunc(r) + req, err := h.transformFunc(r.WithContext(h.scope.WithContext(r.Context()))) if err != nil { return nil, err } From f1cc2f1bb77133aa7748414c74f15d692fcbe6c0 Mon Sep 17 00:00:00 2001 From: Elizabeth Worstell Date: Mon, 9 Nov 2026 12:20:06 -0800 Subject: [PATCH 4/5] fix: mark the triggering upstream 429 as no-store The 429 that starts a cooldown now has Cache-Control: no-store, so a downstream cache cannot keep it after the cooldown ends. Wrap the GitHub API error to satisfy wrapcheck. Co-authored-by: Chain <492cad42391b4a5c84d831885f468e6f1699c0a8c39241f1c002235ece37ee69@buzz> Co-Authored-By: Claude Opus 5.5 Signed-off-by: Elizabeth Worstell --- internal/httputil/backoff.go | 2 ++ internal/httputil/backoff_test.go | 3 ++- internal/strategy/github_releases.go | 2 +- 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/internal/httputil/backoff.go b/internal/httputil/backoff.go index 93fb5513..dd40cc5d 100644 --- a/internal/httputil/backoff.go +++ b/internal/httputil/backoff.go @@ -83,6 +83,8 @@ func (t *BackoffTransport) RoundTrip(r *http.Request) (*http.Response, error) { 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)) } diff --git a/internal/httputil/backoff_test.go b/internal/httputil/backoff_test.go index e32439b2..61ebcb6f 100644 --- a/internal/httputil/backoff_test.go +++ b/internal/httputil/backoff_test.go @@ -42,7 +42,7 @@ func TestBackoffTransport(t *testing.T) { calls := 0 base := roundTripFunc(func(r *http.Request) (*http.Response, error) { calls++ - return &http.Response{StatusCode: http.StatusTooManyRequests, Header: http.Header{"Retry-After": {value}}, + 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) @@ -62,6 +62,7 @@ func TestBackoffTransport(t *testing.T) { 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) diff --git a/internal/strategy/github_releases.go b/internal/strategy/github_releases.go index b6f469de..4b012771 100644 --- a/internal/strategy/github_releases.go +++ b/internal/strategy/github_releases.go @@ -184,7 +184,7 @@ func (g *GitHubReleases) downloadRelease(ctx context.Context, org, repo, release defer resp.Body.Close() if resp.StatusCode != http.StatusOK { - return nil, httputil.UpstreamErrorf(resp, "GitHub API returned %d", resp.StatusCode) + return nil, errors.WithStack(httputil.UpstreamErrorf(resp, "GitHub API returned %d", resp.StatusCode)) } var releaseInfo struct { From 258027facfc85b36d7925fcfdea64f6fe8b74a7b Mon Sep 17 00:00:00 2001 From: Elizabeth Worstell Date: Mon, 9 Nov 2026 13:34:41 -0800 Subject: [PATCH 5/5] fix: keep the cache client pool tuning when the default transport is wrapped NewHTTPClient now clones the standard library transport captured before cachewd wraps http.DefaultTransport, so cache clients keep 100 idle connections per host and do not share upstream 429 cooldowns. Co-Authored-By: Claude Opus 5.5 --- client/client.go | 16 ++++++++++------ client/client_test.go | 13 ++++++++----- 2 files changed, 18 insertions(+), 11 deletions(-) diff --git a/client/client.go b/client/client.go index 8f5066c7..1805d695 100644 --- a/client/client.go +++ b/client/client.go @@ -65,6 +65,10 @@ type CacheWriter interface { Abort(err error) error } +// stdTransport is captured before cachewd wraps http.DefaultTransport with +// upstream 429 cooldowns, so cache clients keep their own tuned pool. +var stdTransport = http.DefaultTransport.(*http.Transport) //nolint:errcheck,gochecknoglobals + // HeaderFunc returns headers to attach to each outgoing request. type HeaderFunc func() http.Header @@ -77,13 +81,13 @@ type HeaderFunc func() http.Header // tracer provider is configured, otelhttp falls back to a no-op tracer, so // this is cost-free for callers that have not opted in to tracing. func NewHTTPClient(headerFunc HeaderFunc) *http.Client { - transport := http.DefaultTransport - if base, ok := transport.(*http.Transport); ok { - cloned := base.Clone() - cloned.MaxIdleConns = 100 - cloned.MaxIdleConnsPerHost = 100 - transport = cloned + base, ok := http.DefaultTransport.(*http.Transport) + if !ok { + base = stdTransport } + transport := base.Clone() + transport.MaxIdleConns = 100 + transport.MaxIdleConnsPerHost = 100 var rt http.RoundTripper = otelhttp.NewTransport(transport) if headerFunc != nil { diff --git a/client/client_test.go b/client/client_test.go index 1794a48c..82925595 100644 --- a/client/client_test.go +++ b/client/client_test.go @@ -26,14 +26,17 @@ import ( ) func TestHTTPClientWithWrappedDefaultTransport(t *testing.T) { - original := http.DefaultTransport - t.Cleanup(func() { http.DefaultTransport = original }) //nolint:reassign - http.DefaultTransport = roundTripperFunc(func(r *http.Request) (*http.Response, error) { //nolint:reassign + server := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { assert.Equal(t, "token", r.Header.Get("Authorization")) - return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: http.NoBody, Request: r}, nil + })) + defer server.Close() + original := http.DefaultTransport + t.Cleanup(func() { http.DefaultTransport = original }) //nolint:reassign + http.DefaultTransport = roundTripperFunc(func(*http.Request) (*http.Response, error) { //nolint:reassign + return nil, errors.New("wrapped default transport used") }) c := client.NewHTTPClient(func() http.Header { return http.Header{"Authorization": {"token"}} }) - r, err := http.NewRequestWithContext(t.Context(), http.MethodGet, "http://example.com", nil) + r, err := http.NewRequestWithContext(t.Context(), http.MethodGet, server.URL, nil) assert.NoError(t, err) resp, err := c.Do(r) assert.NoError(t, err)