The first public release of Fabled Minstrel #158

Merged
bvandeusen merged 256 commits from dev into main 2026-12-03 21:41:58 -05:00
8 changed files with 769 additions and 830 deletions
Showing only changes of commit 487e11f59f - Show all commits
+35 -112
View File
@@ -3,53 +3,20 @@ package coverart
import ( import (
"context" "context"
"errors" "errors"
"fmt"
"sync"
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror" "git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
"git.fabledsword.com/bvandeusen/minstrel/internal/providers"
) )
// Provider is the base shape every cover-art source implements. // Provider is the base shape every cover-art source implements; the
// Providers register themselves at init() time via Register(). The // capability interfaces below say what it can fetch. Providers register at
// enricher reads the current per-provider settings and dispatches to // init() via Register(). Its ID is persisted in cover_art_source /
// the capability methods below. // artist_art_source and keyed in cover_art_provider_settings.
type Provider interface { type Provider = providers.Provider
// 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
// DisplayName is the human-readable label shown in the admin // ProviderSettings is what Configure receives. TheAudioDB falls back to
// Settings card. // its public test key on an empty APIKey; MBCAA ignores the key.
DisplayName() string type ProviderSettings = providers.Settings
// 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
}
// ArtistRef is the lookup key passed to ArtistArtProvider.FetchArtistArt. // ArtistRef is the lookup key passed to ArtistArtProvider.FetchArtistArt.
// MBID is preferred when present; Name is the always-populated fallback // 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) FetchArtistArt(ctx context.Context, ref ArtistRef) (thumb, fanart []byte, err error)
} }
// TestableProvider is an opt-in capability: providers that can answer // TestableProvider can answer the admin Test-Connection button. MBCAA and
// "is my config working?" without performing a full enrichment cycle. // TheAudioDB implement it.
// Used by the admin Test-Connection button. MBCAA and TheAudioDB type TestableProvider = providers.Testable
// implement this.
type TestableProvider interface {
Provider
TestConnection(ctx context.Context) error
}
// ErrNotTestable is returned by the SettingsService.TestProvider // ErrNotTestable and ErrProviderNotFound are the shared providers errors,
// method when the named provider doesn't implement TestableProvider. // so a handler can test for either family's with one errors.Is.
var ErrNotTestable = errors.New("coverart: provider does not support test connection") var (
ErrNotTestable = providers.ErrNotTestable
// ErrProviderNotFound is returned when the named provider is not ErrProviderNotFound = providers.ErrProviderNotFound
// registered. )
var ErrProviderNotFound = errors.New("coverart: provider not registered")
// ErrNotFound indicates the upstream confirmed there is no art for // ErrNotFound indicates the upstream confirmed there is no art for
// this MBID — a terminal-this-pass result. The enricher treats this // this MBID — a terminal-this-pass result. The enricher treats this
@@ -124,63 +85,25 @@ var ErrNotFound = apierror.ErrNotFound
// scan pass can retry. // scan pass can retry.
var ErrTransient = errors.New("coverart: transient error") var ErrTransient = errors.New("coverart: transient error")
// registry is the package-private list of all compiled-in providers. // registry is every compiled-in cover-art provider. The enricher iterates
// Providers register at init() via Register(). The enricher iterates // it filtered by the current settings.
// over this list filtered by the current per-provider Settings. var registry = providers.NewRegistry("coverart")
var registry = struct {
mu sync.Mutex
providers []Provider
}{}
// Register adds a provider to the registry. Must be called from // Register adds a provider. Call it from a provider file's init(); a
// init() of a provider file (provider_mbcaa.go, provider_theaudiodb.go, // duplicate ID panics.
// etc.). Calling twice with the same ID panics — providers are func Register(p Provider) { registry.Register(p) }
// 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)
}
// AllProviders returns a snapshot of all registered providers in // AllProviders returns a snapshot of every registered provider in
// registration order. Caller must not mutate the returned slice. // registration order.
func AllProviders() []Provider { func AllProviders() []Provider { return registry.All() }
registry.mu.Lock()
defer registry.mu.Unlock()
out := make([]Provider, len(registry.providers))
copy(out, registry.providers)
return out
}
// ProviderByID looks up a registered provider by ID. Returns // ProviderByID returns the registered provider with id, or
// ErrProviderNotFound if no such provider has registered. // ErrProviderNotFound.
func ProviderByID(id string) (Provider, error) { func ProviderByID(id string) (Provider, error) { return registry.ByID(id) }
registry.mu.Lock()
defer registry.mu.Unlock()
for _, p := range registry.providers {
if p.ID() == id {
return p, nil
}
}
return nil, ErrProviderNotFound
}
// resetRegistryForTests clears the registry. Test-only helper // resetRegistryForTests empties the registry. Tests only.
// (provider_test.go); never called from production code. func resetRegistryForTests() { registry.ResetForTests() }
func resetRegistryForTests() {
registry.mu.Lock()
defer registry.mu.Unlock()
registry.providers = nil
}
// ResetRegistryForTests is an exported wrapper around resetRegistryForTests // ResetRegistryForTests empties the registry, for tests in other packages
// for use by tests in other packages (e.g. internal/api). Never call from // (internal/api). Tests only.
// production code. func ResetRegistryForTests() { registry.ResetForTests() }
func ResetRegistryForTests() {
resetRegistryForTests()
}
+77 -352
View File
@@ -2,383 +2,108 @@ package coverart
import ( import (
"context" "context"
"crypto/sha256"
"encoding/hex"
"fmt" "fmt"
"log/slog" "log/slog"
"sort"
"strings"
"sync"
"github.com/jackc/pgx/v5/pgxpool" "github.com/jackc/pgx/v5/pgxpool"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
"git.fabledsword.com/bvandeusen/minstrel/internal/providers"
"git.fabledsword.com/bvandeusen/minstrel/internal/secret" "git.fabledsword.com/bvandeusen/minstrel/internal/secret"
) )
// SettingsService reconciles the registry of compiled-in providers // ProviderUpdatePatch is the admin PATCH body; see providers.UpdatePatch.
// with the cover_art_provider_settings table at boot, and on every type ProviderUpdatePatch = providers.UpdatePatch
// admin-initiated update. It owns the cover_art_sources_meta
// singleton's current_version stamp, bumping it whenever the // ProviderInfo is a provider as GET /api/admin/cover-sources shows it.
// *enabled set* of providers changes. 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 { type SettingsService struct {
pool *pgxpool.Pool *providers.Service
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
} }
// ProviderUpdatePatch is the admin-PATCH body shape. nil pointers // NewSettingsService reconciles the registry with the settings table and
// mean "leave unchanged"; non-nil means "set to this value (which // Configures every provider.
// 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.
func NewSettingsService(ctx context.Context, pool *pgxpool.Pool, logger *slog.Logger) (*SettingsService, error) { func NewSettingsService(ctx context.Context, pool *pgxpool.Pool, logger *slog.Logger) (*SettingsService, error) {
s := &SettingsService{ svc, err := providers.NewService(ctx, providers.Config{
pool: pool, Registry: registry,
logger: logger, Store: settingsStore{q: dbq.New(pool)},
enabledIDs: map[string]bool{}, KeyColumn: secret.CoverArtAPIKey,
apiKeys: map[string]string{}, 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 &SettingsService{svc}, nil
return nil, fmt.Errorf("settings service boot: %w", err)
}
return s, nil
} }
// reconcile reads the DB, INSERTs defaults for missing providers, // EnabledAlbumProviders returns the enabled album-cover providers, in
// calls Configure() on each registered provider, and loads the // registration order.
// 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.
func (s *SettingsService) EnabledAlbumProviders() []AlbumCoverProvider { func (s *SettingsService) EnabledAlbumProviders() []AlbumCoverProvider {
s.mu.RLock() return providers.EnabledAs[AlbumCoverProvider](s.Service)
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
} }
// EnabledArtistProviders is the parallel for ArtistArtProvider. // EnabledArtistProviders returns the enabled artist-image providers, in
// registration order.
func (s *SettingsService) EnabledArtistProviders() []ArtistArtProvider { func (s *SettingsService) EnabledArtistProviders() []ArtistArtProvider {
s.mu.RLock() return providers.EnabledAs[ArtistArtProvider](s.Service)
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 out
} }
// CurrentVersion returns the current sources-set version (the stamp // supports names what p can fetch, for the admin view.
// the enricher writes onto rows it processes). func supports(p Provider) []string {
func (s *SettingsService) CurrentVersion() int32 { var out []string
s.mu.RLock()
defer s.mu.RUnlock()
return s.currentVersion
}
// 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)
if err != nil {
return false, 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
}
// 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
}
// 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, ",")
}
// 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
}
// 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[:])
}
// 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
}
// 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 { if _, ok := p.(AlbumCoverProvider); ok {
info.Supports = append(info.Supports, "album_cover") out = append(out, "album_cover")
} }
if _, ok := p.(ArtistArtProvider); ok { if _, ok := p.(ArtistArtProvider); ok {
info.Supports = append(info.Supports, "artist_thumb", "artist_fanart") out = append(out, "artist_thumb", "artist_fanart")
}
if _, ok := p.(TestableProvider); ok {
info.Testable = true
}
out = append(out, info)
} }
return out return out
} }
// 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,
})
}
func (st settingsStore) List(ctx context.Context) ([]providers.Row, error) {
rows, err := st.q.ListProviderSettings(ctx)
if err != nil {
return nil, err
}
out := make([]providers.Row, len(rows))
for i, r := range rows {
out[i] = providers.Row{ProviderID: r.ProviderID, Enabled: r.Enabled, APIKey: r.ApiKey}
}
return out, nil
}
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,
})
}
func (st settingsStore) Version(ctx context.Context) (int32, error) {
return st.q.GetCurrentSourcesVersion(ctx)
}
func (st settingsStore) BumpVersion(ctx context.Context) (int32, error) {
return st.q.BumpSourcesVersion(ctx)
}
func (st settingsStore) ProvidersHash(ctx context.Context) (string, error) {
return st.q.GetCoverArtProvidersHash(ctx)
}
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) 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))
}
}
+112
View File
@@ -0,0 +1,112 @@
// Package providers is the frame the pluggable outside sources hang on:
// cover-art sources (internal/coverart) and tag sources (internal/tags).
//
// Each family keeps its own tables, provider set and capabilities. What they
// share lives here: the compiled-in registry, the settings service that
// reconciles it with the family's settings table (enabled flags, sealed API
// keys, the sources version the enricher stamps), and the admin views of
// it. A fix to key sealing or to the version bump is made once.
package providers
import (
"context"
"errors"
"fmt"
"sync"
)
// Provider is the base shape every source implements.
type Provider interface {
// ID is a stable lowercase token: persisted as the row's source, keyed
// in the family's provider_settings table, and shown in the admin UI.
ID() string
// DisplayName is the label on the admin Settings card.
DisplayName() string
// RequiresAPIKey decides whether the admin UI shows a key field. It
// does not gate the enabled toggle: a source with a usable default
// ships working.
RequiresAPIKey() bool
// DefaultEnabled is whether a fresh install starts with the source on.
// Sources that need a key ship off.
DefaultEnabled() bool
// Configure applies the admin's settings. It is called at boot and on
// every admin change, and must be idempotent and safe to call while the
// enricher is reading.
Configure(Settings) error
}
// Settings is what a provider receives on Configure. An empty APIKey is
// the provider's to interpret: a public default key, or "not configured".
type Settings struct {
Enabled bool
APIKey string
}
// Testable providers can answer "is my config working?" without a full
// enrichment cycle, for the admin Test button.
type Testable interface {
Provider
TestConnection(ctx context.Context) error
}
// ErrProviderNotFound is returned for an ID no provider registered.
var ErrProviderNotFound = errors.New("provider not registered")
// ErrNotTestable is returned when testing a provider that isn't Testable.
var ErrNotTestable = errors.New("provider does not support test connection")
// Registry is one family's compiled-in providers, in registration order.
// Providers register from their file's init().
type Registry struct {
family string
mu sync.Mutex
providers []Provider
}
// NewRegistry returns an empty registry; family names it in panics.
func NewRegistry(family string) *Registry { return &Registry{family: family} }
// Register adds p. A duplicate ID panics: providers are compiled in, so a
// duplicate is a build bug.
func (r *Registry) Register(p Provider) {
r.mu.Lock()
defer r.mu.Unlock()
for _, existing := range r.providers {
if existing.ID() == p.ID() {
panic(fmt.Sprintf("%s: duplicate provider ID %q", r.family, p.ID()))
}
}
r.providers = append(r.providers, p)
}
// All returns a snapshot in registration order.
func (r *Registry) All() []Provider {
r.mu.Lock()
defer r.mu.Unlock()
out := make([]Provider, len(r.providers))
copy(out, r.providers)
return out
}
// ByID returns the registered provider with id, or ErrProviderNotFound.
func (r *Registry) ByID(id string) (Provider, error) {
r.mu.Lock()
defer r.mu.Unlock()
for _, p := range r.providers {
if p.ID() == id {
return p, nil
}
}
return nil, ErrProviderNotFound
}
// ResetForTests empties the registry. Tests only.
func (r *Registry) ResetForTests() {
r.mu.Lock()
defer r.mu.Unlock()
r.providers = nil
}
+307
View File
@@ -0,0 +1,307 @@
package providers
import (
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
"log/slog"
"sort"
"strings"
"sync"
"git.fabledsword.com/bvandeusen/minstrel/internal/secret"
)
// Row is one provider's stored settings. APIKey is sealed, or nil.
type Row struct {
ProviderID string
Enabled bool
APIKey *string
}
// Store is the tables one family keeps its settings in: a row per provider,
// and a singleton holding the sources version and the hash of the
// registered provider set.
type Store interface {
// EnsureRow inserts a default row for a provider that has none.
EnsureRow(ctx context.Context, providerID string, enabled bool, order int32) error
List(ctx context.Context) ([]Row, error)
// Save writes enabled, and the sealed key only when keyChanged.
Save(ctx context.Context, providerID string, enabled, keyChanged bool, sealedKey *string) error
Version(ctx context.Context) (int32, error)
// BumpVersion increments the version and returns it.
BumpVersion(ctx context.Context) (int32, error)
ProvidersHash(ctx context.Context) (string, error)
// BumpVersionForProviders increments the version and stores hash as the
// registered set it was bumped for.
BumpVersionForProviders(ctx context.Context, hash string) (int32, error)
}
// UpdatePatch is the admin PATCH body. A nil field is left as it is; an
// empty APIKey clears the key.
type UpdatePatch struct {
Enabled *bool
APIKey *string
}
// Info is a provider as the admin GET handler shows it.
type Info struct {
ID string
DisplayName string
RequiresAPIKey bool
Supports []string
Enabled bool
APIKeySet bool
DisplayOrder int32
Testable bool
}
// Config is what a family hands NewService.
type Config struct {
Registry *Registry
Store Store
// KeyColumn is where the family's API keys are sealed.
KeyColumn secret.Column
// Supports names a provider's capabilities for the admin view, such as
// "album_cover" or "track_tags".
Supports func(Provider) []string
Logger *slog.Logger
}
// Service reconciles a family's registry with its settings table, caches
// each provider's enabled flag and key, and owns the sources version: the
// stamp the enricher writes onto rows it has tried. The version moves
// whenever the enabled set changes, so rows that found nothing get another
// try through the new chain.
type Service struct {
cfg Config
mu sync.RWMutex
enabledIDs map[string]bool
apiKeys map[string]string
version int32
}
// NewService upserts a default row for every registered provider,
// Configures each with its row, and loads the version.
func NewService(ctx context.Context, cfg Config) (*Service, error) {
s := &Service{cfg: cfg, enabledIDs: map[string]bool{}, apiKeys: map[string]string{}}
registered := cfg.Registry.All()
for i, p := range registered {
if err := cfg.Store.EnsureRow(ctx, p.ID(), p.DefaultEnabled(), int32(i)); err != nil {
return nil, fmt.Errorf("upsert provider %q: %w", p.ID(), err)
}
}
rows, err := cfg.Store.List(ctx)
if err != nil {
return nil, fmt.Errorf("list provider settings: %w", err)
}
byID := map[string]Row{}
for _, r := range rows {
byID[r.ProviderID] = r
}
s.mu.Lock()
defer s.mu.Unlock()
for _, p := range registered {
row, ok := byID[p.ID()]
if !ok {
cfg.Logger.Warn("provider settings: missing row after upsert", "provider", p.ID())
continue
}
s.cache(row)
s.configure(p)
}
if s.version, err = cfg.Store.Version(ctx); err != nil {
return nil, fmt.Errorf("get sources version: %w", err)
}
return s, nil
}
// cache records row; the caller holds mu.
func (s *Service) cache(row Row) {
key := ""
if row.APIKey != nil {
key = secret.Reveal(s.cfg.KeyColumn.Purpose(), row.ProviderID, *row.APIKey)
}
s.enabledIDs[row.ProviderID] = row.Enabled
s.apiKeys[row.ProviderID] = key
}
// configure hands p its cached settings; the caller holds mu.
func (s *Service) configure(p Provider) {
if err := p.Configure(Settings{Enabled: s.enabledIDs[p.ID()], APIKey: s.apiKeys[p.ID()]}); err != nil {
s.cfg.Logger.Warn("provider settings: Configure failed", "provider", p.ID(), "err", err)
}
}
// Enabled returns the enabled providers in registration order.
func (s *Service) Enabled() []Provider {
s.mu.RLock()
defer s.mu.RUnlock()
var out []Provider
for _, p := range s.cfg.Registry.All() {
if s.enabledIDs[p.ID()] {
out = append(out, p)
}
}
return out
}
// EnabledAs returns the enabled providers that implement capability T, in
// registration order.
func EnabledAs[T any](s *Service) []T {
var out []T
for _, p := range s.Enabled() {
if c, ok := p.(T); ok {
out = append(out, c)
}
}
return out
}
// CurrentVersion is the version the enricher stamps onto rows it tries.
func (s *Service) CurrentVersion() int32 {
s.mu.RLock()
defer s.mu.RUnlock()
return s.version
}
// UpdateProvider applies an admin patch and re-Configures the provider.
// versionBumped is true when the enabled set changed; a key change alone
// doesn't move the version.
func (s *Service) UpdateProvider(ctx context.Context, providerID string, patch UpdatePatch) (versionBumped bool, err error) {
p, err := s.cfg.Registry.ByID(providerID)
if err != nil {
return false, err
}
s.mu.RLock()
before := enabledSetSignature(s.enabledIDs)
enabled := s.enabledIDs[providerID]
s.mu.RUnlock()
if patch.Enabled != nil {
enabled = *patch.Enabled
}
sealed, err := secret.SealPtr(s.cfg.KeyColumn.Purpose(), providerID, patch.APIKey)
if err != nil {
return false, fmt.Errorf("seal provider api key: %w", err)
}
if err := s.cfg.Store.Save(ctx, providerID, enabled, patch.APIKey != nil, sealed); err != nil {
return false, fmt.Errorf("update provider settings: %w", err)
}
rows, err := s.cfg.Store.List(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 {
s.cache(r)
}
s.configure(p)
if enabledSetSignature(s.enabledIDs) == before {
return false, nil
}
v, err := s.cfg.Store.BumpVersion(ctx)
if err != nil {
return false, fmt.Errorf("bump sources version: %w", err)
}
s.version = v
return true, nil
}
// enabledSetSignature is the sorted, comma-joined 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, ",")
}
// BumpVersionIfProvidersChanged moves the version when the registered
// provider set differs from the one seen at the last boot, so rows that
// found nothing are tried again through a chain an update widened or
// narrowed. An unchanged set writes nothing.
func (s *Service) BumpVersionIfProvidersChanged(ctx context.Context) (version int32, bumped bool, err error) {
hash := s.registeredHash()
stored, err := s.cfg.Store.ProvidersHash(ctx)
if err != nil {
return 0, false, fmt.Errorf("get providers hash: %w", err)
}
if stored == hash {
return s.CurrentVersion(), false, nil
}
v, err := s.BumpVersion(ctx)
if err != nil {
return 0, false, err
}
return v, true, nil
}
// BumpVersion always moves the version, for the admin's "search again for
// everything that found nothing". It stores the current provider hash too,
// as the boot-time bump would.
func (s *Service) BumpVersion(ctx context.Context) (int32, error) {
v, err := s.cfg.Store.BumpVersionForProviders(ctx, s.registeredHash())
if err != nil {
return 0, fmt.Errorf("bump version: %w", err)
}
s.mu.Lock()
s.version = v
s.mu.Unlock()
return v, nil
}
// registeredHash is the SHA-256 hex of the sorted, colon-joined registered
// provider IDs.
func (s *Service) registeredHash() string {
provs := s.cfg.Registry.All()
ids := make([]string, 0, len(provs))
for _, p := range provs {
ids = append(ids, p.ID())
}
sort.Strings(ids)
sum := sha256.Sum256([]byte(strings.Join(ids, ":")))
return hex.EncodeToString(sum[:])
}
// TestProvider runs the named provider's TestConnection. It returns
// ErrNotTestable when the provider can't test itself.
func (s *Service) TestProvider(ctx context.Context, providerID string) error {
p, err := s.cfg.Registry.ByID(providerID)
if err != nil {
return err
}
tp, ok := p.(Testable)
if !ok {
return ErrNotTestable
}
return tp.TestConnection(ctx)
}
// ListProviderInfo is every registered provider for the admin view, in
// registration order.
func (s *Service) ListProviderInfo() []Info {
s.mu.RLock()
defer s.mu.RUnlock()
var out []Info
for i, p := range s.cfg.Registry.All() {
_, testable := p.(Testable)
out = append(out, Info{
ID: p.ID(),
DisplayName: p.DisplayName(),
RequiresAPIKey: p.RequiresAPIKey(),
Supports: s.cfg.Supports(p),
Enabled: s.enabledIDs[p.ID()],
APIKeySet: s.apiKeys[p.ID()] != "",
DisplayOrder: int32(i),
Testable: testable,
})
}
return out
}
+161
View File
@@ -0,0 +1,161 @@
package providers
import (
"context"
"io"
"log/slog"
"testing"
)
type fakeProvider struct {
id string
defaultOn bool
configured Settings
}
func (p *fakeProvider) ID() string { return p.id }
func (p *fakeProvider) DisplayName() string { return p.id }
func (p *fakeProvider) RequiresAPIKey() bool { return false }
func (p *fakeProvider) DefaultEnabled() bool { return p.defaultOn }
func (p *fakeProvider) Configure(s Settings) error { p.configured = s; return nil }
// fetcher stands in for a family capability such as AlbumCoverProvider.
type fetcher interface {
Provider
Fetch()
}
type fetchingProvider struct{ fakeProvider }
func (*fetchingProvider) Fetch() {}
// memStore is a Store in memory, standing in for a family's tables.
type memStore struct {
rows map[string]Row
order []string
version int32
hash string
}
func newMemStore() *memStore { return &memStore{rows: map[string]Row{}} }
func (m *memStore) EnsureRow(_ context.Context, id string, enabled bool, _ int32) error {
if _, ok := m.rows[id]; !ok {
m.rows[id] = Row{ProviderID: id, Enabled: enabled}
m.order = append(m.order, id)
}
return nil
}
func (m *memStore) List(context.Context) ([]Row, error) {
out := make([]Row, 0, len(m.order))
for _, id := range m.order {
out = append(out, m.rows[id])
}
return out, nil
}
func (m *memStore) Save(_ context.Context, id string, enabled, keyChanged bool, key *string) error {
r := m.rows[id]
r.Enabled = enabled
if keyChanged {
r.APIKey = key
}
m.rows[id] = r
return nil
}
func (m *memStore) Version(context.Context) (int32, error) { return m.version, nil }
func (m *memStore) BumpVersion(context.Context) (int32, error) { m.version++; return m.version, nil }
func (m *memStore) ProvidersHash(context.Context) (string, error) { return m.hash, nil }
func (m *memStore) BumpVersionForProviders(_ context.Context, h string) (int32, error) {
m.hash = h
m.version++
return m.version, nil
}
func newTestService(t *testing.T, ps ...Provider) (*Service, *memStore) {
t.Helper()
reg := NewRegistry("test")
for _, p := range ps {
reg.Register(p)
}
store := newMemStore()
s, err := NewService(context.Background(), Config{
Registry: reg, Store: store,
Supports: func(Provider) []string { return nil },
Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
})
if err != nil {
t.Fatalf("NewService: %v", err)
}
return s, store
}
func TestNewService_ConfiguresEachProviderWithItsDefault(t *testing.T) {
on := &fakeProvider{id: "on", defaultOn: true}
off := &fakeProvider{id: "off"}
s, _ := newTestService(t, on, off)
if !on.configured.Enabled || off.configured.Enabled {
t.Fatalf("configured on=%v off=%v, want true false", on.configured.Enabled, off.configured.Enabled)
}
if got := s.Enabled(); len(got) != 1 || got[0].ID() != "on" {
t.Fatalf("Enabled() = %v, want [on]", got)
}
}
func TestEnabledAs_KeepsOnlyTheCapability(t *testing.T) {
plain := &fakeProvider{id: "plain", defaultOn: true}
fetching := &fetchingProvider{fakeProvider{id: "fetching", defaultOn: true}}
s, _ := newTestService(t, plain, fetching)
got := EnabledAs[fetcher](s)
if len(got) != 1 || got[0].ID() != "fetching" {
t.Fatalf("EnabledAs[fetcher] = %v, want [fetching]", got)
}
}
func TestUpdateProvider_BumpsTheVersionOnlyWhenTheEnabledSetChanges(t *testing.T) {
p := &fakeProvider{id: "p"}
s, store := newTestService(t, p)
ctx := context.Background()
on := true
bumped, err := s.UpdateProvider(ctx, "p", UpdatePatch{Enabled: &on})
if err != nil || !bumped {
t.Fatalf("enable: bumped=%v err=%v, want true nil", bumped, err)
}
if !p.configured.Enabled || s.CurrentVersion() != store.version {
t.Fatalf("after enable: configured=%v version=%d store=%d", p.configured.Enabled, s.CurrentVersion(), store.version)
}
// Clearing the key: a key-only change. (An empty key is stored as
// NULL without sealing, so the test needs no sealing key.)
key := ""
bumped, err = s.UpdateProvider(ctx, "p", UpdatePatch{APIKey: &key})
if err != nil || bumped {
t.Fatalf("key only: bumped=%v err=%v, want false nil", bumped, err)
}
if _, err := s.UpdateProvider(ctx, "nope", UpdatePatch{}); err != ErrProviderNotFound {
t.Fatalf("unknown provider: err=%v, want ErrProviderNotFound", err)
}
}
func TestRegisteredHash_IgnoresRegistrationOrder(t *testing.T) {
a, b := &fakeProvider{id: "a"}, &fakeProvider{id: "b"}
s1, _ := newTestService(t, a, b)
s2, _ := newTestService(t, b, a)
h1, h2 := s1.registeredHash(), s2.registeredHash()
if h1 != h2 || len(h1) != 64 {
t.Fatalf("hashes %q and %q: want equal SHA-256 hex", h1, h2)
}
}
func TestBumpVersionIfProvidersChanged_WritesOnlyOnAChange(t *testing.T) {
s, store := newTestService(t, &fakeProvider{id: "a"})
ctx := context.Background()
if _, bumped, err := s.BumpVersionIfProvidersChanged(ctx); err != nil || !bumped {
t.Fatalf("first boot: bumped=%v err=%v, want true", bumped, err)
}
before := store.version
if _, bumped, err := s.BumpVersionIfProvidersChanged(ctx); err != nil || bumped || store.version != before {
t.Fatalf("same set: bumped=%v version %d→%d, want no write", bumped, before, store.version)
}
}
+31 -92
View File
@@ -4,9 +4,9 @@
// Last.fm, …), caches them in track_tags, and the taste recompute unions // Last.fm, …), caches them in track_tags, and the taste recompute unions
// them alongside tracks.genre. // them alongside tracks.genre.
// //
// The provider model mirrors internal/coverart deliberately: a source is // The provider frame is internal/providers, shared with internal/coverart:
// added by implementing TrackTagProvider and calling Register() in the // a source is added by implementing TrackTagProvider and calling Register()
// provider file's init() — no enricher, settings, or schema change. The // in the provider file's init() — no enricher, settings, or schema change. The
// DB-backed SettingsService then auto-upserts a settings row for it, and // DB-backed SettingsService then auto-upserts a settings row for it, and
// the boot-time provider-hash bump makes previously-settled rows eligible // the boot-time provider-hash bump makes previously-settled rows eligible
// for a retry through the widened chain. // for a retry through the widened chain.
@@ -15,10 +15,9 @@ package tags
import ( import (
"context" "context"
"errors" "errors"
"fmt"
"sync"
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror" "git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
"git.fabledsword.com/bvandeusen/minstrel/internal/providers"
) )
// Tag is one folksonomy tag with a normalized strength in [0,1]. Each // Tag is one folksonomy tag with a normalized strength in [0,1]. Each
@@ -42,38 +41,14 @@ type TrackRef struct {
ArtistMBID string ArtistMBID string
} }
// Provider is the base shape every tag source implements. Providers // Provider is the base shape every tag source implements; TrackTagProvider
// register at init() via Register(). The SettingsService reads the // is what it fetches. Its ID is persisted in tracks.tag_source and keyed in
// per-provider row (enabled, api_key) and calls Configure(). // tag_provider_settings. MusicBrainz (keyless) ships on; Last.fm (keyed)
type Provider interface { // ships off until a key is supplied.
// ID is a stable lowercase token persisted in tracks.tag_source and type Provider = providers.Provider
// keyed in tag_provider_settings.provider_id, and shown in the admin UI.
ID() string
// DisplayName is the human-readable label for the admin Settings card. // ProviderSettings is what Configure receives.
DisplayName() string type ProviderSettings = providers.Settings
// RequiresAPIKey reports whether the provider needs a key to function.
// The admin UI shows/hides the key field on this; it does NOT gate the
// enabled toggle: a provider with usable defaults ships working.
RequiresAPIKey() bool
// DefaultEnabled is whether a freshly-installed Minstrel ships with
// this provider on. MusicBrainz (keyless) returns true; Last.fm
// (keyed) returns false — opt-in once a key is supplied.
DefaultEnabled() bool
// Configure applies the admin's settings. Called at boot and on
// every admin PATCH; must be idempotent and goroutine-safe (the
// enricher may read concurrently).
Configure(ProviderSettings) error
}
// ProviderSettings is the runtime config a provider receives on Configure.
type ProviderSettings struct {
Enabled bool
APIKey string
}
// TrackTagProvider is the tag-fetch capability. Split from Provider so a // TrackTagProvider is the tag-fetch capability. Split from Provider so a
// future source with a different capability (e.g. artist-level tags) can // future source with a different capability (e.g. artist-level tags) can
@@ -87,12 +62,8 @@ type TrackTagProvider interface {
FetchTrackTags(ctx context.Context, ref TrackRef) ([]Tag, error) FetchTrackTags(ctx context.Context, ref TrackRef) ([]Tag, error)
} }
// TestableProvider is an opt-in capability for the admin Test-Connection // TestableProvider can answer the admin Test-Connection button.
// button: answer "is my config working?" without a full enrichment cycle. type TestableProvider = providers.Testable
type TestableProvider interface {
Provider
TestConnection(ctx context.Context) error
}
// ErrNotFound: the provider confirmed it has no tags for this track — a // ErrNotFound: the provider confirmed it has no tags for this track — a
// terminal-this-pass result. The enricher moves to the next provider; if // terminal-this-pass result. The enricher moves to the next provider; if
@@ -104,58 +75,26 @@ var ErrNotFound = apierror.ErrNotFound
// enricher leaves the row's tag_source NULL so the next pass retries. // enricher leaves the row's tag_source NULL so the next pass retries.
var ErrTransient = errors.New("tags: transient error") var ErrTransient = errors.New("tags: transient error")
// ErrProviderNotFound is returned when a named provider is not registered. // ErrProviderNotFound and ErrNotTestable are the shared providers errors.
var ErrProviderNotFound = errors.New("tags: provider not registered") var (
ErrProviderNotFound = providers.ErrProviderNotFound
ErrNotTestable = providers.ErrNotTestable
)
// ErrNotTestable is returned when a provider doesn't implement // registry is every compiled-in tag provider; the enricher iterates it
// TestableProvider. // filtered by settings.
var ErrNotTestable = errors.New("tags: provider does not support test connection") var registry = providers.NewRegistry("tags")
// registry holds all compiled-in providers. Providers register at init() // Register adds a provider. Call it from a provider file's init(); a
// via Register(); the enricher iterates this list filtered by settings. // duplicate ID panics.
var registry = struct { func Register(p Provider) { registry.Register(p) }
mu sync.Mutex
providers []Provider
}{}
// Register adds a provider. Must be called from a provider file's init(). // AllProviders returns a snapshot in registration order.
// Duplicate IDs panic — providers are compiled-in, so it's a build bug. func AllProviders() []Provider { return registry.All() }
func Register(p Provider) {
registry.mu.Lock()
defer registry.mu.Unlock()
for _, existing := range registry.providers {
if existing.ID() == p.ID() {
panic(fmt.Sprintf("tags: duplicate provider ID %q", p.ID()))
}
}
registry.providers = append(registry.providers, p)
}
// AllProviders returns a snapshot in registration order. Do not mutate. // ProviderByID returns the registered provider with id, or
func AllProviders() []Provider { // ErrProviderNotFound.
registry.mu.Lock() func ProviderByID(id string) (Provider, error) { return registry.ByID(id) }
defer registry.mu.Unlock()
out := make([]Provider, len(registry.providers))
copy(out, registry.providers)
return out
}
// ProviderByID looks up a registered provider. Returns ErrProviderNotFound // ResetRegistryForTests empties the registry. Tests only.
// if none matches. func ResetRegistryForTests() { registry.ResetForTests() }
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
}
// ResetRegistryForTests clears the registry. Test-only.
func ResetRegistryForTests() {
registry.mu.Lock()
defer registry.mu.Unlock()
registry.providers = nil
}
+58 -268
View File
@@ -2,309 +2,99 @@ package tags
import ( import (
"context" "context"
"crypto/sha256"
"encoding/hex"
"fmt" "fmt"
"log/slog" "log/slog"
"sort"
"strings"
"sync"
"github.com/jackc/pgx/v5/pgxpool" "github.com/jackc/pgx/v5/pgxpool"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
"git.fabledsword.com/bvandeusen/minstrel/internal/providers"
"git.fabledsword.com/bvandeusen/minstrel/internal/secret" "git.fabledsword.com/bvandeusen/minstrel/internal/secret"
) )
// SettingsService reconciles the compiled-in provider registry with the // ProviderUpdatePatch is the admin PATCH body; see providers.UpdatePatch.
// tag_provider_settings table at boot and on every admin update, and owns type ProviderUpdatePatch = providers.UpdatePatch
// the tag_sources_meta current_version stamp. Parallel to (and independent
// of) coverart's SettingsService — the two never share a row, so a new tag // ProviderInfo is a provider as GET /api/admin/tag-sources shows it.
// source is added without touching art settings. type ProviderInfo = providers.Info
// SettingsService is the tag providers' settings: the shared
// providers.Service over tag_provider_settings and the tag_sources_meta
// version. It shares no row with cover art's, so a tag source is added
// without touching art settings.
type SettingsService struct { type SettingsService struct {
pool *pgxpool.Pool *providers.Service
logger *slog.Logger
mu sync.RWMutex
enabledIDs map[string]bool
apiKeys map[string]string
currentVersion int32
} }
// ProviderUpdatePatch is the admin-PATCH body. nil pointers mean "leave // NewSettingsService reconciles the registry with the settings table and
// unchanged"; non-nil means "set" (empty APIKey clears it). // Configures every provider.
type ProviderUpdatePatch struct {
Enabled *bool
APIKey *string
}
// ProviderInfo is the settings view of a provider for the admin GET handler.
type ProviderInfo struct {
ID string
DisplayName string
RequiresAPIKey bool
Supports []string
Enabled bool
APIKeySet bool
DisplayOrder int32
Testable bool
}
// NewSettingsService boots the service: upserts default rows for any
// registered provider, Configures each with its row, and loads the version.
func NewSettingsService(ctx context.Context, pool *pgxpool.Pool, logger *slog.Logger) (*SettingsService, error) { func NewSettingsService(ctx context.Context, pool *pgxpool.Pool, logger *slog.Logger) (*SettingsService, error) {
s := &SettingsService{ svc, err := providers.NewService(ctx, providers.Config{
pool: pool, Registry: registry,
logger: logger, Store: settingsStore{q: dbq.New(pool)},
enabledIDs: map[string]bool{}, KeyColumn: secret.TagProviderAPIKey,
apiKeys: map[string]string{}, Supports: supports,
} Logger: logger,
if err := s.reconcile(ctx); err != nil { })
if err != nil {
return nil, fmt.Errorf("tag settings boot: %w", err) return nil, fmt.Errorf("tag settings boot: %w", err)
} }
return s, nil return &SettingsService{svc}, nil
} }
// reconcile reads the DB, inserts defaults for missing providers, Configures // EnabledTrackTagProviders returns the enabled track-tag providers, in
// each registered provider, and caches the current version. // registration order.
func (s *SettingsService) reconcile(ctx context.Context) error { func (s *SettingsService) EnabledTrackTagProviders() []TrackTagProvider {
q := dbq.New(s.pool) return providers.EnabledAs[TrackTagProvider](s.Service)
}
registered := AllProviders() // supports names what p can fetch, for the admin view.
for i, p := range registered { func supports(p Provider) []string {
if err := q.UpsertTagProviderSettings(ctx, dbq.UpsertTagProviderSettingsParams{ if _, ok := p.(TrackTagProvider); ok {
ProviderID: p.ID(), return []string{"track_tags"}
Enabled: p.DefaultEnabled(),
DisplayOrder: int32(i),
}); err != nil {
return fmt.Errorf("upsert provider %q: %w", p.ID(), err)
} }
}
rows, err := q.ListTagProviderSettings(ctx)
if err != nil {
return fmt.Errorf("list provider settings: %w", err)
}
settingsByID := map[string]dbq.TagProviderSetting{}
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("tag settings: missing row after upsert", "provider", p.ID())
continue
}
key := ""
if row.ApiKey != nil {
key = secret.Reveal(secret.TagProviderAPIKey.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("tag settings: provider Configure failed", "provider", p.ID(), "err", err)
}
}
v, err := q.GetCurrentTagSourcesVersion(ctx)
if err != nil {
return fmt.Errorf("get current tag sources version: %w", err)
}
s.currentVersion = v
return nil return nil
} }
// EnabledTrackTagProviders returns the enabled providers implementing // settingsStore is tags' providers.Store.
// TrackTagProvider, in registration order. Snapshot — do not mutate. type settingsStore struct{ q *dbq.Queries }
func (s *SettingsService) EnabledTrackTagProviders() []TrackTagProvider {
s.mu.RLock() func (st settingsStore) EnsureRow(ctx context.Context, id string, enabled bool, order int32) error {
defer s.mu.RUnlock() return st.q.UpsertTagProviderSettings(ctx, dbq.UpsertTagProviderSettingsParams{
var out []TrackTagProvider ProviderID: id, Enabled: enabled, DisplayOrder: order,
for _, p := range AllProviders() { })
if !s.enabledIDs[p.ID()] {
continue
}
if tp, ok := p.(TrackTagProvider); ok {
out = append(out, tp)
}
}
return out
} }
// CurrentVersion returns the version the enricher stamps onto rows. func (st settingsStore) List(ctx context.Context) ([]providers.Row, error) {
func (s *SettingsService) CurrentVersion() int32 { rows, err := st.q.ListTagProviderSettings(ctx)
s.mu.RLock()
defer s.mu.RUnlock()
return s.currentVersion
}
// UpdateProvider applies an admin patch. Returns versionBumped=true if the
// enabled set changed (not on key-only changes). Re-Configures the provider.
func (s *SettingsService) UpdateProvider(ctx context.Context, providerID string, patch ProviderUpdatePatch) (bool, error) {
p, err := ProviderByID(providerID)
if err != nil { if err != nil {
return false, err return nil, err
} }
q := dbq.New(s.pool) out := make([]providers.Row, len(rows))
for i, r := range rows {
s.mu.RLock() out[i] = providers.Row{ProviderID: r.ProviderID, Enabled: r.Enabled, APIKey: r.ApiKey}
beforeSig := enabledSetSignature(s.enabledIDs)
currentEnabled := s.enabledIDs[providerID]
s.mu.RUnlock()
enabledVal := currentEnabled
if patch.Enabled != nil {
enabledVal = *patch.Enabled
} }
sealedKey, err := secret.SealPtr(secret.TagProviderAPIKey.Purpose(), providerID, patch.APIKey) return out, nil
if err != nil {
return false, fmt.Errorf("seal provider api key: %w", err)
}
if err := q.UpdateTagProviderSettings(ctx, dbq.UpdateTagProviderSettingsParams{
ProviderID: providerID,
Enabled: enabledVal,
Column3: patch.APIKey != nil,
ApiKey: sealedKey,
}); err != nil {
return false, fmt.Errorf("update provider settings: %w", err)
}
rows, err := q.ListTagProviderSettings(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.TagProviderAPIKey.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("tag settings: Configure after update failed", "provider", providerID, "err", err)
}
}
}
if enabledSetSignature(s.enabledIDs) == beforeSig {
return false, nil
}
newVersion, err := q.BumpTagSourcesVersion(ctx)
if err != nil {
return false, fmt.Errorf("bump tag sources version: %w", err)
}
s.currentVersion = newVersion
return true, nil
} }
// enabledSetSignature is a deterministic string of the enabled provider IDs. func (st settingsStore) Save(ctx context.Context, id string, enabled, keyChanged bool, sealedKey *string) error {
func enabledSetSignature(enabledIDs map[string]bool) string { return st.q.UpdateTagProviderSettings(ctx, dbq.UpdateTagProviderSettingsParams{
ids := make([]string, 0, len(enabledIDs)) ProviderID: id, Enabled: enabled, Column3: keyChanged, ApiKey: sealedKey,
for id, on := range enabledIDs { })
if on {
ids = append(ids, id)
}
}
sort.Strings(ids)
return strings.Join(ids, ",")
} }
// BumpVersionIfProvidersChanged bumps the version + stores the new provider func (st settingsStore) Version(ctx context.Context) (int32, error) {
// hash when the compiled-in provider set changed since the last boot, so return st.q.GetCurrentTagSourcesVersion(ctx)
// 'none' rows become eligible for a retry through the widened chain. This
// is what makes "add a source" a zero-touch change — a new registered
// provider trips this on the next start.
func (s *SettingsService) BumpVersionIfProvidersChanged(ctx context.Context) (version int32, bumped bool, err error) {
hash := registeredProvidersHash()
q := dbq.New(s.pool)
stored, qerr := q.GetTagProvidersHash(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.BumpTagVersionAndSetProvidersHash(ctx, hash)
if berr != nil {
return 0, false, fmt.Errorf("bump version: %w", berr)
}
s.mu.Lock()
s.currentVersion = newVer
s.mu.Unlock()
return newVer, true, nil
} }
// registeredProvidersHash is the SHA-256 hex of the sorted, colon-joined func (st settingsStore) BumpVersion(ctx context.Context) (int32, error) {
// registered provider IDs. return st.q.BumpTagSourcesVersion(ctx)
func registeredProvidersHash() string {
provs := AllProviders()
ids := make([]string, 0, len(provs))
for _, p := range provs {
ids = append(ids, p.ID())
}
sort.Strings(ids)
sum := sha256.Sum256([]byte(strings.Join(ids, ":")))
return hex.EncodeToString(sum[:])
} }
// BumpVersion unconditionally increments the version. Used by the admin func (st settingsStore) ProvidersHash(ctx context.Context) (string, error) {
// "re-search missing tags" action to re-attempt every 'none' row next pass. return st.q.GetTagProvidersHash(ctx)
func (s *SettingsService) BumpVersion(ctx context.Context) (int32, error) {
q := dbq.New(s.pool)
newVer, err := q.BumpTagVersionAndSetProvidersHash(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
} }
// TestProvider invokes TestConnection if the provider supports it. func (st settingsStore) BumpVersionForProviders(ctx context.Context, hash string) (int32, error) {
func (s *SettingsService) TestProvider(ctx context.Context, providerID string) error { return st.q.BumpTagVersionAndSetProvidersHash(ctx, hash)
p, err := ProviderByID(providerID)
if err != nil {
return err
}
tp, ok := p.(TestableProvider)
if !ok {
return ErrNotTestable
}
return tp.TestConnection(ctx)
}
// ListProviderInfo builds the admin-GET view 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.(TrackTagProvider); ok {
info.Supports = append(info.Supports, "track_tags")
}
if _, ok := p.(TestableProvider); ok {
info.Testable = true
}
out = append(out, info)
}
return out
} }