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.
349 lines
12 KiB
Go
349 lines
12 KiB
Go
package artwork
|
||
|
||
import (
|
||
"bytes"
|
||
"cmp"
|
||
"context"
|
||
"io"
|
||
"math"
|
||
"math/rand/v2"
|
||
"sync"
|
||
"time"
|
||
|
||
"github.com/navidrome/navidrome/conf"
|
||
"github.com/navidrome/navidrome/core/agents"
|
||
"github.com/navidrome/navidrome/core/auth"
|
||
"github.com/navidrome/navidrome/core/ffmpeg"
|
||
"github.com/navidrome/navidrome/log"
|
||
"github.com/navidrome/navidrome/model"
|
||
"github.com/navidrome/navidrome/server/events"
|
||
"github.com/navidrome/navidrome/utils/cache"
|
||
)
|
||
|
||
const (
|
||
workerPollInterval = 5 * time.Second
|
||
backoffBase = 5 * time.Second
|
||
// giveUpAfter bounds the retry budget from enqueue; past it the item falls to the
|
||
// periodic stale-absent recheck.
|
||
giveUpAfter = 12 * time.Hour
|
||
)
|
||
|
||
// drainPool drains one class of work with its own slot budget, so a blocking kind cannot
|
||
// occupy slots another kind needs.
|
||
type drainPool struct {
|
||
name string
|
||
kinds []string
|
||
concurrency int
|
||
}
|
||
|
||
// Worker drains the artwork queue: each external agent is rate-limited and circuit-broken
|
||
// independently, and pruneMu serializes prune against the store-write window.
|
||
type Worker struct {
|
||
proc *processor
|
||
agents *agents.Agents
|
||
cache cache.FileCache
|
||
ffmpeg ffmpeg.FFmpeg
|
||
broker events.Broker
|
||
pruneMu sync.RWMutex
|
||
pools []*drainPool
|
||
runCtx context.Context
|
||
|
||
gatesMu sync.Mutex
|
||
gates map[string]*extGate
|
||
}
|
||
|
||
func NewWorker(ds model.DataStore, store *ImageStore, ag *agents.Agents, ffmpeg ffmpeg.FFmpeg, broker events.Broker, imgCache cache.FileCache) *Worker {
|
||
w := &Worker{
|
||
proc: &processor{ds: ds, store: store},
|
||
agents: ag,
|
||
cache: imgCache,
|
||
ffmpeg: ffmpeg,
|
||
broker: broker,
|
||
pools: newDrainPools(),
|
||
runCtx: context.Background(),
|
||
gates: map[string]*extGate{},
|
||
}
|
||
w.proc.resolver = newResolver(ds, ag, ffmpeg, w.gate)
|
||
w.proc.pruneLock = w.pruneMu.RLocker()
|
||
return w
|
||
}
|
||
|
||
// newDrainPools splits the drain by what bounds it: gate() holds a slot while waiting for its
|
||
// rate-limit permit, so a sleeping lookup would crowd out a cover sitting on disk.
|
||
func newDrainPools() []*drainPool {
|
||
budget := conf.MaxOpenConns() // floored at 4, so both remainders below stay positive
|
||
local := min(max(1, conf.Server.DevArtworkWorkerConcurrency), budget-1)
|
||
// More external slots than the rate allows would only sleep in the limiter.
|
||
external := min(max(2, 2*conf.Server.DevArtworkExternalMaxRPS), budget-local)
|
||
return []*drainPool{
|
||
{name: "local", kinds: localDrainKinds, concurrency: local},
|
||
{name: "external", kinds: externalDrainKinds, concurrency: external},
|
||
}
|
||
}
|
||
|
||
// Kind is a proxy for cost: an album that reaches an external agent still costs a local slot.
|
||
var (
|
||
externalDrainKinds = []string{model.KindArtistArtwork.Prefix()}
|
||
localDrainKinds = []string{
|
||
model.KindAlbumArtwork.Prefix(),
|
||
model.KindPlaylistArtwork.Prefix(),
|
||
model.KindRadioArtwork.Prefix(),
|
||
model.KindMediaFileArtwork.Prefix(),
|
||
}
|
||
)
|
||
|
||
// Run blocks draining the queue until ctx is cancelled.
|
||
func (w *Worker) Run(ctx context.Context) error {
|
||
w.runCtx = ctx
|
||
var wg sync.WaitGroup
|
||
for _, p := range w.pools {
|
||
wg.Go(func() { w.runPool(ctx, p) })
|
||
}
|
||
wg.Wait()
|
||
return nil
|
||
}
|
||
|
||
func (w *Worker) runPool(ctx context.Context, p *drainPool) {
|
||
ticker := time.NewTicker(workerPollInterval)
|
||
defer ticker.Stop()
|
||
for {
|
||
n, err := w.drain(ctx, p.concurrency, p.kinds...)
|
||
if err != nil && ctx.Err() == nil {
|
||
log.Warn(ctx, "Artwork: Worker drain failed", "pool", p.name, err)
|
||
}
|
||
if ctx.Err() != nil {
|
||
return
|
||
}
|
||
if n > 0 {
|
||
continue
|
||
}
|
||
select {
|
||
case <-ctx.Done():
|
||
return
|
||
case <-ticker.C:
|
||
}
|
||
}
|
||
}
|
||
|
||
// RunPrune runs prune under the worker's write lock, so no acquisition can place
|
||
// a file while orphans are being reclaimed. This is the only sanctioned prune path.
|
||
func (w *Worker) RunPrune(ctx context.Context) error {
|
||
w.pruneMu.Lock()
|
||
defer w.pruneMu.Unlock()
|
||
return prune(ctx, w.proc.ds, w.proc.store)
|
||
}
|
||
|
||
// Backfill enqueues every entity for re-resolution when the artwork config fingerprint changed,
|
||
// artists first. It reports whether the backfill ran.
|
||
func (w *Worker) Backfill(ctx context.Context) (bool, error) {
|
||
s, err := backfill(ctx, w.proc.ds, func() ImageAgentCount { return NewImageAgentCount(w.agents) })
|
||
return s.Ran, err
|
||
}
|
||
|
||
// EnqueueStaleAbsentAll requeues known-absent entries older than StaleAbsentAge, at most
|
||
// StaleAbsentRecheckBatch per kind, oldest first.
|
||
func (w *Worker) EnqueueStaleAbsentAll(ctx context.Context) error {
|
||
return enqueueStaleAbsentAll(ctx, w.proc.ds)
|
||
}
|
||
|
||
// EnqueueMissingAll requeues entities with no artwork state row: the safety net for anything
|
||
// a scan never enqueued.
|
||
func (w *Worker) EnqueueMissingAll(ctx context.Context) error {
|
||
return enqueueMissingAll(ctx, w.proc.ds)
|
||
}
|
||
|
||
func (w *Worker) drain(ctx context.Context, concurrency int, kinds ...string) (int, error) {
|
||
// Dequeue well past the pool size so a slow external lookup never idles the other slots.
|
||
// DequeueBatch does not mark rows taken, so this is one query per pass, not per slot.
|
||
items, err := w.proc.ds.ArtworkQueue(ctx).DequeueBatch(max(16, 4*concurrency), kinds...)
|
||
if err != nil {
|
||
return 0, err
|
||
}
|
||
if len(items) == 0 {
|
||
return 0, nil
|
||
}
|
||
drainStart := time.Now()
|
||
// Private playlists need an admin identity; resolved per drain because the worker can
|
||
// start before any admin exists.
|
||
ctx = auth.WithAdminUser(ctx, w.proc.ds)
|
||
sem := make(chan struct{}, concurrency)
|
||
var wg sync.WaitGroup
|
||
var refreshMu sync.Mutex
|
||
var refresh []model.ArtworkQueueItem
|
||
for _, item := range items {
|
||
select {
|
||
case sem <- struct{}{}:
|
||
case <-ctx.Done():
|
||
}
|
||
// select picks randomly when both cases are ready, so re-check to never dispatch after cancellation.
|
||
if ctx.Err() != nil {
|
||
wg.Wait()
|
||
return len(items), nil //nolint:nilerr // a cancelled drain is a clean stop, not an error
|
||
}
|
||
wg.Go(func() {
|
||
defer func() { <-sem }()
|
||
out, got := w.process(ctx, item)
|
||
// Absent counts as a visible change too: clients must drop a previously-served
|
||
// immutable cover.
|
||
if out == outcomeFound || out == outcomeFoundStale || out == outcomeAbsent {
|
||
refreshMu.Lock()
|
||
refresh = append(refresh, item)
|
||
refreshMu.Unlock()
|
||
}
|
||
// Post-outcome: the queue row is already settled, so warming the cache can't
|
||
// block or alter queue ops.
|
||
if got != nil {
|
||
w.precache(ctx, got)
|
||
}
|
||
})
|
||
}
|
||
wg.Wait()
|
||
w.broadcastRefresh(ctx, refresh)
|
||
log.Debug(ctx, "Artwork: Drained a batch", "kinds", kinds, "items", len(items),
|
||
"refreshed", len(refresh), "concurrency", concurrency, "elapsed", time.Since(drainStart))
|
||
return len(items), nil
|
||
}
|
||
|
||
// artworkKindToResource maps a kind to its UI resource name; media_file maps to "song", so
|
||
// this can't derive from Kind.String().
|
||
var artworkKindToResource = map[model.Kind]string{
|
||
model.KindAlbumArtwork: "album",
|
||
model.KindArtistArtwork: "artist",
|
||
model.KindPlaylistArtwork: "playlist",
|
||
model.KindRadioArtwork: "radio",
|
||
model.KindMediaFileArtwork: "song",
|
||
}
|
||
|
||
// broadcastRefresh emits one coalesced RefreshResource for the batch, so UIs re-fetch the
|
||
// affected records and pick up the new coverArt id.
|
||
func (w *Worker) broadcastRefresh(ctx context.Context, found []model.ArtworkQueueItem) {
|
||
if len(found) == 0 {
|
||
return
|
||
}
|
||
event := &events.RefreshResource{}
|
||
byResource := map[string][]string{}
|
||
for _, it := range found {
|
||
kind, _ := model.ParseKind(it.ItemKind)
|
||
if res, ok := artworkKindToResource[kind]; ok {
|
||
byResource[res] = append(byResource[res], it.ItemID)
|
||
}
|
||
}
|
||
if len(byResource) == 0 {
|
||
return
|
||
}
|
||
for res, ids := range byResource {
|
||
event = event.With(res, ids...)
|
||
}
|
||
w.broker.SendBroadcastMessage(ctx, event)
|
||
}
|
||
|
||
func (w *Worker) process(ctx context.Context, item model.ArtworkQueueItem) (outcome, *acquired) {
|
||
item.ImageType = cmp.Or(item.ImageType, model.ImageTypePrimary)
|
||
trace := &ChainTrace{}
|
||
ctx = withTrace(ctx, trace)
|
||
out, got, retryIn := w.proc.acquire(ctx, item)
|
||
|
||
queue := w.proc.ds.ArtworkQueue(ctx)
|
||
switch out {
|
||
case outcomeFound, outcomeAbsent:
|
||
// A scan that re-enqueued this row mid-flight reset its retry_at, so the row survives
|
||
// here and the next drain re-resolves it.
|
||
if err := queue.DeleteIfUnchanged(item.ItemKind, item.ItemID, item.ImageType, item.RetryAt); err != nil {
|
||
log.Warn(ctx, "Artwork: Could not delete processed queue item", "kind", item.ItemKind, "id", item.ItemID, err)
|
||
}
|
||
case outcomeFoundStale, outcomeFailed:
|
||
retryAt := time.Now().Add(retryDelay(item.Attempts, retryIn))
|
||
encoded := trace.encode("")
|
||
if retryAt.Before(item.EnqueuedAt.Add(giveUpAfter)) {
|
||
// A mid-flight re-enqueue reset retry_at; stale backoff must not stomp its
|
||
// fresh, immediate eligibility.
|
||
if err := queue.MarkFailedIfUnchanged(item.ItemKind, item.ItemID, item.ImageType, item.RetryAt, retryAt, encoded); err != nil {
|
||
log.Warn(ctx, "Artwork: Could not reschedule failed queue item", "kind", item.ItemKind, "id", item.ItemID, err)
|
||
}
|
||
log.Debug(ctx, "Artwork: Rescheduled item", "kind", item.ItemKind, "id", item.ItemID,
|
||
"outcome", out, "attempts", item.Attempts+1, "retryIn", time.Until(retryAt),
|
||
"budgetLeft", time.Until(item.EnqueuedAt.Add(giveUpAfter)))
|
||
break
|
||
}
|
||
// Absent is only recoverable where a periodic recheck revisits it, so other kinds keep
|
||
// no row; art already being served is kept, as exhaustion means unreachable, not removed.
|
||
settled := "kept previous state"
|
||
if out == outcomeFailed && hasRecheckPath(item.ItemKind) && !w.hasResolvedArtwork(ctx, item) {
|
||
writeAbsent(ctx, w.proc.ds.Artwork(ctx), item)
|
||
settled = "recorded absent"
|
||
}
|
||
// The queue row is about to go, taking the only record of the failure with it. This write is
|
||
// unconditional (not CAS-guarded) — safe only because the drain resolves each item serially.
|
||
w.recordGiveUp(ctx, item, encoded)
|
||
log.Info(ctx, "Artwork: Retry budget exhausted, giving up", "kind", item.ItemKind, "id", item.ItemID,
|
||
"outcome", out, "attempts", item.Attempts+1, "budget", giveUpAfter, "settled", settled)
|
||
if err := queue.DeleteIfUnchanged(item.ItemKind, item.ItemID, item.ImageType, item.RetryAt); err != nil {
|
||
log.Warn(ctx, "Artwork: Could not remove exhausted queue item", "kind", item.ItemKind, "id", item.ItemID, err)
|
||
}
|
||
}
|
||
return out, got
|
||
}
|
||
|
||
// recordGiveUp keeps the last failure on the state row after the queue row is deleted. An item
|
||
// that never resolved has no row to update, and creating one would settle it absent.
|
||
func (w *Worker) recordGiveUp(ctx context.Context, item model.ArtworkQueueItem, trace string) {
|
||
kind, ok := model.ParseKind(item.ItemKind)
|
||
if !ok {
|
||
return
|
||
}
|
||
if err := w.proc.ds.Artwork(ctx).PutLastFailure(kind, item.ItemID, item.ImageType, trace); err != nil {
|
||
log.Warn(ctx, "Artwork: Could not record the last failure", "kind", item.ItemKind, "id", item.ItemID, err)
|
||
}
|
||
}
|
||
|
||
func (w *Worker) hasResolvedArtwork(ctx context.Context, item model.ArtworkQueueItem) bool {
|
||
kind, ok := model.ParseKind(item.ItemKind)
|
||
if !ok {
|
||
return false
|
||
}
|
||
ia, err := w.proc.ds.Artwork(ctx).GetItemArtwork(kind, item.ItemID, item.ImageType)
|
||
return err == nil && ia.Hash != ""
|
||
}
|
||
|
||
// precache warms the resize cache at the UI cover size from the bytes just acquired, so the
|
||
// first UI request hits without re-reading the rows or the file.
|
||
func (w *Worker) precache(ctx context.Context, got *acquired) {
|
||
if !conf.Server.EnableArtworkPrecache || w.cache == nil || w.cache.Disabled(ctx) {
|
||
return
|
||
}
|
||
precacheStart := time.Now()
|
||
// Same key as the serving path: square must match what the list surfaces request, or this
|
||
// warms a key nothing reads.
|
||
item := &resizedItem{
|
||
hash: got.ia.Hash,
|
||
size: conf.Server.UICoverArtSize,
|
||
square: true,
|
||
ffmpeg: w.ffmpeg,
|
||
open: func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(got.data)), nil },
|
||
}
|
||
stream, err := w.cache.Get(ctx, item)
|
||
if err != nil {
|
||
log.Debug(ctx, "Artwork: Precache failed", "kind", got.ia.ItemKind, "id", got.ia.ItemID, err)
|
||
return
|
||
}
|
||
_, _ = io.Copy(io.Discard, stream)
|
||
_ = stream.Close()
|
||
log.Trace(ctx, "Artwork: Precached UI size", "kind", got.ia.ItemKind, "id", got.ia.ItemID,
|
||
"size", conf.Server.UICoverArtSize, "elapsed", time.Since(precacheStart))
|
||
}
|
||
|
||
// backoffFor returns min(5s×4^n, giveUpAfter) scaled by (1+jitter), with jitter in [-0.4, 0.4].
|
||
func backoffFor(attempts int, jitter float64) time.Duration {
|
||
d := min(float64(backoffBase)*math.Pow(4, float64(attempts)), float64(giveUpAfter))
|
||
return time.Duration(d * (1 + jitter))
|
||
}
|
||
|
||
func backoff(attempts int) time.Duration {
|
||
return backoffFor(attempts, rand.Float64()*0.8-0.4) //nolint:gosec // retry jitter, not security-sensitive
|
||
}
|
||
|
||
// retryDelay is how long a failed item waits: our backoff, unless the provider asked for longer.
|
||
func retryDelay(attempts int, hint time.Duration) time.Duration {
|
||
return max(backoff(attempts), hint)
|
||
}
|