feat(admin): switches for ListenBrainz similarity and MusicBrainz track lists
release / go (push) Successful in 1m50s
release / web (push) Successful in 1m15s
release / govulncheck (push) Successful in 20s
release / integration (push) Successful in 4m11s
release / android (push) Successful in 4m33s
release / Build signed APK (push) Successful in 4m40s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 22s
release / Verify release artifacts (tag releases only) (push) Skipped

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 <noreply@anthropic.com>
This commit is contained in:
2026-11-26 08:59:25 -05:00
co-authored by Claude Opus 5.5
parent 1942cb39cf
commit 3491cf4c58
24 changed files with 571 additions and 22 deletions
+19 -1
View File
@@ -27,6 +27,7 @@ import (
"git.fabledsword.com/bvandeusen/minstrel/internal/gc" "git.fabledsword.com/bvandeusen/minstrel/internal/gc"
"git.fabledsword.com/bvandeusen/minstrel/internal/library" "git.fabledsword.com/bvandeusen/minstrel/internal/library"
"git.fabledsword.com/bvandeusen/minstrel/internal/logging" "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/mailer"
"git.fabledsword.com/bvandeusen/minstrel/internal/notifications" "git.fabledsword.com/bvandeusen/minstrel/internal/notifications"
"git.fabledsword.com/bvandeusen/minstrel/internal/playlists" "git.fabledsword.com/bvandeusen/minstrel/internal/playlists"
@@ -195,6 +196,14 @@ func run() error {
logger.Warn("loudness settings: using defaults", "err", loudErr) 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 // AcoustID lookup settings: shared by the lookup worker and the
// admin API. A load failure leaves the lookup off. // admin API. A load failure leaves the lookup off.
acoustIDSettings, acoustIDErr := library.NewAcoustIDSettingsService(ctx, pool) acoustIDSettings, acoustIDErr := library.NewAcoustIDSettingsService(ctx, pool)
@@ -287,7 +296,9 @@ func run() error {
// Similarity ingest worker: hourly, fetches ListenBrainz similarity for up // Similarity ingest worker: hourly, fetches ListenBrainz similarity for up
// to 5 played tracks and 5 played artists, each re-fetched at most weekly. // to 5 played tracks and 5 played artists, each re-fetched at most weekly.
// The endpoints are public, so no token is needed. // 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 := similarity.NewWorker(pool, listenbrainz.NewClient(), logger.With("component", "similarity"))
similarityWorker.Enabled = func() bool { return lookupSettings.Get().ListenBrainzSimilarity }
go similarityWorker.Run(ctx) go similarityWorker.Run(ctx)
// Household co-play worker: recomputes artist–artist // 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. // decide, a few a pass. See internal/library/duplicate_resolve.go.
go library.NewDuplicateResolveWorker(pool, logger.With("component", "duplicate_resolve"), go library.NewDuplicateResolveWorker(pool, logger.With("component", "duplicate_resolve"),
cfg.Storage.DataDir, fpSettings, library.ResolveSources{ 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) }).Run(ctx)
// library_changes compactor: daily, deletes // library_changes compactor: daily, deletes
@@ -450,6 +467,7 @@ func run() error {
srv.FingerprintSettings = fpSettings srv.FingerprintSettings = fpSettings
srv.LoudnessSettings = loudSettings srv.LoudnessSettings = loudSettings
srv.AcoustIDLookup = acoustIDLookup srv.AcoustIDLookup = acoustIDLookup
srv.LookupSettings = lookupSettings
// The server's own backup: the loop runs the nightly schedule, and the // The server's own backup: the loop runs the nightly schedule, and the
// admin page starts, tests and configures the same instance. // admin page starts, tests and configures the same instance.
backups := backup.NewService(pool, logger.With("component", "backup"), buildinfo.Version) backups := backup.NewService(pool, logger.With("component", "backup"), buildinfo.Version)
+4 -2
View File
@@ -21,6 +21,8 @@ decisions that look odd at first. For deployment steps, see
replaced after that. replaced after that.
- **The first account** on an empty server needs the setup token from the - **The first account** on an empty server needs the setup token from the
server log (see [hosting](./hosting.md#first-account)). 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, - **Password-reset links** are built only from the configured public address,
never from the request's `Host` header. never from the request's `Host` header.
@@ -120,11 +122,11 @@ own:
| Service | What is sent | When | To turn it off | | 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`) | 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** | | 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** | | 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** | | 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: These are sent only once you set them up:
- **AcoustID** (`api.acoustid.org`) gets a song's audio fingerprint and length - **AcoustID** (`api.acoustid.org`) gets a song's audio fingerprint and length
+48
View File
@@ -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))
}
+9 -1
View File
@@ -19,6 +19,7 @@ import (
"git.fabledsword.com/bvandeusen/minstrel/internal/coverart" "git.fabledsword.com/bvandeusen/minstrel/internal/coverart"
"git.fabledsword.com/bvandeusen/minstrel/internal/eventbus" "git.fabledsword.com/bvandeusen/minstrel/internal/eventbus"
"git.fabledsword.com/bvandeusen/minstrel/internal/library" "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/mailer"
"git.fabledsword.com/bvandeusen/minstrel/internal/netsettings" "git.fabledsword.com/bvandeusen/minstrel/internal/netsettings"
"git.fabledsword.com/bvandeusen/minstrel/internal/notifications" "git.fabledsword.com/bvandeusen/minstrel/internal/notifications"
@@ -34,7 +35,7 @@ import (
// Mount attaches /api/* handlers to r. Public endpoints (login) are outside // Mount attaches /api/* handlers to r. Public endpoints (login) are outside
// RequireUser; everything else is gated by the middleware. The events writer // RequireUser; everything else is gated by the middleware. The events writer
// is shared with the Subsonic mount so /rest/scrobble feeds the same store. // 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())) rng := rand.New(rand.NewSource(rand.Int63()))
setupToken, err := auth.NewSetupToken() setupToken, err := auth.NewSetupToken()
if err != nil { if err != nil {
@@ -65,6 +66,7 @@ func Mount(r chi.Router, pool *pgxpool.Pool, logger *slog.Logger, events *playev
fingerprintSettings: fpSettings, fingerprintSettings: fpSettings,
loudnessSettings: loudSettings, loudnessSettings: loudSettings,
acoustIDLookup: acoustIDLookup, acoustIDLookup: acoustIDLookup,
lookupSettings: lookupSettings,
backups: backups, backups: backups,
restart: restart, restart: restart,
leveled: newLeveledRenderer(dataDir, loudSettings, logger), 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.Get("/library/acoustid", h.handleGetAcoustID)
admin.Put("/library/acoustid-settings", h.handleUpdateAcoustIDSettings) admin.Put("/library/acoustid-settings", h.handleUpdateAcoustIDSettings)
admin.Post("/library/acoustid/run", h.handleRunAcoustIDLookup) 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) admin.Get("/library/acoustid/unsettled", h.handleListUnsettledAcoustID)
// Duplicates report: proposals from the duplicate sweep, a // Duplicates report: proposals from the duplicate sweep, a
// trigger to sweep now, dismissal, and the merge, which deletes // 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 // acoustIDLookup is the AcoustID lookup worker: its settings, its
// status and "look up now". Nil serves the defaults (off). // status and "look up now". Nil serves the defaults (off).
acoustIDLookup *library.AcoustIDLookupWorker 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 is the server's own backup: settings, status, test and run.
backups *backup.Service backups *backup.Service
// restart stops the server and starts it again in place, so a restored // restart stops the server and starts it again in place, so a restored
+1 -1
View File
@@ -497,7 +497,7 @@ func TestRoutesRegisteredInMount(t *testing.T) {
r := chi.NewRouter() r := chi.NewRouter()
w := playevents.NewWriter(h.pool, slog.New(slog.NewTextHandler(io.Discard, nil)), w := playevents.NewWriter(h.pool, slog.New(slog.NewTextHandler(io.Discard, nil)),
30*time.Minute, 0.5, 30000) 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{ paths := []string{
"/api/artists", "/api/artists",
+52
View File
@@ -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
}
+7 -5
View File
@@ -328,6 +328,13 @@ type ListenbrainzSimilarRecording struct {
Score float64 Score float64
} }
type LookupSetting struct {
ID bool
ListenbrainzSimilarity bool
MusicbrainzTrackLists bool
UpdatedAt pgtype.Timestamptz
}
type LoudnessSetting struct { type LoudnessSetting struct {
ID bool ID bool
Enabled bool Enabled bool
@@ -515,11 +522,6 @@ type RecommendationWeightProfile struct {
ContextTimeWeight float64 ContextTimeWeight float64
} }
type RegistrationSetting struct {
ID bool
Mode string
}
type ScanRun struct { type ScanRun struct {
ID pgtype.UUID ID pgtype.UUID
StartedAt pgtype.Timestamptz StartedAt pgtype.Timestamptz
@@ -0,0 +1 @@
DROP TABLE lookup_settings;
@@ -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);
+10
View File
@@ -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 *;
+7
View File
@@ -157,6 +157,13 @@ func ResetDB(t *testing.T, pool *pgxpool.Pool) {
); err != nil { ); err != nil {
t.Fatalf("dbtest.ResetDB reset loudness settings: %v", err) 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. // 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 { if _, err := pool.Exec(ctx, "UPDATE library_changes_trimmed SET through = 0"); err != nil {
t.Fatalf("dbtest.ResetDB reset library_changes_trimmed: %v", err) t.Fatalf("dbtest.ResetDB reset library_changes_trimmed: %v", err)
+7 -1
View File
@@ -122,9 +122,15 @@ func mergePlan(g *resolveGroup) (ok bool, survivor int) {
} }
// TrackListFetcher reads a release group's releases and track lists from // 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 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 // RecordingIdentifier asks AcoustID which recordings a file may be
// (AcoustIDLookupWorker.IdentifyRecordings). // (AcoustIDLookupWorker.IdentifyRecordings).
type RecordingIdentifier func(ctx context.Context, path string) ([]string, error) type RecordingIdentifier func(ctx context.Context, path string) ([]string, error)
@@ -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. // Without a track list that decides, nothing is removed.
func TestResolveDuplicates_LeavesAnUndecidedSlotForTheOperator_Integration(t *testing.T) { func TestResolveDuplicates_LeavesAnUndecidedSlotForTheOperator_Integration(t *testing.T) {
f := newOneAlbumFixture(t, "acoustic", "Void", "Reach") f := newOneAlbumFixture(t, "acoustic", "Void", "Reach")
+3 -1
View File
@@ -200,7 +200,9 @@ func settleWrongSlots(
} }
if len(tracks) == 0 && fetches > 0 && neverRead(ctx, q, rg) { if len(tracks) == 0 && fetches > 0 && neverRead(ctx, q, rg) {
fetches-- 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) logger.Info("duplicate resolve: fetching the album's track list failed", "release_group", rg, "err", err)
if errors.Is(err, musicbrainz.ErrUnreachable) { if errors.Is(err, musicbrainz.ErrUnreachable) {
fetches = 0 fetches = 0
+88
View File
@@ -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,
}
}
+67
View File
@@ -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)
}
}
+14 -1
View File
@@ -22,6 +22,7 @@ import (
"git.fabledsword.com/bvandeusen/minstrel/internal/coverart" "git.fabledsword.com/bvandeusen/minstrel/internal/coverart"
"git.fabledsword.com/bvandeusen/minstrel/internal/eventbus" "git.fabledsword.com/bvandeusen/minstrel/internal/eventbus"
"git.fabledsword.com/bvandeusen/minstrel/internal/library" "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/mailer"
"git.fabledsword.com/bvandeusen/minstrel/internal/netsettings" "git.fabledsword.com/bvandeusen/minstrel/internal/netsettings"
"git.fabledsword.com/bvandeusen/minstrel/internal/playevents" "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; // 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. // one is built (and never run) so the admin routes still answer.
AcoustIDLookup *library.AcoustIDLookupWorker 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 // 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. // nightly schedule. Nil builds one that runs only when an admin asks.
Backups *backup.Service Backups *backup.Service
@@ -188,11 +193,19 @@ func (s *Server) Router() http.Handler {
} }
acoustIDLookup = library.NewAcoustIDLookupWorker(s.Pool, s.Logger, acoustIDSettings, nil) 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 backups := s.Backups
if backups == nil { if backups == nil {
backups = backup.NewService(s.Pool, s.Logger, buildinfo.Version) 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 // /api/admin/scan is the only admin route owned by the server package
// (it needs the Scanner). Register it as a single inline-middleware // (it needs the Scanner). Register it as a single inline-middleware
// route — using r.Route("/api/admin", ...) here would create a second // route — using r.Route("/api/admin", ...) here would create a second
+10 -2
View File
@@ -40,6 +40,11 @@ type Worker struct {
tick time.Duration tick time.Duration
batch int32 batch int32
topK int // per artist 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, // NewWorker constructs a worker with production defaults: 1h tick,
@@ -73,17 +78,20 @@ func (w *Worker) Run(ctx context.Context) {
} }
} }
// tickOnce drains one batch of tracks and one batch of artists, then // tickOnce drains one batch of tracks and one batch of artists, unless an
// re-resolves every cached answer against the library. Per-row errors are // 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. // logged and skipped. 429 aborts the fetching, not the resolve.
func (w *Worker) tickOnce(ctx context.Context) error { func (w *Worker) tickOnce(ctx context.Context) error {
q := dbq.New(w.pool) q := dbq.New(w.pool)
if w.Enabled == nil || w.Enabled() {
if err := w.tickTracks(ctx, q); err != nil { if err := w.tickTracks(ctx, q); err != nil {
return err return err
} }
if err := w.tickArtists(ctx, q); err != nil { if err := w.tickArtists(ctx, q); err != nil {
return err return err
} }
}
// Links recordings that reached the library since their seed was fetched: // Links recordings that reached the library since their seed was fetched:
// a scan, an import, an MBID from the AcoustID lookup. // a scan, an import, an MBID from the AcoustID lookup.
if err := q.ResolveListenBrainzTrackEdges(ctx, nil); err != nil { if err := q.ResolveListenBrainzTrackEdges(ctx, nil); err != nil {
@@ -624,3 +624,32 @@ func TestTickOnce_PermanentErrorCountsAsFetched(t *testing.T) {
t.Errorf("fetches recorded: tracks=%d artists=%d, want 1 and 1", tracks, artists) 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")
}
}
+18
View File
@@ -318,6 +318,24 @@ export async function updateLoudnessSettings(s: LoudnessSettings): Promise<Loudn
return api.put<LoudnessSettings>('/api/admin/library/loudness-settings', s); return api.put<LoudnessSettings>('/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<LookupSettings> {
return api.get<LookupSettings>('/api/admin/lookup-settings');
}
export async function updateLookupSettings(s: LookupSettings): Promise<LookupSettings> {
return api.put<LookupSettings>('/api/admin/lookup-settings', s);
}
// The library's folders ----------------------------------------------- // The library's folders -----------------------------------------------
export type LibraryFolder = { export type LibraryFolder = {
@@ -0,0 +1,81 @@
<script lang="ts">
import { onMount } from 'svelte';
import { getLookupSettings, updateLookupSettings, type LookupSettings } from '#lib/api/admin.js';
import { errMessage } from '#lib/api/errors.js';
import { pushToast } from '#lib/stores/toast.svelte.js';
import SettingsGroup from '#lib/components/settings/SettingsGroup.svelte';
import SettingRow from '#lib/components/settings/SettingRow.svelte';
// The outside lookups that no cover art or tag source covers, each with
// a switch that saves as it is flipped. Both start on; turning one off
// stops the requests and keeps what was already fetched.
let settings = $state<LookupSettings | null>(null);
let saving = $state(false);
let loadError = $state(false);
async function load() {
try {
settings = await getLookupSettings();
loadError = false;
} catch {
loadError = true;
}
}
onMount(load);
async function flip(key: keyof LookupSettings, on: boolean) {
if (!settings) return;
const before = settings;
settings = { ...settings, [key]: on };
saving = true;
try {
settings = await updateLookupSettings(settings);
} catch (e) {
settings = before;
pushToast(`Couldn't save: ${errMessage(e)}`, 'error');
} finally {
saving = false;
}
}
const rows: { key: keyof LookupSettings; label: string; hint: string }[] = [
{
key: 'listenbrainz_similarity',
label: 'ListenBrainz similar songs',
hint: 'Which songs and artists go together, for radio and the mixes.'
},
{
key: 'musicbrainz_track_lists',
label: 'MusicBrainz track lists',
hint: "An album's songs, so the duplicate resolver can spot a misfiled copy."
}
];
</script>
<SettingsGroup title="Other lookups" hint="Asked in the background; what was already fetched is kept.">
{#if settings}
{#each rows as row (row.key)}
<SettingRow label={row.label} hint={row.hint} for="lookup-{row.key}">
<input
id="lookup-{row.key}"
type="checkbox"
role="switch"
aria-checked={settings[row.key]}
checked={settings[row.key]}
disabled={saving}
onchange={(e) => flip(row.key, e.currentTarget.checked)}
class="h-4 w-4 cursor-pointer accent-accent"
/>
</SettingRow>
{/each}
{:else if loadError}
<p class="px-4 py-3 text-sm text-error-fg">
Couldn't load these settings.
<button type="button" class="underline hover:no-underline" onclick={load}>Try again</button>
</p>
{:else}
<p class="px-4 py-3 text-sm text-text-secondary">Loading…</p>
{/if}
</SettingsGroup>
@@ -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();
});
});
+3 -1
View File
@@ -12,11 +12,12 @@
import { qk } from '#lib/api/queries.js'; import { qk } from '#lib/api/queries.js';
import AcoustIDCard from '#lib/components/AcoustIDCard.svelte'; import AcoustIDCard from '#lib/components/AcoustIDCard.svelte';
import ProviderGroup from '#lib/components/admin/ProviderGroup.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'; import SettingsColumns from '#lib/components/settings/SettingsColumns.svelte';
// Admin › Metadata sources: the outside sources Minstrel asks // Admin › Metadata sources: the outside sources Minstrel asks
// about your music. AcoustID names a recording from its sound; the cover // 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 client = useQueryClient();
const coverStore = createCoverProvidersQuery(); const coverStore = createCoverProvidersQuery();
@@ -88,5 +89,6 @@
keyPlaceholder="Paste a key to use this source" keyPlaceholder="Paste a key to use this source"
note={tagNote} note={tagNote}
/> />
<LookupSettingsCard />
{/snippet} {/snippet}
</SettingsColumns> </SettingsColumns>
@@ -20,7 +20,10 @@ vi.mock('#lib/api/admin.js', () => ({
getAcoustID: vi.fn(() => new Promise(() => {})), getAcoustID: vi.fn(() => new Promise(() => {})),
updateAcoustIDSettings: vi.fn(), updateAcoustIDSettings: vi.fn(),
runAcoustIDLookup: 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'; import MetadataPage from './+page.svelte';