refactor(providers): one paced, retrying HTTP client for cover art and tags (#8002)
coverart/httpclient.go and tags/httpclient.go were the same client: pacing, exponential backoff with jitter, 401/403-as-transient, body caps. Tags had added a User-Agent and a shared Pacer, cover art an image GET. providers.HTTPClient now has all of it, with the tests that were in coverart. ErrTransient is shared too, so both families' errors.Is still match. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,243 @@
|
||||
package providers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math/rand"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
|
||||
)
|
||||
|
||||
// ErrNotFound means the upstream confirmed it has nothing for this item: a
|
||||
// terminal answer for this pass, so the enricher tries the next provider.
|
||||
// It is apierror.ErrNotFound, so handler error mapping resolves it too.
|
||||
var ErrNotFound = apierror.ErrNotFound
|
||||
|
||||
// ErrTransient means a temporary failure (5xx, 429 after retries, network,
|
||||
// timeout, a rejected key): the enricher leaves the row unsettled and a
|
||||
// later pass retries.
|
||||
var ErrTransient = errors.New("transient upstream error")
|
||||
|
||||
// HTTPOptions configures an HTTPClient. Zero values get the defaults: 3
|
||||
// retries, 250ms base backoff, a 1MB JSON and 5MB image body limit, and an
|
||||
// http.Client with a 30s timeout.
|
||||
type HTTPOptions struct {
|
||||
HTTPClient *http.Client
|
||||
// Name prefixes wrapped error messages, such as "lastfm: build request".
|
||||
Name string
|
||||
// UserAgent is sent on every request when set. MusicBrainz rejects
|
||||
// requests without a descriptive one.
|
||||
UserAgent string
|
||||
// MinInterval spaces requests; 0 disables spacing.
|
||||
MinInterval time.Duration
|
||||
// Pacer, when set, replaces MinInterval: requests wait on it instead.
|
||||
// MusicBrainz's providers pass musicbrainz.Shared(), because its limit is
|
||||
// per address and the release catalogue spends the same budget.
|
||||
Pacer interface{ Wait(context.Context) error }
|
||||
// MaxRetries is how many times a 429, a 5xx or a network error is
|
||||
// retried.
|
||||
MaxRetries int
|
||||
// BaseBackoff is the backoff unit: 2^attempt × base ± 20%.
|
||||
BaseBackoff time.Duration
|
||||
// TreatAuthAsTransient maps 401/403 to ErrTransient, so a bad or
|
||||
// expired key retries later rather than settling the row as "none".
|
||||
// Keyed providers want this.
|
||||
TreatAuthAsTransient bool
|
||||
// JSONBodyLimit and ImageBodyLimit cap a response body, against a
|
||||
// runaway upstream.
|
||||
JSONBodyLimit int64
|
||||
ImageBodyLimit int64
|
||||
}
|
||||
|
||||
// HTTPClient performs paced, retrying GETs against a JSON or image
|
||||
// upstream. Each provider owns one, configured with its own pacing and
|
||||
// auth semantics.
|
||||
type HTTPClient struct {
|
||||
opts HTTPOptions
|
||||
|
||||
mu sync.Mutex
|
||||
lastCall time.Time
|
||||
}
|
||||
|
||||
// NewHTTPClient fills opts' defaults and returns a client.
|
||||
func NewHTTPClient(opts HTTPOptions) *HTTPClient {
|
||||
if opts.HTTPClient == nil {
|
||||
opts.HTTPClient = &http.Client{Timeout: 30 * time.Second}
|
||||
}
|
||||
if opts.MaxRetries == 0 {
|
||||
opts.MaxRetries = 3
|
||||
}
|
||||
if opts.BaseBackoff == 0 {
|
||||
opts.BaseBackoff = 250 * time.Millisecond
|
||||
}
|
||||
if opts.JSONBodyLimit == 0 {
|
||||
opts.JSONBodyLimit = 1 * 1024 * 1024
|
||||
}
|
||||
if opts.ImageBodyLimit == 0 {
|
||||
opts.ImageBodyLimit = 5 * 1024 * 1024
|
||||
}
|
||||
return &HTTPClient{opts: opts}
|
||||
}
|
||||
|
||||
// GetJSON sends GET fullURL and decodes the 200 body into out. It retries
|
||||
// 429, 5xx and network errors with exponential backoff up to MaxRetries.
|
||||
// 404 is ErrNotFound; any other non-2xx is a wrapped ErrTransient.
|
||||
func (c *HTTPClient) GetJSON(ctx context.Context, fullURL string, out any) error {
|
||||
for attempt := 0; attempt <= c.opts.MaxRetries; attempt++ {
|
||||
resp, retry, err := c.attempt(ctx, fullURL, "application/json", attempt)
|
||||
if retry {
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
body, rerr := io.ReadAll(io.LimitReader(resp.Body, c.opts.JSONBodyLimit))
|
||||
_ = resp.Body.Close()
|
||||
if rerr != nil {
|
||||
return fmt.Errorf("%w: read body: %v", ErrTransient, rerr)
|
||||
}
|
||||
if uerr := json.Unmarshal(body, out); uerr != nil {
|
||||
return fmt.Errorf("%w: decode body: %v", ErrTransient, uerr)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("%w: exhausted retries", ErrTransient)
|
||||
}
|
||||
|
||||
// GetImage sends GET imgURL and returns the body. It does not retry: image
|
||||
// endpoints are CDN-backed and rarely answer 429. 404 is ErrNotFound; any
|
||||
// other failure is a wrapped ErrTransient.
|
||||
func (c *HTTPClient) GetImage(ctx context.Context, imgURL string) ([]byte, error) {
|
||||
if err := c.pace(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := c.do(ctx, imgURL, "image/*")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
switch {
|
||||
case resp.StatusCode == http.StatusNotFound:
|
||||
return nil, ErrNotFound
|
||||
case resp.StatusCode != http.StatusOK:
|
||||
return nil, fmt.Errorf("%w: status %d", ErrTransient, resp.StatusCode)
|
||||
}
|
||||
body, err := io.ReadAll(io.LimitReader(resp.Body, c.opts.ImageBodyLimit))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: read body: %v", ErrTransient, err)
|
||||
}
|
||||
return body, nil
|
||||
}
|
||||
|
||||
// attempt makes one paced request. It answers retry=true to go round again
|
||||
// (after backing off), a terminal error, or the 200 response with its body
|
||||
// still open.
|
||||
func (c *HTTPClient) attempt(ctx context.Context, fullURL, accept string, attempt int) (*http.Response, bool, error) {
|
||||
if err := c.pace(ctx); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
resp, err := c.do(ctx, fullURL, accept)
|
||||
if err != nil {
|
||||
if attempt < c.opts.MaxRetries {
|
||||
if waitErr := c.backoff(ctx, attempt); waitErr != nil {
|
||||
return nil, false, waitErr
|
||||
}
|
||||
return nil, true, nil
|
||||
}
|
||||
return nil, false, err
|
||||
}
|
||||
switch {
|
||||
case resp.StatusCode == http.StatusOK:
|
||||
return resp, false, nil
|
||||
case resp.StatusCode == http.StatusNotFound:
|
||||
_ = resp.Body.Close()
|
||||
return nil, false, ErrNotFound
|
||||
case c.opts.TreatAuthAsTransient &&
|
||||
(resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden):
|
||||
_ = resp.Body.Close()
|
||||
return nil, false, fmt.Errorf("%w: status %d (auth)", ErrTransient, resp.StatusCode)
|
||||
case resp.StatusCode == http.StatusTooManyRequests || resp.StatusCode >= 500:
|
||||
_ = resp.Body.Close()
|
||||
if attempt < c.opts.MaxRetries {
|
||||
if waitErr := c.backoff(ctx, attempt); waitErr != nil {
|
||||
return nil, false, waitErr
|
||||
}
|
||||
return nil, true, nil
|
||||
}
|
||||
return nil, false, fmt.Errorf("%w: status %d", ErrTransient, resp.StatusCode)
|
||||
default:
|
||||
_ = resp.Body.Close()
|
||||
return nil, false, fmt.Errorf("%w: status %d", ErrTransient, resp.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
// do sends one GET. A failure to send is a wrapped ErrTransient.
|
||||
func (c *HTTPClient) do(ctx context.Context, fullURL, accept string) (*http.Response, error) {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, fullURL, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s: build request: %w", c.opts.Name, err)
|
||||
}
|
||||
req.Header.Set("Accept", accept)
|
||||
if c.opts.UserAgent != "" {
|
||||
req.Header.Set("User-Agent", c.opts.UserAgent)
|
||||
}
|
||||
resp, err := c.opts.HTTPClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: %v", ErrTransient, err)
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// pace waits on the Pacer, or until MinInterval has passed since the last
|
||||
// request, then claims the slot.
|
||||
func (c *HTTPClient) pace(ctx context.Context) error {
|
||||
if c.opts.Pacer != nil {
|
||||
return c.opts.Pacer.Wait(ctx)
|
||||
}
|
||||
if c.opts.MinInterval <= 0 {
|
||||
return nil
|
||||
}
|
||||
c.mu.Lock()
|
||||
wait := time.Until(c.lastCall.Add(c.opts.MinInterval))
|
||||
if wait > 0 {
|
||||
timer := time.NewTimer(wait)
|
||||
c.mu.Unlock()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
timer.Stop()
|
||||
return ctx.Err()
|
||||
case <-timer.C:
|
||||
}
|
||||
c.mu.Lock()
|
||||
}
|
||||
c.lastCall = time.Now()
|
||||
c.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
// backoff sleeps 2^attempt × BaseBackoff ± 20%, or until ctx is done.
|
||||
func (c *HTTPClient) backoff(ctx context.Context, attempt int) error {
|
||||
base := time.Duration(1<<attempt) * c.opts.BaseBackoff
|
||||
jitterRange := int64(base) / 5
|
||||
if jitterRange <= 0 {
|
||||
jitterRange = 1
|
||||
}
|
||||
jitter := time.Duration(rand.Int63n(jitterRange))
|
||||
if rand.Intn(2) == 0 {
|
||||
jitter = -jitter
|
||||
}
|
||||
timer := time.NewTimer(base + jitter)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-timer.C:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
package providers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestHTTPClient_GetJSON_Success(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"name":"alice"}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
c := NewHTTPClient(HTTPOptions{Name: "test"})
|
||||
var got struct{ Name string }
|
||||
if err := c.GetJSON(context.Background(), srv.URL, &got); err != nil {
|
||||
t.Fatalf("unexpected err: %v", err)
|
||||
}
|
||||
if got.Name != "alice" {
|
||||
t.Errorf("Name = %q, want alice", got.Name)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTTPClient_GetJSON_404IsNotFound(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
c := NewHTTPClient(HTTPOptions{Name: "test"})
|
||||
var out any
|
||||
err := c.GetJSON(context.Background(), srv.URL, &out)
|
||||
if !errors.Is(err, ErrNotFound) {
|
||||
t.Errorf("err = %v, want ErrNotFound", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTTPClient_GetJSON_RetryOn429ThenSuccess(t *testing.T) {
|
||||
var calls atomic.Int32
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
n := calls.Add(1)
|
||||
if n < 3 {
|
||||
w.WriteHeader(http.StatusTooManyRequests)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"ok":true}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
c := NewHTTPClient(HTTPOptions{
|
||||
Name: "test",
|
||||
MaxRetries: 3,
|
||||
BaseBackoff: 1 * time.Millisecond, // tiny so the test is fast
|
||||
})
|
||||
var got struct{ OK bool }
|
||||
if err := c.GetJSON(context.Background(), srv.URL, &got); err != nil {
|
||||
t.Fatalf("unexpected err: %v", err)
|
||||
}
|
||||
if calls.Load() != 3 {
|
||||
t.Errorf("calls = %d, want 3", calls.Load())
|
||||
}
|
||||
if !got.OK {
|
||||
t.Errorf("OK = false, want true")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTTPClient_GetJSON_RetryOn5xxThenExhausted(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
c := NewHTTPClient(HTTPOptions{
|
||||
Name: "test",
|
||||
MaxRetries: 2,
|
||||
BaseBackoff: 1 * time.Millisecond,
|
||||
})
|
||||
var out any
|
||||
err := c.GetJSON(context.Background(), srv.URL, &out)
|
||||
if !errors.Is(err, ErrTransient) {
|
||||
t.Errorf("err = %v, want ErrTransient", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTTPClient_GetJSON_AuthAsTransient(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
c := NewHTTPClient(HTTPOptions{
|
||||
Name: "test",
|
||||
TreatAuthAsTransient: true,
|
||||
})
|
||||
var out any
|
||||
err := c.GetJSON(context.Background(), srv.URL, &out)
|
||||
if !errors.Is(err, ErrTransient) {
|
||||
t.Errorf("err = %v, want ErrTransient", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTTPClient_GetJSON_AuthPassthroughByDefault(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
c := NewHTTPClient(HTTPOptions{Name: "test"})
|
||||
var out any
|
||||
err := c.GetJSON(context.Background(), srv.URL, &out)
|
||||
if !errors.Is(err, ErrTransient) {
|
||||
// 401 is non-2xx so it falls into the generic transient bucket.
|
||||
t.Errorf("err = %v, want ErrTransient (generic non-2xx)", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTTPClient_GetJSON_MalformedBody(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = w.Write([]byte(`not json`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
c := NewHTTPClient(HTTPOptions{Name: "test"})
|
||||
var got struct{ Name string }
|
||||
err := c.GetJSON(context.Background(), srv.URL, &got)
|
||||
if !errors.Is(err, ErrTransient) {
|
||||
t.Errorf("err = %v, want ErrTransient", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTTPClient_GetJSON_ContextCancel(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
c := NewHTTPClient(HTTPOptions{
|
||||
Name: "test",
|
||||
MaxRetries: 5,
|
||||
BaseBackoff: 200 * time.Millisecond,
|
||||
})
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
|
||||
defer cancel()
|
||||
var out any
|
||||
err := c.GetJSON(ctx, srv.URL, &out)
|
||||
if !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Errorf("err = %v, want context.DeadlineExceeded", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTTPClient_GetImage_Success(t *testing.T) {
|
||||
want := []byte("\x89PNG\x0d\x0a\x1a\x0a-fake-png-bytes")
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "image/png")
|
||||
_, _ = w.Write(want)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
c := NewHTTPClient(HTTPOptions{Name: "test"})
|
||||
got, err := c.GetImage(context.Background(), srv.URL)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected err: %v", err)
|
||||
}
|
||||
if string(got) != string(want) {
|
||||
t.Errorf("body mismatch")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTTPClient_GetImage_404IsNotFound(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
c := NewHTTPClient(HTTPOptions{Name: "test"})
|
||||
_, err := c.GetImage(context.Background(), srv.URL)
|
||||
if !errors.Is(err, ErrNotFound) {
|
||||
t.Errorf("err = %v, want ErrNotFound", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTTPClient_RateLimit(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
_ = json.NewEncoder(w).Encode(struct{ OK bool }{true})
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
c := NewHTTPClient(HTTPOptions{
|
||||
Name: "test",
|
||||
MinInterval: 50 * time.Millisecond,
|
||||
})
|
||||
var out struct{ OK bool }
|
||||
t0 := time.Now()
|
||||
if err := c.GetJSON(context.Background(), srv.URL, &out); err != nil {
|
||||
t.Fatalf("first call: %v", err)
|
||||
}
|
||||
if err := c.GetJSON(context.Background(), srv.URL, &out); err != nil {
|
||||
t.Fatalf("second call: %v", err)
|
||||
}
|
||||
elapsed := time.Since(t0)
|
||||
if elapsed < 50*time.Millisecond {
|
||||
t.Errorf("elapsed %v, want >= 50ms (rate limit)", elapsed)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user