Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/*`).
Expand Down
10 changes: 9 additions & 1 deletion client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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

Expand Down
19 changes: 19 additions & 0 deletions client/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
23 changes: 18 additions & 5 deletions cmd/cachewd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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).
Expand Down Expand Up @@ -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
}
Expand Down
136 changes: 136 additions & 0 deletions internal/httputil/backoff.go
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)
Comment thread
worstell marked this conversation as resolved.
Resolved
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
}
122 changes: 122 additions & 0 deletions internal/httputil/backoff_test.go
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"])
})
}
Loading
Loading