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
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:
@@ -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
@@ -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
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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);
|
||||
@@ -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 *;
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user