Files
minstrel/internal/providers/httpclient.go
T
bvandeusenandClaude Opus 5.5 5d2c533074
release / go (push) Successful in 1m48s
release / web (push) Successful in 1m19s
release / integration (push) Successful in 2m38s
release / govulncheck (push) Successful in 20s
release / android (push) Successful in 4m29s
release / Build signed APK (push) Successful in 4m57s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Publish the release image to GHCR (dispatch only) (push) Skipped
release / Build + push container image (push) Successful in 14s
release / Verify release artifacts (tag releases only) (push) Skipped
providers: remove TreatAuthAsTransient, which changed only an error's text (#8299)
Without the option a 401 or 403 already fell to the default branch, which
answers ErrTransient without a retry, the same as the option's own branch.
The only difference was "(auth)" in the message. TheAudioDB and both
Last.fm providers set it; none read the message. The reason it gave, that
a bad key retries later instead of settling the row as "none", now sits on
the default branch, and the client's status table checks 401 and 403.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 15:31:09 -05:00

253 lines
7.7 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package providers
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"math/rand"
"net/http"
"sync"
"time"
"github.com/Fabled-Sword/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
// 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
interval *Interval
}
// 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, interval: NewInterval(opts.MinInterval)}
}
// Interval spaces calls at least every apart. Share one between clients
// that spend the same upstream budget. A zero interval never waits.
type Interval struct {
every time.Duration
mu sync.Mutex
lastCall time.Time
}
// NewInterval returns an Interval spacing calls every apart.
func NewInterval(every time.Duration) *Interval { return &Interval{every: every} }
// Wait blocks until the interval has passed since the last call, or ctx
// ends, then claims the slot.
func (iv *Interval) Wait(ctx context.Context) error {
if iv.every <= 0 {
return nil
}
iv.mu.Lock()
wait := time.Until(iv.lastCall.Add(iv.every))
if wait > 0 {
timer := time.NewTimer(wait)
iv.mu.Unlock()
select {
case <-ctx.Done():
timer.Stop()
return ctx.Err()
case <-timer.C:
}
iv.mu.Lock()
}
iv.lastCall = time.Now()
iv.mu.Unlock()
return nil
}
// 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 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:
// Any other answer, a refused key's 401 or 403 included, is
// transient: a bad or expired key is asked again later instead of
// settling the row as having nothing to find.
_ = 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 on the client's own interval.
func (c *HTTPClient) pace(ctx context.Context) error {
if c.opts.Pacer != nil {
return c.opts.Pacer.Wait(ctx)
}
return c.interval.Wait(ctx)
}
// 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
}
}