From 3491cf4c581491009555897213dd7902959001bc Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Thu, 26 Nov 2026 08:59:25 -0500 Subject: [PATCH] feat(admin): switches for ListenBrainz similarity and MusicBrainz track lists MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Both lookups ran with no way to stop them. Admin › Metadata sources now has an "Other lookups" group with a switch each, both on by default (lookup_settings, migration 0111). Off, the similarity worker asks ListenBrainz nothing and still links what it already fetched; the duplicate resolver gets ErrLookupOff and decides from the track lists it already has. The setting is backed up, and docs/security.md names the switches. docs/security.md also says every account but the first needs an invite. Co-Authored-By: Claude Opus 5.5 --- cmd/minstrel/main.go | 20 ++++- docs/security.md | 6 +- internal/api/admin_lookups.go | 48 ++++++++++ internal/api/api.go | 10 ++- internal/api/library_test.go | 2 +- internal/db/dbq/lookup_settings.sql.go | 52 +++++++++++ internal/db/dbq/models.go | 12 +-- .../migrations/0111_lookup_settings.down.sql | 1 + .../db/migrations/0111_lookup_settings.up.sql | 12 +++ internal/db/queries/lookup_settings.sql | 10 +++ internal/dbtest/reset.go | 7 ++ internal/library/duplicate_resolve.go | 8 +- internal/library/duplicate_resolve_test.go | 22 +++++ internal/library/duplicate_settle.go | 4 +- internal/lookups/lookups.go | 88 +++++++++++++++++++ internal/lookups/lookups_test.go | 67 ++++++++++++++ internal/server/server.go | 15 +++- internal/similarity/worker.go | 22 +++-- .../similarity/worker_integration_test.go | 29 ++++++ web/src/lib/api/admin.ts | 18 ++++ .../admin/LookupSettingsCard.svelte | 81 +++++++++++++++++ .../admin/LookupSettingsCard.test.ts | 50 +++++++++++ web/src/routes/admin/metadata/+page.svelte | 4 +- .../routes/admin/metadata/metadata.test.ts | 5 +- 24 files changed, 571 insertions(+), 22 deletions(-) create mode 100644 internal/api/admin_lookups.go create mode 100644 internal/db/dbq/lookup_settings.sql.go create mode 100644 internal/db/migrations/0111_lookup_settings.down.sql create mode 100644 internal/db/migrations/0111_lookup_settings.up.sql create mode 100644 internal/db/queries/lookup_settings.sql create mode 100644 internal/lookups/lookups.go create mode 100644 internal/lookups/lookups_test.go create mode 100644 web/src/lib/components/admin/LookupSettingsCard.svelte create mode 100644 web/src/lib/components/admin/LookupSettingsCard.test.ts diff --git a/cmd/minstrel/main.go b/cmd/minstrel/main.go index 539196b7..e38ffd76 100644 --- a/cmd/minstrel/main.go +++ b/cmd/minstrel/main.go @@ -27,6 +27,7 @@ import ( "git.fabledsword.com/bvandeusen/minstrel/internal/gc" "git.fabledsword.com/bvandeusen/minstrel/internal/library" "git.fabledsword.com/bvandeusen/minstrel/internal/logging" + "git.fabledsword.com/bvandeusen/minstrel/internal/lookups" "git.fabledsword.com/bvandeusen/minstrel/internal/mailer" "git.fabledsword.com/bvandeusen/minstrel/internal/notifications" "git.fabledsword.com/bvandeusen/minstrel/internal/playlists" @@ -195,6 +196,14 @@ func run() error { logger.Warn("loudness settings: using defaults", "err", loudErr) } + // Switches for ListenBrainz similarity and MusicBrainz track lists: + // shared by the similarity worker, the duplicate resolver and the admin + // API. A load failure leaves both on, as on a new install. + lookupSettings, lookupErr := lookups.New(ctx, pool) + if lookupErr != nil { + logger.Warn("lookup settings: using defaults", "err", lookupErr) + } + // AcoustID lookup settings: shared by the lookup worker and the // admin API. A load failure leaves the lookup off. acoustIDSettings, acoustIDErr := library.NewAcoustIDSettingsService(ctx, pool) @@ -287,7 +296,9 @@ func run() error { // Similarity ingest worker: hourly, fetches ListenBrainz similarity for up // to 5 played tracks and 5 played artists, each re-fetched at most weekly. // The endpoints are public, so no token is needed. + // An admin can switch it off under Metadata sources. similarityWorker := similarity.NewWorker(pool, listenbrainz.NewClient(), logger.With("component", "similarity")) + similarityWorker.Enabled = func() bool { return lookupSettings.Get().ListenBrainzSimilarity } go similarityWorker.Run(ctx) // Household co-play worker: recomputes artist–artist @@ -369,7 +380,13 @@ func run() error { // decide, a few a pass. See internal/library/duplicate_resolve.go. go library.NewDuplicateResolveWorker(pool, logger.With("component", "duplicate_resolve"), cfg.Storage.DataDir, fpSettings, library.ResolveSources{ - TrackLists: cat.RefreshReleaseGroup, Identify: acoustIDLookup.IdentifyRecordings, + TrackLists: func(ctx context.Context, releaseGroupMBID string) error { + if !lookupSettings.Get().MusicBrainzTrackLists { + return library.ErrLookupOff + } + return cat.RefreshReleaseGroup(ctx, releaseGroupMBID) + }, + Identify: acoustIDLookup.IdentifyRecordings, }).Run(ctx) // library_changes compactor: daily, deletes @@ -450,6 +467,7 @@ func run() error { srv.FingerprintSettings = fpSettings srv.LoudnessSettings = loudSettings srv.AcoustIDLookup = acoustIDLookup + srv.LookupSettings = lookupSettings // The server's own backup: the loop runs the nightly schedule, and the // admin page starts, tests and configures the same instance. backups := backup.NewService(pool, logger.With("component", "backup"), buildinfo.Version) diff --git a/docs/security.md b/docs/security.md index 669fd9bd..b7fe2b66 100644 --- a/docs/security.md +++ b/docs/security.md @@ -21,6 +21,8 @@ decisions that look odd at first. For deployment steps, see replaced after that. - **The first account** on an empty server needs the setup token from the server log (see [hosting](./hosting.md#first-account)). +- **Every other account needs an invite** that an admin makes in + **Admin › Users**. There is no open sign-up. - **Password-reset links** are built only from the configured public address, never from the request's `Host` header. @@ -120,11 +122,11 @@ own: | Service | What is sent | When | To turn it off | | --- | --- | --- | --- | | MusicBrainz (`musicbrainz.org`) | A song's or artist's MusicBrainz id | To fetch genre tags | **Admin › Metadata sources › Tags** | -| MusicBrainz (`musicbrainz.org`) | An album's MusicBrainz release-group id | When the duplicate resolver needs the album's track list | No switch | +| MusicBrainz (`musicbrainz.org`) | An album's MusicBrainz release-group id | When the duplicate resolver needs the album's track list | **Admin › Metadata sources › Other lookups** | | Cover Art Archive (`coverartarchive.org`) | An album's MusicBrainz id | To fetch a missing album cover | **Admin › Metadata sources › Cover art** | | Deezer (`api.deezer.com`) | An artist's name, or an artist and album title | To fetch a missing cover or artist picture | **Admin › Metadata sources › Cover art** | | TheAudioDB (`theaudiodb.com`) | An album's or artist's MusicBrainz id | To fetch a missing cover or artist picture | **Admin › Metadata sources › Cover art** | -| ListenBrainz Labs (`labs.api.listenbrainz.org`) | MusicBrainz ids of songs and artists people have played | Hourly, for radio's similar-song data | No switch | +| ListenBrainz Labs (`labs.api.listenbrainz.org`) | MusicBrainz ids of songs and artists people have played | Hourly, for radio's similar-song data | **Admin › Metadata sources › Other lookups** | These are sent only once you set them up: - **AcoustID** (`api.acoustid.org`) gets a song's audio fingerprint and length diff --git a/internal/api/admin_lookups.go b/internal/api/admin_lookups.go new file mode 100644 index 00000000..b238f2a2 --- /dev/null +++ b/internal/api/admin_lookups.go @@ -0,0 +1,48 @@ +package api + +import ( + "encoding/json" + "net/http" + + "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" + "git.fabledsword.com/bvandeusen/minstrel/internal/lookups" +) + +// lookupSettingsBody is the wire shape for GET and PUT +// /api/admin/lookup-settings: the switches for the outside lookups no +// metadata source covers. +type lookupSettingsBody struct { + ListenBrainzSimilarity bool `json:"listenbrainz_similarity"` + MusicBrainzTrackLists bool `json:"musicbrainz_track_lists"` +} + +func lookupSettingsBodyOf(s lookups.Settings) lookupSettingsBody { + return lookupSettingsBody{ + ListenBrainzSimilarity: s.ListenBrainzSimilarity, + MusicBrainzTrackLists: s.MusicBrainzTrackLists, + } +} + +// handleGetLookupSettings implements GET /api/admin/lookup-settings. +func (h *handlers) handleGetLookupSettings(w http.ResponseWriter, _ *http.Request) { + writeJSON(w, http.StatusOK, lookupSettingsBodyOf(h.lookupSettings.Get())) +} + +// handleUpdateLookupSettings implements PUT /api/admin/lookup-settings. A +// whole-row write: a switch the body leaves out is saved as off. +func (h *handlers) handleUpdateLookupSettings(w http.ResponseWriter, r *http.Request) { + var req lookupSettingsBody + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + writeErr(w, apierror.BadRequest("invalid_body", "malformed JSON")) + return + } + saved, err := h.lookupSettings.Set(r.Context(), lookups.Settings{ + ListenBrainzSimilarity: req.ListenBrainzSimilarity, + MusicBrainzTrackLists: req.MusicBrainzTrackLists, + }) + if err != nil { + writeErrWithLog(w, h.logger, "admin lookup settings: update failed", apierror.Internal(err)) + return + } + writeJSON(w, http.StatusOK, lookupSettingsBodyOf(saved)) +} diff --git a/internal/api/api.go b/internal/api/api.go index 6d1da824..455b61c6 100644 --- a/internal/api/api.go +++ b/internal/api/api.go @@ -19,6 +19,7 @@ import ( "git.fabledsword.com/bvandeusen/minstrel/internal/coverart" "git.fabledsword.com/bvandeusen/minstrel/internal/eventbus" "git.fabledsword.com/bvandeusen/minstrel/internal/library" + "git.fabledsword.com/bvandeusen/minstrel/internal/lookups" "git.fabledsword.com/bvandeusen/minstrel/internal/mailer" "git.fabledsword.com/bvandeusen/minstrel/internal/netsettings" "git.fabledsword.com/bvandeusen/minstrel/internal/notifications" @@ -34,7 +35,7 @@ import ( // Mount attaches /api/* handlers to r. Public endpoints (login) are outside // RequireUser; everything else is gated by the middleware. The events writer // is shared with the Subsonic mount so /rest/scrobble feeds the same store. -func Mount(r chi.Router, pool *pgxpool.Pool, logger *slog.Logger, events *playevents.Writer, recCfg config.RecommendationConfig, recSettings *recsettings.Service, quarantineSvc *quarantine.Service, tracksSvc *tracks.Service, playlistsSvc *playlists.Service, coverEnricher *coverart.Enricher, coverSettings *coverart.SettingsService, tagSettings *tags.SettingsService, scanner *library.Scanner, scanCfg library.RunScanConfig, dataDir string, sender mailer.Sender, bus *eventbus.Bus, playlistScheduler *playlists.Scheduler, streamSecret []byte, netSettings *netsettings.Service, fpSettings *library.FingerprintSettingsService, loudSettings *library.LoudnessSettingsService, acoustIDLookup *library.AcoustIDLookupWorker, backups *backup.Service, restart func()) { +func Mount(r chi.Router, pool *pgxpool.Pool, logger *slog.Logger, events *playevents.Writer, recCfg config.RecommendationConfig, recSettings *recsettings.Service, quarantineSvc *quarantine.Service, tracksSvc *tracks.Service, playlistsSvc *playlists.Service, coverEnricher *coverart.Enricher, coverSettings *coverart.SettingsService, tagSettings *tags.SettingsService, scanner *library.Scanner, scanCfg library.RunScanConfig, dataDir string, sender mailer.Sender, bus *eventbus.Bus, playlistScheduler *playlists.Scheduler, streamSecret []byte, netSettings *netsettings.Service, fpSettings *library.FingerprintSettingsService, loudSettings *library.LoudnessSettingsService, acoustIDLookup *library.AcoustIDLookupWorker, lookupSettings *lookups.Service, backups *backup.Service, restart func()) { rng := rand.New(rand.NewSource(rand.Int63())) setupToken, err := auth.NewSetupToken() if err != nil { @@ -65,6 +66,7 @@ func Mount(r chi.Router, pool *pgxpool.Pool, logger *slog.Logger, events *playev fingerprintSettings: fpSettings, loudnessSettings: loudSettings, acoustIDLookup: acoustIDLookup, + lookupSettings: lookupSettings, backups: backups, restart: restart, leveled: newLeveledRenderer(dataDir, loudSettings, logger), @@ -238,6 +240,8 @@ func Mount(r chi.Router, pool *pgxpool.Pool, logger *slog.Logger, events *playev admin.Get("/library/acoustid", h.handleGetAcoustID) admin.Put("/library/acoustid-settings", h.handleUpdateAcoustIDSettings) admin.Post("/library/acoustid/run", h.handleRunAcoustIDLookup) + admin.Get("/lookup-settings", h.handleGetLookupSettings) + admin.Put("/lookup-settings", h.handleUpdateLookupSettings) admin.Get("/library/acoustid/unsettled", h.handleListUnsettledAcoustID) // Duplicates report: proposals from the duplicate sweep, a // trigger to sweep now, dismissal, and the merge, which deletes @@ -345,6 +349,10 @@ type handlers struct { // acoustIDLookup is the AcoustID lookup worker: its settings, its // status and "look up now". Nil serves the defaults (off). acoustIDLookup *library.AcoustIDLookupWorker + // lookupSettings are the switches for ListenBrainz similarity and + // MusicBrainz track lists, the same instance their workers read. Nil + // serves the defaults (both on) and refuses saves. + lookupSettings *lookups.Service // backups is the server's own backup: settings, status, test and run. backups *backup.Service // restart stops the server and starts it again in place, so a restored diff --git a/internal/api/library_test.go b/internal/api/library_test.go index 5c7bae5a..9e145d46 100644 --- a/internal/api/library_test.go +++ b/internal/api/library_test.go @@ -497,7 +497,7 @@ func TestRoutesRegisteredInMount(t *testing.T) { r := chi.NewRouter() w := playevents.NewWriter(h.pool, slog.New(slog.NewTextHandler(io.Discard, nil)), 30*time.Minute, 0.5, 30000) - Mount(r, h.pool, h.logger, w, config.RecommendationConfig{RadioSize: 50, RadioSizeMax: 200, RecentlyPlayedHours: 1}, h.recSettings, h.quarantine, h.tracks, h.playlists, h.coverart, h.coverSettings, h.tagSettings, h.scanner, h.scanCfg, h.dataDir, nil, eventbus.New(), nil, nil, h.netSettings, nil, nil, nil, backup.NewService(h.pool, h.logger, "test"), nil) + Mount(r, h.pool, h.logger, w, config.RecommendationConfig{RadioSize: 50, RadioSizeMax: 200, RecentlyPlayedHours: 1}, h.recSettings, h.quarantine, h.tracks, h.playlists, h.coverart, h.coverSettings, h.tagSettings, h.scanner, h.scanCfg, h.dataDir, nil, eventbus.New(), nil, nil, h.netSettings, nil, nil, nil, nil, backup.NewService(h.pool, h.logger, "test"), nil) paths := []string{ "/api/artists", diff --git a/internal/db/dbq/lookup_settings.sql.go b/internal/db/dbq/lookup_settings.sql.go new file mode 100644 index 00000000..135c146c --- /dev/null +++ b/internal/db/dbq/lookup_settings.sql.go @@ -0,0 +1,52 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: lookup_settings.sql + +package dbq + +import ( + "context" +) + +const getLookupSettings = `-- name: GetLookupSettings :one +SELECT id, listenbrainz_similarity, musicbrainz_track_lists, updated_at FROM lookup_settings WHERE id = true +` + +func (q *Queries) GetLookupSettings(ctx context.Context) (LookupSetting, error) { + row := q.db.QueryRow(ctx, getLookupSettings) + var i LookupSetting + err := row.Scan( + &i.ID, + &i.ListenbrainzSimilarity, + &i.MusicbrainzTrackLists, + &i.UpdatedAt, + ) + return i, err +} + +const updateLookupSettings = `-- name: UpdateLookupSettings :one +UPDATE lookup_settings + SET listenbrainz_similarity = $1, + musicbrainz_track_lists = $2, + updated_at = now() + WHERE id = true +RETURNING id, listenbrainz_similarity, musicbrainz_track_lists, updated_at +` + +type UpdateLookupSettingsParams struct { + ListenbrainzSimilarity bool + MusicbrainzTrackLists bool +} + +func (q *Queries) UpdateLookupSettings(ctx context.Context, arg UpdateLookupSettingsParams) (LookupSetting, error) { + row := q.db.QueryRow(ctx, updateLookupSettings, arg.ListenbrainzSimilarity, arg.MusicbrainzTrackLists) + var i LookupSetting + err := row.Scan( + &i.ID, + &i.ListenbrainzSimilarity, + &i.MusicbrainzTrackLists, + &i.UpdatedAt, + ) + return i, err +} diff --git a/internal/db/dbq/models.go b/internal/db/dbq/models.go index b43b9007..7ea40a32 100644 --- a/internal/db/dbq/models.go +++ b/internal/db/dbq/models.go @@ -328,6 +328,13 @@ type ListenbrainzSimilarRecording struct { Score float64 } +type LookupSetting struct { + ID bool + ListenbrainzSimilarity bool + MusicbrainzTrackLists bool + UpdatedAt pgtype.Timestamptz +} + type LoudnessSetting struct { ID bool Enabled bool @@ -515,11 +522,6 @@ type RecommendationWeightProfile struct { ContextTimeWeight float64 } -type RegistrationSetting struct { - ID bool - Mode string -} - type ScanRun struct { ID pgtype.UUID StartedAt pgtype.Timestamptz diff --git a/internal/db/migrations/0111_lookup_settings.down.sql b/internal/db/migrations/0111_lookup_settings.down.sql new file mode 100644 index 00000000..f4afec89 --- /dev/null +++ b/internal/db/migrations/0111_lookup_settings.down.sql @@ -0,0 +1 @@ +DROP TABLE lookup_settings; diff --git a/internal/db/migrations/0111_lookup_settings.up.sql b/internal/db/migrations/0111_lookup_settings.up.sql new file mode 100644 index 00000000..fdf7831f --- /dev/null +++ b/internal/db/migrations/0111_lookup_settings.up.sql @@ -0,0 +1,12 @@ +-- Switches for the two outside lookups that no source under Admin › Metadata +-- sources covers: ListenBrainz's similar songs and artists, which radio and +-- the mixes draw on, and MusicBrainz's album track lists, which the duplicate +-- resolver reads to tell a song filed in the wrong slot from a repeat. Both +-- start on; turning one off keeps what was already fetched. +CREATE TABLE lookup_settings ( + id boolean PRIMARY KEY DEFAULT true CHECK (id), + listenbrainz_similarity boolean NOT NULL DEFAULT true, + musicbrainz_track_lists boolean NOT NULL DEFAULT true, + updated_at timestamptz NOT NULL DEFAULT now() +); +INSERT INTO lookup_settings (id) VALUES (true); diff --git a/internal/db/queries/lookup_settings.sql b/internal/db/queries/lookup_settings.sql new file mode 100644 index 00000000..10a0c3c0 --- /dev/null +++ b/internal/db/queries/lookup_settings.sql @@ -0,0 +1,10 @@ +-- name: GetLookupSettings :one +SELECT * FROM lookup_settings WHERE id = true; + +-- name: UpdateLookupSettings :one +UPDATE lookup_settings + SET listenbrainz_similarity = sqlc.arg(listenbrainz_similarity), + musicbrainz_track_lists = sqlc.arg(musicbrainz_track_lists), + updated_at = now() + WHERE id = true +RETURNING *; diff --git a/internal/dbtest/reset.go b/internal/dbtest/reset.go index 8e3c07ad..1d35d06b 100644 --- a/internal/dbtest/reset.go +++ b/internal/dbtest/reset.go @@ -157,6 +157,13 @@ func ResetDB(t *testing.T, pool *pgxpool.Pool) { ); err != nil { t.Fatalf("dbtest.ResetDB reset loudness settings: %v", err) } + // The outside-lookup switches, back to on. + if _, err := pool.Exec(ctx, ` + UPDATE lookup_settings + SET listenbrainz_similarity = DEFAULT, musicbrainz_track_lists = DEFAULT, updated_at = DEFAULT`, + ); err != nil { + t.Fatalf("dbtest.ResetDB reset lookup settings: %v", err) + } // The change log's trimmed mark, a singleton: nothing has been trimmed. if _, err := pool.Exec(ctx, "UPDATE library_changes_trimmed SET through = 0"); err != nil { t.Fatalf("dbtest.ResetDB reset library_changes_trimmed: %v", err) diff --git a/internal/library/duplicate_resolve.go b/internal/library/duplicate_resolve.go index 6b434a37..ed50fb4a 100644 --- a/internal/library/duplicate_resolve.go +++ b/internal/library/duplicate_resolve.go @@ -122,9 +122,15 @@ func mergePlan(g *resolveGroup) (ok bool, survivor int) { } // TrackListFetcher reads a release group's releases and track lists from -// MusicBrainz into the catalogue (catalogue.Service.RefreshReleaseGroup). +// MusicBrainz into the catalogue (catalogue.Service.RefreshReleaseGroup). It +// returns ErrLookupOff while an admin has switched the lookup off. type TrackListFetcher func(ctx context.Context, releaseGroupMBID string) error +// ErrLookupOff is a TrackListFetcher's answer while an admin has switched +// MusicBrainz track lists off. The pass then decides from the track lists +// already read, without asking again until the next pass. +var ErrLookupOff = errors.New("an admin has switched this lookup off") + // RecordingIdentifier asks AcoustID which recordings a file may be // (AcoustIDLookupWorker.IdentifyRecordings). type RecordingIdentifier func(ctx context.Context, path string) ([]string, error) diff --git a/internal/library/duplicate_resolve_test.go b/internal/library/duplicate_resolve_test.go index 04647fc3..6403d741 100644 --- a/internal/library/duplicate_resolve_test.go +++ b/internal/library/duplicate_resolve_test.go @@ -665,6 +665,28 @@ func TestResolveDuplicates_FetchesAMissingTrackList_Integration(t *testing.T) { } } +// With MusicBrainz track lists switched off, the resolver asks once, gets +// ErrLookupOff, and removes nothing it can't decide without the list. +func TestResolveDuplicates_TrackListsSwitchedOff_Integration(t *testing.T) { + f := newOneAlbumFixture(t, "acoustic", "Void", "Reach") + if _, err := f.pool.Exec(context.Background(), + `UPDATE albums SET release_group_mbid = $2 WHERE id = $1`, f.album.ID, "rg-off"); err != nil { + t.Fatal(err) + } + calls := 0 + off := func(context.Context, string) error { + calls++ + return ErrLookupOff + } + res, err := ResolveDuplicatesWith(context.Background(), f.pool, nil, "", true, ResolveSources{TrackLists: off}) + if err != nil { + t.Fatal(err) + } + if calls != 1 || res.WrongFiles != 0 || !exists(f.aPath) || !exists(f.bPath) { + t.Fatalf("fetches %d, result %+v; want one refused fetch and both copies kept", calls, res) + } +} + // Without a track list that decides, nothing is removed. func TestResolveDuplicates_LeavesAnUndecidedSlotForTheOperator_Integration(t *testing.T) { f := newOneAlbumFixture(t, "acoustic", "Void", "Reach") diff --git a/internal/library/duplicate_settle.go b/internal/library/duplicate_settle.go index fb881a11..f0a9a066 100644 --- a/internal/library/duplicate_settle.go +++ b/internal/library/duplicate_settle.go @@ -200,7 +200,9 @@ func settleWrongSlots( } if len(tracks) == 0 && fetches > 0 && neverRead(ctx, q, rg) { fetches-- - if err := src.TrackLists(ctx, rg); err != nil { + if err := src.TrackLists(ctx, rg); errors.Is(err, ErrLookupOff) { + fetches = 0 + } else if err != nil { logger.Info("duplicate resolve: fetching the album's track list failed", "release_group", rg, "err", err) if errors.Is(err, musicbrainz.ErrUnreachable) { fetches = 0 diff --git a/internal/lookups/lookups.go b/internal/lookups/lookups.go new file mode 100644 index 00000000..7edbeb72 --- /dev/null +++ b/internal/lookups/lookups.go @@ -0,0 +1,88 @@ +// Package lookups holds the admin's switches for the outside lookups that no +// metadata source setting covers: ListenBrainz's similar songs and artists, +// and MusicBrainz's album track lists for the duplicate resolver. Both are on +// unless an admin turns them off under Admin › Metadata sources. Turning one +// off stops the requests and keeps what was already fetched. +package lookups + +import ( + "context" + "errors" + "fmt" + "sync" + + "github.com/jackc/pgx/v5/pgxpool" + + "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" +) + +// Settings mirrors the lookup_settings row. +type Settings struct { + // ListenBrainzSimilarity lets the similarity worker ask ListenBrainz Labs + // which songs and artists are like the ones people play. + ListenBrainzSimilarity bool + // MusicBrainzTrackLists lets the duplicate resolver read an album's track + // list from MusicBrainz when it has never been read. + MusicBrainzTrackLists bool +} + +// Defaults mirrors the table's column defaults, so a database that can't be +// read behaves as a new install does. +var Defaults = Settings{ListenBrainzSimilarity: true, MusicBrainzTrackLists: true} + +// Service caches the settings and saves them. One instance is shared by the +// workers and the admin API, so a save reaches the workers at once. +type Service struct { + pool *pgxpool.Pool + + mu sync.RWMutex + cur Settings +} + +// New loads the settings once. It always returns a usable service, holding +// the defaults when the load fails; the error says so. +func New(ctx context.Context, pool *pgxpool.Pool) (*Service, error) { + s := &Service{pool: pool, cur: Defaults} + row, err := dbq.New(pool).GetLookupSettings(ctx) + if err != nil { + return s, fmt.Errorf("lookup settings: load: %w", err) + } + s.cur = fromRow(row) + return s, nil +} + +// Get returns the cached settings. A nil service answers with the defaults. +func (s *Service) Get() Settings { + if s == nil { + return Defaults + } + s.mu.RLock() + defer s.mu.RUnlock() + return s.cur +} + +// Set saves and re-caches. +func (s *Service) Set(ctx context.Context, in Settings) (Settings, error) { + if s == nil { + return Settings{}, errors.New("lookup settings: no settings service") + } + row, err := dbq.New(s.pool).UpdateLookupSettings(ctx, dbq.UpdateLookupSettingsParams{ + ListenbrainzSimilarity: in.ListenBrainzSimilarity, + MusicbrainzTrackLists: in.MusicBrainzTrackLists, + }) + if err != nil { + return Settings{}, fmt.Errorf("lookup settings: save: %w", err) + } + out := fromRow(row) + s.mu.Lock() + s.cur = out + s.mu.Unlock() + return out, nil +} + +func fromRow(row dbq.LookupSetting) Settings { + return Settings{ + ListenBrainzSimilarity: row.ListenbrainzSimilarity, + MusicBrainzTrackLists: row.MusicbrainzTrackLists, + } +} diff --git a/internal/lookups/lookups_test.go b/internal/lookups/lookups_test.go new file mode 100644 index 00000000..9175e4c2 --- /dev/null +++ b/internal/lookups/lookups_test.go @@ -0,0 +1,67 @@ +package lookups + +import ( + "context" + "io" + "log/slog" + "os" + "testing" + + "github.com/jackc/pgx/v5/pgxpool" + + "git.fabledsword.com/bvandeusen/minstrel/internal/db" + "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" +) + +// With no settings service, both lookups are on, as on a new install. +func TestGet_WithoutAServiceBothLookupsAreOn(t *testing.T) { + var s *Service + if got := s.Get(); got != Defaults || !got.ListenBrainzSimilarity || !got.MusicBrainzTrackLists { + t.Errorf("nil service = %+v, want both on", got) + } +} + +// A new install starts with both on; a save is cached for the workers and +// read back by a server started afterwards. +func TestSettings_StartOnAndKeepWhatIsSaved_Integration(t *testing.T) { + if testing.Short() { + t.Skip("skipping in -short mode") + } + dsn := os.Getenv("MINSTREL_TEST_DATABASE_URL") + if dsn == "" { + t.Skip("MINSTREL_TEST_DATABASE_URL not set") + } + if err := db.Migrate(dsn, slog.New(slog.NewTextHandler(io.Discard, nil))); err != nil { + t.Fatalf("migrate: %v", err) + } + ctx := context.Background() + pool, err := pgxpool.New(ctx, dsn) + if err != nil { + t.Fatalf("pool: %v", err) + } + t.Cleanup(pool.Close) + dbtest.ResetDB(t, pool) + + s, err := New(ctx, pool) + if err != nil { + t.Fatalf("load: %v", err) + } + if got := s.Get(); got != Defaults { + t.Fatalf("new install = %+v, want both on", got) + } + + off := Settings{ListenBrainzSimilarity: false, MusicBrainzTrackLists: true} + if _, err := s.Set(ctx, off); err != nil { + t.Fatalf("save: %v", err) + } + if got := s.Get(); got != off { + t.Errorf("cached = %+v, want %+v", got, off) + } + again, err := New(ctx, pool) + if err != nil { + t.Fatalf("reload: %v", err) + } + if got := again.Get(); got != off { + t.Errorf("after a restart = %+v, want %+v", got, off) + } +} diff --git a/internal/server/server.go b/internal/server/server.go index 7f22f1fb..4a0994b1 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -22,6 +22,7 @@ import ( "git.fabledsword.com/bvandeusen/minstrel/internal/coverart" "git.fabledsword.com/bvandeusen/minstrel/internal/eventbus" "git.fabledsword.com/bvandeusen/minstrel/internal/library" + "git.fabledsword.com/bvandeusen/minstrel/internal/lookups" "git.fabledsword.com/bvandeusen/minstrel/internal/mailer" "git.fabledsword.com/bvandeusen/minstrel/internal/netsettings" "git.fabledsword.com/bvandeusen/minstrel/internal/playevents" @@ -90,6 +91,10 @@ type Server struct { // status and "look up now" the admin card drives. Nil in test contexts; // one is built (and never run) so the admin routes still answer. AcoustIDLookup *library.AcoustIDLookupWorker + // LookupSettings are the switches for ListenBrainz similarity and + // MusicBrainz track lists, shared with the workers that make those + // requests. Nil makes the router load its own. + LookupSettings *lookups.Service // Backups is the server's own backup, the instance whose loop runs the // nightly schedule. Nil builds one that runs only when an admin asks. Backups *backup.Service @@ -188,11 +193,19 @@ func (s *Server) Router() http.Handler { } acoustIDLookup = library.NewAcoustIDLookupWorker(s.Pool, s.Logger, acoustIDSettings, nil) } + lookupSettings := s.LookupSettings + if lookupSettings == nil { + var err error + lookupSettings, err = lookups.New(context.Background(), s.Pool) + if err != nil { + s.Logger.Warn("lookup settings unavailable; serving defaults", "err", err) + } + } backups := s.Backups if backups == nil { backups = backup.NewService(s.Pool, s.Logger, buildinfo.Version) } - api.Mount(r, s.Pool, s.Logger, writer, s.RecommendationCfg, recSettings, quarantineSvc, tracksSvc, playlistsSvc, s.CoverEnricher, s.CoverSettings, s.TagSettings, s.LibraryScanner, s.ScanCfg, s.DataDir, smtpSender, bus, s.PlaylistScheduler, s.StreamSecret, netSettings, fpSettings, loudSettings, acoustIDLookup, backups, s.Restart) + api.Mount(r, s.Pool, s.Logger, writer, s.RecommendationCfg, recSettings, quarantineSvc, tracksSvc, playlistsSvc, s.CoverEnricher, s.CoverSettings, s.TagSettings, s.LibraryScanner, s.ScanCfg, s.DataDir, smtpSender, bus, s.PlaylistScheduler, s.StreamSecret, netSettings, fpSettings, loudSettings, acoustIDLookup, lookupSettings, backups, s.Restart) // /api/admin/scan is the only admin route owned by the server package // (it needs the Scanner). Register it as a single inline-middleware // route — using r.Route("/api/admin", ...) here would create a second diff --git a/internal/similarity/worker.go b/internal/similarity/worker.go index 29db25e4..2075cd61 100644 --- a/internal/similarity/worker.go +++ b/internal/similarity/worker.go @@ -40,6 +40,11 @@ type Worker struct { tick time.Duration batch int32 topK int // per artist + + // Enabled reports whether an admin allows asking ListenBrainz; nil means + // it is allowed. While it is off a tick asks nothing, and what was + // fetched before keeps feeding radio and the mixes. + Enabled func() bool } // NewWorker constructs a worker with production defaults: 1h tick, @@ -73,16 +78,19 @@ func (w *Worker) Run(ctx context.Context) { } } -// tickOnce drains one batch of tracks and one batch of artists, then -// re-resolves every cached answer against the library. Per-row errors are +// tickOnce drains one batch of tracks and one batch of artists, unless an +// admin has switched ListenBrainz similarity off, then re-resolves every +// cached answer against the library. Per-row errors are // logged and skipped. 429 aborts the fetching, not the resolve. func (w *Worker) tickOnce(ctx context.Context) error { q := dbq.New(w.pool) - if err := w.tickTracks(ctx, q); err != nil { - return err - } - if err := w.tickArtists(ctx, q); err != nil { - return err + if w.Enabled == nil || w.Enabled() { + if err := w.tickTracks(ctx, q); err != nil { + return err + } + if err := w.tickArtists(ctx, q); err != nil { + return err + } } // Links recordings that reached the library since their seed was fetched: // a scan, an import, an MBID from the AcoustID lookup. diff --git a/internal/similarity/worker_integration_test.go b/internal/similarity/worker_integration_test.go index dfa35f96..aeabeb79 100644 --- a/internal/similarity/worker_integration_test.go +++ b/internal/similarity/worker_integration_test.go @@ -624,3 +624,32 @@ func TestTickOnce_PermanentErrorCountsAsFetched(t *testing.T) { t.Errorf("fetches recorded: tracks=%d artists=%d, want 1 and 1", tracks, artists) } } + +// With ListenBrainz similarity switched off, a tick asks ListenBrainz nothing. +func TestTickOnce_SwitchedOffAsksNothing(t *testing.T) { + f := newFixture(t) + mbidA := "11111111-1111-1111-1111-111111111111" + trackA := seedTrack(t, f, "A", &mbidA) + markPlayed(t, f, trackA.ID) + var asked atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + asked.Add(1) + _, _ = w.Write([]byte(`[]`)) + })) + defer srv.Close() + w := newTestWorker(f, srv.URL) + w.Enabled = func() bool { return false } + if err := w.tickOnce(context.Background()); err != nil { + t.Fatalf("tickOnce: %v", err) + } + if n := asked.Load(); n != 0 { + t.Errorf("ListenBrainz was asked %d times while switched off", n) + } + w.Enabled = func() bool { return true } + if err := w.tickOnce(context.Background()); err != nil { + t.Fatalf("tickOnce: %v", err) + } + if asked.Load() == 0 { + t.Error("switched back on, a tick should ask ListenBrainz again") + } +} diff --git a/web/src/lib/api/admin.ts b/web/src/lib/api/admin.ts index 495d13ff..8e0f64e0 100644 --- a/web/src/lib/api/admin.ts +++ b/web/src/lib/api/admin.ts @@ -318,6 +318,24 @@ export async function updateLoudnessSettings(s: LoudnessSettings): Promise('/api/admin/library/loudness-settings', s); } +// Outside lookups no metadata source covers --------------------------- + +/** Switches for ListenBrainz's similar songs and artists (radio and the + * mixes) and MusicBrainz's album track lists (the duplicate resolver). + * Both are on unless an admin turns them off. */ +export type LookupSettings = { + listenbrainz_similarity: boolean; + musicbrainz_track_lists: boolean; +}; + +export async function getLookupSettings(): Promise { + return api.get('/api/admin/lookup-settings'); +} + +export async function updateLookupSettings(s: LookupSettings): Promise { + return api.put('/api/admin/lookup-settings', s); +} + // The library's folders ----------------------------------------------- export type LibraryFolder = { diff --git a/web/src/lib/components/admin/LookupSettingsCard.svelte b/web/src/lib/components/admin/LookupSettingsCard.svelte new file mode 100644 index 00000000..de4e6187 --- /dev/null +++ b/web/src/lib/components/admin/LookupSettingsCard.svelte @@ -0,0 +1,81 @@ + + + + {#if settings} + {#each rows as row (row.key)} + + flip(row.key, e.currentTarget.checked)} + class="h-4 w-4 cursor-pointer accent-accent" + /> + + {/each} + {:else if loadError} +

+ Couldn't load these settings. + +

+ {:else} +

Loading…

+ {/if} +
diff --git a/web/src/lib/components/admin/LookupSettingsCard.test.ts b/web/src/lib/components/admin/LookupSettingsCard.test.ts new file mode 100644 index 00000000..c8b1fb73 --- /dev/null +++ b/web/src/lib/components/admin/LookupSettingsCard.test.ts @@ -0,0 +1,50 @@ +import { afterEach, describe, expect, test, vi } from 'vitest'; +import { render, screen, fireEvent, waitFor } from '@testing-library/svelte'; + +vi.mock('#lib/api/admin.js', () => ({ + getLookupSettings: vi.fn(), + updateLookupSettings: vi.fn() +})); +vi.mock('#lib/stores/toast.svelte.js', () => ({ pushToast: vi.fn() })); + +import LookupSettingsCard from './LookupSettingsCard.svelte'; +import { getLookupSettings, updateLookupSettings } from '#lib/api/admin.js'; +import { pushToast } from '#lib/stores/toast.svelte.js'; + +const bothOn = { listenbrainz_similarity: true, musicbrainz_track_lists: true }; + +afterEach(() => vi.clearAllMocks()); + +describe('LookupSettingsCard', () => { + test('shows both lookups on, and saves a switch as it is flipped', async () => { + vi.mocked(getLookupSettings).mockResolvedValue(bothOn); + vi.mocked(updateLookupSettings).mockImplementation(async (s) => s); + render(LookupSettingsCard); + + const lb = await screen.findByRole('switch', { name: /listenbrainz similar songs/i }); + const mb = screen.getByRole('switch', { name: /musicbrainz track lists/i }); + expect(lb).toBeChecked(); + expect(mb).toBeChecked(); + + await fireEvent.click(lb); + await waitFor(() => + expect(updateLookupSettings).toHaveBeenCalledWith({ + listenbrainz_similarity: false, + musicbrainz_track_lists: true + }) + ); + await waitFor(() => expect(lb).not.toBeChecked()); + expect(mb).toBeChecked(); + }); + + test('a failed save puts the switch back and says so', async () => { + vi.mocked(getLookupSettings).mockResolvedValue(bothOn); + vi.mocked(updateLookupSettings).mockRejectedValue(new Error('offline')); + render(LookupSettingsCard); + + const mb = await screen.findByRole('switch', { name: /musicbrainz track lists/i }); + await fireEvent.click(mb); + await waitFor(() => expect(pushToast).toHaveBeenCalled()); + expect(mb).toBeChecked(); + }); +}); diff --git a/web/src/routes/admin/metadata/+page.svelte b/web/src/routes/admin/metadata/+page.svelte index 8c004fa1..9c0432e9 100644 --- a/web/src/routes/admin/metadata/+page.svelte +++ b/web/src/routes/admin/metadata/+page.svelte @@ -12,11 +12,12 @@ import { qk } from '#lib/api/queries.js'; import AcoustIDCard from '#lib/components/AcoustIDCard.svelte'; import ProviderGroup from '#lib/components/admin/ProviderGroup.svelte'; + import LookupSettingsCard from '#lib/components/admin/LookupSettingsCard.svelte'; import SettingsColumns from '#lib/components/settings/SettingsColumns.svelte'; // Admin › Metadata sources: the outside sources Minstrel asks // about your music. AcoustID names a recording from its sound; the cover - // art and tag sources share one block. + // art and tag sources share one block; the other lookups have a switch each. const client = useQueryClient(); const coverStore = createCoverProvidersQuery(); @@ -88,5 +89,6 @@ keyPlaceholder="Paste a key to use this source" note={tagNote} /> + {/snippet} diff --git a/web/src/routes/admin/metadata/metadata.test.ts b/web/src/routes/admin/metadata/metadata.test.ts index 464deb4c..a70dbd11 100644 --- a/web/src/routes/admin/metadata/metadata.test.ts +++ b/web/src/routes/admin/metadata/metadata.test.ts @@ -20,7 +20,10 @@ vi.mock('#lib/api/admin.js', () => ({ getAcoustID: vi.fn(() => new Promise(() => {})), updateAcoustIDSettings: vi.fn(), runAcoustIDLookup: vi.fn(), - listUnsettledAcoustID: vi.fn() + listUnsettledAcoustID: vi.fn(), + // LookupSettingsCard loads on mount and has its own suite; left pending. + getLookupSettings: vi.fn(() => new Promise(() => {})), + updateLookupSettings: vi.fn() })); import MetadataPage from './+page.svelte';