diff --git a/core/lyrics/lyrics.go b/core/lyrics/lyrics.go index 46a93314e..65cac877a 100644 --- a/core/lyrics/lyrics.go +++ b/core/lyrics/lyrics.go @@ -3,12 +3,14 @@ package lyrics import ( "context" "strings" + "time" . "github.com/Masterminds/squirrel" "github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/log" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/persistence" + "github.com/navidrome/navidrome/utils/cache" ) // maxLegacyLyricsCandidates bounds the duplicate window scanned by the legacy @@ -16,6 +18,12 @@ import ( // matches without turning it into an unbounded table scan. const maxLegacyLyricsCandidates = 10 +const ( + lyricsCacheSize = 1000 + lyricsCacheTTL = 5 * time.Minute + lyricsLoadTimeout = time.Minute +) + // Provider fetches lyrics for a single media file. It is the contract // implemented by individual lyrics sources, such as plugins. type Provider interface { @@ -37,12 +45,25 @@ type PluginLoader interface { type lyricsService struct { ds model.DataStore pluginLoader PluginLoader + pluginCache cache.SimpleCache[pluginKey, model.LyricList] +} + +type pluginKey struct { + plugin string + mediaFileID string } // NewLyrics creates a new lyrics service. pluginLoader may be nil if no plugin // system is available. func NewLyrics(ds model.DataStore, pluginLoader PluginLoader) Lyrics { - return &lyricsService{ds: ds, pluginLoader: pluginLoader} + return &lyricsService{ + ds: ds, + pluginLoader: pluginLoader, + pluginCache: cache.NewSimpleCache[pluginKey, model.LyricList](cache.Options{ + SizeLimit: lyricsCacheSize, + DefaultTTL: lyricsCacheTTL, + }), + } } // GetLyrics returns lyrics for the given media file, trying sources in the diff --git a/core/lyrics/lyrics_test.go b/core/lyrics/lyrics_test.go index b029d3351..03ba70bda 100644 --- a/core/lyrics/lyrics_test.go +++ b/core/lyrics/lyrics_test.go @@ -365,6 +365,77 @@ var _ = Describe("Lyrics", func() { }) }) + Context("caching", func() { + var mockLoader *mockPluginLoader + var svc lyrics.Lyrics + + BeforeEach(func() { + conf.Update(func(c *conf.Options) { c.LyricsPriority = "test-lyrics-plugin" }) + mockLoader = &mockPluginLoader{} + svc = lyrics.NewLyrics(nil, mockLoader) + mf.ID = "mf-1" + }) + + It("serves a repeated request for the same track from the cache", func() { + mockLoader.lyrics = unsyncedLyrics + _, err := svc.GetLyrics(ctx, &mf) + Expect(err).ToNot(HaveOccurred()) + + list, err := svc.GetLyrics(ctx, &mf) + Expect(err).ToNot(HaveOccurred()) + Expect(list).To(Equal(unsyncedLyrics)) + Expect(mockLoader.calls).To(Equal(1)) + }) + + It("caches a miss, so a track without lyrics does not reach the plugin again", func() { + for range 2 { + list, err := svc.GetLyrics(ctx, &mf) + Expect(err).ToNot(HaveOccurred()) + Expect(list).To(BeEmpty()) + } + Expect(mockLoader.calls).To(Equal(1)) + }) + + It("caches a plugin error as a miss, since some plugins report no lyrics as an error", func() { + mockLoader.err = fmt.Errorf("no lyrics found from any provider") + for range 2 { + list, err := svc.GetLyrics(ctx, &mf) + Expect(err).ToNot(HaveOccurred()) + Expect(list).To(BeEmpty()) + } + Expect(mockLoader.calls).To(Equal(1)) + }) + + It("looks up each track separately", func() { + other := mf + other.ID = "mf-2" + _, _ = svc.GetLyrics(ctx, &mf) + _, _ = svc.GetLyrics(ctx, &other) + Expect(mockLoader.calls).To(Equal(2)) + }) + + It("finishes and caches the lookup when the caller's request is cancelled", func() { + mockLoader.lyrics = unsyncedLyrics + cancelled, cancel := context.WithCancel(ctx) + cancel() + + list, err := svc.GetLyrics(cancelled, &mf) + Expect(err).ToNot(HaveOccurred()) + Expect(list).To(Equal(unsyncedLyrics)) + + list, err = svc.GetLyrics(ctx, &mf) + Expect(err).ToNot(HaveOccurred()) + Expect(list).To(Equal(unsyncedLyrics)) + Expect(mockLoader.calls).To(Equal(1)) + }) + + It("bounds the lookup with a deadline", func() { + _, err := svc.GetLyrics(ctx, &mf) + Expect(err).ToNot(HaveOccurred()) + Expect(mockLoader.hadDeadline).To(BeTrue()) + }) + }) + var _ = Describe("GetLyricsByArtistTitle", func() { var svc lyrics.Lyrics var repo *tests.MockMediaFileRepo @@ -410,10 +481,12 @@ var _ = Describe("Lyrics", func() { }) type mockPluginLoader struct { - lyrics model.LyricList - err error - notFound bool - pluginName string // expected plugin name (exact match, like real manager) + lyrics model.LyricList + err error + notFound bool + pluginName string // expected plugin name (exact match, like real manager) + calls int + hadDeadline bool } func (m *mockPluginLoader) PluginNames(_ string) []string { @@ -431,14 +504,18 @@ func (m *mockPluginLoader) LoadLyricsProvider(name string) (lyrics.Provider, boo if m.pluginName != "" && name != m.pluginName { return nil, false } - return &mockLyricsProvider{lyrics: m.lyrics, err: m.err}, true + return &mockLyricsProvider{loader: m}, true } type mockLyricsProvider struct { - lyrics model.LyricList - err error + loader *mockPluginLoader } -func (m *mockLyricsProvider) GetLyrics(_ context.Context, _ *model.MediaFile) (model.LyricList, error) { - return m.lyrics, m.err +func (m *mockLyricsProvider) GetLyrics(ctx context.Context, _ *model.MediaFile) (model.LyricList, error) { + m.loader.calls++ + _, m.loader.hadDeadline = ctx.Deadline() + if err := ctx.Err(); err != nil { + return nil, err + } + return m.loader.lyrics, m.loader.err } diff --git a/core/lyrics/sources.go b/core/lyrics/sources.go index 23c20122d..864cbb32c 100644 --- a/core/lyrics/sources.go +++ b/core/lyrics/sources.go @@ -7,6 +7,7 @@ import ( "io" "io/fs" "path" + "time" "github.com/navidrome/navidrome/core/storage" "github.com/navidrome/navidrome/log" @@ -68,7 +69,8 @@ func fromExternalFile(ctx context.Context, mf *model.MediaFile, suffix string) ( return list, nil } -// fromPlugin attempts to load lyrics from a plugin with the given name. +// fromPlugin attempts to load lyrics from a plugin with the given name. Results are cached, +// misses included: clients ask for every track in a queue, and plugin lookups are slow. func (l *lyricsService) fromPlugin(ctx context.Context, mf *model.MediaFile, pluginName string) (model.LyricList, error) { if l.pluginLoader == nil { log.Debug(ctx, "Invalid lyric source", "source", pluginName) @@ -81,13 +83,20 @@ func (l *lyricsService) fromPlugin(ctx context.Context, mf *model.MediaFile, plu return nil, nil } - lyricsList, err := provider.GetLyrics(ctx, mf) - if err != nil { - return nil, err - } - - if len(lyricsList) > 0 { - log.Trace(ctx, "Retrieved lyrics from plugin", "plugin", pluginName, "count", len(lyricsList)) - } - return lyricsList, nil + key := pluginKey{plugin: pluginName, mediaFileID: mf.ID} + return l.pluginCache.GetWithLoader(key, func(pluginKey) (model.LyricList, time.Duration, error) { + // Concurrent callers share one load, so one cancelled request must not abort it for the others. + loadCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), lyricsLoadTimeout) + defer cancel() + lyricsList, err := provider.GetLyrics(loadCtx, mf) + if err != nil { + // Cached as a miss: some plugins report "no lyrics" as an error. + log.Error(ctx, "Error getting lyrics from plugin", "plugin", pluginName, err) + return nil, 0, nil + } + if len(lyricsList) > 0 { + log.Trace(ctx, "Retrieved lyrics from plugin", "plugin", pluginName, "count", len(lyricsList)) + } + return lyricsList, 0, nil + }) } diff --git a/server/jellyfin/README.md b/server/jellyfin/README.md index 2df74a419..c0cf2a18e 100644 --- a/server/jellyfin/README.md +++ b/server/jellyfin/README.md @@ -278,10 +278,8 @@ The stream endpoints reuse the same transcode-decision pipeline as the Subsonic word-level `Cues` when present), resolved through the full `core/lyrics` pipeline (embedded, `.lrc` sidecars, plugins per `LyricsPriority`). No lyrics returns `404`, never an empty `200`. -Results, misses included, are cached for 5 minutes: Jellify fetches lyrics for every played track and -Feishin on every song change, so lyric-less tracks are the hot path. Concurrent misses on the same -track share one pipeline run. That run is detached from the request, so a cancelled request doesn't -fail it for other waiters, and its context has a one-minute deadline. +`core/lyrics` caches plugin results, misses included, for 5 minutes: Jellify fetches lyrics for every played +track and Feishin on every song change, so lyric-less tracks are the hot path. Finamp opens its lyrics view only when the track has a `Lyric` `MediaStream` (`HasLyrics` is just a list badge). Browse lists set both from embedded lyrics only. `PlaybackInfo` runs the full pipeline diff --git a/server/jellyfin/api.go b/server/jellyfin/api.go index ed3a735b0..9d28423e0 100644 --- a/server/jellyfin/api.go +++ b/server/jellyfin/api.go @@ -3,7 +3,6 @@ package jellyfin import ( "encoding/json" "net/http" - "time" "github.com/go-chi/chi/v5" "golang.org/x/sync/singleflight" @@ -23,7 +22,6 @@ import ( "github.com/navidrome/navidrome/server" "github.com/navidrome/navidrome/server/events" "github.com/navidrome/navidrome/server/jellyfin/dto" - "github.com/navidrome/navidrome/utils/cache" ) type Router struct { @@ -39,7 +37,6 @@ type Router struct { sonic sonic.Engine lyrics lyrics.Lyrics broker events.Broker - lyricsCache cache.SimpleCache[string, model.LyricList] similarFlight singleflight.Group quickConnect quickconnect.QuickConnect serverIDVal string @@ -53,10 +50,6 @@ func New(ds model.DataStore, artwork artwork.Artwork, streamer stream.MediaStrea ds: ds, artwork: artwork, streamer: streamer, transcodeDecider: transcodeDecider, players: players, scrobbler: scrobbler, playlists: playlists, provider: provider, sonic: sonicSvc, lyrics: lyricsSvc, broker: broker, quickConnect: quickConnect, - lyricsCache: cache.NewSimpleCache[string, model.LyricList](cache.Options{ - SizeLimit: 1000, - DefaultTTL: 5 * time.Minute, - }), } r.Handler = r.routes() return r diff --git a/server/jellyfin/lyrics.go b/server/jellyfin/lyrics.go index a9d77ba19..7299e5143 100644 --- a/server/jellyfin/lyrics.go +++ b/server/jellyfin/lyrics.go @@ -3,27 +3,15 @@ package jellyfin import ( "context" "net/http" - "time" "github.com/navidrome/navidrome/log" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/server/jellyfin/dto" ) -const lyricsLoadTimeout = time.Minute - -// cachedLyrics resolves lyrics through the full source pipeline (embedded, sidecar, plugins), -// caching results — including empty: clients poll per played track, so misses are the hot path. -func (api *Router) cachedLyrics(ctx context.Context, mf *model.MediaFile) model.LyricList { - // The load is shared across requests (singleflight) and cached, so don't let one - // cancelled request abort it for everybody — detach it from the request's lifetime, - // keeping a bound so a hung plugin can't pin the fetch (and its plugin slot) forever. - loadCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), lyricsLoadTimeout) - defer cancel() - list, err := api.lyricsCache.GetWithLoader(mf.ID, func(string) (model.LyricList, time.Duration, error) { - l, err := api.lyrics.GetLyrics(loadCtx, mf) - return l, 0, err // 0 → cache DefaultTTL - }) +// lyricsFor resolves lyrics through the full source pipeline (embedded, sidecar, plugins). +func (api *Router) lyricsFor(ctx context.Context, mf *model.MediaFile) model.LyricList { + list, err := api.lyrics.GetLyrics(ctx, mf) if err != nil { log.Error(ctx, "Error getting lyrics", "id", mf.ID, "title", mf.Title, err) return nil @@ -38,7 +26,7 @@ func (api *Router) getLyrics(w http.ResponseWriter, r *http.Request) { if !ok { return } - main, found := servableLyric(api.cachedLyrics(r.Context(), mf)) + main, found := servableLyric(api.lyricsFor(r.Context(), mf)) if !found { http.Error(w, "Not Found", http.StatusNotFound) return diff --git a/server/jellyfin/lyrics_test.go b/server/jellyfin/lyrics_test.go index fb00563de..1a0ee41ce 100644 --- a/server/jellyfin/lyrics_test.go +++ b/server/jellyfin/lyrics_test.go @@ -10,25 +10,17 @@ import ( "github.com/navidrome/navidrome/model/request" "github.com/navidrome/navidrome/server/jellyfin/dto" "github.com/navidrome/navidrome/tests" - "github.com/navidrome/navidrome/utils/cache" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) -// fakeLyricsService returns canned lyrics per media-file ID and counts calls. +// fakeLyricsService returns canned lyrics per media-file ID. type fakeLyricsService struct { - lyrics map[string]model.LyricList - err error - calls int - hadDeadline bool + lyrics map[string]model.LyricList + err error } -func (f *fakeLyricsService) GetLyrics(ctx context.Context, mf *model.MediaFile) (model.LyricList, error) { - f.calls++ - _, f.hadDeadline = ctx.Deadline() - if err := ctx.Err(); err != nil { - return nil, err - } +func (f *fakeLyricsService) GetLyrics(_ context.Context, mf *model.MediaFile) (model.LyricList, error) { if f.err != nil { return nil, f.err } @@ -41,10 +33,6 @@ func (f *fakeLyricsService) GetLyricsByArtistTitle(context.Context, string, stri func p(ms int64) *int64 { return &ms } -func newTestLyricsCache() cache.SimpleCache[string, model.LyricList] { - return cache.NewSimpleCache[string, model.LyricList](cache.Options{SizeLimit: 1000}) -} - var _ = Describe("getLyrics", func() { var api *Router var ds *tests.MockDataStore @@ -58,9 +46,8 @@ var _ = Describe("getLyrics", func() { }) fake = &fakeLyricsService{lyrics: map[string]model.LyricList{}} api = &Router{ - ds: ds, - lyrics: fake, - lyricsCache: newTestLyricsCache(), + ds: ds, + lyrics: fake, } }) @@ -119,37 +106,4 @@ var _ = Describe("getLyrics", func() { w := doRequest("unknown") Expect(w.Code).To(Equal(http.StatusNotFound)) }) - - It("caches results so a second request doesn't re-invoke the service", func() { - fake.lyrics[testID("s1")] = model.LyricList{ - {Kind: "main", Synced: true, Line: []model.Line{{Start: p(1000), Value: "hello"}}}, - } - Expect(doRequest(testID("s1")).Code).To(Equal(http.StatusOK)) - Expect(doRequest(testID("s1")).Code).To(Equal(http.StatusOK)) - Expect(fake.calls).To(Equal(1)) - }) - - It("caches empty results too", func() { - Expect(doRequest(testID("s2")).Code).To(Equal(http.StatusNotFound)) - Expect(doRequest(testID("s2")).Code).To(Equal(http.StatusNotFound)) - Expect(fake.calls).To(Equal(1)) - }) - - It("completes and caches the fetch even when the request context is cancelled", func() { - fake.lyrics[testID("s1")] = model.LyricList{ - {Kind: "main", Synced: true, Line: []model.Line{{Start: p(1000), Value: "hello"}}}, - } - ctx, cancel := context.WithCancel(context.Background()) - cancel() - - list := api.cachedLyrics(ctx, &model.MediaFile{ID: testID("s1")}) - Expect(list).ToNot(BeEmpty()) - Expect(doRequest(testID("s1")).Code).To(Equal(http.StatusOK)) - Expect(fake.calls).To(Equal(1)) - }) - - It("bounds the detached fetch with a timeout", func() { - Expect(doRequest(testID("s2")).Code).To(Equal(http.StatusNotFound)) - Expect(fake.hadDeadline).To(BeTrue()) - }) }) diff --git a/server/jellyfin/stream.go b/server/jellyfin/stream.go index 6ca2e11b2..9a627ee5e 100644 --- a/server/jellyfin/stream.go +++ b/server/jellyfin/stream.go @@ -53,7 +53,7 @@ func (api *Router) getPlaybackInfo(w http.ResponseWriter, r *http.Request) { // The mapper only sees embedded lyrics; per-track we can afford the full pipeline // (sidecars, plugins) so Finamp's Lyric-stream gate reflects every source. if !slices.ContainsFunc(src.MediaStreams, func(s dto.MediaStream) bool { return s.Type == "Lyric" }) { - if _, found := servableLyric(api.cachedLyrics(r.Context(), mf)); found { + if _, found := servableLyric(api.lyricsFor(r.Context(), mf)); found { src.MediaStreams = append(src.MediaStreams, dto.MediaStream{ Type: "Lyric", Index: len(src.MediaStreams), IsExternal: true, }) diff --git a/server/jellyfin/stream_test.go b/server/jellyfin/stream_test.go index 08357d14d..dc670376d 100644 --- a/server/jellyfin/stream_test.go +++ b/server/jellyfin/stream_test.go @@ -35,8 +35,7 @@ var _ = Describe("Stream", func() { decider = &fakeTranscodeDecider{} api = &Router{ ds: ds, streamer: streamer, transcodeDecider: decider, - lyrics: &fakeLyricsService{lyrics: map[string]model.LyricList{}}, - lyricsCache: newTestLyricsCache(), + lyrics: &fakeLyricsService{lyrics: map[string]model.LyricList{}}, } })