mirror of
https://github.com/navidrome/navidrome.git
synced 2026-08-31 07:30:32 +00:00
* feat(agents): retry-later error type with optional server delay
Add agents.ErrRetryLater and agents.RetryLaterError, which carries the
delay requested by an external service (e.g. ListenBrainz's
X-RateLimit-Reset-In). scrobbler.ErrRetryLater becomes an alias of the new
sentinel, so existing errors.Is checks and the plugin error-string protocol
keep working unchanged. Groundwork for honoring server-requested retry
delays across scrobbling, metadata agents and artwork.
Song.Equals tests moved to song_test.go to enable external test package.
* fix(scrobbler): honor backoff window and server-requested retry delay
ListenBrainz 429s were decoded into a typed error that classified as
unrecoverable, silently discarding the scrobble (a JSON-bodied 429 was
measured live). The client now maps any 429 to agents.RetryLaterError,
carrying X-RateLimit-Reset-In when present (capped at 1h). Last.fm error 29
(rate limit) is now retryable like 11/16. The buffer's drain loop no longer
lets wake signals bypass an active backoff window - new plays enqueue but
drain only when the window closes - and the wait honors the server delay
via max(backoff, retryIn).
* feat(agents): skip cooling-down agents in aggregate calls
When an agent reports retry-later, remember a per-agent cooldown deadline
(the server-requested delay, or 1 minute when unspecified) and skip that
agent in all aggregate metadata calls until it passes. A round that found
no data but skipped or saw a throttled agent returns ErrRetryLater instead
of ErrNotFound, so callers cannot mistake rate limiting for a definitive
'no data' answer.
* feat(artwork): honor server-requested retry delay when rescheduling
When an external image lookup fails with a retry-later error carrying a
delay (e.g. a 429 with X-RateLimit-Reset-In), the chain trace carries the
largest such hint back to the worker, which reschedules the item at
max(exponential backoff, server delay) instead of backoff alone.
* feat(plugins): retry-later with optional delay for scrobbler and agent plugins
Scrobbler plugins can now return scrobbler(retry_later:N) to request a
retry in N seconds (capped at 1h); the bare token keeps its old meaning.
Metadata-agent plugins, which had no error vocabulary at all, gain the
parallel agent(retry_later[:N]) token, mapped to agents.RetryLaterError so
the aggregate's cooldown and the artwork worker honor plugin throttling
the same way as built-in agents.
* fix: address whole-branch review findings for retry-later handling
Narrow the aggregate's throttled rule to the spec sentence: core.Agents returns
ErrRetryLater only when no agent answered at all (all skipped-cooling or
retry-later). An agent that does not implement the called method now returns an
internal errUnsupported instead of ErrNotFound, so it counts as "did not run" —
without that, the always-appended local agent would answer for biography, URL
and images and make ErrRetryLater unreachable.
Wire the consequence in core/external: a throttled round no longer stamps
ExternalInfoUpdatedAt (artist and album), so the empty result is not cached for
the TTL, and TopSongs maps ErrRetryLater to the same empty-200 the not-found
path already produced instead of a new client-facing error.
Move the Last.fm code-29 mapping into the client's central error construction so
every metadata path produces RetryLaterError, and map ListenBrainz's body-level
code 429 (sent with a non-429 HTTP status) the same way.
Clamp server- and plugin-requested delays in seconds before scaling to a
Duration, in all three parse sites: a header of 18446744074 wrapped past 2^64 and
came out as a 0.29s delay.
Also: extract the artwork worker's reschedule computation into retryDelay() and
cover both it and the trace RetryIn wiring with tests; collapse the double regex
call in mapScrobblerError; drop capabilities.ScrobblerErrorRetryLaterIn (ndpgen
never emits funcs, so plugin authors could not reach it); regenerate the PDKs so
MetadataAgentError reaches the Go and Rust SDKs; de-flake the cooldown tests
(long RetryIn for the skip case, separate expiry spec); and cover the max()
retry-delay aggregation across users in the scrobble buffer.
* refactor: dedupe retry-later parsing and simplify error collection
- Add agents.NewRetryLater and agents.RetryLaterFromSeconds, with a single
1h cap, replacing the parse+clamp+multiply logic and the maxRetryInSeconds
constant duplicated across listenbrainz, plugins and the agent adapter.
- Move HTTP header parsing to httpclient.RetryAfter, so the transport layer
owns it and stays domain-agnostic; drop retryInFromHeaders from the
ListenBrainz client. Covered by a new Ginkgo table in that package.
- Collapse the two near-identical plugin retry_later regexes into one
parseRetryLater(prefix, msg) shared by the agent and scrobbler adapters.
- Fold the duplicated noteRetryIn snippet from fetchArtistImage and
fetchAlbumImage into recordAgent, which already branched on the same
isTransientExternal condition.
- Replace the atomic.Bool + note() closure in populateArtistInfo with
errgroup's own error collection; the group carries no context, so a
returned error does not cancel its siblings.
- Reuse recoveringScrobbler for the per-user delay test instead of a third
double, and switch fakeScrobbler's mutex-guarded error to the
atomic.Pointer idiom already used in the same package.
* refactor(listenbrainz): keep rate-limit header parsing in the adapter
The X-RateLimit-Reset-In header is ListenBrainz's own convention, not a
shared one: Last.fm sends no rate-limit headers at all and reports its
limit as a body code, and no other integration in tree sends Retry-After.
A parser in utils/httpclient implied a uniformity across services that
does not exist, so it moves back next to the only client that can know
which header its service sends.
* refactor(agents): collapse the retry-later sentinel and error into one type
ErrRetryLater is now the zero-delay RetryLaterError rather than a separate
errors.New value, so errors.Is and errors.AsType both match the sentinel and
every delay-carrying variant. That removes the trap where a bare sentinel
silently skipped the AsType path, and lets every consumer read the delay off
the error directly: the RetryIn accessor and the two constructors are gone,
with the policy cap applied where untrusted input is parsed.
* refactor(agents): split the cooldown store from the per-dispatch tally
The cooldown map and mutex become a cooldowns value with active/park, holding
no knowledge of errors; agentAttempts records one dispatch's outcomes and owns
the classification that noteAgentError used to hide behind a bool. The three
dispatch loops now touch a single object: skip folds the cooldown check and the
throttled flag into one call, so the store never appears in the loops.
* refactor(agents): share one dispatch loop between the agent call helpers
callAgentMethod and callAgentSliceMethod ran identical loops, differing only in
how they test a result for emptiness: a slice cannot be compared against its
zero value, so the two could not share a constraint. Both now delegate to
callAgent, which takes that test as a parameter. Keeping the loop in one place
matters more than the lines saved: it holds the cooldown skip, the attempt
recording and the empty-dispatch verdict, and a fix applied to one copy but not
the other would be silent.
* test: cover the two retry-later paths a mutation could break silently
Both gaps were proven, not guessed: making the artwork worker pass 0 instead
of the collected hint left all 386 specs green, and replacing the default
agent cooldown with 0 left the agents suite green. The worker test drives a
throttled image agent through drain and asserts the persisted retry_at, and
the cooldown test parks an agent that asked to be retried without naming a
delay, which is what Last.fm does on every rate limit.
* refactor(artwork): carry the external failure as an error, not a flag plus a trace field
The retry delay was riding on ChainTrace, a diagnostic that gets persisted, while
the very same signal — an external source faulted — already travelled by value as
resolution.extError. That was two mechanisms for one idea, and it put control-flow
state inside a serializable trace.
resolution.extError and chainState.extErr become the error itself, so a caller
checks err != nil for the fault and errors.AsType for the delay the provider asked
for. The agent loops return that error last, per convention, and longerRetry keeps
whichever failure wants the longer wait. ChainTrace goes back to holding only steps
and no longer imports core/agents.
* fix(artwork): check the resolve error before reading its resolution
Reading res.extError before the err check was safe only because every error path
in resolve returns a bare resolution{}; a future path returning a partly-filled
one would have been read silently. The failure path now returns no delay
explicitly.
* test(artwork): assert the delay acquire reports, not just its downstream effect
acquire's retry delay was only covered through the worker's persisted retry_at,
one layer away from where the value is computed. Both outcomes are now pinned at
the processor: a plain failure asks for nothing, a throttled provider's delay is
passed through.
* refactor: share the retry-seconds parse and drop the backoff deadline arithmetic
The clamp-before-scaling invariant lived in two parsers and was independently
re-tested in three files with the same magic number; a fix applied to one copy
would have left the others wrapping a huge value down to a fraction of a second.
It moves to agents.ParseRetryIn.
The buffer tracked an absolute retryDeadline only to re-arm a timer that was
already armed for the same instant; a backingOff flag says the same thing without
the arithmetic. The plugin token regex now carries its capability in the pattern
instead of capturing and comparing, so another capability's token in the same
message cannot mask it. resolution.extError becomes extErr, matching its
chainState counterpart.
* fix(agents): keep the longer cooldown when parks overlap
Calls to one agent overlap, so a short cooldown could land after a long one
started and cut it short. park now keeps whichever deadline is later, matching
the rule longerRetry already applies on the artwork side. No in-tree provider
can currently produce two different delays for the same agent, so this is
hardening rather than a fix for observed behaviour.
* fix(agents): parse the retry delay at a fixed width
strconv.Atoi parses into the native int, so on the 32-bit targets we ship
(linux/386, windows/386, three ARM variants) a delay above MaxInt32 seconds
overflowed and became unspecified instead of being capped. No provider sends a
68-year delay, so this is not user-visible, but the overflow tests asserted the
cap and would have failed on those architectures, where tests never run.
* fix(plugins): anchor the retry_later regex to a word boundary
Prevents a superstring like useragent(retry_later) from matching the
agent capability token.
479 lines
22 KiB
Go
479 lines
22 KiB
Go
package external_test
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
|
|
_ "github.com/navidrome/navidrome/adapters/lastfm"
|
|
_ "github.com/navidrome/navidrome/adapters/listenbrainz"
|
|
"github.com/navidrome/navidrome/conf"
|
|
"github.com/navidrome/navidrome/conf/configtest"
|
|
"github.com/navidrome/navidrome/core/agents"
|
|
. "github.com/navidrome/navidrome/core/external"
|
|
"github.com/navidrome/navidrome/core/matcher"
|
|
"github.com/navidrome/navidrome/model"
|
|
"github.com/navidrome/navidrome/tests"
|
|
. "github.com/onsi/ginkgo/v2"
|
|
. "github.com/onsi/gomega"
|
|
"github.com/stretchr/testify/mock"
|
|
)
|
|
|
|
var _ = Describe("Provider - TopSongs", func() {
|
|
var (
|
|
p Provider
|
|
artistRepo *mockArtistRepo // From provider_helper_test.go
|
|
mediaFileRepo *mockMediaFileRepo // From provider_helper_test.go
|
|
ag *mockAgents // Consolidated mock from export_test.go
|
|
ctx context.Context
|
|
)
|
|
|
|
BeforeEach(func() {
|
|
DeferCleanup(configtest.SetupConfig())
|
|
// Disable fuzzy matching for these tests to avoid unexpected GetAll calls
|
|
conf.Server.Matcher.FuzzyThreshold = 100
|
|
|
|
ctx = GinkgoT().Context()
|
|
|
|
artistRepo = newMockArtistRepo() // Use helper mock
|
|
mediaFileRepo = newMockMediaFileRepo() // Use helper mock
|
|
|
|
// Configure tests.MockDataStore to use the testify/mock-based repos
|
|
ds := &tests.MockDataStore{
|
|
MockedArtist: artistRepo,
|
|
MockedMediaFile: mediaFileRepo,
|
|
}
|
|
|
|
ag = new(mockAgents)
|
|
|
|
p = NewProvider(ds, ag, matcher.New(ds), &fakeBroker{})
|
|
})
|
|
|
|
It("returns top songs for a known artist", func() {
|
|
// Mock finding the artist
|
|
artist1 := model.Artist{ID: "artist-1", Name: "Artist One", MbzArtistID: "mbid-artist-1"}
|
|
artistRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.Artists{artist1}, nil).Once()
|
|
|
|
// Mock agent response
|
|
agentSongs := []agents.Song{
|
|
{Name: "Song One", MBID: "mbid-song-1"},
|
|
{Name: "Song Two", MBID: "mbid-song-2"},
|
|
}
|
|
ag.On("GetArtistTopSongs", ctx, "artist-1", "Artist One", "mbid-artist-1", 2).Return(agentSongs, nil).Once()
|
|
|
|
// Mock finding matching tracks (both returned in a single query)
|
|
song1 := model.MediaFile{ID: "song-1", Title: "Song One", ArtistID: "artist-1", MbzRecordingID: "mbid-song-1"}
|
|
song2 := model.MediaFile{ID: "song-2", Title: "Song Two", ArtistID: "artist-1", MbzRecordingID: "mbid-song-2"}
|
|
mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{song1, song2}, nil).Once()
|
|
|
|
songs, err := p.TopSongs(ctx, "Artist One", "", 2)
|
|
|
|
Expect(err).ToNot(HaveOccurred())
|
|
Expect(songs).To(HaveLen(2))
|
|
Expect(songs[0].ID).To(Equal("song-1"))
|
|
Expect(songs[1].ID).To(Equal("song-2"))
|
|
artistRepo.AssertExpectations(GinkgoT())
|
|
ag.AssertExpectations(GinkgoT())
|
|
mediaFileRepo.AssertExpectations(GinkgoT())
|
|
})
|
|
|
|
Context("artist id and/or name", func() {
|
|
artist1 := model.Artist{ID: "artist-1", Name: "Artist One", MbzArtistID: "mbid-artist-1"}
|
|
|
|
BeforeEach(func() {
|
|
agentSongs := []agents.Song{{Name: "Song One", MBID: "mbid-song-1"}}
|
|
ag.On("GetArtistTopSongs", ctx, "artist-1", "Artist One", "mbid-artist-1", 2).Return(agentSongs, nil).Once()
|
|
|
|
song1 := model.MediaFile{ID: "song-1", Title: "Song One", ArtistID: "artist-1", MbzRecordingID: "mbid-song-1"}
|
|
mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{song1}, nil).Once()
|
|
})
|
|
|
|
It("returns top songs for a known artist by id only", func() {
|
|
artistRepo.On("Get", "artist-1").Return(&artist1, nil).Once()
|
|
|
|
songs, err := p.TopSongs(ctx, "", "artist-1", 2)
|
|
|
|
Expect(err).ToNot(HaveOccurred())
|
|
Expect(songs).To(HaveLen(1))
|
|
Expect(songs[0].ID).To(Equal("song-1"))
|
|
artistRepo.AssertExpectations(GinkgoT())
|
|
ag.AssertExpectations(GinkgoT())
|
|
mediaFileRepo.AssertExpectations(GinkgoT())
|
|
})
|
|
|
|
It("returns top songs for a known artist by id, falling back to name", func() {
|
|
artistRepo.On("Get", "fake-id").Return(nil, model.ErrNotFound).Once()
|
|
artistRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.Artists{artist1}, nil).Once()
|
|
|
|
songs, err := p.TopSongs(ctx, "Artist One", "fake-id", 2)
|
|
|
|
Expect(err).ToNot(HaveOccurred())
|
|
Expect(songs).To(HaveLen(1))
|
|
Expect(songs[0].ID).To(Equal("song-1"))
|
|
artistRepo.AssertExpectations(GinkgoT())
|
|
ag.AssertExpectations(GinkgoT())
|
|
mediaFileRepo.AssertExpectations(GinkgoT())
|
|
})
|
|
})
|
|
|
|
It("bails if lookup by id returns a fatal error", func() {
|
|
artistRepo.On("Get", "artist-1").Return(nil, model.ErrInvalidAuth).Once()
|
|
songs, err := p.TopSongs(ctx, "Artist One", "artist-1", 2)
|
|
Expect(songs).To(BeEmpty())
|
|
Expect(err).To(HaveOccurred())
|
|
})
|
|
|
|
It("bails if lookup by name returns a fatal error", func() {
|
|
artistRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(nil, model.ErrInvalidAuth).Once()
|
|
songs, err := p.TopSongs(ctx, "Artist One", "", 2)
|
|
Expect(songs).To(BeEmpty())
|
|
Expect(err).To(HaveOccurred())
|
|
})
|
|
|
|
It("backfills name and MBID onto an unnamed primary credit (the queried artist) and matches", func() {
|
|
artist1 := model.Artist{ID: "artist-1", Name: "Artist One", MbzArtistID: "mbid-artist-1"}
|
|
artistRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.Artists{artist1}, nil)
|
|
|
|
// Agent leaves the first credit unnamed (e.g. an MBID-less collaborator slot). That blank
|
|
// credit IS the queried artist, so enrichment fills both name and MBID; the song then matches
|
|
// the queried artist's track via the backfilled identity.
|
|
agentSongs := []agents.Song{
|
|
{Name: "Song One", Artists: []agents.Artist{{}}},
|
|
}
|
|
ag.On("GetArtistTopSongs", ctx, "artist-1", "Artist One", "mbid-artist-1", 1).Return(agentSongs, nil).Once()
|
|
|
|
track := model.MediaFile{
|
|
ID: "song-1", Title: "Song One", ArtistID: "artist-1",
|
|
Participants: model.Participants{model.RoleArtist: model.ParticipantList{
|
|
{Artist: model.Artist{ID: "artist-1", Name: "Artist One", OrderArtistName: "artist one", MbzArtistID: "mbid-artist-1"}},
|
|
}},
|
|
}
|
|
mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{track}, nil)
|
|
|
|
songs, err := p.TopSongs(ctx, "Artist One", "", 1)
|
|
|
|
Expect(err).ToNot(HaveOccurred())
|
|
Expect(songs).To(HaveLen(1))
|
|
Expect(songs[0].ID).To(Equal("song-1"))
|
|
})
|
|
|
|
It("does not stamp the queried MBID onto an already-named different first credit", func() {
|
|
// The queried artist (One) appears only as a featured collaborator; the displayed first credit
|
|
// is a DIFFERENT artist (Two) returned without an MBID. Enrichment must NOT assign One's MBID
|
|
// to Two — only Two's name match (which fails here) or One's own credit may resolve the track.
|
|
artist1 := model.Artist{ID: "artist-1", Name: "Artist One", MbzArtistID: "mbid-artist-1"}
|
|
artistRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.Artists{artist1}, nil)
|
|
|
|
agentSongs := []agents.Song{
|
|
{Name: "Collab Song", Artists: []agents.Artist{{Name: "Artist Two"}}},
|
|
}
|
|
ag.On("GetArtistTopSongs", ctx, "artist-1", "Artist One", "mbid-artist-1", 1).Return(agentSongs, nil).Once()
|
|
|
|
// Library track is credited to Artist One (the queried artist) under a same title. If the
|
|
// queried MBID were wrongly stamped onto the "Artist Two" credit, that mismatched name+MBID artistRepo.On("Get", "fake-id").Return(nil, model.ErrNotFound).Once()
|
|
|
|
// could mis-resolve. With the guard, "Artist Two" stays MBID-less and does not match One's track.
|
|
track := model.MediaFile{
|
|
ID: "one-track", Title: "Collab Song", ArtistID: "artist-1",
|
|
Participants: model.Participants{model.RoleArtist: model.ParticipantList{
|
|
{Artist: model.Artist{ID: "artist-1", Name: "Artist One", OrderArtistName: "artist one", MbzArtistID: "mbid-artist-1"}},
|
|
}},
|
|
}
|
|
mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{track}, nil)
|
|
|
|
songs, err := p.TopSongs(ctx, "Artist One", "", 1)
|
|
|
|
Expect(err).ToNot(HaveOccurred())
|
|
// "Artist Two" (named, MBID-less, not in the library) does not resolve to One's track.
|
|
Expect(songs).To(BeEmpty())
|
|
})
|
|
|
|
It("returns nil for an unknown artist", func() {
|
|
// Mock artist not found
|
|
artistRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.Artists{}, nil).Once()
|
|
|
|
songs, err := p.TopSongs(ctx, "Unknown Artist", "", 5)
|
|
|
|
Expect(err).ToNot(HaveOccurred()) // TopSongs returns nil error if artist not found
|
|
Expect(songs).To(BeNil())
|
|
artistRepo.AssertExpectations(GinkgoT())
|
|
ag.AssertNotCalled(GinkgoT(), "GetArtistTopSongs", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything)
|
|
})
|
|
|
|
It("returns error when the agent returns an error", func() {
|
|
// Mock finding the artist
|
|
artist1 := model.Artist{ID: "artist-1", Name: "Artist One", MbzArtistID: "mbid-artist-1"}
|
|
artistRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.Artists{artist1}, nil).Once()
|
|
|
|
// Mock agent error
|
|
agentErr := errors.New("agent error")
|
|
ag.On("GetArtistTopSongs", ctx, "artist-1", "Artist One", "mbid-artist-1", 5).Return(nil, agentErr).Once()
|
|
|
|
songs, err := p.TopSongs(ctx, "Artist One", "", 5)
|
|
|
|
Expect(err).To(MatchError(agentErr))
|
|
Expect(songs).To(BeNil())
|
|
artistRepo.AssertExpectations(GinkgoT())
|
|
ag.AssertExpectations(GinkgoT())
|
|
})
|
|
|
|
It("returns ErrNotFound when the agent returns ErrNotFound", func() {
|
|
// Mock finding the artist
|
|
artist1 := model.Artist{ID: "artist-1", Name: "Artist One", MbzArtistID: "mbid-artist-1"}
|
|
artistRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.Artists{artist1}, nil).Once()
|
|
|
|
// Mock agent ErrNotFound
|
|
ag.On("GetArtistTopSongs", ctx, "artist-1", "Artist One", "mbid-artist-1", 5).Return(nil, agents.ErrNotFound).Once()
|
|
|
|
songs, err := p.TopSongs(ctx, "Artist One", "", 5)
|
|
|
|
Expect(err).To(MatchError(model.ErrNotFound))
|
|
Expect(songs).To(BeNil())
|
|
artistRepo.AssertExpectations(GinkgoT())
|
|
ag.AssertExpectations(GinkgoT())
|
|
})
|
|
|
|
// This endpoint answered with an empty list before retry-later existed; it must keep doing so.
|
|
It("returns an empty list, not a client error, when the agents are throttled", func() {
|
|
artist1 := model.Artist{ID: "artist-1", Name: "Artist One", MbzArtistID: "mbid-artist-1"}
|
|
artistRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.Artists{artist1}, nil).Once()
|
|
ag.On("GetArtistTopSongs", ctx, "artist-1", "Artist One", "mbid-artist-1", 5).
|
|
Return(nil, agents.ErrRetryLater).Once()
|
|
|
|
songs, err := p.TopSongs(ctx, "Artist One", "", 5)
|
|
|
|
Expect(songs).To(BeEmpty())
|
|
Expect(err).To(MatchError(model.ErrNotFound), "the handler renders this as an empty 200")
|
|
Expect(err).ToNot(MatchError(agents.ErrRetryLater))
|
|
ag.AssertExpectations(GinkgoT())
|
|
})
|
|
|
|
It("returns fewer songs if count is less than available top songs", func() {
|
|
// Mock finding the artist
|
|
artist1 := model.Artist{ID: "artist-1", Name: "Artist One", MbzArtistID: "mbid-artist-1"}
|
|
artistRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.Artists{artist1}, nil).Once()
|
|
|
|
// Mock agent response (only need 1 for the test)
|
|
agentSongs := []agents.Song{{Name: "Song One", MBID: "mbid-song-1"}}
|
|
ag.On("GetArtistTopSongs", ctx, "artist-1", "Artist One", "mbid-artist-1", 1).Return(agentSongs, nil).Once()
|
|
|
|
// Mock finding matching track
|
|
song1 := model.MediaFile{ID: "song-1", Title: "Song One", ArtistID: "artist-1", MbzRecordingID: "mbid-song-1"}
|
|
mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{song1}, nil).Once()
|
|
|
|
songs, err := p.TopSongs(ctx, "Artist One", "", 1)
|
|
|
|
Expect(err).ToNot(HaveOccurred())
|
|
Expect(songs).To(HaveLen(1))
|
|
Expect(songs[0].ID).To(Equal("song-1"))
|
|
artistRepo.AssertExpectations(GinkgoT())
|
|
ag.AssertExpectations(GinkgoT())
|
|
mediaFileRepo.AssertExpectations(GinkgoT())
|
|
})
|
|
|
|
It("returns fewer songs if fewer matching tracks are found", func() {
|
|
// Mock finding the artist
|
|
artist1 := model.Artist{ID: "artist-1", Name: "Artist One", MbzArtistID: "mbid-artist-1"}
|
|
artistRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.Artists{artist1}, nil).Once()
|
|
// Matcher artist resolution for the title-match path (song2 falls through).
|
|
artistRepo.On("GetAll", mock.Anything).Return(model.Artists{artist1}, nil).Maybe()
|
|
|
|
// Mock agent response
|
|
agentSongs := []agents.Song{
|
|
{Name: "Song One", MBID: "mbid-song-1"},
|
|
{Name: "Song Two", MBID: "mbid-song-2"},
|
|
}
|
|
ag.On("GetArtistTopSongs", ctx, "artist-1", "Artist One", "mbid-artist-1", 2).Return(agentSongs, nil).Once()
|
|
|
|
// Mock finding matching tracks (only find song 1 on bulk query)
|
|
song1 := model.MediaFile{ID: "song-1", Title: "Song One", ArtistID: "artist-1", MbzRecordingID: "mbid-song-1"}
|
|
mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{song1}, nil).Once() // bulk MBID query
|
|
mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{}, nil).Once() // title track-fetch for song2: no match
|
|
|
|
songs, err := p.TopSongs(ctx, "Artist One", "", 2)
|
|
|
|
Expect(err).ToNot(HaveOccurred())
|
|
Expect(songs).To(HaveLen(1))
|
|
Expect(songs[0].ID).To(Equal("song-1"))
|
|
artistRepo.AssertExpectations(GinkgoT())
|
|
ag.AssertExpectations(GinkgoT())
|
|
mediaFileRepo.AssertExpectations(GinkgoT())
|
|
})
|
|
|
|
It("returns error when context is canceled during agent call", func() {
|
|
// Mock finding the artist
|
|
artist1 := model.Artist{ID: "artist-1", Name: "Artist One", MbzArtistID: "mbid-artist-1"}
|
|
artistRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.Artists{artist1}, nil).Once()
|
|
|
|
// Setup context that will be canceled
|
|
canceledCtx, cancel := context.WithCancel(ctx)
|
|
|
|
// Mock agent call to return context canceled error
|
|
ag.On("GetArtistTopSongs", canceledCtx, "artist-1", "Artist One", "mbid-artist-1", 5).Return(nil, context.Canceled).Once()
|
|
|
|
cancel() // Cancel the context before calling
|
|
songs, err := p.TopSongs(canceledCtx, "Artist One", "", 5)
|
|
|
|
Expect(err).To(MatchError(context.Canceled))
|
|
Expect(songs).To(BeNil())
|
|
artistRepo.AssertExpectations(GinkgoT())
|
|
ag.AssertExpectations(GinkgoT())
|
|
})
|
|
|
|
It("falls back to title matching when MbzRecordingID is missing", func() {
|
|
// Mock finding the artist
|
|
artist1 := model.Artist{ID: "artist-1", Name: "Artist One", MbzArtistID: "mbid-artist-1"}
|
|
artistRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.Artists{artist1}, nil).Once()
|
|
// Matcher artist resolution for both title-fallback songs.
|
|
artistRepo.On("GetAll", mock.Anything).Return(model.Artists{artist1}, nil).Maybe()
|
|
|
|
// Mock agent response with songs that have NO MBID (empty string)
|
|
agentSongs := []agents.Song{
|
|
{Name: "Song One", MBID: ""}, // No MBID, should fall back to title matching
|
|
{Name: "Song Two", MBID: ""}, // No MBID, should fall back to title matching
|
|
}
|
|
ag.On("GetArtistTopSongs", ctx, "artist-1", "Artist One", "mbid-artist-1", 2).Return(agentSongs, nil).Once()
|
|
|
|
// Title track-fetch: tracks must carry RoleArtist participants so back-mapping routes them.
|
|
participant1 := model.Participant{Artist: model.Artist{ID: "artist-1", Name: "Artist One", OrderArtistName: "artist one"}}
|
|
song1 := model.MediaFile{
|
|
ID: "song-1", Title: "Song One", Artist: "Artist One", ArtistID: "artist-1",
|
|
Participants: model.Participants{model.RoleArtist: model.ParticipantList{participant1}},
|
|
}
|
|
song2 := model.MediaFile{
|
|
ID: "song-2", Title: "Song Two", Artist: "Artist One", ArtistID: "artist-1",
|
|
Participants: model.Participants{model.RoleArtist: model.ParticipantList{participant1}},
|
|
}
|
|
mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{song1, song2}, nil).Once()
|
|
|
|
songs, err := p.TopSongs(ctx, "Artist One", "", 2)
|
|
|
|
Expect(err).ToNot(HaveOccurred())
|
|
Expect(songs).To(HaveLen(2))
|
|
Expect(songs[0].ID).To(Equal("song-1"))
|
|
Expect(songs[1].ID).To(Equal("song-2"))
|
|
artistRepo.AssertExpectations(GinkgoT())
|
|
ag.AssertExpectations(GinkgoT())
|
|
mediaFileRepo.AssertExpectations(GinkgoT())
|
|
})
|
|
|
|
It("combines MBID and title matching when some songs have missing MbzRecordingID", func() {
|
|
// Mock finding the artist
|
|
artist1 := model.Artist{ID: "artist-1", Name: "Artist One", MbzArtistID: "mbid-artist-1"}
|
|
artistRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.Artists{artist1}, nil).Once()
|
|
// Matcher artist resolution for song2's title-fallback path.
|
|
artistRepo.On("GetAll", mock.Anything).Return(model.Artists{artist1}, nil).Maybe()
|
|
|
|
// Mock agent response with mixed MBID availability
|
|
agentSongs := []agents.Song{
|
|
{Name: "Song One", MBID: "mbid-song-1"}, // Has MBID, should match by MBID
|
|
{Name: "Song Two", MBID: ""}, // No MBID, should fall back to title matching
|
|
}
|
|
ag.On("GetArtistTopSongs", ctx, "artist-1", "Artist One", "mbid-artist-1", 2).Return(agentSongs, nil).Once()
|
|
|
|
// Mock the MBID query (finds song1 by MBID)
|
|
song1 := model.MediaFile{ID: "song-1", Title: "Song One", ArtistID: "artist-1", MbzRecordingID: "mbid-song-1", OrderTitle: "song one"}
|
|
mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{song1}, nil).Once()
|
|
|
|
// Title track-fetch: song2 must carry RoleArtist participants for back-mapping.
|
|
participant1 := model.Participant{Artist: model.Artist{ID: "artist-1", Name: "Artist One", OrderArtistName: "artist one"}}
|
|
song2 := model.MediaFile{
|
|
ID: "song-2", Title: "Song Two", Artist: "Artist One", ArtistID: "artist-1",
|
|
Participants: model.Participants{model.RoleArtist: model.ParticipantList{participant1}},
|
|
}
|
|
mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{song2}, nil).Once()
|
|
|
|
songs, err := p.TopSongs(ctx, "Artist One", "", 2)
|
|
|
|
Expect(err).ToNot(HaveOccurred())
|
|
Expect(songs).To(HaveLen(2))
|
|
Expect(songs[0].ID).To(Equal("song-1")) // Found by MBID
|
|
Expect(songs[1].ID).To(Equal("song-2")) // Found by title
|
|
artistRepo.AssertExpectations(GinkgoT())
|
|
ag.AssertExpectations(GinkgoT())
|
|
mediaFileRepo.AssertExpectations(GinkgoT())
|
|
})
|
|
|
|
It("only returns requested count when provider returns additional items", func() {
|
|
// Mock finding the artist
|
|
artist1 := model.Artist{ID: "artist-1", Name: "Artist One", MbzArtistID: "mbid-artist-1"}
|
|
artistRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.Artists{artist1}, nil).Once()
|
|
|
|
// Mock agent response
|
|
agentSongs := []agents.Song{
|
|
{Name: "Song One", MBID: "mbid-song-1"},
|
|
{Name: "Song Two", MBID: "mbid-song-2"},
|
|
}
|
|
ag.On("GetArtistTopSongs", ctx, "artist-1", "Artist One", "mbid-artist-1", 1).Return(agentSongs, nil).Once()
|
|
|
|
// Mock finding matching tracks (both returned in a single query)
|
|
song1 := model.MediaFile{ID: "song-1", Title: "Song One", ArtistID: "artist-1", MbzRecordingID: "mbid-song-1"}
|
|
song2 := model.MediaFile{ID: "song-2", Title: "Song Two", ArtistID: "artist-1", MbzRecordingID: "mbid-song-2"}
|
|
mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{song1, song2}, nil).Once()
|
|
|
|
songs, err := p.TopSongs(ctx, "Artist One", "", 1)
|
|
|
|
Expect(err).ToNot(HaveOccurred())
|
|
Expect(songs).To(HaveLen(1))
|
|
Expect(songs[0].ID).To(Equal("song-1"))
|
|
artistRepo.AssertExpectations(GinkgoT())
|
|
ag.AssertExpectations(GinkgoT())
|
|
mediaFileRepo.AssertExpectations(GinkgoT())
|
|
})
|
|
|
|
It("matches songs by ID first when agent provides IDs", func() {
|
|
// Mock finding the artist
|
|
artist1 := model.Artist{ID: "artist-1", Name: "Artist One", MbzArtistID: "mbid-artist-1"}
|
|
artistRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.Artists{artist1}, nil).Once()
|
|
|
|
// Mock agent response with IDs provided (highest priority matching)
|
|
// Note: Songs have no MBID to ensure only ID matching is used
|
|
agentSongs := []agents.Song{
|
|
{ID: "song-1", Name: "Song One"},
|
|
{ID: "song-2", Name: "Song Two"},
|
|
}
|
|
ag.On("GetArtistTopSongs", ctx, "artist-1", "Artist One", "mbid-artist-1", 2).Return(agentSongs, nil).Once()
|
|
|
|
// Mock ID lookup (first query - should match both songs directly)
|
|
song1 := model.MediaFile{ID: "song-1", Title: "Song One", ArtistID: "artist-1"}
|
|
song2 := model.MediaFile{ID: "song-2", Title: "Song Two", ArtistID: "artist-1"}
|
|
mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{song1, song2}, nil).Once()
|
|
|
|
songs, err := p.TopSongs(ctx, "Artist One", "", 2)
|
|
|
|
Expect(err).ToNot(HaveOccurred())
|
|
Expect(songs).To(HaveLen(2))
|
|
Expect(songs[0].ID).To(Equal("song-1"))
|
|
Expect(songs[1].ID).To(Equal("song-2"))
|
|
artistRepo.AssertExpectations(GinkgoT())
|
|
ag.AssertExpectations(GinkgoT())
|
|
mediaFileRepo.AssertExpectations(GinkgoT())
|
|
})
|
|
|
|
It("falls back to MBID when ID is not found", func() {
|
|
// Mock finding the artist
|
|
artist1 := model.Artist{ID: "artist-1", Name: "Artist One", MbzArtistID: "mbid-artist-1"}
|
|
artistRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.Artists{artist1}, nil).Once()
|
|
|
|
// Mock agent response with ID that won't be found, but MBID that will
|
|
agentSongs := []agents.Song{
|
|
{ID: "non-existent-id", Name: "Song One", MBID: "mbid-song-1"},
|
|
}
|
|
ag.On("GetArtistTopSongs", ctx, "artist-1", "Artist One", "mbid-artist-1", 1).Return(agentSongs, nil).Once()
|
|
|
|
// Mock ID lookup - returns empty (ID not found)
|
|
mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{}, nil).Once()
|
|
// Mock MBID lookup - finds the song
|
|
song1 := model.MediaFile{ID: "song-1", Title: "Song One", ArtistID: "artist-1", MbzRecordingID: "mbid-song-1"}
|
|
mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{song1}, nil).Once()
|
|
|
|
songs, err := p.TopSongs(ctx, "Artist One", "", 1)
|
|
|
|
Expect(err).ToNot(HaveOccurred())
|
|
Expect(songs).To(HaveLen(1))
|
|
Expect(songs[0].ID).To(Equal("song-1"))
|
|
artistRepo.AssertExpectations(GinkgoT())
|
|
ag.AssertExpectations(GinkgoT())
|
|
mediaFileRepo.AssertExpectations(GinkgoT())
|
|
})
|
|
})
|