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:
2026-11-26 12:58:55 -05:00
co-authored by Claude Opus 5.5
parent 487e11f59f
commit b901560edf
16 changed files with 333 additions and 471 deletions
-207
View File
@@ -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
}
}
-212
View File
@@ -1,212 +0,0 @@
package coverart
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(httpClientOptions{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(httpClientOptions{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(httpClientOptions{
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(httpClientOptions{
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(httpClientOptions{
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(httpClientOptions{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(httpClientOptions{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(httpClientOptions{
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(httpClientOptions{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(httpClientOptions{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(httpClientOptions{
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)
}
}
+1 -2
View File
@@ -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
View File
@@ -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.
+7 -5
View File
@@ -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
View File
@@ -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.
+10 -8
View File
@@ -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,
+10 -8
View File
@@ -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 {