feat: wire main loop with periodic sync+scan and sync_interval config

Replace compute-only run() with an immediate sync+scan followed by a
ticker-driven periodic loop, add the sync.interval config field (default
6h) with defaults and validation, and add tests for the scheduling logic.
This commit is contained in:
2026-07-19 22:27:06 +03:00
parent dc4bdcdab0
commit 0635ca8a87
6 changed files with 313 additions and 30 deletions

View File

@@ -7,20 +7,22 @@ import (
"os"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"naviwatcher/internal/config"
"naviwatcher/internal/database"
"naviwatcher/internal/navidrome"
"naviwatcher/internal/scanner"
)
func TestAppRun_ScanLogsMissingReleases(t *testing.T) {
// Verify the compute-only run() hook scans monitored artists and returns
// nil without starting notifier/web. Uses an in-memory DB with one
// monitored artist that has one missing release (Animals) vs a local album
// (The Wall). The context is left live so the scan actually executes; we
// cancel shortly after to let run() return cleanly.
// Verify run() performs the sync+scan pipeline once (via the injected
// syncFn) and then blocks until ctx cancellation, returning nil. The
// injected syncFn performs the scan and logs the missing release, mirroring
// what syncAndScan does against live clients.
db, err := database.New(":memory:")
if err != nil {
t.Fatalf("database.New() error: %v", err)
@@ -49,21 +51,31 @@ func TestAppRun_ScanLogsMissingReleases(t *testing.T) {
t.Fatalf("seed external release: %v", err)
}
var buf bytes.Buffer
log.SetOutput(&buf)
defer log.SetOutput(os.Stderr)
app := &App{
cfg: &config.Config{Scanner: config.ScannerConfig{FuzzyThreshold: 0.85}},
db: db,
cfg: &config.Config{
Scanner: config.ScannerConfig{FuzzyThreshold: 0.85},
Sync: config.SyncConfig{Interval: time.Hour},
},
db: db,
syncFn: func(ctx context.Context) error {
missing, err := scanner.ScanAll(ctx, db, 0.85)
if err != nil {
return err
}
for _, m := range missing {
log.Printf(" missing: artist=%s rgid=%s title=%q", m.ArtistID, m.RGID, m.Title)
}
return nil
},
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Capture run()'s log output so we assert that run() ITSELF performed
// the scan (not a separately re-run ScanAll). This guards against the
// hook silently becoming a no-op while still passing.
var buf bytes.Buffer
log.SetOutput(&buf)
defer log.SetOutput(os.Stderr)
// Run the (blocking) hook in a goroutine; cancel after it has had time to
// perform the scan so run() returns nil via the ctx.Done() path.
done := make(chan error, 1)
@@ -83,6 +95,98 @@ func TestAppRun_ScanLogsMissingReleases(t *testing.T) {
}
}
func TestStartPeriodicSync_FiresOnTick(t *testing.T) {
var calls int64
var wg sync.WaitGroup
wg.Add(2)
app := &App{
cfg: &config.Config{Sync: config.SyncConfig{Interval: 20 * time.Millisecond}},
syncFn: func(ctx context.Context) error {
atomic.AddInt64(&calls, 1)
wg.Done()
return nil
},
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go app.startPeriodicSync(ctx)
if !waitWG(&wg, 2*time.Second) {
t.Fatal("expected syncFn to be called at least twice within timeout")
}
if got := atomic.LoadInt64(&calls); got < 2 {
t.Errorf("expected at least 2 sync calls, got %d", got)
}
cancel()
}
func TestStartPeriodicSync_CancelsCleanly(t *testing.T) {
var calls int64
app := &App{
cfg: &config.Config{Sync: config.SyncConfig{Interval: time.Hour}},
syncFn: func(ctx context.Context) error {
atomic.AddInt64(&calls, 1)
return nil
},
}
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
go func() {
app.startPeriodicSync(ctx)
close(done)
}()
// With a 1h interval the ticker would never fire on its own; cancel should
// return promptly.
cancel()
select {
case <-done:
// clean exit
case <-time.After(2 * time.Second):
t.Fatal("startPeriodicSync did not exit after ctx cancellation")
}
if got := atomic.LoadInt64(&calls); got != 0 {
t.Errorf("expected no sync calls with 1h interval, got %d", got)
}
}
func TestDoSync_UsesInjectedSyncFn(t *testing.T) {
// Verify doSync prefers an injected syncFn when present (so the periodic
// loop and immediate run can be driven by tests without live clients),
// and falls back to the real syncAndScan otherwise.
db, err := database.New(":memory:")
if err != nil {
t.Fatalf("database.New() error: %v", err)
}
defer db.Close()
var called int32
app := &App{
cfg: &config.Config{Sync: config.SyncConfig{Interval: time.Hour}},
db: db,
syncFn: func(ctx context.Context) error {
atomic.StoreInt32(&called, 1)
return nil
},
}
if err := app.doSync(context.Background()); err != nil {
t.Fatalf("doSync returned error: %v", err)
}
if atomic.LoadInt32(&called) != 1 {
t.Fatal("expected injected syncFn to be called")
}
}
func TestConfigIntegration(t *testing.T) {
// Integration test: write a minimal valid config and load it via config.LoadConfig,
// verifying the full path that main() uses.
@@ -212,6 +316,7 @@ func TestAppRun_GracefulShutdown(t *testing.T) {
MusicBrainz: config.MusicBrainzConfig{
UserAgent: "NaviWatcher/1.0 ( test@example.com )",
},
Sync: config.SyncConfig{Interval: time.Hour},
}
prevFactory := navidromeClientFactory
@@ -260,3 +365,18 @@ musicbrainz:
t.Fatal("expected config validation error for empty musicbrainz.user_agent, got nil")
}
}
// waitWG waits for wg with a timeout; returns true if it completed in time.
func waitWG(wg *sync.WaitGroup, timeout time.Duration) bool {
done := make(chan struct{})
go func() {
wg.Wait()
close(done)
}()
select {
case <-done:
return true
case <-time.After(timeout):
return false
}
}