From b901560edf79cd85ecdb5ff2f279ad5b835029c2 Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Thu, 26 Nov 2026 12:58:55 -0500 Subject: [PATCH] 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 --- internal/coverart/httpclient.go | 207 --------------- internal/coverart/provider.go | 3 +- internal/coverart/provider_deezer.go | 14 +- internal/coverart/provider_deezer_test.go | 12 +- internal/coverart/provider_lastfm.go | 14 +- internal/coverart/provider_lastfm_test.go | 18 +- internal/coverart/provider_theaudiodb.go | 18 +- internal/coverart/provider_theaudiodb_test.go | 6 +- internal/providers/httpclient.go | 243 ++++++++++++++++++ .../httpclient_test.go | 48 ++-- internal/tags/httpclient.go | 191 -------------- internal/tags/provider.go | 3 +- internal/tags/provider_lastfm.go | 10 +- internal/tags/provider_lastfm_test.go | 4 +- internal/tags/provider_musicbrainz.go | 9 +- internal/tags/provider_musicbrainz_test.go | 4 +- 16 files changed, 333 insertions(+), 471 deletions(-) delete mode 100644 internal/coverart/httpclient.go create mode 100644 internal/providers/httpclient.go rename internal/{coverart => providers}/httpclient_test.go (80%) delete mode 100644 internal/tags/httpclient.go diff --git a/internal/coverart/httpclient.go b/internal/coverart/httpclient.go deleted file mode 100644 index b9023dff..00000000 --- a/internal/coverart/httpclient.go +++ /dev/null @@ -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<, 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) } diff --git a/internal/coverart/provider_theaudiodb_test.go b/internal/coverart/provider_theaudiodb_test.go index 471688a9..9dbb12e0 100644 --- a/internal/coverart/provider_theaudiodb_test.go +++ b/internal/coverart/provider_theaudiodb_test.go @@ -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 { diff --git a/internal/providers/httpclient.go b/internal/providers/httpclient.go new file mode 100644 index 00000000..84dbb677 --- /dev/null +++ b/internal/providers/httpclient.go @@ -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<= 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<