package library import ( "context" "io" "log/slog" "testing" "time" "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" "github.com/Fabled-Sword/minstrel/internal/dbtest" ) // triggerTestPool opens the test database with no scan runs recorded. func triggerTestPool(t *testing.T) *pgxpool.Pool { t.Helper() pool := dbtest.Open(t) // Reset scan_runs so each test starts clean. if _, err := pool.Exec(context.Background(), `DELETE FROM scan_runs`); err != nil { t.Fatalf("reset: %v", err) } return pool } // quietLogger returns a logger that drops all output. func quietLogger() *slog.Logger { return slog.New(slog.NewTextHandler(io.Discard, nil)) } // A scan starts unless another is running. A run that has been "running" for // two hours is a crashed one: it is closed as reaped and a new scan starts. func TestTryStartScan_StartsUnlessAFreshScanIsRunning(t *testing.T) { for _, tc := range []struct { name string inFlightAge string // "" seeds no run wantStarted bool }{ {"nothing running", "", true}, {"a fresh run", "0 seconds", false}, {"a stale run", "2 hours", true}, } { t.Run(tc.name, func(t *testing.T) { pool := triggerTestPool(t) ctx := context.Background() var seeded pgtype.UUID if tc.inFlightAge != "" { if err := pool.QueryRow(ctx, `INSERT INTO scan_runs (started_at) VALUES (now() - $1::interval) RETURNING id`, tc.inFlightAge, ).Scan(&seeded); err != nil { t.Fatalf("seed: %v", err) } } // scanner/enricher nil: the goroutine that uses them is detached // and not awaited. started, existing, err := TryStartScan(ctx, pool, nil, nil, quietLogger(), RunScanConfig{}) if err != nil { t.Fatalf("err = %v, want nil", err) } if started != tc.wantStarted { t.Errorf("started = %v, want %v", started, tc.wantStarted) } if tc.wantStarted && existing != nil { t.Errorf("existing = %v, want nil", existing) } if !tc.wantStarted && (existing == nil || existing.ID != seeded) { t.Errorf("existing = %v, want the running row %v", existing, seeded) } if tc.name == "a stale run" { var finishedAt pgtype.Timestamptz var errMsg *string if err := pool.QueryRow(ctx, `SELECT finished_at, error_message FROM scan_runs WHERE id = $1`, seeded, ).Scan(&finishedAt, &errMsg); err != nil { t.Fatalf("verify reap: %v", err) } if !finishedAt.Valid || errMsg == nil || *errMsg != "reaped (stale)" { t.Errorf("stale row finished=%v message=%v, want closed as 'reaped (stale)'", finishedAt.Valid, errMsg) } } if started { // Give the detached goroutine a moment. time.Sleep(50 * time.Millisecond) } }) } }