navidrome/model/artwork_id.go
Deluan Quintão ffc68e29db
feat(cli): add artwork cancel to call off queued artwork work (#6006)
* feat(cli): add `artwork cancel` to call off queued artwork work

A bulk backfill had no off switch. Changing an artwork setting bumps the config
fingerprint, which enqueues every entity in the library, and the only way to stop
it was to turn agents off -- which changes the fingerprint again and enqueues a
second full backfill. The escape hatch was the trap.

`artwork cancel` deletes pending queue rows selected by --kind and/or --priority,
with the --dry-run/confirm/-y flow `reprocess` already uses. Cancelling by
priority is the point: it drops a runaway backfill while leaving the bump-priority
rows an operator queued by hand.

It only touches the queue. Resolved artwork and the item_artwork state behind
`artwork explain` are left alone, and the trace of why a cancelled item last
failed goes with its row. Preserving that trace would mean writing it to
last_failure, which `explain` prints under "Gave up after" -- reporting a
cancellation as an exhausted retry budget. The help text says the trace is
discarded instead.

Two limits the help text states, because neither is guessable: work already
dequeued is not interrupted, and an item with no artwork state yet can be queued
again by the hourly missing-artwork recheck. Cancel calls off queued work; it
does not stop the worker.

--kind validates against RefreshableKinds, not the RecheckKinds `reprocess` uses:
the queue holds media file rows, so --all has to reach them. PurgeQueued follows
the repository's naming rule -- it finds its own rows and reports how many went --
and ignores retry_at, since a row still backing off is pending work. The preview
reuses CountByKindAndPriority rather than adding a counter. reprocessConfirm
became confirmUnlessYes(yes, in, verb) now that two commands prompt.

* refactor(cli): share the artwork queue filter between the preview and the delete

Follow-up cleanup on the previous commit; no change to what the command does,
apart from --all, noted below.

The "which rows does cancel touch" predicate was written three times: once as SQL
in PurgeQueued, once in Go in cmd's matchingQueueStats, and once more in the mock.
The preview and the delete could therefore drift, and the mock would keep the
tests green while they did. persistence now has one artworkQueueFilter, shared by
PurgeQueued and a new CountQueued, and cmd does no filtering at all.

That also makes the preview cheaper. It counted the whole queue and filtered in
Go, so `artwork cancel --kind al` scanned every row of every kind to print a
handful. CountQueued pushes the filter into SQL, which the drain index serves as a
range seek. CountByKindAndPriority is gone: it is CountQueued(nil, nil).

--all now selects with an empty filter instead of enumerating RefreshableKinds.
It is what the flag help already claimed, and the enumeration was narrower than
its own documentation -- a queue row whose item_kind this build does not know
survived `--all` with no flag combination able to remove it. It also restores
SQLite's truncate path: measured with EXPLAIN QUERY PLAN, a bare DELETE plans to
nothing, while `WHERE (1=1)` -- which an empty squirrel And renders -- plans to a
full index scan. A test pins the filter's emptiness so that cannot regress
silently.

Also folded together three copies of the parse-and-dedup loop (parseAll), two
copies of the queue-stats table (printQueueStats, now shared with `artwork
status`), two copies of the stat sum (queueTotal), and four copies of the
kind-to-prefix mapping (model.KindPrefixes). The PurgeQueued specs became one
DescribeTable that asserts count and delete agree on every selection.

* docs(cli): say when `artwork cancel` evaluates its selection

The help text covered the two limits that surprise an operator after the fact, but
not the one that bites during the prompt: the count is a preview, and the filters
run again on confirm. A scan or a manual refresh landing in between is cancelled
without ever appearing in the table the operator agreed to.

Deleting only the previewed rows was considered and rejected. The exposure is one
item re-resolving on next view instead of immediately: clearing an item's artwork
state is what every recovery path selects on, so a lost Bump row from
artwork.Refresh comes back at the same priority via provisional() on the next
request, and otherwise within the hour via EnqueueAllMissing. Buying a guarantee
against that costs the truncate path on --all, the flag that exists for a
29k-item backfill.

* refactor(cli): share one set of flag targets across the artwork subcommands

reprocess and cancel each declared their own kinds/all/dry-run/yes variables, but
cobra only ever parses the one subcommand being run, so the two sets could never
hold values at the same time. backup.go already binds one backupDir across two
subcommands and one force across two more; this follows that.

Ten package-level variables become six. Each command keeps its own help string
and its own valid-kind list, so --kind still reports RecheckKinds for reprocess
and RefreshableKinds for cancel, and --source and --priority stay registered only
on the command that has them.

The priority lookup table is now knownPriorities, freeing the artworkPriorities
name for the flag. The new name also reads better against priorityName's fallback
for a value it does not know.
2026-08-21 14:03:59 -04:00

169 lines
4.3 KiB
Go

package model
import (
"errors"
"fmt"
"strconv"
"strings"
"time"
"github.com/navidrome/navidrome/utils/slice"
)
type Kind struct {
prefix string
name string
}
func (k Kind) String() string {
return k.name
}
// Prefix is the short token used in artwork ids and the item_artwork.item_kind column.
func (k Kind) Prefix() string {
return k.prefix
}
var (
KindMediaFileArtwork = Kind{"mf", "media_file"}
KindArtistArtwork = Kind{"ar", "artist"}
KindAlbumArtwork = Kind{"al", "album"}
KindPlaylistArtwork = Kind{"pl", "playlist"}
KindDiscArtwork = Kind{"dc", "disc"}
KindRadioArtwork = Kind{"ra", "radio"}
)
var artworkKindMap = map[string]Kind{
KindMediaFileArtwork.prefix: KindMediaFileArtwork,
KindArtistArtwork.prefix: KindArtistArtwork,
KindAlbumArtwork.prefix: KindAlbumArtwork,
KindPlaylistArtwork.prefix: KindPlaylistArtwork,
KindDiscArtwork.prefix: KindDiscArtwork,
KindRadioArtwork.prefix: KindRadioArtwork,
}
// KindPrefixes leaves the typed Kind domain for the item_kind column, or for a help string.
func KindPrefixes(kinds []Kind) []string {
return slice.Map(kinds, func(k Kind) string { return k.prefix })
}
// ParseKind resolves an item_kind prefix (e.g. "al") to its Kind, reporting whether it was known.
// Use it at string boundaries — URL params, the item_kind column — to enter the typed Kind domain.
func ParseKind(prefix string) (Kind, bool) {
k, ok := artworkKindMap[prefix]
return k, ok
}
type ArtworkID struct {
Kind Kind
ID string
Hash string // content-hash suffix; "" = unknown/none
LastUpdate time.Time // legacy: populated only when parsing old _<hexTimestamp> tokens
}
func (id ArtworkID) String() string {
if id.ID == "" {
return ""
}
s := fmt.Sprintf("%s-%s", id.Kind.prefix, id.ID)
if id.Hash != "" {
return s + "_" + id.Hash
}
return s
}
func NewArtworkID(kind Kind, id string, lastUpdate *time.Time) ArtworkID {
artID := ArtworkID{Kind: kind, ID: id}
if lastUpdate != nil {
artID.LastUpdate = *lastUpdate
}
return artID
}
func ParseArtworkID(id string) (ArtworkID, error) {
parts := strings.SplitN(id, "-", 2)
if len(parts) != 2 {
return ArtworkID{}, errors.New("invalid artwork id")
}
kind, ok := artworkKindMap[parts[0]]
if !ok {
return ArtworkID{}, errors.New("invalid artwork kind")
}
parsedID := ArtworkID{
Kind: kind,
ID: parts[1],
}
parts = strings.SplitN(parts[1], "_", 2)
if len(parts) == 2 {
parsedID.ID = parts[0]
suffix := parts[1]
switch {
// Hash detection must come first: a 16-hex value with the high bit set overflows int64.
case isImageHash(suffix):
parsedID.Hash = suffix
case suffix != "0":
if lastUpdate, err := strconv.ParseInt(suffix, 16, 64); err == nil {
parsedID.LastUpdate = time.Unix(lastUpdate, 0)
}
}
}
return parsedID, nil
}
// isImageHash reports whether s is a 16-char lowercase-hex XXH3-64 content hash.
func isImageHash(s string) bool {
if len(s) != 16 {
return false
}
for _, c := range s {
if !(c >= '0' && c <= '9' || c >= 'a' && c <= 'f') {
return false
}
}
return true
}
func MustParseArtworkID(id string) ArtworkID {
artID, err := ParseArtworkID(id)
if err != nil {
panic(artID)
}
return artID
}
func DiscArtworkID(albumID string, discNumber int) string {
return fmt.Sprintf("%s:%d", albumID, discNumber)
}
func ParseDiscArtworkID(id string) (albumID string, discNumber int, err error) {
parts := strings.SplitN(id, ":", 2)
if len(parts) != 2 || parts[1] == "" {
return "", 0, errors.New("invalid disc artwork id")
}
num, err := strconv.Atoi(parts[1])
if err != nil {
return "", 0, fmt.Errorf("invalid disc number in artwork id: %w", err)
}
return parts[0], num, nil
}
func artworkIDFromAlbum(al Album) ArtworkID {
return ArtworkID{Kind: KindAlbumArtwork, ID: al.ID, Hash: al.ImageHash}
}
func artworkIDFromMediaFile(mf MediaFile) ArtworkID {
return ArtworkID{Kind: KindMediaFileArtwork, ID: mf.ID, Hash: mf.ImageHash}
}
func artworkIDFromPlaylist(pls Playlist) ArtworkID {
return ArtworkID{Kind: KindPlaylistArtwork, ID: pls.ID, Hash: pls.ImageHash}
}
func artworkIDFromArtist(ar Artist) ArtworkID {
return ArtworkID{Kind: KindArtistArtwork, ID: ar.ID, Hash: ar.ImageHash}
}
func artworkIDFromRadio(r Radio) ArtworkID {
return ArtworkID{Kind: KindRadioArtwork, ID: r.ID, Hash: r.ImageHash}
}