// 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, } }