release / go (push) Successful in 2m7s
release / web (push) Successful in 1m25s
release / govulncheck (push) Successful in 21s
release / integration (push) Successful in 4m30s
release / android (push) Successful in 4m39s
release / Build signed APK (push) Successful in 5m10s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 29s
release / Verify release artifacts (tag releases only) (push) Skipped
- Module path: github.com/Fabled-Sword/minstrel, in go.mod, every import and the Dockerfile's version ldflags. - buildinfo.ProjectURL, the contact outside services see in Minstrel's User-Agent: https://github.com/Fabled-Sword/minstrel. - README's compose example pulls ghcr.io/fabled-sword/minstrel:latest. - docs/security.md sends problem reports to the GitHub issues. - The demo-library stack builds Minstrel from the checkout, since :dev is not published to GHCR. - hygiene.go's same-site example uses example.com names. The workbench CI (.gitea/, ci/, export-ignored) still builds and publishes :dev to the private registry. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
258 lines
7.9 KiB
Go
258 lines
7.9 KiB
Go
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
|
||
// 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
|
||
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 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 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
|
||
}
|
||
}
|