The first public release of Fabled Minstrel #158
@@ -1,207 +0,0 @@
|
||||
package coverart
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"math/rand"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// httpClientOptions configures a httpClient. Zero values get sensible
|
||||
// defaults: 3 retries, 250ms base backoff, 1MB JSON body limit, 5MB
|
||||
// image body limit, default http.Client with 30s timeout.
|
||||
type httpClientOptions struct {
|
||||
HTTPClient *http.Client
|
||||
// Name is used as the prefix in wrapped error messages
|
||||
// (e.g. "coverart lastfm: build request: ..."). Required.
|
||||
Name string
|
||||
// MinInterval throttles requests; 0 disables rate limiting.
|
||||
MinInterval time.Duration
|
||||
// MaxRetries is the number of retry attempts on 429 / 5xx.
|
||||
MaxRetries int
|
||||
// BaseBackoff is the base unit for exponential backoff; the
|
||||
// helper sleeps 2^attempt × BaseBackoff ± 20% jitter.
|
||||
BaseBackoff time.Duration
|
||||
// TreatAuthAsTransient maps 401/403 responses to ErrTransient
|
||||
// (vs. passing through as a generic non-2xx error). Providers
|
||||
// with API keys (lastfm, theaudiodb) want this; key-less
|
||||
// providers (deezer) leave it false.
|
||||
TreatAuthAsTransient bool
|
||||
// JSONBodyLimit and ImageBodyLimit cap the response body read
|
||||
// to protect against runaway upstreams.
|
||||
JSONBodyLimit int64
|
||||
ImageBodyLimit int64
|
||||
}
|
||||
|
||||
// httpClient performs rate-limited, retrying GETs against an HTTP
|
||||
// JSON or image upstream. Shared by the cover-art providers — each
|
||||
// constructs its own client with provider-specific intervals and auth
|
||||
// semantics, then calls getJSON/getImage with fully-formed URLs.
|
||||
type httpClient struct {
|
||||
opts httpClientOptions
|
||||
|
||||
mu sync.Mutex
|
||||
lastCall time.Time
|
||||
}
|
||||
|
||||
func newHTTPClient(opts httpClientOptions) *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, decodes the 200 body into out (capped at
|
||||
// JSONBodyLimit). Retries 429/5xx with exponential backoff up to
|
||||
// MaxRetries. 404 → ErrNotFound. Non-2xx → wrapped ErrTransient.
|
||||
func (c *httpClient) getJSON(ctx context.Context, fullURL string, out any) error {
|
||||
for attempt := 0; attempt <= c.opts.MaxRetries; attempt++ {
|
||||
if err := c.rateLimitWait(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, fullURL, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("coverart %s: build request: %w", c.opts.Name, err)
|
||||
}
|
||||
req.Header.Set("Accept", "application/json")
|
||||
|
||||
resp, err := c.opts.HTTPClient.Do(req)
|
||||
if err != nil {
|
||||
if attempt < c.opts.MaxRetries {
|
||||
if waitErr := c.backoff(ctx, attempt); waitErr != nil {
|
||||
return waitErr
|
||||
}
|
||||
continue
|
||||
}
|
||||
return fmt.Errorf("%w: %v", ErrTransient, err)
|
||||
}
|
||||
|
||||
switch {
|
||||
case resp.StatusCode == http.StatusNotFound:
|
||||
_ = resp.Body.Close()
|
||||
return ErrNotFound
|
||||
case c.opts.TreatAuthAsTransient &&
|
||||
(resp.StatusCode == http.StatusUnauthorized ||
|
||||
resp.StatusCode == http.StatusForbidden):
|
||||
_ = resp.Body.Close()
|
||||
return 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 waitErr
|
||||
}
|
||||
continue
|
||||
}
|
||||
return fmt.Errorf("%w: status %d", ErrTransient, resp.StatusCode)
|
||||
case resp.StatusCode != http.StatusOK:
|
||||
_ = resp.Body.Close()
|
||||
return fmt.Errorf("%w: status %d", ErrTransient, resp.StatusCode)
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(io.LimitReader(resp.Body, c.opts.JSONBodyLimit))
|
||||
_ = resp.Body.Close()
|
||||
if err != nil {
|
||||
return fmt.Errorf("%w: read body: %v", ErrTransient, err)
|
||||
}
|
||||
if err := json.Unmarshal(body, out); err != nil {
|
||||
return fmt.Errorf("%w: decode body: %v", ErrTransient, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("%w: exhausted retries", ErrTransient)
|
||||
}
|
||||
|
||||
// getImage sends GET imgURL, returns the body bytes (capped at
|
||||
// ImageBodyLimit). 404 → ErrNotFound; non-2xx / network → ErrTransient.
|
||||
// No retry — image endpoints are typically CDN-backed and 429s are rare.
|
||||
func (c *httpClient) getImage(ctx context.Context, imgURL string) ([]byte, error) {
|
||||
if err := c.rateLimitWait(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, imgURL, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("coverart %s: build request: %w", c.opts.Name, err)
|
||||
}
|
||||
req.Header.Set("Accept", "image/*")
|
||||
resp, err := c.opts.HTTPClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: %v", ErrTransient, 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
|
||||
}
|
||||
|
||||
// rateLimitWait blocks until at least MinInterval has elapsed since the
|
||||
// last call, then claims the slot. Disabled when MinInterval is 0.
|
||||
func (c *httpClient) rateLimitWait(ctx context.Context) error {
|
||||
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 for 2^attempt × BaseBackoff ± 20% jitter, 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
|
||||
}
|
||||
d := base + jitter
|
||||
timer := time.NewTimer(d)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-timer.C:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,6 @@ package coverart
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/providers"
|
||||
@@ -83,7 +82,7 @@ var ErrNotFound = apierror.ErrNotFound
|
||||
// ErrTransient indicates a temporary failure (5xx, network, timeout,
|
||||
// auth issue). The enricher leaves the row's source NULL so the next
|
||||
// scan pass can retry.
|
||||
var ErrTransient = errors.New("coverart: transient error")
|
||||
var ErrTransient = providers.ErrTransient
|
||||
|
||||
// registry is every compiled-in cover-art provider. The enricher iterates
|
||||
// it filtered by the current settings.
|
||||
|
||||
@@ -8,6 +8,8 @@ import (
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/providers"
|
||||
)
|
||||
|
||||
// deezerBaseURL is a var (not const) so tests can override it to point
|
||||
@@ -30,12 +32,12 @@ const (
|
||||
// serialises calls so the rate limit applies uniformly.
|
||||
type deezerProvider struct {
|
||||
enabled atomic.Bool
|
||||
client *httpClient
|
||||
client *providers.HTTPClient
|
||||
}
|
||||
|
||||
func init() {
|
||||
Register(&deezerProvider{
|
||||
client: newHTTPClient(httpClientOptions{
|
||||
client: providers.NewHTTPClient(providers.HTTPOptions{
|
||||
Name: "deezer",
|
||||
HTTPClient: &http.Client{Timeout: 30 * time.Second},
|
||||
MinInterval: deezerMinPeriod,
|
||||
@@ -83,7 +85,7 @@ func (p *deezerProvider) FetchArtistArt(ctx context.Context, ref ArtistRef) (thu
|
||||
PictureBig string `json:"picture_big"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err := p.client.getJSON(ctx, deezerBaseURL+"/search/artist?"+q.Encode(), &resp); err != nil {
|
||||
if err := p.client.GetJSON(ctx, deezerBaseURL+"/search/artist?"+q.Encode(), &resp); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if len(resp.Data) == 0 {
|
||||
@@ -100,7 +102,7 @@ func (p *deezerProvider) FetchArtistArt(ctx context.Context, ref ArtistRef) (thu
|
||||
if imgURL == "" {
|
||||
return nil, nil, ErrNotFound
|
||||
}
|
||||
img, ferr := p.client.getImage(ctx, imgURL)
|
||||
img, ferr := p.client.GetImage(ctx, imgURL)
|
||||
if ferr != nil {
|
||||
return nil, nil, ferr
|
||||
}
|
||||
@@ -132,7 +134,7 @@ func (p *deezerProvider) FetchAlbumCover(ctx context.Context, ref AlbumRef) ([]b
|
||||
} `json:"artist"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err := p.client.getJSON(ctx, deezerBaseURL+"/search/album?"+q.Encode(), &resp); err != nil {
|
||||
if err := p.client.GetJSON(ctx, deezerBaseURL+"/search/album?"+q.Encode(), &resp); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(resp.Data) == 0 {
|
||||
@@ -149,7 +151,7 @@ func (p *deezerProvider) FetchAlbumCover(ctx context.Context, ref AlbumRef) ([]b
|
||||
if imgURL == "" {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return p.client.getImage(ctx, imgURL)
|
||||
return p.client.GetImage(ctx, imgURL)
|
||||
}
|
||||
|
||||
// Compile-time check: the new provider implements both interfaces.
|
||||
|
||||
@@ -8,6 +8,8 @@ import (
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/providers"
|
||||
)
|
||||
|
||||
// newDeezerTestProvider returns a fresh enabled provider configured
|
||||
@@ -18,7 +20,7 @@ func newDeezerTestProvider(t *testing.T, baseURL string) *deezerProvider {
|
||||
deezerBaseURL = baseURL
|
||||
t.Cleanup(func() { deezerBaseURL = old })
|
||||
|
||||
p := &deezerProvider{client: newHTTPClient(httpClientOptions{Name: "deezer", HTTPClient: &http.Client{Timeout: 5 * time.Second}, BaseBackoff: time.Millisecond})}
|
||||
p := &deezerProvider{client: providers.NewHTTPClient(providers.HTTPOptions{Name: "deezer", HTTPClient: &http.Client{Timeout: 5 * time.Second}, BaseBackoff: time.Millisecond})}
|
||||
p.enabled.Store(true)
|
||||
return p
|
||||
}
|
||||
@@ -93,7 +95,7 @@ func TestDeezer_FetchArtistArt_NameMismatch(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestDeezer_FetchArtistArt_EmptyName(t *testing.T) {
|
||||
p := &deezerProvider{client: newHTTPClient(httpClientOptions{Name: "deezer", HTTPClient: &http.Client{Timeout: 5 * time.Second}, BaseBackoff: time.Millisecond})}
|
||||
p := &deezerProvider{client: providers.NewHTTPClient(providers.HTTPOptions{Name: "deezer", HTTPClient: &http.Client{Timeout: 5 * time.Second}, BaseBackoff: time.Millisecond})}
|
||||
p.enabled.Store(true)
|
||||
_, _, err := p.FetchArtistArt(context.Background(), ArtistRef{})
|
||||
if !errors.Is(err, ErrNotFound) {
|
||||
@@ -102,7 +104,7 @@ func TestDeezer_FetchArtistArt_EmptyName(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestDeezer_FetchArtistArt_Disabled(t *testing.T) {
|
||||
p := &deezerProvider{client: newHTTPClient(httpClientOptions{Name: "deezer", HTTPClient: &http.Client{Timeout: 5 * time.Second}, BaseBackoff: time.Millisecond})}
|
||||
p := &deezerProvider{client: providers.NewHTTPClient(providers.HTTPOptions{Name: "deezer", HTTPClient: &http.Client{Timeout: 5 * time.Second}, BaseBackoff: time.Millisecond})}
|
||||
// enabled defaults to false
|
||||
_, _, err := p.FetchArtistArt(context.Background(), ArtistRef{Name: "X"})
|
||||
if !errors.Is(err, ErrNotFound) {
|
||||
@@ -150,7 +152,7 @@ func TestDeezer_FetchAlbumCover_TitleMismatch(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestDeezer_FetchAlbumCover_MissingFields(t *testing.T) {
|
||||
p := &deezerProvider{client: newHTTPClient(httpClientOptions{Name: "deezer", HTTPClient: &http.Client{Timeout: 5 * time.Second}, BaseBackoff: time.Millisecond})}
|
||||
p := &deezerProvider{client: providers.NewHTTPClient(providers.HTTPOptions{Name: "deezer", HTTPClient: &http.Client{Timeout: 5 * time.Second}, BaseBackoff: time.Millisecond})}
|
||||
p.enabled.Store(true)
|
||||
|
||||
cases := []AlbumRef{
|
||||
@@ -180,7 +182,7 @@ func TestDeezer_RateLimit_Serializes(t *testing.T) {
|
||||
// Build a provider WITH the production MinInterval so this test can
|
||||
// verify the rate-limit actually serializes. Other tests use
|
||||
// newDeezerTestProvider which leaves MinInterval=0 for speed.
|
||||
p := &deezerProvider{client: newHTTPClient(httpClientOptions{
|
||||
p := &deezerProvider{client: providers.NewHTTPClient(providers.HTTPOptions{
|
||||
Name: "deezer",
|
||||
HTTPClient: &http.Client{Timeout: 5 * time.Second},
|
||||
MinInterval: deezerMinPeriod,
|
||||
|
||||
@@ -8,6 +8,8 @@ import (
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/providers"
|
||||
)
|
||||
|
||||
// lastfmBaseURL is a var (not const) so tests can override it.
|
||||
@@ -41,12 +43,12 @@ var lastfmPlaceholderHashes = map[string]bool{
|
||||
type lastfmProvider struct {
|
||||
enabled atomic.Bool
|
||||
apiKey atomic.Pointer[string]
|
||||
client *httpClient
|
||||
client *providers.HTTPClient
|
||||
}
|
||||
|
||||
func init() {
|
||||
Register(&lastfmProvider{
|
||||
client: newHTTPClient(httpClientOptions{
|
||||
client: providers.NewHTTPClient(providers.HTTPOptions{
|
||||
Name: "lastfm",
|
||||
HTTPClient: &http.Client{Timeout: 30 * time.Second},
|
||||
MinInterval: lastfmMinPeriod,
|
||||
@@ -111,7 +113,7 @@ func (p *lastfmProvider) FetchArtistArt(ctx context.Context, ref ArtistRef) (thu
|
||||
} `json:"artist"`
|
||||
Error int `json:"error"` // present on error responses
|
||||
}
|
||||
if err := p.client.getJSON(ctx, lastfmBaseURL+"?"+q.Encode(), &resp); err != nil {
|
||||
if err := p.client.GetJSON(ctx, lastfmBaseURL+"?"+q.Encode(), &resp); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if resp.Error != 0 || resp.Artist.Name == "" {
|
||||
@@ -121,7 +123,7 @@ func (p *lastfmProvider) FetchArtistArt(ctx context.Context, ref ArtistRef) (thu
|
||||
if imgURL == "" || isLastfmPlaceholder(imgURL) {
|
||||
return nil, nil, ErrNotFound
|
||||
}
|
||||
img, ferr := p.client.getImage(ctx, imgURL)
|
||||
img, ferr := p.client.GetImage(ctx, imgURL)
|
||||
if ferr != nil {
|
||||
return nil, nil, ferr
|
||||
}
|
||||
@@ -157,7 +159,7 @@ func (p *lastfmProvider) FetchAlbumCover(ctx context.Context, ref AlbumRef) ([]b
|
||||
} `json:"album"`
|
||||
Error int `json:"error"`
|
||||
}
|
||||
if err := p.client.getJSON(ctx, lastfmBaseURL+"?"+q.Encode(), &resp); err != nil {
|
||||
if err := p.client.GetJSON(ctx, lastfmBaseURL+"?"+q.Encode(), &resp); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Error != 0 || resp.Album.Name == "" {
|
||||
@@ -167,7 +169,7 @@ func (p *lastfmProvider) FetchAlbumCover(ctx context.Context, ref AlbumRef) ([]b
|
||||
if imgURL == "" || isLastfmPlaceholder(imgURL) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return p.client.getImage(ctx, imgURL)
|
||||
return p.client.GetImage(ctx, imgURL)
|
||||
}
|
||||
|
||||
// lastfmImage models one entry of Last.fm's image[] array.
|
||||
|
||||
@@ -8,6 +8,8 @@ import (
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/providers"
|
||||
)
|
||||
|
||||
// newLastfmTestProvider returns a fresh enabled provider configured
|
||||
@@ -19,7 +21,7 @@ func newLastfmTestProvider(t *testing.T, baseURL, key string) *lastfmProvider {
|
||||
lastfmBaseURL = baseURL
|
||||
t.Cleanup(func() { lastfmBaseURL = prevBase })
|
||||
|
||||
p := &lastfmProvider{client: newHTTPClient(httpClientOptions{Name: "lastfm", HTTPClient: &http.Client{Timeout: 5 * time.Second}, TreatAuthAsTransient: true, BaseBackoff: time.Millisecond})}
|
||||
p := &lastfmProvider{client: providers.NewHTTPClient(providers.HTTPOptions{Name: "lastfm", HTTPClient: &http.Client{Timeout: 5 * time.Second}, TreatAuthAsTransient: true, BaseBackoff: time.Millisecond})}
|
||||
p.enabled.Store(true)
|
||||
p.apiKey.Store(&key)
|
||||
return p
|
||||
@@ -177,7 +179,7 @@ func TestLastfm_FetchArtistArt_ErrorResponse(t *testing.T) {
|
||||
|
||||
func TestLastfm_FetchArtistArt_EmptyAPIKey(t *testing.T) {
|
||||
// Enabled but no key: every call must return ErrNotFound, not a network error.
|
||||
p := &lastfmProvider{client: newHTTPClient(httpClientOptions{Name: "lastfm", HTTPClient: &http.Client{Timeout: 5 * time.Second}, TreatAuthAsTransient: true, BaseBackoff: time.Millisecond})}
|
||||
p := &lastfmProvider{client: providers.NewHTTPClient(providers.HTTPOptions{Name: "lastfm", HTTPClient: &http.Client{Timeout: 5 * time.Second}, TreatAuthAsTransient: true, BaseBackoff: time.Millisecond})}
|
||||
p.enabled.Store(true)
|
||||
emptyKey := ""
|
||||
p.apiKey.Store(&emptyKey)
|
||||
@@ -190,7 +192,7 @@ func TestLastfm_FetchArtistArt_EmptyAPIKey(t *testing.T) {
|
||||
|
||||
func TestLastfm_FetchArtistArt_Disabled(t *testing.T) {
|
||||
// Key set but disabled.
|
||||
p := &lastfmProvider{client: newHTTPClient(httpClientOptions{Name: "lastfm", HTTPClient: &http.Client{Timeout: 5 * time.Second}, TreatAuthAsTransient: true, BaseBackoff: time.Millisecond})}
|
||||
p := &lastfmProvider{client: providers.NewHTTPClient(providers.HTTPOptions{Name: "lastfm", HTTPClient: &http.Client{Timeout: 5 * time.Second}, TreatAuthAsTransient: true, BaseBackoff: time.Millisecond})}
|
||||
// enabled defaults to false
|
||||
key := "some-key"
|
||||
p.apiKey.Store(&key)
|
||||
@@ -203,7 +205,7 @@ func TestLastfm_FetchArtistArt_Disabled(t *testing.T) {
|
||||
|
||||
func TestLastfm_FetchArtistArt_EmptyRefs(t *testing.T) {
|
||||
// Neither MBID nor Name: ErrNotFound without making any HTTP call.
|
||||
p := &lastfmProvider{client: newHTTPClient(httpClientOptions{Name: "lastfm", HTTPClient: &http.Client{Timeout: 5 * time.Second}, TreatAuthAsTransient: true, BaseBackoff: time.Millisecond})}
|
||||
p := &lastfmProvider{client: providers.NewHTTPClient(providers.HTTPOptions{Name: "lastfm", HTTPClient: &http.Client{Timeout: 5 * time.Second}, TreatAuthAsTransient: true, BaseBackoff: time.Millisecond})}
|
||||
p.enabled.Store(true)
|
||||
key := "test-key"
|
||||
p.apiKey.Store(&key)
|
||||
@@ -301,7 +303,7 @@ func TestLastfm_FetchAlbumCover_WithMBIDHint(t *testing.T) {
|
||||
// ── FetchAlbumCover — missing fields ─────────────────────────────────────────
|
||||
|
||||
func TestLastfm_FetchAlbumCover_MissingFields(t *testing.T) {
|
||||
p := &lastfmProvider{client: newHTTPClient(httpClientOptions{Name: "lastfm", HTTPClient: &http.Client{Timeout: 5 * time.Second}, TreatAuthAsTransient: true, BaseBackoff: time.Millisecond})}
|
||||
p := &lastfmProvider{client: providers.NewHTTPClient(providers.HTTPOptions{Name: "lastfm", HTTPClient: &http.Client{Timeout: 5 * time.Second}, TreatAuthAsTransient: true, BaseBackoff: time.Millisecond})}
|
||||
p.enabled.Store(true)
|
||||
key := "test-key"
|
||||
p.apiKey.Store(&key)
|
||||
@@ -320,7 +322,7 @@ func TestLastfm_FetchAlbumCover_MissingFields(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestLastfm_FetchAlbumCover_EmptyAPIKey(t *testing.T) {
|
||||
p := &lastfmProvider{client: newHTTPClient(httpClientOptions{Name: "lastfm", HTTPClient: &http.Client{Timeout: 5 * time.Second}, TreatAuthAsTransient: true, BaseBackoff: time.Millisecond})}
|
||||
p := &lastfmProvider{client: providers.NewHTTPClient(providers.HTTPOptions{Name: "lastfm", HTTPClient: &http.Client{Timeout: 5 * time.Second}, TreatAuthAsTransient: true, BaseBackoff: time.Millisecond})}
|
||||
p.enabled.Store(true)
|
||||
emptyKey := ""
|
||||
p.apiKey.Store(&emptyKey)
|
||||
@@ -332,7 +334,7 @@ func TestLastfm_FetchAlbumCover_EmptyAPIKey(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestLastfm_FetchAlbumCover_Disabled(t *testing.T) {
|
||||
p := &lastfmProvider{client: newHTTPClient(httpClientOptions{Name: "lastfm", HTTPClient: &http.Client{Timeout: 5 * time.Second}, TreatAuthAsTransient: true, BaseBackoff: time.Millisecond})}
|
||||
p := &lastfmProvider{client: providers.NewHTTPClient(providers.HTTPOptions{Name: "lastfm", HTTPClient: &http.Client{Timeout: 5 * time.Second}, TreatAuthAsTransient: true, BaseBackoff: time.Millisecond})}
|
||||
// enabled defaults to false
|
||||
key := "some-key"
|
||||
p.apiKey.Store(&key)
|
||||
@@ -360,7 +362,7 @@ func TestLastfm_RateLimit_Serializes(t *testing.T) {
|
||||
// Build a provider WITH the production MinInterval so this test can
|
||||
// verify the rate-limit actually serializes. Other tests use
|
||||
// newLastfmTestProvider which leaves MinInterval=0 for speed.
|
||||
p := &lastfmProvider{client: newHTTPClient(httpClientOptions{
|
||||
p := &lastfmProvider{client: providers.NewHTTPClient(providers.HTTPOptions{
|
||||
Name: "lastfm",
|
||||
HTTPClient: &http.Client{Timeout: 5 * time.Second},
|
||||
MinInterval: lastfmMinPeriod,
|
||||
|
||||
@@ -7,6 +7,8 @@ import (
|
||||
"net/http"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/providers"
|
||||
)
|
||||
|
||||
// theAudioDBBaseURL is a var (not const) so tests can override it
|
||||
@@ -43,12 +45,12 @@ const (
|
||||
type theAudioDBProvider struct {
|
||||
enabled atomic.Bool
|
||||
apiKey atomic.Pointer[string] // nil until first Configure; falls back to test key when empty
|
||||
client *httpClient
|
||||
client *providers.HTTPClient
|
||||
}
|
||||
|
||||
func init() {
|
||||
Register(&theAudioDBProvider{
|
||||
client: newHTTPClient(httpClientOptions{
|
||||
client: providers.NewHTTPClient(providers.HTTPOptions{
|
||||
Name: "theaudiodb",
|
||||
HTTPClient: &http.Client{Timeout: 30 * time.Second},
|
||||
MinInterval: theAudioDBMinPeriod,
|
||||
@@ -105,13 +107,13 @@ func (p *theAudioDBProvider) FetchAlbumCover(ctx context.Context, ref AlbumRef)
|
||||
StrAlbumThumb *string `json:"strAlbumThumb"`
|
||||
} `json:"album"`
|
||||
}
|
||||
if err := p.client.getJSON(ctx, p.jsonURL("album-mb.php?i="+ref.MBID), &resp); err != nil {
|
||||
if err := p.client.GetJSON(ctx, p.jsonURL("album-mb.php?i="+ref.MBID), &resp); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(resp.Album) == 0 || resp.Album[0].StrAlbumThumb == nil || *resp.Album[0].StrAlbumThumb == "" {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return p.client.getImage(ctx, *resp.Album[0].StrAlbumThumb)
|
||||
return p.client.GetImage(ctx, *resp.Album[0].StrAlbumThumb)
|
||||
}
|
||||
|
||||
// FetchArtistArt hits /artist-mb.php?i=<mbid>, parses strArtistThumb +
|
||||
@@ -139,7 +141,7 @@ func (p *theAudioDBProvider) FetchArtistArt(ctx context.Context, ref ArtistRef)
|
||||
StrArtistFanart *string `json:"strArtistFanart"`
|
||||
} `json:"artists"`
|
||||
}
|
||||
if err := p.client.getJSON(ctx, p.jsonURL("artist-mb.php?i="+ref.MBID), &resp); err != nil {
|
||||
if err := p.client.GetJSON(ctx, p.jsonURL("artist-mb.php?i="+ref.MBID), &resp); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if len(resp.Artists) == 0 {
|
||||
@@ -159,7 +161,7 @@ func (p *theAudioDBProvider) FetchArtistArt(ctx context.Context, ref ArtistRef)
|
||||
}
|
||||
|
||||
if thumbURL != "" {
|
||||
thumb, err = p.client.getImage(ctx, thumbURL)
|
||||
thumb, err = p.client.GetImage(ctx, thumbURL)
|
||||
if err != nil && !errors.Is(err, ErrTransient) && !errors.Is(err, ErrNotFound) {
|
||||
return nil, nil, err
|
||||
}
|
||||
@@ -169,7 +171,7 @@ func (p *theAudioDBProvider) FetchArtistArt(ctx context.Context, ref ArtistRef)
|
||||
}
|
||||
}
|
||||
if fanartURL != "" {
|
||||
fanart, err = p.client.getImage(ctx, fanartURL)
|
||||
fanart, err = p.client.GetImage(ctx, fanartURL)
|
||||
if err != nil && !errors.Is(err, ErrTransient) && !errors.Is(err, ErrNotFound) {
|
||||
return thumb, nil, err
|
||||
}
|
||||
@@ -201,5 +203,5 @@ func (p *theAudioDBProvider) TestConnection(ctx context.Context) error {
|
||||
IDAlbum *string `json:"idAlbum"`
|
||||
} `json:"album"`
|
||||
}
|
||||
return p.client.getJSON(ctx, p.jsonURL("album-mb.php?i="+theAudioDBTestSampleMBID), &resp)
|
||||
return p.client.GetJSON(ctx, p.jsonURL("album-mb.php?i="+theAudioDBTestSampleMBID), &resp)
|
||||
}
|
||||
|
||||
@@ -10,6 +10,8 @@ import (
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/providers"
|
||||
)
|
||||
|
||||
// withTheAudioDBBaseURL temporarily redirects theAudioDBBaseURL to a
|
||||
@@ -28,7 +30,7 @@ func newTheAudioDBProviderForTest(t *testing.T, mockURL string) *theAudioDBProvi
|
||||
withTheAudioDBBaseURL(t, mockURL)
|
||||
|
||||
p := &theAudioDBProvider{
|
||||
client: newHTTPClient(httpClientOptions{Name: "theaudiodb", HTTPClient: &http.Client{Timeout: 5 * time.Second}, TreatAuthAsTransient: true, BaseBackoff: time.Millisecond}),
|
||||
client: providers.NewHTTPClient(providers.HTTPOptions{Name: "theaudiodb", HTTPClient: &http.Client{Timeout: 5 * time.Second}, TreatAuthAsTransient: true, BaseBackoff: time.Millisecond}),
|
||||
}
|
||||
Register(p)
|
||||
p.enabled.Store(true)
|
||||
@@ -234,7 +236,7 @@ func TestTheAudioDB_DefaultsToTestKeyOnEmpty(t *testing.T) {
|
||||
defer resetRegistryForTests()
|
||||
withTheAudioDBBaseURL(t, srv.URL)
|
||||
|
||||
p := &theAudioDBProvider{client: newHTTPClient(httpClientOptions{Name: "theaudiodb", HTTPClient: &http.Client{Timeout: 5 * time.Second}, TreatAuthAsTransient: true, BaseBackoff: time.Millisecond})}
|
||||
p := &theAudioDBProvider{client: providers.NewHTTPClient(providers.HTTPOptions{Name: "theaudiodb", HTTPClient: &http.Client{Timeout: 5 * time.Second}, TreatAuthAsTransient: true, BaseBackoff: time.Millisecond})}
|
||||
Register(p)
|
||||
// Configure with empty key — should fall back to test key.
|
||||
if err := p.Configure(ProviderSettings{Enabled: true, APIKey: ""}); err != nil {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package coverart
|
||||
package providers
|
||||
|
||||
import (
|
||||
"context"
|
||||
@@ -18,9 +18,9 @@ func TestHTTPClient_GetJSON_Success(t *testing.T) {
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
c := newHTTPClient(httpClientOptions{Name: "test"})
|
||||
c := NewHTTPClient(HTTPOptions{Name: "test"})
|
||||
var got struct{ Name string }
|
||||
if err := c.getJSON(context.Background(), srv.URL, &got); err != nil {
|
||||
if err := c.GetJSON(context.Background(), srv.URL, &got); err != nil {
|
||||
t.Fatalf("unexpected err: %v", err)
|
||||
}
|
||||
if got.Name != "alice" {
|
||||
@@ -34,9 +34,9 @@ func TestHTTPClient_GetJSON_404IsNotFound(t *testing.T) {
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
c := newHTTPClient(httpClientOptions{Name: "test"})
|
||||
c := NewHTTPClient(HTTPOptions{Name: "test"})
|
||||
var out any
|
||||
err := c.getJSON(context.Background(), srv.URL, &out)
|
||||
err := c.GetJSON(context.Background(), srv.URL, &out)
|
||||
if !errors.Is(err, ErrNotFound) {
|
||||
t.Errorf("err = %v, want ErrNotFound", err)
|
||||
}
|
||||
@@ -55,13 +55,13 @@ func TestHTTPClient_GetJSON_RetryOn429ThenSuccess(t *testing.T) {
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
c := newHTTPClient(httpClientOptions{
|
||||
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 {
|
||||
if err := c.GetJSON(context.Background(), srv.URL, &got); err != nil {
|
||||
t.Fatalf("unexpected err: %v", err)
|
||||
}
|
||||
if calls.Load() != 3 {
|
||||
@@ -78,13 +78,13 @@ func TestHTTPClient_GetJSON_RetryOn5xxThenExhausted(t *testing.T) {
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
c := newHTTPClient(httpClientOptions{
|
||||
c := NewHTTPClient(HTTPOptions{
|
||||
Name: "test",
|
||||
MaxRetries: 2,
|
||||
BaseBackoff: 1 * time.Millisecond,
|
||||
})
|
||||
var out any
|
||||
err := c.getJSON(context.Background(), srv.URL, &out)
|
||||
err := c.GetJSON(context.Background(), srv.URL, &out)
|
||||
if !errors.Is(err, ErrTransient) {
|
||||
t.Errorf("err = %v, want ErrTransient", err)
|
||||
}
|
||||
@@ -96,12 +96,12 @@ func TestHTTPClient_GetJSON_AuthAsTransient(t *testing.T) {
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
c := newHTTPClient(httpClientOptions{
|
||||
c := NewHTTPClient(HTTPOptions{
|
||||
Name: "test",
|
||||
TreatAuthAsTransient: true,
|
||||
})
|
||||
var out any
|
||||
err := c.getJSON(context.Background(), srv.URL, &out)
|
||||
err := c.GetJSON(context.Background(), srv.URL, &out)
|
||||
if !errors.Is(err, ErrTransient) {
|
||||
t.Errorf("err = %v, want ErrTransient", err)
|
||||
}
|
||||
@@ -113,9 +113,9 @@ func TestHTTPClient_GetJSON_AuthPassthroughByDefault(t *testing.T) {
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
c := newHTTPClient(httpClientOptions{Name: "test"})
|
||||
c := NewHTTPClient(HTTPOptions{Name: "test"})
|
||||
var out any
|
||||
err := c.getJSON(context.Background(), srv.URL, &out)
|
||||
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)
|
||||
@@ -128,9 +128,9 @@ func TestHTTPClient_GetJSON_MalformedBody(t *testing.T) {
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
c := newHTTPClient(httpClientOptions{Name: "test"})
|
||||
c := NewHTTPClient(HTTPOptions{Name: "test"})
|
||||
var got struct{ Name string }
|
||||
err := c.getJSON(context.Background(), srv.URL, &got)
|
||||
err := c.GetJSON(context.Background(), srv.URL, &got)
|
||||
if !errors.Is(err, ErrTransient) {
|
||||
t.Errorf("err = %v, want ErrTransient", err)
|
||||
}
|
||||
@@ -142,7 +142,7 @@ func TestHTTPClient_GetJSON_ContextCancel(t *testing.T) {
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
c := newHTTPClient(httpClientOptions{
|
||||
c := NewHTTPClient(HTTPOptions{
|
||||
Name: "test",
|
||||
MaxRetries: 5,
|
||||
BaseBackoff: 200 * time.Millisecond,
|
||||
@@ -150,7 +150,7 @@ func TestHTTPClient_GetJSON_ContextCancel(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
|
||||
defer cancel()
|
||||
var out any
|
||||
err := c.getJSON(ctx, srv.URL, &out)
|
||||
err := c.GetJSON(ctx, srv.URL, &out)
|
||||
if !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Errorf("err = %v, want context.DeadlineExceeded", err)
|
||||
}
|
||||
@@ -164,8 +164,8 @@ func TestHTTPClient_GetImage_Success(t *testing.T) {
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
c := newHTTPClient(httpClientOptions{Name: "test"})
|
||||
got, err := c.getImage(context.Background(), srv.URL)
|
||||
c := NewHTTPClient(HTTPOptions{Name: "test"})
|
||||
got, err := c.GetImage(context.Background(), srv.URL)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected err: %v", err)
|
||||
}
|
||||
@@ -180,8 +180,8 @@ func TestHTTPClient_GetImage_404IsNotFound(t *testing.T) {
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
c := newHTTPClient(httpClientOptions{Name: "test"})
|
||||
_, err := c.getImage(context.Background(), srv.URL)
|
||||
c := NewHTTPClient(HTTPOptions{Name: "test"})
|
||||
_, err := c.GetImage(context.Background(), srv.URL)
|
||||
if !errors.Is(err, ErrNotFound) {
|
||||
t.Errorf("err = %v, want ErrNotFound", err)
|
||||
}
|
||||
@@ -193,16 +193,16 @@ func TestHTTPClient_RateLimit(t *testing.T) {
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
c := newHTTPClient(httpClientOptions{
|
||||
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 {
|
||||
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 {
|
||||
if err := c.GetJSON(context.Background(), srv.URL, &out); err != nil {
|
||||
t.Fatalf("second call: %v", err)
|
||||
}
|
||||
elapsed := time.Since(t0)
|
||||
@@ -1,191 +0,0 @@
|
||||
package tags
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"math/rand"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// httpClientOptions configures a httpClient. A trimmed sibling of the
|
||||
// coverart HTTP helper — JSON-only (tag APIs return no binary), plus a
|
||||
// User-Agent field because MusicBrainz rejects requests without one.
|
||||
// Kept local to this package so tag enrichment never depends on
|
||||
// coverart's internals.
|
||||
type httpClientOptions struct {
|
||||
HTTPClient *http.Client
|
||||
// Name prefixes wrapped error messages (e.g. "tags lastfm: ...").
|
||||
Name string
|
||||
// UserAgent is sent on every request. MusicBrainz mandates a
|
||||
// descriptive one; empty omits the header.
|
||||
UserAgent string
|
||||
// MinInterval throttles requests; 0 disables rate limiting.
|
||||
MinInterval time.Duration
|
||||
// Pacer, when set, replaces MinInterval: requests wait on it instead.
|
||||
// MusicBrainz's provider passes musicbrainz.Shared(), because its limit
|
||||
// is per address and the release catalogue spends the same budget.
|
||||
Pacer interface{ Wait(context.Context) error }
|
||||
// MaxRetries is the number of retry attempts on 429 / 5xx.
|
||||
MaxRetries int
|
||||
// BaseBackoff is the base unit for exponential backoff (2^attempt × base ± 20%).
|
||||
BaseBackoff time.Duration
|
||||
// TreatAuthAsTransient maps 401/403 to ErrTransient (keyed providers
|
||||
// want this so a bad/expired key retries rather than settling 'none').
|
||||
TreatAuthAsTransient bool
|
||||
// JSONBodyLimit caps the response body read.
|
||||
JSONBodyLimit int64
|
||||
}
|
||||
|
||||
// httpClient performs rate-limited, retrying JSON GETs. Each provider
|
||||
// owns one, configured with provider-specific intervals + auth semantics.
|
||||
type httpClient struct {
|
||||
opts httpClientOptions
|
||||
|
||||
mu sync.Mutex
|
||||
lastCall time.Time
|
||||
}
|
||||
|
||||
func newHTTPClient(opts httpClientOptions) *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
|
||||
}
|
||||
return &httpClient{opts: opts}
|
||||
}
|
||||
|
||||
// getJSON sends GET fullURL and decodes the 200 body into out (capped at
|
||||
// JSONBodyLimit). Retries 429/5xx with exponential backoff up to
|
||||
// MaxRetries. 404 → ErrNotFound; other non-2xx → wrapped ErrTransient.
|
||||
func (c *httpClient) getJSON(ctx context.Context, fullURL string, out any) error {
|
||||
for attempt := 0; attempt <= c.opts.MaxRetries; attempt++ {
|
||||
if err := c.rateLimitWait(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, fullURL, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("tags %s: build request: %w", c.opts.Name, err)
|
||||
}
|
||||
req.Header.Set("Accept", "application/json")
|
||||
if c.opts.UserAgent != "" {
|
||||
req.Header.Set("User-Agent", c.opts.UserAgent)
|
||||
}
|
||||
|
||||
resp, err := c.opts.HTTPClient.Do(req)
|
||||
if err != nil {
|
||||
if attempt < c.opts.MaxRetries {
|
||||
if waitErr := c.backoff(ctx, attempt); waitErr != nil {
|
||||
return waitErr
|
||||
}
|
||||
continue
|
||||
}
|
||||
return fmt.Errorf("%w: %v", ErrTransient, err)
|
||||
}
|
||||
|
||||
retry, ferr := c.handleStatus(ctx, resp, attempt)
|
||||
if retry {
|
||||
continue
|
||||
}
|
||||
if ferr != nil {
|
||||
return ferr
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
// handleStatus classifies a response. Returns retry=true to loop again
|
||||
// (after backing off), or a terminal error, or (false, nil) to proceed to
|
||||
// body read. Closes the body on every path except the proceed case.
|
||||
func (c *httpClient) handleStatus(ctx context.Context, resp *http.Response, attempt int) (retry bool, err error) {
|
||||
switch {
|
||||
case resp.StatusCode == http.StatusNotFound:
|
||||
_ = resp.Body.Close()
|
||||
return false, ErrNotFound
|
||||
case c.opts.TreatAuthAsTransient &&
|
||||
(resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden):
|
||||
_ = resp.Body.Close()
|
||||
return 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 false, waitErr
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
return false, fmt.Errorf("%w: status %d", ErrTransient, resp.StatusCode)
|
||||
case resp.StatusCode != http.StatusOK:
|
||||
_ = resp.Body.Close()
|
||||
return false, fmt.Errorf("%w: status %d", ErrTransient, resp.StatusCode)
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// rateLimitWait blocks until MinInterval has elapsed since the last call,
|
||||
// then claims the slot. Disabled when MinInterval is 0.
|
||||
func (c *httpClient) rateLimitWait(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 for 2^attempt × BaseBackoff ± 20% jitter, 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
|
||||
}
|
||||
}
|
||||
@@ -14,7 +14,6 @@ package tags
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/providers"
|
||||
@@ -73,7 +72,7 @@ var ErrNotFound = apierror.ErrNotFound
|
||||
|
||||
// ErrTransient: a temporary failure (5xx, network, timeout, auth). The
|
||||
// enricher leaves the row's tag_source NULL so the next pass retries.
|
||||
var ErrTransient = errors.New("tags: transient error")
|
||||
var ErrTransient = providers.ErrTransient
|
||||
|
||||
// ErrProviderNotFound and ErrNotTestable are the shared providers errors.
|
||||
var (
|
||||
|
||||
@@ -7,6 +7,8 @@ import (
|
||||
"net/url"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/providers"
|
||||
)
|
||||
|
||||
// lastfmBaseURL is a var (not const) so tests can override it.
|
||||
@@ -33,12 +35,12 @@ var lastfmTransientErrors = map[int]bool{8: true, 11: true, 16: true, 29: true}
|
||||
type lastfmProvider struct {
|
||||
enabled atomic.Bool
|
||||
apiKey atomic.Pointer[string]
|
||||
client *httpClient
|
||||
client *providers.HTTPClient
|
||||
}
|
||||
|
||||
func init() {
|
||||
Register(&lastfmProvider{
|
||||
client: newHTTPClient(httpClientOptions{
|
||||
client: providers.NewHTTPClient(providers.HTTPOptions{
|
||||
Name: "lastfm",
|
||||
HTTPClient: &http.Client{Timeout: 30 * time.Second},
|
||||
MinInterval: lastfmMinPeriod,
|
||||
@@ -105,7 +107,7 @@ func (p *lastfmProvider) FetchTrackTags(ctx context.Context, ref TrackRef) ([]Ta
|
||||
}
|
||||
|
||||
var resp lastfmTopTags
|
||||
if err := p.client.getJSON(ctx, lastfmBaseURL+"?"+q.Encode(), &resp); err != nil {
|
||||
if err := p.client.GetJSON(ctx, lastfmBaseURL+"?"+q.Encode(), &resp); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Error != 0 {
|
||||
@@ -134,7 +136,7 @@ func (p *lastfmProvider) TestConnection(ctx context.Context) error {
|
||||
"track": {"Creep"},
|
||||
}
|
||||
var resp lastfmTopTags
|
||||
err := p.client.getJSON(ctx, lastfmBaseURL+"?"+q.Encode(), &resp)
|
||||
err := p.client.GetJSON(ctx, lastfmBaseURL+"?"+q.Encode(), &resp)
|
||||
if err != nil && !errors.Is(err, ErrNotFound) {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -7,10 +7,12 @@ import (
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/providers"
|
||||
)
|
||||
|
||||
func newLastfmProvider(enabled bool, key string) *lastfmProvider {
|
||||
p := &lastfmProvider{client: newHTTPClient(httpClientOptions{
|
||||
p := &lastfmProvider{client: providers.NewHTTPClient(providers.HTTPOptions{
|
||||
Name: "lastfm", MaxRetries: 1, TreatAuthAsTransient: true,
|
||||
})}
|
||||
_ = p.Configure(ProviderSettings{Enabled: enabled, APIKey: key})
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"time"
|
||||
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/musicbrainz"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/providers"
|
||||
)
|
||||
|
||||
// mbBaseURL is a var (not const) so tests can point it at an httptest server.
|
||||
@@ -31,12 +32,12 @@ const (
|
||||
// coarser signal. Name-based lookup is deferred to providers like Last.fm.
|
||||
type musicbrainzProvider struct {
|
||||
enabled atomic.Bool
|
||||
client *httpClient
|
||||
client *providers.HTTPClient
|
||||
}
|
||||
|
||||
func init() {
|
||||
Register(&musicbrainzProvider{
|
||||
client: newHTTPClient(httpClientOptions{
|
||||
client: providers.NewHTTPClient(providers.HTTPOptions{
|
||||
Name: "musicbrainz",
|
||||
UserAgent: mbUserAgent,
|
||||
HTTPClient: &http.Client{Timeout: 30 * time.Second},
|
||||
@@ -106,7 +107,7 @@ func (p *musicbrainzProvider) fetchEntityTags(ctx context.Context, entity, mbid
|
||||
q := url.Values{"inc": {"tags"}, "fmt": {"json"}}
|
||||
full := mbBaseURL + "/" + entity + "/" + url.PathEscape(mbid) + "?" + q.Encode()
|
||||
var resp mbTagsResponse
|
||||
if err := p.client.getJSON(ctx, full, &resp); err != nil {
|
||||
if err := p.client.GetJSON(ctx, full, &resp); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tags := normalizeMBTags(resp.Tags)
|
||||
@@ -123,7 +124,7 @@ func (p *musicbrainzProvider) fetchEntityTags(ctx context.Context, entity, mbid
|
||||
func (p *musicbrainzProvider) TestConnection(ctx context.Context) error {
|
||||
full := mbBaseURL + "/recording?query=*&limit=1&fmt=json"
|
||||
var discard map[string]any
|
||||
err := p.client.getJSON(ctx, full, &discard)
|
||||
err := p.client.GetJSON(ctx, full, &discard)
|
||||
if err == nil || errors.Is(err, ErrNotFound) {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -7,10 +7,12 @@ import (
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/providers"
|
||||
)
|
||||
|
||||
func newMBProvider(enabled bool) *musicbrainzProvider {
|
||||
p := &musicbrainzProvider{client: newHTTPClient(httpClientOptions{Name: "musicbrainz", MaxRetries: 1})}
|
||||
p := &musicbrainzProvider{client: providers.NewHTTPClient(providers.HTTPOptions{Name: "musicbrainz", MaxRetries: 1})}
|
||||
_ = p.Configure(ProviderSettings{Enabled: enabled})
|
||||
return p
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user