diff --git a/README.md b/README.md index 767ba24e..bdf2273c 100644 --- a/README.md +++ b/README.md @@ -217,6 +217,16 @@ spool { } ``` +## Upstream Rate Limits + +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. + +```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..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,7 +81,11 @@ 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 + base, ok := http.DefaultTransport.(*http.Transport) + if !ok { + base = stdTransport + } + transport := base.Clone() transport.MaxIdleConns = 100 transport.MaxIdleConnsPerHost = 100 diff --git a/client/client_test.go b/client/client_test.go index 2bd08497..82925595 100644 --- a/client/client_test.go +++ b/client/client_test.go @@ -25,6 +25,25 @@ import ( "github.com/block/cachew/client" ) +func TestHTTPClientWithWrappedDefaultTransport(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { + assert.Equal(t, "token", r.Header.Get("Authorization")) + })) + 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, server.URL, 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..dd40cc5d --- /dev/null +++ b/internal/httputil/backoff.go @@ -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 +} diff --git a/internal/httputil/backoff_test.go b/internal/httputil/backoff_test.go new file mode 100644 index 00000000..61ebcb6f --- /dev/null +++ b/internal/httputil/backoff_test.go @@ -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"]) + }) +} 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..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.Errorf(resp.StatusCode, "GitHub API returned %d", resp.StatusCode) + return nil, errors.WithStack(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 86aef9c0..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,13 +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 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 = scope return &Handler{ - client: client, + client: &scoped, + scope: scope, cache: c, spools: spools.NewGroup(spool.ReleaseCompleted), cacheKeyFunc: func(r *http.Request) CacheKeyParts { @@ -416,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 } diff --git a/internal/strategy/handler/handler_test.go b/internal/strategy/handler/handler_test.go index bd51e79a..a9e92d30 100644 --- a/internal/strategy/handler/handler_test.go +++ b/internal/strategy/handler/handler_test.go @@ -999,3 +999,52 @@ func TestCacheResultLabelsServerMetrics(t *testing.T) { } assert.Equal(t, map[string]int64{handler.CacheHit: 1, handler.CacheMiss: 3, handler.CacheCoalesced: 1}, got) } + +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) { + 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() + 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 _, 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 { + 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(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) {