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>
244 lines
7.4 KiB
Go
244 lines
7.4 KiB
Go
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
|
||
}
|
||
}
|