sonda/internal/library/manager.go
tgiachi 46463846b3 feat(library): named media libraries managed through the API
- feat(storage): libraries table (name, path); audio_files points at a library
  by id instead of repeating the root path; migration 0005 for both drivers
  turns every existing root into a library and keeps file ids, tracks and the
  missing flag
- feat(library): Libraries service validates names and paths: absolute, an
  existing directory, never the filesystem root, never inside or around
  another library (checked on real paths, so symlinks cannot hide an overlap)
- feat(api): admin-only GET/POST /libraries, PATCH/DELETE /libraries/{id} and
  POST /libraries/{id}/scan; deleting a library drops its index entries and
  keeps tracks and listening history
- feat(library): the scanner and the scan manager work on libraries; scanning
  with no libraries answers 409 no_libraries
- feat(streaming): the library directory comes from the database instead of
  a configured list of roots
- breaking(config): library.roots is removed; an old config fails with a hint
  to use POST /api/v1/libraries
- test: CRUD and duplicates on both databases, path change keeps files,
  upgrade of a database written before libraries existed
2026-11-11 13:30:25 +01:00

122 lines
3.1 KiB
Go

package library
import (
"context"
"errors"
"fmt"
"sync"
"time"
)
// Errors returned when a scan cannot start.
var (
ErrScanRunning = errors.New("a scan is already running")
ErrNoLibraries = errors.New("there are no libraries to scan")
)
// LibrarySource lists the libraries a scan can cover. LibraryStore satisfies it.
type LibrarySource interface {
ListLibraries(ctx context.Context) ([]Library, error)
GetLibrary(ctx context.Context, id int64) (Library, error)
}
// Status describes the scan state for the API.
type Status struct {
Running bool
StartedAt time.Time
LastFinishedAt time.Time
Last *Summary // result of the last finished scan
LastError string
}
// Manager runs at most one background scan at a time.
type Manager struct {
scanner *Scanner
libraries LibrarySource
mu sync.Mutex
status Status
onFinish func(Summary, error)
}
// NewManager builds a Manager that scans libraries from the given source.
func NewManager(scanner *Scanner, libraries LibrarySource) *Manager {
return &Manager{scanner: scanner, libraries: libraries}
}
// OnFinish registers a function called once after every scan, with the result
// of that scan. Unlike hub events it is never dropped. Set it before Start.
// A new scan may start while a callback is still running, so callbacks of
// consecutive scans can overlap: keep the function safe for concurrent use.
func (m *Manager) OnFinish(fn func(Summary, error)) {
m.mu.Lock()
defer m.mu.Unlock()
m.onFinish = fn
}
// Start scans every library in the background. ctx bounds the scan, so pass a
// context that lives as long as the application, not an HTTP request.
// It returns ErrNoLibraries when none are defined.
func (m *Manager) Start(ctx context.Context) error {
libs, err := m.libraries.ListLibraries(ctx)
if err != nil {
return fmt.Errorf("list libraries: %w", err)
}
if len(libs) == 0 {
return ErrNoLibraries
}
return m.start(ctx, libs)
}
// StartLibrary scans a single library in the background.
// It returns ErrLibraryNotFound for an unknown id.
func (m *Manager) StartLibrary(ctx context.Context, id int64) error {
lib, err := m.libraries.GetLibrary(ctx, id)
if err != nil {
return err
}
return m.start(ctx, []Library{lib})
}
func (m *Manager) start(ctx context.Context, libs []Library) error {
m.mu.Lock()
defer m.mu.Unlock()
if m.status.Running {
return ErrScanRunning
}
m.status.Running = true
m.status.StartedAt = time.Now()
go m.run(ctx, libs)
return nil
}
func (m *Manager) run(ctx context.Context, libs []Library) {
sum, err := m.scanner.Scan(ctx, libs)
m.mu.Lock()
m.status.Running = false
m.status.LastFinishedAt = time.Now()
m.status.Last = &sum
m.status.LastError = ""
if err != nil {
m.status.LastError = err.Error()
}
fn := m.onFinish
m.mu.Unlock()
if fn != nil {
fn(sum, err)
}
}
// Status returns a snapshot of the scan state.
func (m *Manager) Status() Status {
m.mu.Lock()
defer m.mu.Unlock()
return m.status
}
// Subscribe returns a channel of scan events (see Hub.Subscribe).
func (m *Manager) Subscribe(buffer int) (<-chan Event, func()) {
return m.scanner.hub.Subscribe(buffer)
}