navidrome/utils/cache/simple_cache.go
Deluan Quintão 94eb6c522b
Some checks are pending
Pipeline: Test, Lint, Build / Get version info (push) Waiting to run
Pipeline: Test, Lint, Build / Lint Go code (push) Waiting to run
Pipeline: Test, Lint, Build / Test Go code (push) Waiting to run
Pipeline: Test, Lint, Build / Test Go code (Windows) (push) Waiting to run
Pipeline: Test, Lint, Build / Test JS code (push) Waiting to run
Pipeline: Test, Lint, Build / Lint i18n files (push) Waiting to run
Pipeline: Test, Lint, Build / Check Docker configuration (push) Waiting to run
Pipeline: Test, Lint, Build / Build (push) Blocked by required conditions
Pipeline: Test, Lint, Build / Build-1 (push) Blocked by required conditions
Pipeline: Test, Lint, Build / Package/Release (push) Blocked by required conditions
Pipeline: Test, Lint, Build / Build-2 (push) Blocked by required conditions
Pipeline: Test, Lint, Build / Build-3 (push) Blocked by required conditions
Pipeline: Test, Lint, Build / Build-4 (push) Blocked by required conditions
Pipeline: Test, Lint, Build / Build-5 (push) Blocked by required conditions
Pipeline: Test, Lint, Build / Upload Linux PKG (push) Blocked by required conditions
Pipeline: Test, Lint, Build / Build-6 (push) Blocked by required conditions
Pipeline: Test, Lint, Build / Build-7 (push) Blocked by required conditions
Pipeline: Test, Lint, Build / Build-8 (push) Blocked by required conditions
Pipeline: Test, Lint, Build / Build-9 (push) Blocked by required conditions
Pipeline: Test, Lint, Build / Build-10 (push) Blocked by required conditions
Pipeline: Test, Lint, Build / Push to GHCR (push) Blocked by required conditions
Pipeline: Test, Lint, Build / Push to Docker Hub (push) Blocked by required conditions
Pipeline: Test, Lint, Build / Cleanup digest artifacts (push) Blocked by required conditions
Pipeline: Test, Lint, Build / Build Windows installers (push) Blocked by required conditions
feat(subsonic): implement playbackReport OpenSubsonic extension (#5442)
* feat(req): add Float64Or helper for parsing float query params

* feat(scrobbler): extend NowPlayingInfo with state/position/rate fields

* feat(scrobbler): implement ReportPlayback with state machine and auto-scrobble

* feat(responses): add state/positionMs/playbackRate to NowPlayingEntry

* feat(subsonic): add reportPlayback endpoint handler

* feat(subsonic): include state/positionMs/playbackRate in getNowPlaying response

* feat(subsonic): register playbackReport OpenSubsonic extension

* test(e2e): add reportPlayback endpoint e2e tests

* refactor(scrobbler): simplify ReportPlayback — extract helpers, remove duplication

- Add state constants and exported ValidStates map
- Extract remainingTTL() helper (was duplicated 3x)
- Merge playing/paused switch cases into single branch
- Use Get instead of GetWithParticipants for non-stopped states
- Guard NowPlayingCount broadcast with count-change detection
- Use cache entry for NowPlaying dispatch instead of extra DB query
- Remove redundant Position field from NowPlayingInfo

* refactor(scrobbler): skip DB query in playing/paused when playMap has entry

* fix(play_tracker): handle errors when adding/updating NowPlayingInfo in cache

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(play_tracker): replace sort with slices.SortFunc for NowPlayingInfo

Signed-off-by: Deluan <deluan@navidrome.org>

* fix(play_tracker): check all ReportPlayback errors in tests

Replace _ = with explicit error assertions to avoid masking
failures in intermediate calls.

Signed-off-by: Deluan <deluan@navidrome.org>

* test(e2e): use real PlayTracker and assert getNowPlaying after reportPlayback

Replace noopPlayTracker with a real PlayTracker backed by the E2E
database. E2E tests now verify the full round-trip: reportPlayback
creates/updates/removes entries visible via getNowPlaying, including
state, positionMs, and playbackRate fields.

Export NewPlayTracker constructor for use outside the scrobbler package.

* fix(play_tracker): account for playback rate in TTL and detect track switches

The remainingTTL function now divides remaining time by the playback rate,
so cache entries expire correctly at non-1x speeds (e.g., 2x playback halves
the TTL). Zero/negative rates default to 1.0. The playing/paused case now
checks if the cached MediaFile ID matches the reported mediaId, falling back
to a DB fetch when the client switches tracks without sending stopped/starting.
Adds parameterized tests for remainingTTL covering rate variations and edge cases.

* fix(subsonic): validate positionMs and playbackRate in reportPlayback

Reject negative positionMs values and invalid playbackRate values (NaN,
Inf, zero, negative) at the API boundary before they reach TTL and
position estimation math. Returns clear error messages for each case.

* feat(play_tracker): add ClientId and ClientName to ReportPlayback parameters

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(play_tracker): replace NowPlaying method with ReportPlayback calls

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(play_tracker_test): remove redundant TTL behavior tests and clean up mockPluginLoader

Signed-off-by: Deluan <deluan@navidrome.org>

---------

Signed-off-by: Deluan <deluan@navidrome.org>
2026-04-30 23:04:05 -04:00

158 lines
3.6 KiB
Go

package cache
import (
"context"
"errors"
"fmt"
"runtime"
"sync/atomic"
"time"
"github.com/jellydator/ttlcache/v3"
. "github.com/navidrome/navidrome/utils/gg"
)
type SimpleCache[K comparable, V any] interface {
Add(key K, value V) error
AddWithTTL(key K, value V, ttl time.Duration) error
Get(key K) (V, error)
GetWithLoader(key K, loader func(key K) (V, time.Duration, error)) (V, error)
Remove(key K)
Keys() []K
Values() []V
Len() int
OnExpiration(fn func(K, V)) func()
}
type Options struct {
SizeLimit uint64
DefaultTTL time.Duration
}
func NewSimpleCache[K comparable, V any](options ...Options) SimpleCache[K, V] {
opts := []ttlcache.Option[K, V]{
ttlcache.WithDisableTouchOnHit[K, V](),
}
if len(options) > 0 {
o := options[0]
if o.SizeLimit > 0 {
opts = append(opts, ttlcache.WithCapacity[K, V](o.SizeLimit))
}
if o.DefaultTTL > 0 {
opts = append(opts, ttlcache.WithTTL[K, V](o.DefaultTTL))
}
}
c := ttlcache.New[K, V](opts...)
cache := &simpleCache[K, V]{
data: c,
}
go cache.data.Start()
// Automatic cleanup to prevent goroutine leak when cache is garbage collected
runtime.AddCleanup(cache, func(ttlCache *ttlcache.Cache[K, V]) {
ttlCache.Stop()
}, cache.data)
return cache
}
const evictionTimeout = 1 * time.Hour
type simpleCache[K comparable, V any] struct {
data *ttlcache.Cache[K, V]
evictionDeadline atomic.Pointer[time.Time]
}
func (c *simpleCache[K, V]) Add(key K, value V) error {
c.evictExpired()
return c.AddWithTTL(key, value, ttlcache.DefaultTTL)
}
func (c *simpleCache[K, V]) AddWithTTL(key K, value V, ttl time.Duration) error {
c.evictExpired()
item := c.data.Set(key, value, ttl)
if item == nil {
return errors.New("failed to add item")
}
return nil
}
func (c *simpleCache[K, V]) Remove(key K) {
c.data.Delete(key)
}
func (c *simpleCache[K, V]) Get(key K) (V, error) {
item := c.data.Get(key)
if item == nil {
var zero V
return zero, errors.New("item not found")
}
return item.Value(), nil
}
func (c *simpleCache[K, V]) GetWithLoader(key K, loader func(key K) (V, time.Duration, error)) (V, error) {
var err error
loaderWrapper := ttlcache.LoaderFunc[K, V](
func(t *ttlcache.Cache[K, V], key K) *ttlcache.Item[K, V] {
c.evictExpired()
var value V
var ttl time.Duration
value, ttl, err = loader(key)
if err != nil {
return nil
}
return t.Set(key, value, ttl)
},
)
item := c.data.Get(key, ttlcache.WithLoader[K, V](loaderWrapper))
if item == nil {
var zero V
if err != nil {
return zero, fmt.Errorf("cache error: loader returned %w", err)
}
return zero, errors.New("item not found")
}
return item.Value(), nil
}
func (c *simpleCache[K, V]) evictExpired() {
if c.evictionDeadline.Load() == nil || c.evictionDeadline.Load().Before(time.Now()) {
c.data.DeleteExpired()
c.evictionDeadline.Store(P(time.Now().Add(evictionTimeout)))
}
}
func (c *simpleCache[K, V]) Keys() []K {
res := make([]K, 0, c.data.Len())
c.data.Range(func(item *ttlcache.Item[K, V]) bool {
if !item.IsExpired() {
res = append(res, item.Key())
}
return true
})
return res
}
func (c *simpleCache[K, V]) Values() []V {
res := make([]V, 0, c.data.Len())
c.data.Range(func(item *ttlcache.Item[K, V]) bool {
if !item.IsExpired() {
res = append(res, item.Value())
}
return true
})
return res
}
func (c *simpleCache[K, V]) Len() int {
return c.data.Len()
}
func (c *simpleCache[K, V]) OnExpiration(fn func(K, V)) func() {
return c.data.OnEviction(func(_ context.Context, reason ttlcache.EvictionReason, item *ttlcache.Item[K, V]) {
if reason == ttlcache.EvictionReasonExpired {
fn(item.Key(), item.Value())
}
})
}