refactor(providers): cover art and tags share one registry and settings service (#8002)

coverart and tags each carried a line-for-line copy of the provider
registry and the settings service: reconcile at boot, seal and reveal
API keys, bump the sources version when the enabled set or the
registered set changes. A fix to either had to be made twice.

internal/providers now holds Registry, Service (over a small Store
interface) and EnabledAs[T]. Each family keeps its own tables, provider
set and capabilities: a 40-line Store adapter over its sqlc queries and
its capability views (EnabledAlbumProviders, EnabledTrackTagProviders).
Provider, ProviderSettings, TestableProvider, ProviderInfo and
ProviderUpdatePatch stay as the families' names for the shared types.
The service has unit tests over an in-memory store.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-26 12:57:19 -05:00
co-authored by Claude Opus 5.5
parent 58fb2bbe9d
commit 487e11f59f
8 changed files with 769 additions and 830 deletions
+35 -112
View File
@@ -3,53 +3,20 @@ package coverart
import (
"context"
"errors"
"fmt"
"sync"
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
"git.fabledsword.com/bvandeusen/minstrel/internal/providers"
)
// Provider is the base shape every cover-art source implements.
// Providers register themselves at init() time via Register(). The
// enricher reads the current per-provider settings and dispatches to
// the capability methods below.
type Provider interface {
// ID is a stable lowercase token persisted in DB columns
// (cover_art_source / artist_art_source) and the
// cover_art_provider_settings.provider_id key, and shown in the admin UI.
ID() string
// Provider is the base shape every cover-art source implements; the
// capability interfaces below say what it can fetch. Providers register at
// init() via Register(). Its ID is persisted in cover_art_source /
// artist_art_source and keyed in cover_art_provider_settings.
type Provider = providers.Provider
// DisplayName is the human-readable label shown in the admin
// Settings card.
DisplayName() string
// RequiresAPIKey reports whether the provider needs a key to
// function. True for theaudiodb / fanart.tv; false for mbcaa.
// The admin UI uses this to show or hide the api_key text field;
// it does NOT gate the enabled toggle (per the no-coercive-
// settings principle, providers with usable defaults — such as
// TheAudioDB's public test key — ship working).
RequiresAPIKey() bool
// DefaultEnabled is whether a freshly-installed Minstrel ships
// with this provider on. Providers that need an API key ship off.
DefaultEnabled() bool
// Configure receives the admin's settings (api_key, enabled
// flag) and applies them. Called at boot during reconciliation
// and on every admin PATCH. Implementations must be idempotent
// and goroutine-safe (the enricher may be reading concurrently).
Configure(ProviderSettings) error
}
// ProviderSettings is the runtime config a provider receives when
// Configure() is called. Providers may interpret an empty APIKey
// however they wish — TheAudioDB falls back to its public test key,
// MBCAA ignores the field entirely.
type ProviderSettings struct {
Enabled bool
APIKey string
}
// ProviderSettings is what Configure receives. TheAudioDB falls back to
// its public test key on an empty APIKey; MBCAA ignores the key.
type ProviderSettings = providers.Settings
// ArtistRef is the lookup key passed to ArtistArtProvider.FetchArtistArt.
// MBID is preferred when present; Name is the always-populated fallback
@@ -92,22 +59,16 @@ type ArtistArtProvider interface {
FetchArtistArt(ctx context.Context, ref ArtistRef) (thumb, fanart []byte, err error)
}
// TestableProvider is an opt-in capability: providers that can answer
// "is my config working?" without performing a full enrichment cycle.
// Used by the admin Test-Connection button. MBCAA and TheAudioDB
// implement this.
type TestableProvider interface {
Provider
TestConnection(ctx context.Context) error
}
// TestableProvider can answer the admin Test-Connection button. MBCAA and
// TheAudioDB implement it.
type TestableProvider = providers.Testable
// ErrNotTestable is returned by the SettingsService.TestProvider
// method when the named provider doesn't implement TestableProvider.
var ErrNotTestable = errors.New("coverart: provider does not support test connection")
// ErrProviderNotFound is returned when the named provider is not
// registered.
var ErrProviderNotFound = errors.New("coverart: provider not registered")
// ErrNotTestable and ErrProviderNotFound are the shared providers errors,
// so a handler can test for either family's with one errors.Is.
var (
ErrNotTestable = providers.ErrNotTestable
ErrProviderNotFound = providers.ErrProviderNotFound
)
// ErrNotFound indicates the upstream confirmed there is no art for
// this MBID — a terminal-this-pass result. The enricher treats this
@@ -124,63 +85,25 @@ var ErrNotFound = apierror.ErrNotFound
// scan pass can retry.
var ErrTransient = errors.New("coverart: transient error")
// registry is the package-private list of all compiled-in providers.
// Providers register at init() via Register(). The enricher iterates
// over this list filtered by the current per-provider Settings.
var registry = struct {
mu sync.Mutex
providers []Provider
}{}
// registry is every compiled-in cover-art provider. The enricher iterates
// it filtered by the current settings.
var registry = providers.NewRegistry("coverart")
// Register adds a provider to the registry. Must be called from
// init() of a provider file (provider_mbcaa.go, provider_theaudiodb.go,
// etc.). Calling twice with the same ID panics — providers are
// compiled-in, duplicate registration is a build-time bug.
func Register(p Provider) {
registry.mu.Lock()
defer registry.mu.Unlock()
for _, existing := range registry.providers {
if existing.ID() == p.ID() {
panic(fmt.Sprintf("coverart: duplicate provider ID %q", p.ID()))
}
}
registry.providers = append(registry.providers, p)
}
// Register adds a provider. Call it from a provider file's init(); a
// duplicate ID panics.
func Register(p Provider) { registry.Register(p) }
// AllProviders returns a snapshot of all registered providers in
// registration order. Caller must not mutate the returned slice.
func AllProviders() []Provider {
registry.mu.Lock()
defer registry.mu.Unlock()
out := make([]Provider, len(registry.providers))
copy(out, registry.providers)
return out
}
// AllProviders returns a snapshot of every registered provider in
// registration order.
func AllProviders() []Provider { return registry.All() }
// ProviderByID looks up a registered provider by ID. Returns
// ErrProviderNotFound if no such provider has registered.
func ProviderByID(id string) (Provider, error) {
registry.mu.Lock()
defer registry.mu.Unlock()
for _, p := range registry.providers {
if p.ID() == id {
return p, nil
}
}
return nil, ErrProviderNotFound
}
// ProviderByID returns the registered provider with id, or
// ErrProviderNotFound.
func ProviderByID(id string) (Provider, error) { return registry.ByID(id) }
// resetRegistryForTests clears the registry. Test-only helper
// (provider_test.go); never called from production code.
func resetRegistryForTests() {
registry.mu.Lock()
defer registry.mu.Unlock()
registry.providers = nil
}
// resetRegistryForTests empties the registry. Tests only.
func resetRegistryForTests() { registry.ResetForTests() }
// ResetRegistryForTests is an exported wrapper around resetRegistryForTests
// for use by tests in other packages (e.g. internal/api). Never call from
// production code.
func ResetRegistryForTests() {
resetRegistryForTests()
}
// ResetRegistryForTests empties the registry, for tests in other packages
// (internal/api). Tests only.
func ResetRegistryForTests() { registry.ResetForTests() }
+65 -340
View File
@@ -2,383 +2,108 @@ package coverart
import (
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
"log/slog"
"sort"
"strings"
"sync"
"github.com/jackc/pgx/v5/pgxpool"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
"git.fabledsword.com/bvandeusen/minstrel/internal/providers"
"git.fabledsword.com/bvandeusen/minstrel/internal/secret"
)
// SettingsService reconciles the registry of compiled-in providers
// with the cover_art_provider_settings table at boot, and on every
// admin-initiated update. It owns the cover_art_sources_meta
// singleton's current_version stamp, bumping it whenever the
// *enabled set* of providers changes.
// ProviderUpdatePatch is the admin PATCH body; see providers.UpdatePatch.
type ProviderUpdatePatch = providers.UpdatePatch
// ProviderInfo is a provider as GET /api/admin/cover-sources shows it.
type ProviderInfo = providers.Info
// SettingsService is the cover-art providers' settings: the shared
// providers.Service over cover_art_provider_settings and the
// cover_art_sources_meta version, plus the cover-art capability views.
type SettingsService struct {
pool *pgxpool.Pool
logger *slog.Logger
mu sync.RWMutex
enabledIDs map[string]bool // provider_id → enabled
apiKeys map[string]string // provider_id → api_key (empty if NULL)
currentVersion int32
*providers.Service
}
// ProviderUpdatePatch is the admin-PATCH body shape. nil pointers
// mean "leave unchanged"; non-nil means "set to this value (which
// may be empty string for api_key clearing)".
type ProviderUpdatePatch struct {
Enabled *bool
APIKey *string
}
// ProviderInfo is the SettingsService's view of a provider for the
// admin GET handler. Combines registry metadata with DB settings.
type ProviderInfo struct {
ID string
DisplayName string
RequiresAPIKey bool
Supports []string // "album_cover", "artist_thumb", "artist_fanart"
Enabled bool
APIKeySet bool
DisplayOrder int32
Testable bool
}
// NewSettingsService boots the service: reads the DB rows, INSERTs
// defaults for any registered provider missing a row, calls
// Configure() on every registered provider with the row data, and
// loads the current_version. Returns the populated service.
// NewSettingsService reconciles the registry with the settings table and
// Configures every provider.
func NewSettingsService(ctx context.Context, pool *pgxpool.Pool, logger *slog.Logger) (*SettingsService, error) {
s := &SettingsService{
pool: pool,
logger: logger,
enabledIDs: map[string]bool{},
apiKeys: map[string]string{},
svc, err := providers.NewService(ctx, providers.Config{
Registry: registry,
Store: settingsStore{q: dbq.New(pool)},
KeyColumn: secret.CoverArtAPIKey,
Supports: supports,
Logger: logger,
})
if err != nil {
return nil, fmt.Errorf("cover art settings boot: %w", err)
}
if err := s.reconcile(ctx); err != nil {
return nil, fmt.Errorf("settings service boot: %w", err)
}
return s, nil
return &SettingsService{svc}, nil
}
// reconcile reads the DB, INSERTs defaults for missing providers,
// calls Configure() on each registered provider, and loads the
// current_version into the cache.
func (s *SettingsService) reconcile(ctx context.Context) error {
q := dbq.New(s.pool)
// Insert defaults for any registered provider missing a row.
registered := AllProviders()
for i, p := range registered {
if err := q.UpsertProviderSettings(ctx, dbq.UpsertProviderSettingsParams{
ProviderID: p.ID(),
Enabled: p.DefaultEnabled(),
DisplayOrder: int32(i),
}); err != nil {
return fmt.Errorf("upsert provider %q: %w", p.ID(), err)
}
}
// Read all rows back.
rows, err := q.ListProviderSettings(ctx)
if err != nil {
return fmt.Errorf("list provider settings: %w", err)
}
// Build the lookup maps and call Configure on each registered
// provider with the corresponding row data.
settingsByID := map[string]dbq.CoverArtProviderSetting{}
for _, r := range rows {
settingsByID[r.ProviderID] = r
}
s.mu.Lock()
defer s.mu.Unlock()
s.enabledIDs = map[string]bool{}
s.apiKeys = map[string]string{}
for _, p := range registered {
row, ok := settingsByID[p.ID()]
if !ok {
s.logger.Warn("settings: missing row after upsert", "provider", p.ID())
continue
}
key := ""
if row.ApiKey != nil {
key = secret.Reveal(secret.CoverArtAPIKey.Purpose(), row.ProviderID, *row.ApiKey)
}
s.enabledIDs[p.ID()] = row.Enabled
s.apiKeys[p.ID()] = key
if err := p.Configure(ProviderSettings{Enabled: row.Enabled, APIKey: key}); err != nil {
s.logger.Warn("settings: provider Configure failed",
"provider", p.ID(), "err", err)
}
}
v, err := q.GetCurrentSourcesVersion(ctx)
if err != nil {
return fmt.Errorf("get current sources version: %w", err)
}
s.currentVersion = v
return nil
}
// EnabledAlbumProviders returns the enabled providers that implement
// AlbumCoverProvider, in registration order. Snapshot — caller must
// not mutate.
// EnabledAlbumProviders returns the enabled album-cover providers, in
// registration order.
func (s *SettingsService) EnabledAlbumProviders() []AlbumCoverProvider {
s.mu.RLock()
defer s.mu.RUnlock()
var out []AlbumCoverProvider
for _, p := range AllProviders() {
if !s.enabledIDs[p.ID()] {
continue
}
if ap, ok := p.(AlbumCoverProvider); ok {
out = append(out, ap)
}
}
return out
return providers.EnabledAs[AlbumCoverProvider](s.Service)
}
// EnabledArtistProviders is the parallel for ArtistArtProvider.
// EnabledArtistProviders returns the enabled artist-image providers, in
// registration order.
func (s *SettingsService) EnabledArtistProviders() []ArtistArtProvider {
s.mu.RLock()
defer s.mu.RUnlock()
var out []ArtistArtProvider
for _, p := range AllProviders() {
if !s.enabledIDs[p.ID()] {
continue
}
if ap, ok := p.(ArtistArtProvider); ok {
out = append(out, ap)
}
return providers.EnabledAs[ArtistArtProvider](s.Service)
}
// supports names what p can fetch, for the admin view.
func supports(p Provider) []string {
var out []string
if _, ok := p.(AlbumCoverProvider); ok {
out = append(out, "album_cover")
}
if _, ok := p.(ArtistArtProvider); ok {
out = append(out, "artist_thumb", "artist_fanart")
}
return out
}
// CurrentVersion returns the current sources-set version (the stamp
// the enricher writes onto rows it processes).
func (s *SettingsService) CurrentVersion() int32 {
s.mu.RLock()
defer s.mu.RUnlock()
return s.currentVersion
// settingsStore is cover art's providers.Store.
type settingsStore struct{ q *dbq.Queries }
func (st settingsStore) EnsureRow(ctx context.Context, id string, enabled bool, order int32) error {
return st.q.UpsertProviderSettings(ctx, dbq.UpsertProviderSettingsParams{
ProviderID: id, Enabled: enabled, DisplayOrder: order,
})
}
// UpdateProvider applies an admin-UI patch. Returns versionBumped=true
// if the change altered the *enabled set* (not on key changes).
// Re-runs the provider's Configure() with the new settings.
func (s *SettingsService) UpdateProvider(ctx context.Context, providerID string, patch ProviderUpdatePatch) (bool, error) {
p, err := ProviderByID(providerID)
func (st settingsStore) List(ctx context.Context) ([]providers.Row, error) {
rows, err := st.q.ListProviderSettings(ctx)
if err != nil {
return false, err
return nil, err
}
q := dbq.New(s.pool)
// Compute current enabled-set signature before applying the patch.
s.mu.RLock()
beforeSig := enabledSetSignature(s.enabledIDs)
// Use the cached enabled value when the patch doesn't specify it,
// since the sqlc-generated Enabled field is bool (not *bool) and
// COALESCE($2, enabled) only works with a nullable param. Passing
// the current value when nil achieves the same "leave unchanged"
// semantics.
currentEnabled := s.enabledIDs[providerID]
s.mu.RUnlock()
enabledVal := currentEnabled
if patch.Enabled != nil {
enabledVal = *patch.Enabled
out := make([]providers.Row, len(rows))
for i, r := range rows {
out[i] = providers.Row{ProviderID: r.ProviderID, Enabled: r.Enabled, APIKey: r.ApiKey}
}
// Apply DB update. The sqlc-generated UpdateProviderSettingsParams
// uses Column3/ApiKey because the underlying SQL has $3::boolean
// (apiKeyChanged flag) and $4 (api_key value). The actual generated
// field for $4 is ApiKey *string.
apiKeyChanged := patch.APIKey != nil
sealedKey, err := secret.SealPtr(secret.CoverArtAPIKey.Purpose(), providerID, patch.APIKey)
if err != nil {
return false, fmt.Errorf("seal provider api key: %w", err)
}
if err := q.UpdateProviderSettings(ctx, dbq.UpdateProviderSettingsParams{
ProviderID: providerID,
Enabled: enabledVal,
Column3: apiKeyChanged,
ApiKey: sealedKey,
}); err != nil {
return false, fmt.Errorf("update provider settings: %w", err)
}
// Re-read rows + re-cache + Configure the changed provider.
rows, err := q.ListProviderSettings(ctx)
if err != nil {
return false, fmt.Errorf("re-list provider settings: %w", err)
}
s.mu.Lock()
defer s.mu.Unlock()
for _, r := range rows {
key := ""
if r.ApiKey != nil {
key = secret.Reveal(secret.CoverArtAPIKey.Purpose(), r.ProviderID, *r.ApiKey)
}
s.enabledIDs[r.ProviderID] = r.Enabled
s.apiKeys[r.ProviderID] = key
if r.ProviderID == providerID {
if err := p.Configure(ProviderSettings{Enabled: r.Enabled, APIKey: key}); err != nil {
s.logger.Warn("provider Configure failed after update",
"provider", providerID, "err", err)
}
}
}
afterSig := enabledSetSignature(s.enabledIDs)
if beforeSig == afterSig {
return false, nil
}
newVersion, err := q.BumpSourcesVersion(ctx)
if err != nil {
return false, fmt.Errorf("bump sources version: %w", err)
}
s.currentVersion = newVersion
return true, nil
return out, nil
}
// enabledSetSignature returns a deterministic string of the
// currently-enabled provider IDs.
func enabledSetSignature(enabledIDs map[string]bool) string {
ids := make([]string, 0, len(enabledIDs))
for id, on := range enabledIDs {
if on {
ids = append(ids, id)
}
}
sort.Strings(ids)
return strings.Join(ids, ",")
func (st settingsStore) Save(ctx context.Context, id string, enabled, keyChanged bool, sealedKey *string) error {
return st.q.UpdateProviderSettings(ctx, dbq.UpdateProviderSettingsParams{
ProviderID: id, Enabled: enabled, Column3: keyChanged, ApiKey: sealedKey,
})
}
// BumpVersionIfProvidersChanged compares the current registered-provider
// set (by ID) to the last set seen on a prior successful boot. If
// different, it atomically increments cover_art_sources_meta.current_version
// and stores the new hash, returning (newVersion, true, nil). If
// unchanged, returns (currentVersion, false, nil) without touching the DB.
//
// Used at boot to ensure rows previously settled to 'none' get re-tried
// once after a provider chain change (an update registers a new provider,
// or removes one). The version bump makes 'none' rows eligible on the next
// enrichment pass with no manual step.
func (s *SettingsService) BumpVersionIfProvidersChanged(ctx context.Context) (version int32, bumped bool, err error) {
hash := registeredProvidersHash()
q := dbq.New(s.pool)
stored, qerr := q.GetCoverArtProvidersHash(ctx)
if qerr != nil {
return 0, false, fmt.Errorf("get providers hash: %w", qerr)
}
if stored == hash {
return s.CurrentVersion(), false, nil
}
newVer, berr := q.BumpVersionAndSetProvidersHash(ctx, hash)
if berr != nil {
return 0, false, fmt.Errorf("bump version: %w", berr)
}
// Update the in-memory version so the next enrichment pass sees the new value.
s.mu.Lock()
s.currentVersion = newVer
s.mu.Unlock()
return newVer, true, nil
func (st settingsStore) Version(ctx context.Context) (int32, error) {
return st.q.GetCurrentSourcesVersion(ctx)
}
// registeredProvidersHash returns the SHA-256 hex of the sorted,
// colon-joined registered provider IDs.
func registeredProvidersHash() string {
provs := AllProviders()
ids := make([]string, 0, len(provs))
for _, p := range provs {
ids = append(ids, p.ID())
}
sort.Strings(ids)
joined := strings.Join(ids, ":")
sum := sha256.Sum256([]byte(joined))
return hex.EncodeToString(sum[:])
func (st settingsStore) BumpVersion(ctx context.Context) (int32, error) {
return st.q.BumpSourcesVersion(ctx)
}
// BumpVersion unconditionally increments cover_art_sources_meta.current_version
// and returns the new value. Used by the manual "Re-search missing art"
// admin endpoint, to re-attempt every 'none' row
// on the next enrichment pass.
//
// Distinct from BumpVersionIfProvidersChanged: that method is the boot-
// time auto-bump and skips the DB write when the registered-provider
// hash matches. This method always writes.
func (s *SettingsService) BumpVersion(ctx context.Context) (int32, error) {
q := dbq.New(s.pool)
// Reuse BumpVersionAndSetProvidersHash with the current registered-
// providers hash; this keeps the stored hash consistent (a manual
// bump is conceptually equivalent to "force the auto-bump path").
newVer, err := q.BumpVersionAndSetProvidersHash(ctx, registeredProvidersHash())
if err != nil {
return 0, fmt.Errorf("bump version: %w", err)
}
s.mu.Lock()
s.currentVersion = newVer
s.mu.Unlock()
return newVer, nil
func (st settingsStore) ProvidersHash(ctx context.Context) (string, error) {
return st.q.GetCoverArtProvidersHash(ctx)
}
// TestProvider invokes TestConnection on the named provider if it
// implements TestableProvider. Returns ErrNotTestable if the
// provider doesn't, ErrProviderNotFound if not registered.
func (s *SettingsService) TestProvider(ctx context.Context, providerID string) error {
p, err := ProviderByID(providerID)
if err != nil {
return err
}
tp, ok := p.(TestableProvider)
if !ok {
return ErrNotTestable
}
return tp.TestConnection(ctx)
}
// ListProviderInfo builds the wire-shaped slice for GET
// /api/admin/cover-sources. Returns providers in registration order.
func (s *SettingsService) ListProviderInfo() []ProviderInfo {
s.mu.RLock()
defer s.mu.RUnlock()
var out []ProviderInfo
for i, p := range AllProviders() {
info := ProviderInfo{
ID: p.ID(),
DisplayName: p.DisplayName(),
RequiresAPIKey: p.RequiresAPIKey(),
Enabled: s.enabledIDs[p.ID()],
APIKeySet: s.apiKeys[p.ID()] != "",
DisplayOrder: int32(i),
}
if _, ok := p.(AlbumCoverProvider); ok {
info.Supports = append(info.Supports, "album_cover")
}
if _, ok := p.(ArtistArtProvider); ok {
info.Supports = append(info.Supports, "artist_thumb", "artist_fanart")
}
if _, ok := p.(TestableProvider); ok {
info.Testable = true
}
out = append(out, info)
}
return out
func (st settingsStore) BumpVersionForProviders(ctx context.Context, hash string) (int32, error) {
return st.q.BumpVersionAndSetProvidersHash(ctx, hash)
}
-18
View File
@@ -334,21 +334,3 @@ func TestSettingsService_BumpVersion_Increments(t *testing.T) {
t.Errorf("second newVer = %d, want %d", newVer2, afterFirst+1)
}
}
// TestRegisteredProvidersHash_StableAcrossOrder: registry order
// shouldn't matter because we sort before hashing.
func TestRegisteredProvidersHash_StableAcrossOrder(t *testing.T) {
// Hash is a function of the registered set; in this test it just
// needs to be deterministic and non-empty.
h1 := registeredProvidersHash()
h2 := registeredProvidersHash()
if h1 != h2 {
t.Errorf("hash is not deterministic: %q vs %q", h1, h2)
}
if h1 == "" {
t.Errorf("hash empty; expected at least one provider registered (or empty set is valid)")
}
if len(h1) != 64 {
t.Errorf("hash length = %d, want 64 (SHA-256 hex)", len(h1))
}
}