release / go (push) Successful in 2m7s
release / web (push) Successful in 1m25s
release / govulncheck (push) Successful in 21s
release / integration (push) Successful in 4m30s
release / android (push) Successful in 4m39s
release / Build signed APK (push) Successful in 5m10s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 29s
release / Verify release artifacts (tag releases only) (push) Skipped
- Module path: github.com/Fabled-Sword/minstrel, in go.mod, every import and the Dockerfile's version ldflags. - buildinfo.ProjectURL, the contact outside services see in Minstrel's User-Agent: https://github.com/Fabled-Sword/minstrel. - README's compose example pulls ghcr.io/fabled-sword/minstrel:latest. - docs/security.md sends problem reports to the GitHub issues. - The demo-library stack builds Minstrel from the checkout, since :dev is not published to GHCR. - hygiene.go's same-site example uses example.com names. The workbench CI (.gitea/, ci/, export-ignored) still builds and publishes :dev to the private registry. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
320 lines
9.3 KiB
Go
320 lines
9.3 KiB
Go
package providers
|
|
|
|
import (
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"fmt"
|
|
"log/slog"
|
|
"sort"
|
|
"strings"
|
|
"sync"
|
|
|
|
"github.com/Fabled-Sword/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, or an enabled source gains or loses its
|
|
// key, 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 sources signature changed: the enabled set,
|
|
// or whether an enabled source has a key. Replacing one key with another
|
|
// 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 := s.sourcesSignature()
|
|
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 s.sourcesSignature() == 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
|
|
}
|
|
|
|
// sourcesSignature is the sorted, comma-joined enabled provider IDs, each
|
|
// marked "+key" when it has a key; the caller holds mu (read or write).
|
|
//
|
|
// The key belongs in it because a source that needs one, such as Last.fm,
|
|
// answers "not found" without it, and the enricher settles a row tried
|
|
// through it as found-nothing at the current version. Switching Last.fm on
|
|
// before entering its key would otherwise settle every gap without it, and
|
|
// the key, once saved, would never bring Last.fm back to them.
|
|
func (s *Service) sourcesSignature() string {
|
|
ids := make([]string, 0, len(s.enabledIDs))
|
|
for id, on := range s.enabledIDs {
|
|
if !on {
|
|
continue
|
|
}
|
|
if s.apiKeys[id] != "" {
|
|
id += "+key"
|
|
}
|
|
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
|
|
}
|