sonda/internal/library/manager.go
tgiachi 11aa47e79f fix: refresh match keys at startup and re-check file type after stat
- fix(storage): RefreshMatchKeys recomputes name_key and title_key for rows
  created before migration 0003, whose SQL lower() key is ASCII-only on SQLite;
  idempotent, runs at every start
- fix(library): re-check that the stat result is a regular file, closing the
  window where a path is swapped for a FIFO or symlink after the directory read
- docs(library): note that OnFinish callbacks of consecutive scans can overlap
- test: old rows with approximate keys are matched after the refresh
2026-11-11 12:30:43 +01:00

90 lines
2.2 KiB
Go

package library
import (
"context"
"errors"
"sync"
"time"
)
// ErrScanRunning is returned by Start while a scan is in progress.
var ErrScanRunning = errors.New("a scan is already running")
// 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 of the configured roots.
type Manager struct {
scanner *Scanner
roots []string
mu sync.Mutex
status Status
onFinish func(Summary, error)
}
// 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
}
// NewManager builds a Manager for the given roots.
func NewManager(scanner *Scanner, roots []string) *Manager {
return &Manager{scanner: scanner, roots: roots}
}
// Start launches a scan in the background. ctx bounds the scan, so pass a
// context that lives as long as the application, not an HTTP request.
func (m *Manager) Start(ctx context.Context) 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)
return nil
}
func (m *Manager) run(ctx context.Context) {
sum, err := m.scanner.Scan(ctx, m.roots)
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)
}