The first public release of Fabled Minstrel #158
@@ -12,13 +12,10 @@ import (
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/providers"
|
||||
)
|
||||
|
||||
// lastfmBaseURL is a var (not const) so tests can override it.
|
||||
var lastfmBaseURL = "https://ws.audioscrobbler.com/2.0/"
|
||||
// lastfmBaseURL is a var (not const) so tests can point it at a test server.
|
||||
var lastfmBaseURL = providers.LastfmBaseURL
|
||||
|
||||
const (
|
||||
// lastfmMinPeriod throttles to 4 req/s under their 5/s per-key ceiling.
|
||||
lastfmMinPeriod = 250 * time.Millisecond
|
||||
|
||||
lastfmMaxRetries = 3
|
||||
)
|
||||
|
||||
@@ -51,7 +48,7 @@ func init() {
|
||||
client: providers.NewHTTPClient(providers.HTTPOptions{
|
||||
Name: "lastfm",
|
||||
HTTPClient: &http.Client{Timeout: 30 * time.Second},
|
||||
MinInterval: lastfmMinPeriod,
|
||||
Pacer: providers.LastfmPacer,
|
||||
MaxRetries: lastfmMaxRetries,
|
||||
TreatAuthAsTransient: true,
|
||||
}),
|
||||
@@ -116,7 +113,10 @@ func (p *lastfmProvider) FetchArtistArt(ctx context.Context, ref ArtistRef) (thu
|
||||
if err := p.client.GetJSON(ctx, lastfmBaseURL+"?"+q.Encode(), &resp); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if resp.Error != 0 || resp.Artist.Name == "" {
|
||||
if err := providers.LastfmError(resp.Error); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if resp.Artist.Name == "" {
|
||||
return nil, nil, ErrNotFound
|
||||
}
|
||||
imgURL := pickLargestImage(resp.Artist.Image)
|
||||
@@ -162,7 +162,10 @@ func (p *lastfmProvider) FetchAlbumCover(ctx context.Context, ref AlbumRef) ([]b
|
||||
if err := p.client.GetJSON(ctx, lastfmBaseURL+"?"+q.Encode(), &resp); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Error != 0 || resp.Album.Name == "" {
|
||||
if err := providers.LastfmError(resp.Error); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Album.Name == "" {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
imgURL := pickLargestImage(resp.Album.Image)
|
||||
|
||||
@@ -347,6 +347,9 @@ func TestLastfm_FetchAlbumCover_Disabled(t *testing.T) {
|
||||
|
||||
// ── Rate-limit serialization ─────────────────────────────────────────────────
|
||||
|
||||
// lastfmTestPeriod is providers.LastfmPacer's spacing.
|
||||
const lastfmTestPeriod = 250 * time.Millisecond
|
||||
|
||||
func TestLastfm_RateLimit_Serializes(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
@@ -359,13 +362,13 @@ func TestLastfm_RateLimit_Serializes(t *testing.T) {
|
||||
lastfmBaseURL = srv.URL + "/"
|
||||
t.Cleanup(func() { lastfmBaseURL = prevBase })
|
||||
|
||||
// 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.
|
||||
// Build a provider WITH a fresh production-rate pacer so this test can
|
||||
// verify the pacing actually serializes. Other tests use
|
||||
// newLastfmTestProvider, which doesn't pace, for speed.
|
||||
p := &lastfmProvider{client: providers.NewHTTPClient(providers.HTTPOptions{
|
||||
Name: "lastfm",
|
||||
HTTPClient: &http.Client{Timeout: 5 * time.Second},
|
||||
MinInterval: lastfmMinPeriod,
|
||||
Pacer: providers.NewInterval(lastfmTestPeriod),
|
||||
TreatAuthAsTransient: true,
|
||||
BaseBackoff: time.Millisecond,
|
||||
})}
|
||||
@@ -378,9 +381,9 @@ func TestLastfm_RateLimit_Serializes(t *testing.T) {
|
||||
_, _, _ = p.FetchArtistArt(context.Background(), ArtistRef{Name: "B"})
|
||||
elapsed := time.Since(start)
|
||||
|
||||
if elapsed < lastfmMinPeriod {
|
||||
if elapsed < lastfmTestPeriod {
|
||||
t.Errorf("two back-to-back calls completed in %v, want at least %v (rate-limit didn't serialize)",
|
||||
elapsed, lastfmMinPeriod)
|
||||
elapsed, lastfmTestPeriod)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -516,3 +519,16 @@ func TestPickLargestImage(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A rate-limit answer in a 200 body is retried later, not read as "no art".
|
||||
func TestLastfm_RateLimitCodeIsTransient(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"error":29,"message":"Rate limit exceeded"}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
p := newLastfmTestProvider(t, srv.URL+"/", "test-key")
|
||||
if _, err := p.FetchAlbumCover(context.Background(), AlbumRef{ArtistName: "A", AlbumTitle: "B"}); !errors.Is(err, ErrTransient) {
|
||||
t.Fatalf("err = %v, want ErrTransient", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -59,10 +59,8 @@ type HTTPOptions struct {
|
||||
// upstream. Each provider owns one, configured with its own pacing and
|
||||
// auth semantics.
|
||||
type HTTPClient struct {
|
||||
opts HTTPOptions
|
||||
|
||||
mu sync.Mutex
|
||||
lastCall time.Time
|
||||
opts HTTPOptions
|
||||
interval *Interval
|
||||
}
|
||||
|
||||
// NewHTTPClient fills opts' defaults and returns a client.
|
||||
@@ -82,7 +80,42 @@ func NewHTTPClient(opts HTTPOptions) *HTTPClient {
|
||||
if opts.ImageBodyLimit == 0 {
|
||||
opts.ImageBodyLimit = 5 * 1024 * 1024
|
||||
}
|
||||
return &HTTPClient{opts: opts}
|
||||
return &HTTPClient{opts: opts, interval: NewInterval(opts.MinInterval)}
|
||||
}
|
||||
|
||||
// Interval spaces calls at least every apart. Share one between clients
|
||||
// that spend the same upstream budget. A zero interval never waits.
|
||||
type Interval struct {
|
||||
every time.Duration
|
||||
mu sync.Mutex
|
||||
lastCall time.Time
|
||||
}
|
||||
|
||||
// NewInterval returns an Interval spacing calls every apart.
|
||||
func NewInterval(every time.Duration) *Interval { return &Interval{every: every} }
|
||||
|
||||
// Wait blocks until the interval has passed since the last call, or ctx
|
||||
// ends, then claims the slot.
|
||||
func (iv *Interval) Wait(ctx context.Context) error {
|
||||
if iv.every <= 0 {
|
||||
return nil
|
||||
}
|
||||
iv.mu.Lock()
|
||||
wait := time.Until(iv.lastCall.Add(iv.every))
|
||||
if wait > 0 {
|
||||
timer := time.NewTimer(wait)
|
||||
iv.mu.Unlock()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
timer.Stop()
|
||||
return ctx.Err()
|
||||
case <-timer.C:
|
||||
}
|
||||
iv.mu.Lock()
|
||||
}
|
||||
iv.lastCall = time.Now()
|
||||
iv.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetJSON sends GET fullURL and decodes the 200 body into out. It retries
|
||||
@@ -194,31 +227,12 @@ func (c *HTTPClient) do(ctx context.Context, fullURL, accept string) (*http.Resp
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// pace waits on the Pacer, or until MinInterval has passed since the last
|
||||
// request, then claims the slot.
|
||||
// pace waits on the Pacer, or on the client's own interval.
|
||||
func (c *HTTPClient) pace(ctx context.Context) error {
|
||||
if c.opts.Pacer != nil {
|
||||
return c.opts.Pacer.Wait(ctx)
|
||||
}
|
||||
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
|
||||
return c.interval.Wait(ctx)
|
||||
}
|
||||
|
||||
// backoff sleeps 2^attempt × BaseBackoff ± 20%, or until ctx is done.
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
package providers
|
||||
|
||||
import "time"
|
||||
|
||||
// LastfmBaseURL is Last.fm's API root, used by both the cover-art and the
|
||||
// tag Last.fm providers.
|
||||
const LastfmBaseURL = "https://ws.audioscrobbler.com/2.0/"
|
||||
|
||||
// LastfmPacer spaces every Last.fm request this server makes, whichever
|
||||
// family asks: 4 a second, under Last.fm's 5 a second per key. Each
|
||||
// family pacing on its own could reach 8 a second when an admin uses one
|
||||
// key for both.
|
||||
var LastfmPacer = NewInterval(250 * time.Millisecond)
|
||||
|
||||
// lastfmTransientCodes are the JSON error codes that mean "try again"
|
||||
// rather than "no data": 8 operation failed, 11 and 16 service temporarily
|
||||
// unavailable, 29 rate limit exceeded.
|
||||
var lastfmTransientCodes = map[int]bool{8: true, 11: true, 16: true, 29: true}
|
||||
|
||||
// LastfmError maps the error field Last.fm returns in a 200 body. 0 is no
|
||||
// error. A transient code is ErrTransient, so the row is retried on a later
|
||||
// pass instead of settling as having nothing from Last.fm; anything else (6
|
||||
// not found, 10 invalid key, …) is ErrNotFound, and the chain moves on.
|
||||
func LastfmError(code int) error {
|
||||
switch {
|
||||
case code == 0:
|
||||
return nil
|
||||
case lastfmTransientCodes[code]:
|
||||
return ErrTransient
|
||||
default:
|
||||
return ErrNotFound
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package providers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestLastfmError(t *testing.T) {
|
||||
for code, want := range map[int]error{0: nil, 6: ErrNotFound, 10: ErrNotFound, 8: ErrTransient, 11: ErrTransient, 16: ErrTransient, 29: ErrTransient} {
|
||||
if got := LastfmError(code); !errors.Is(got, want) || (want == nil && got != nil) {
|
||||
t.Errorf("LastfmError(%d) = %v, want %v", code, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,23 +11,14 @@ import (
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/providers"
|
||||
)
|
||||
|
||||
// lastfmBaseURL is a var (not const) so tests can override it.
|
||||
var lastfmBaseURL = "https://ws.audioscrobbler.com/2.0/"
|
||||
// lastfmBaseURL is a var (not const) so tests can point it at a test server.
|
||||
var lastfmBaseURL = providers.LastfmBaseURL
|
||||
|
||||
const (
|
||||
// lastfmMinPeriod throttles to 4 req/s under the 5/s per-key ceiling.
|
||||
lastfmMinPeriod = 250 * time.Millisecond
|
||||
// lastfmTagMaxCount is Last.fm's top-tag count scale (0-100 popularity).
|
||||
lastfmTagMaxCount = 100.0
|
||||
)
|
||||
|
||||
// lastfmTransientErrors are Last.fm JSON-level error codes that mean
|
||||
// "try again" rather than "no data": 8 operation failed, 11/16 service
|
||||
// temporarily unavailable, 29 rate limit. Everything else non-zero
|
||||
// (6 not found, 10 invalid key, …) is treated as ErrNotFound so the
|
||||
// chain simply skips this provider for the track.
|
||||
var lastfmTransientErrors = map[int]bool{8: true, 11: true, 16: true, 29: true}
|
||||
|
||||
// lastfmProvider fetches track-level folksonomy tags via Last.fm's
|
||||
// track.getTopTags. Requires an operator-supplied API key; stays inert
|
||||
// (ErrNotFound on every call) when disabled or unkeyed. Name-based, so it
|
||||
@@ -43,7 +34,7 @@ func init() {
|
||||
client: providers.NewHTTPClient(providers.HTTPOptions{
|
||||
Name: "lastfm",
|
||||
HTTPClient: &http.Client{Timeout: 30 * time.Second},
|
||||
MinInterval: lastfmMinPeriod,
|
||||
Pacer: providers.LastfmPacer,
|
||||
MaxRetries: 3,
|
||||
TreatAuthAsTransient: true,
|
||||
}),
|
||||
@@ -110,11 +101,8 @@ func (p *lastfmProvider) FetchTrackTags(ctx context.Context, ref TrackRef) ([]Ta
|
||||
if err := p.client.GetJSON(ctx, lastfmBaseURL+"?"+q.Encode(), &resp); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Error != 0 {
|
||||
if lastfmTransientErrors[resp.Error] {
|
||||
return nil, ErrTransient
|
||||
}
|
||||
return nil, ErrNotFound
|
||||
if err := providers.LastfmError(resp.Error); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := normalizeLastfmTags(resp.TopTags.Tag)
|
||||
if len(out) == 0 {
|
||||
|
||||
Reference in New Issue
Block a user