feat(jobs): surface background jobs with progress, logs and controls
Add a central job registry that library scans and search index builds report into, so background work is visible instead of buried in the settings page. - backend/jobs: registry with per-job ring-buffer logs, capability-driven controls, and one coalesced JobsChanged snapshot at 4Hz - pause survives restart via a job_state table; a paused scan is adopted back on launch and skipped by the soft scan - top-bar indicator, popover, details drawer and a Jobs page replacing the config page's scan UI; per-library start/stop retained - scan timing breakdown moves into the job log, Full rescan to the Jobs page; delete the orphaned library-manager component Also add cmd/indexbuild and cmd/indexexport so the explore index can be built once centrally rather than by every install, which today streams ~205GB from the ListenBrainz spark dump on first run. indexbuild picks build/refresh/rebuild from index state; the Gitea workflow runs it on push, weekly, or manually and publishes only when content changed. fresh-install no longer defaults YJ_HOME under /tmp: it is tmpfs on most distros, and the import needs ~6GB of real disk. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
@@ -20,6 +20,7 @@ import (
|
||||
"yellowjacket/backend/database"
|
||||
"yellowjacket/backend/explore"
|
||||
"yellowjacket/backend/frontendutil"
|
||||
"yellowjacket/backend/jobs"
|
||||
"yellowjacket/backend/library"
|
||||
"yellowjacket/backend/mediacontrols"
|
||||
"yellowjacket/backend/player"
|
||||
@@ -44,6 +45,7 @@ type YellowJacketApp struct {
|
||||
queue *queue.Queue
|
||||
explore *explore.Service
|
||||
autotag *autotagservice.Service
|
||||
jobs *jobs.Registry
|
||||
mediaControls mediacontrols.Handler
|
||||
tagWriter *tagwriter.TagWriter
|
||||
appContext context.Context
|
||||
@@ -148,6 +150,16 @@ func NewYellowJacketApp(
|
||||
yjApp.logger.WithGroup("explore"), yjApp.database,
|
||||
)
|
||||
|
||||
// create the background job registry and wire it into the
|
||||
// subsystems that run long jobs, so scans and index builds all
|
||||
// report through one surface.
|
||||
yjApp.jobs = jobs.NewRegistry(
|
||||
yjApp.logger.WithGroup("jobs"),
|
||||
jobs.NewStore(yjApp.database, yjApp.logger.WithGroup("jobs")),
|
||||
)
|
||||
yjApp.library.SetJobRegistry(yjApp.jobs)
|
||||
yjApp.explore.SetJobRegistry(yjApp.jobs)
|
||||
|
||||
// create autotag service (depends on explore + tagWriter)
|
||||
yjApp.autotag = autotagservice.NewService(
|
||||
yjApp.logger.WithGroup("autotag"),
|
||||
@@ -166,6 +178,7 @@ func NewYellowJacketApp(
|
||||
yjApp.tagWriter,
|
||||
yjApp.explore,
|
||||
yjApp.autotag,
|
||||
jobs.NewService(yjApp.jobs),
|
||||
}
|
||||
|
||||
return yjApp, nil
|
||||
@@ -219,6 +232,13 @@ func (yj *YellowJacketApp) OnStartup(ctx context.Context) {
|
||||
yj.tagWriter.SetContext(ctx)
|
||||
yj.explore.SetContext(ctx)
|
||||
yj.autotag.SetContext(ctx)
|
||||
yj.jobs.SetContext(ctx)
|
||||
|
||||
// Bring back jobs the user paused before the last shutdown, still
|
||||
// paused. Must run before the soft scan in OnDomReady, which
|
||||
// checks these records so it does not restart a paused library.
|
||||
yj.library.RestorePausedScans()
|
||||
yj.explore.AdoptPausedIndexBuild()
|
||||
|
||||
// Wire queue (created in NewYellowJacketApp for Wails binding)
|
||||
yj.queue.SetContext(ctx)
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
-- Durable state for background jobs. Currently holds one row per job
|
||||
-- that the user paused, so a paused library scan or search index build
|
||||
-- comes back paused after a restart instead of silently resuming (or
|
||||
-- silently never running again).
|
||||
--
|
||||
-- Rows are written when a durable job enters the paused state and
|
||||
-- deleted on resume, cancel, or completion — this is not a job history
|
||||
-- table, and it stays at zero rows in the common case.
|
||||
CREATE TABLE IF NOT EXISTS job_state (
|
||||
id TEXT PRIMARY KEY,
|
||||
kind TEXT NOT NULL,
|
||||
title TEXT NOT NULL DEFAULT '',
|
||||
subtitle TEXT NOT NULL DEFAULT '',
|
||||
paused_at TEXT NOT NULL
|
||||
);
|
||||
@@ -77,6 +77,14 @@ type HttpCache struct {
|
||||
EntityType string
|
||||
}
|
||||
|
||||
type JobState struct {
|
||||
ID string
|
||||
Kind string
|
||||
Title string
|
||||
Subtitle string
|
||||
PausedAt string
|
||||
}
|
||||
|
||||
type Library struct {
|
||||
ID int64
|
||||
Name string
|
||||
|
||||
@@ -87,6 +87,15 @@ const (
|
||||
AutotagPrefetchFinished = "AutotagPrefetchFinished" // {processed, total}
|
||||
)
|
||||
|
||||
// Background job events.
|
||||
const (
|
||||
// JobsChanged carries a full snapshot of every known background job
|
||||
// (see backend/jobs). A full snapshot rather than a delta means a
|
||||
// component mounting mid-scan is correct from its first event.
|
||||
// Emitted coalesced, at most every 250ms.
|
||||
JobsChanged = "JobsChanged"
|
||||
)
|
||||
|
||||
// Explore / search index events.
|
||||
const (
|
||||
IndexStatusChanged = "IndexStatusChanged"
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
|
||||
"yellowjacket/backend/database"
|
||||
"yellowjacket/backend/events"
|
||||
"yellowjacket/backend/jobs"
|
||||
)
|
||||
|
||||
// Service is the Wails-bound service for the explore feature.
|
||||
@@ -148,6 +149,52 @@ func (e *Service) StopIndexBuild() {
|
||||
e.index.StopBuild()
|
||||
}
|
||||
|
||||
// SetJobRegistry wires the background job registry into the search
|
||||
// index so its build reports progress and controls to the frontend.
|
||||
func (e *Service) SetJobRegistry(reg *jobs.Registry) {
|
||||
e.index.SetJobRegistry(reg)
|
||||
}
|
||||
|
||||
// AdoptPausedIndexBuild re-registers a build paused in a previous
|
||||
// session so it appears in the jobs panel, still paused.
|
||||
func (e *Service) AdoptPausedIndexBuild() {
|
||||
e.index.AdoptPausedBuild()
|
||||
}
|
||||
|
||||
// IndexImportComplete reports whether the dump import has finished all
|
||||
// of its stages. Distinct from IsIndexReady, which only means the index
|
||||
// holds enough rows to answer queries — a partially imported index is
|
||||
// ready but not complete. Used by the headless builder to decide
|
||||
// whether another run is needed.
|
||||
func (e *Service) IndexImportComplete() bool {
|
||||
return e.index.ImportComplete()
|
||||
}
|
||||
|
||||
// IndexBaselineSeries returns the incremental listens series the index's
|
||||
// popularity is caught up to. A change across a refresh means new data
|
||||
// was folded in.
|
||||
func (e *Service) IndexBaselineSeries() int {
|
||||
return e.index.BaselineSeries()
|
||||
}
|
||||
|
||||
// IndexLastImported returns when the dump import last completed, or the
|
||||
// zero time if it never has.
|
||||
func (e *Service) IndexLastImported() time.Time {
|
||||
return e.index.LastImported()
|
||||
}
|
||||
|
||||
// PrepareIndexRebuild clears the completion marker so the next build
|
||||
// re-imports from the newest published dump.
|
||||
func (e *Service) PrepareIndexRebuild() {
|
||||
e.index.PrepareRebuild()
|
||||
}
|
||||
|
||||
// RefreshIndexNow folds newly published incremental listens dumps into
|
||||
// the index synchronously. Pass 0 to bypass the cadence gate.
|
||||
func (e *Service) RefreshIndexNow(minInterval time.Duration) {
|
||||
e.index.RefreshNow(e.ctx, minInterval)
|
||||
}
|
||||
|
||||
// IsIndexReady returns true once the index has been populated.
|
||||
func (e *Service) IsIndexReady() bool {
|
||||
return e.index.IsReady()
|
||||
|
||||
@@ -0,0 +1,380 @@
|
||||
package explore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"yellowjacket/backend/jobs"
|
||||
)
|
||||
|
||||
// errIndexStageFailed wraps the per-stage error text reported by the
|
||||
// dump importer so the job carries a typed failure.
|
||||
var errIndexStageFailed = errors.New("index build stage failed")
|
||||
|
||||
// indexJobID is the stable registry ID for the search index build.
|
||||
// There is only ever one, so the ID is a constant.
|
||||
const indexJobID = "index:build"
|
||||
|
||||
// indexPausedKey marks a build the user paused. It lives in
|
||||
// explore_index_meta alongside the import's other checkpoints so a
|
||||
// paused build stays paused across a restart instead of resuming on
|
||||
// the next launch.
|
||||
const indexPausedKey = "index_build_paused"
|
||||
|
||||
// SetJobRegistry wires the background job registry so index builds
|
||||
// report progress, stage state, logs, and pause/cancel controls.
|
||||
func (si *SearchIndex) SetJobRegistry(reg *jobs.Registry) {
|
||||
si.mu.Lock()
|
||||
si.jobs = reg
|
||||
si.mu.Unlock()
|
||||
}
|
||||
|
||||
// jobRegistry returns the registry, or nil when none is wired.
|
||||
func (si *SearchIndex) jobRegistry() *jobs.Registry {
|
||||
si.mu.RLock()
|
||||
defer si.mu.RUnlock()
|
||||
|
||||
return si.jobs
|
||||
}
|
||||
|
||||
// logIndexJob appends a line to the index build's job log, if a build
|
||||
// job is currently registered.
|
||||
func (si *SearchIndex) logIndexJob(level jobs.Level, message string) {
|
||||
reg := si.jobRegistry()
|
||||
if reg == nil {
|
||||
return
|
||||
}
|
||||
|
||||
if h := reg.Get(indexJobID); h != nil {
|
||||
h.Logf(level, message)
|
||||
}
|
||||
}
|
||||
|
||||
// indexJobSpec builds the registry spec for the index build.
|
||||
//
|
||||
// The build is genuinely pausable rather than merely cancellable: the
|
||||
// dump importer checkpoints its listen-count offset to counts.bin and
|
||||
// its stage to state.json, so stopping and restarting picks up where it
|
||||
// left off instead of re-downloading multiple gigabytes.
|
||||
func (si *SearchIndex) indexJobSpec(state jobs.State) jobs.Spec {
|
||||
return jobs.Spec{
|
||||
ID: indexJobID,
|
||||
Kind: jobs.KindIndexBuild,
|
||||
Title: "Building search index",
|
||||
Subtitle: "MusicBrainz catalog + ListenBrainz popularity",
|
||||
State: state,
|
||||
Caps: jobs.Caps{
|
||||
Pausable: true,
|
||||
Cancellable: true,
|
||||
},
|
||||
Durable: true,
|
||||
Controls: jobs.Controls{
|
||||
Pause: si.PauseBuild,
|
||||
Resume: si.ResumeBuild,
|
||||
Cancel: si.CancelBuild,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// syncIndexJob mirrors an IndexStatus snapshot into the job registry.
|
||||
// It is driven from emitStatus, which every status mutation already
|
||||
// funnels through, so there is no path that updates one view and not
|
||||
// the other.
|
||||
func (si *SearchIndex) syncIndexJob(status IndexStatus) {
|
||||
reg := si.jobRegistry()
|
||||
if reg == nil {
|
||||
return
|
||||
}
|
||||
|
||||
si.mu.RLock()
|
||||
paused := si.buildPaused
|
||||
si.mu.RUnlock()
|
||||
|
||||
h := reg.Get(indexJobID)
|
||||
|
||||
// A build with no stages is the early-return path in runDumpBuild
|
||||
// (the catalog import is already done). Nothing to show.
|
||||
if h == nil {
|
||||
if !status.Building || len(status.Tiers) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
h = reg.Start(si.indexJobSpec(jobs.StateRunning))
|
||||
h.Logf(jobs.LevelInfo, "Index build started")
|
||||
}
|
||||
|
||||
// A finished job is immutable. Without this guard the 3-second
|
||||
// status ticker would keep touching it forever, re-emitting
|
||||
// JobsChanged long after the build ended.
|
||||
if h.State().IsTerminal() {
|
||||
return
|
||||
}
|
||||
|
||||
si.applyStagesToJob(h, status)
|
||||
|
||||
if status.Building {
|
||||
// Don't stomp a pause or cancel that is still settling; those
|
||||
// transitions are confirmed by their own control paths.
|
||||
if h.State() == jobs.StateQueued {
|
||||
h.SetState(jobs.StateRunning)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
si.finishIndexJob(h, paused)
|
||||
}
|
||||
|
||||
// applyStagesToJob maps index tiers onto job stages and derives the
|
||||
// headline progress bar from whichever tier is currently running.
|
||||
func (si *SearchIndex) applyStagesToJob(h *jobs.Handle, status IndexStatus) {
|
||||
stages := make([]jobs.Stage, 0, len(status.Tiers))
|
||||
|
||||
var (
|
||||
phase string
|
||||
current, total int64
|
||||
foundRunningTier bool
|
||||
)
|
||||
|
||||
for _, t := range status.Tiers {
|
||||
stages = append(stages, jobs.Stage{
|
||||
Name: t.Name,
|
||||
State: t.State,
|
||||
Current: int64(t.Completed),
|
||||
Total: int64(t.Total),
|
||||
Error: t.Error,
|
||||
})
|
||||
|
||||
if t.State == "running" && !foundRunningTier {
|
||||
foundRunningTier = true
|
||||
phase = t.Name
|
||||
current = int64(t.Completed)
|
||||
total = int64(t.Total)
|
||||
}
|
||||
}
|
||||
|
||||
h.SetStages(stages)
|
||||
|
||||
if foundRunningTier {
|
||||
h.SetPhase(phase)
|
||||
h.SetProgress(current, total)
|
||||
}
|
||||
|
||||
h.SetStats([]jobs.Stat{
|
||||
{Label: "Artists", Value: strconv.Itoa(status.Artists)},
|
||||
{Label: "Release groups", Value: strconv.Itoa(status.ReleaseGroups)},
|
||||
{Label: "Recordings", Value: strconv.Itoa(status.Recordings)},
|
||||
{Label: "Total rows", Value: strconv.Itoa(status.TotalRows)},
|
||||
})
|
||||
}
|
||||
|
||||
// finishIndexJob resolves a build that is no longer running into the
|
||||
// right terminal (or paused) state. A stopped build that never wrote
|
||||
// the done marker is reported as cancelled rather than complete —
|
||||
// claiming success for a half-finished import would be a lie.
|
||||
func (si *SearchIndex) finishIndexJob(h *jobs.Handle, paused bool) {
|
||||
if h.State().IsTerminal() || h.State() == jobs.StatePaused {
|
||||
return
|
||||
}
|
||||
|
||||
// A stage that errored means the build failed; reporting that as
|
||||
// "stopped" would hide a real failure behind a neutral word.
|
||||
if !paused {
|
||||
for _, stage := range h.Snapshot().Stages {
|
||||
if stage.State == "error" {
|
||||
h.Fail(fmt.Errorf("%w: %s: %s",
|
||||
errIndexStageFailed, stage.Name, stage.Error))
|
||||
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if paused {
|
||||
h.SetPhase("Paused")
|
||||
h.SetState(jobs.StatePaused)
|
||||
h.Logf(jobs.LevelInfo,
|
||||
"Build paused — progress is checkpointed and will resume "+
|
||||
"from here")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if si.hasMeta(dumpImportDoneKey) {
|
||||
h.Logf(jobs.LevelInfo, "Index build complete")
|
||||
h.Complete()
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
h.Logf(jobs.LevelInfo, "Build stopped before finishing")
|
||||
h.Cancelled()
|
||||
}
|
||||
|
||||
// PauseBuild stops the in-flight index build and remembers that the
|
||||
// user asked for it, so it is not restarted automatically — including
|
||||
// on the next launch. Blocks until the build goroutine exits; the job
|
||||
// registry invokes controls on their own goroutine.
|
||||
func (si *SearchIndex) PauseBuild() {
|
||||
si.mu.Lock()
|
||||
si.buildPaused = true
|
||||
si.mu.Unlock()
|
||||
|
||||
si.setMeta(indexPausedKey, "1")
|
||||
si.StopBuild()
|
||||
si.emitStatus()
|
||||
}
|
||||
|
||||
// ResumeBuild clears the pause and restarts the build, which picks up
|
||||
// from the importer's last checkpoint.
|
||||
func (si *SearchIndex) ResumeBuild() {
|
||||
si.mu.Lock()
|
||||
si.buildPaused = false
|
||||
ctx := si.runtimeCtx
|
||||
si.mu.Unlock()
|
||||
|
||||
si.deleteMeta(indexPausedKey)
|
||||
|
||||
if reg := si.jobRegistry(); reg != nil {
|
||||
if h := reg.Get(indexJobID); h != nil {
|
||||
h.SetState(jobs.StateRunning)
|
||||
h.Logf(jobs.LevelInfo, "Resuming from last checkpoint")
|
||||
}
|
||||
}
|
||||
|
||||
if ctx != nil {
|
||||
si.StartBuild(ctx)
|
||||
}
|
||||
}
|
||||
|
||||
// CancelBuild stops the build without marking it paused. The importer's
|
||||
// on-disk checkpoints are left in place, so starting a new build later
|
||||
// still resumes rather than re-downloading — cancel here means "stop
|
||||
// working now", not "throw away the progress".
|
||||
func (si *SearchIndex) CancelBuild() {
|
||||
si.mu.Lock()
|
||||
si.buildPaused = false
|
||||
si.mu.Unlock()
|
||||
|
||||
si.deleteMeta(indexPausedKey)
|
||||
si.StopBuild()
|
||||
si.emitStatus()
|
||||
}
|
||||
|
||||
// ImportComplete reports whether the dump import wrote its done marker,
|
||||
// meaning every stage finished. A resumable import that was interrupted
|
||||
// leaves this false even though the index may already be queryable.
|
||||
func (si *SearchIndex) ImportComplete() bool {
|
||||
return si.hasMeta(dumpImportDoneKey)
|
||||
}
|
||||
|
||||
// BaselineSeries returns the incremental listens series the index's
|
||||
// popularity numbers are currently caught up to, or 0 when no baseline
|
||||
// import has completed. A change in this value between two runs is the
|
||||
// signal that a refresh actually folded in new data.
|
||||
func (si *SearchIndex) BaselineSeries() int {
|
||||
series, _ := si.metaInt(listensAppliedSeriesKey)
|
||||
|
||||
return series
|
||||
}
|
||||
|
||||
// LastImported returns when the dump import last completed, or the zero
|
||||
// time if it never has. Drives the rebuild cadence.
|
||||
func (si *SearchIndex) LastImported() time.Time {
|
||||
rows, err := si.db.QueryContext(
|
||||
"SELECT value FROM explore_index_meta WHERE key = ?", dumpImportDoneKey,
|
||||
)
|
||||
if err != nil {
|
||||
return time.Time{}
|
||||
}
|
||||
|
||||
defer func() { _ = rows.Close() }()
|
||||
|
||||
if !rows.Next() {
|
||||
return time.Time{}
|
||||
}
|
||||
|
||||
var raw string
|
||||
if err := rows.Scan(&raw); err != nil {
|
||||
return time.Time{}
|
||||
}
|
||||
|
||||
parsed, err := time.Parse(time.RFC3339, raw)
|
||||
if err != nil {
|
||||
return time.Time{}
|
||||
}
|
||||
|
||||
return parsed
|
||||
}
|
||||
|
||||
// PrepareRebuild clears the completion marker so the next StartBuild
|
||||
// re-imports from the newest published dump instead of short-circuiting.
|
||||
//
|
||||
// The importer deletes its staging directory on completion, so there is
|
||||
// no stale checkpoint to clear as well — a rebuild rediscovers the
|
||||
// current dump and starts from offset zero. Existing rows are left in
|
||||
// place: assembly upserts by MBID, so the index stays queryable
|
||||
// throughout rather than going empty for the length of a re-import.
|
||||
func (si *SearchIndex) PrepareRebuild() {
|
||||
si.deleteMeta(dumpImportDoneKey)
|
||||
si.logger.Info("search index: cleared completion marker for rebuild")
|
||||
}
|
||||
|
||||
// RefreshNow folds any newly published incremental listens dumps into
|
||||
// the index's popularity numbers, synchronously. Pass 0 to bypass the
|
||||
// cadence gate.
|
||||
func (si *SearchIndex) RefreshNow(ctx context.Context, minInterval time.Duration) {
|
||||
si.RefreshListenCounts(ctx, minInterval)
|
||||
}
|
||||
|
||||
// buildPausedByUser reports whether a build was paused and not resumed,
|
||||
// including by a previous session.
|
||||
func (si *SearchIndex) buildPausedByUser() bool {
|
||||
si.mu.RLock()
|
||||
paused := si.buildPaused
|
||||
si.mu.RUnlock()
|
||||
|
||||
if paused {
|
||||
return true
|
||||
}
|
||||
|
||||
return si.hasMeta(indexPausedKey)
|
||||
}
|
||||
|
||||
// AdoptPausedBuild re-registers a build that was paused when the app
|
||||
// last shut down, so it shows up in the jobs panel with a resume button
|
||||
// instead of silently not running. Called during startup.
|
||||
func (si *SearchIndex) AdoptPausedBuild() {
|
||||
reg := si.jobRegistry()
|
||||
if reg == nil {
|
||||
return
|
||||
}
|
||||
|
||||
// A completed import cannot be meaningfully paused; clear a stale
|
||||
// marker rather than showing a job that would never do anything.
|
||||
if si.hasMeta(dumpImportDoneKey) {
|
||||
si.deleteMeta(indexPausedKey)
|
||||
reg.Remove(indexJobID)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if !si.hasMeta(indexPausedKey) {
|
||||
return
|
||||
}
|
||||
|
||||
si.mu.Lock()
|
||||
si.buildPaused = true
|
||||
si.mu.Unlock()
|
||||
|
||||
h := reg.Start(si.indexJobSpec(jobs.StatePaused))
|
||||
h.SetPhase("Paused")
|
||||
h.Logf(jobs.LevelInfo,
|
||||
"Paused in a previous session — resume to continue from the "+
|
||||
"last checkpoint")
|
||||
|
||||
si.logger.Info("search index: restored paused build")
|
||||
}
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
|
||||
"yellowjacket/backend/database"
|
||||
"yellowjacket/backend/events"
|
||||
"yellowjacket/backend/jobs"
|
||||
)
|
||||
|
||||
// Index build parameters.
|
||||
@@ -217,6 +218,12 @@ type SearchIndex struct {
|
||||
|
||||
// Build status tracking — read by GetIndexStatus for the UI.
|
||||
buildStatus IndexStatus
|
||||
|
||||
// jobs is the background job registry; buildPaused records that the
|
||||
// user paused the build, distinguishing a deliberate stop from a
|
||||
// build that merely finished. Both are protected by mu.
|
||||
jobs *jobs.Registry
|
||||
buildPaused bool
|
||||
}
|
||||
|
||||
// prefixCacheEntry is one memoised generic-query result.
|
||||
@@ -495,6 +502,15 @@ func (si *SearchIndex) PersistSimilarArtists(sourceMBID string, similar []LBSimi
|
||||
// StartBuild launches the background index build goroutine.
|
||||
// Returns immediately.
|
||||
func (si *SearchIndex) StartBuild(ctx context.Context) {
|
||||
// A build the user paused stays paused until they resume it —
|
||||
// including across restarts, where the marker is read back from
|
||||
// explore_index_meta. ResumeBuild clears it before calling here.
|
||||
if si.buildPausedByUser() {
|
||||
si.logger.Info("search index: build is paused, not starting")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
si.mu.Lock()
|
||||
// Don't start if already running.
|
||||
if si.cancel != nil {
|
||||
@@ -639,10 +655,16 @@ func (si *SearchIndex) setTierStatus(name, state string, total, completed int) {
|
||||
|
||||
for i := range si.buildStatus.Tiers {
|
||||
if si.buildStatus.Tiers[i].Name == name {
|
||||
transitioned := si.buildStatus.Tiers[i].State != state
|
||||
si.buildStatus.Tiers[i].State = state
|
||||
si.buildStatus.Tiers[i].Total = total
|
||||
si.buildStatus.Tiers[i].Completed = completed
|
||||
si.mu.Unlock()
|
||||
|
||||
if transitioned {
|
||||
si.logIndexJob(jobs.LevelInfo, "Stage "+state+": "+name)
|
||||
}
|
||||
|
||||
si.emitStatus()
|
||||
|
||||
return
|
||||
@@ -669,6 +691,8 @@ func (si *SearchIndex) setTierError(name, errMsg string) {
|
||||
si.buildStatus.Tiers[i].State = "error"
|
||||
si.buildStatus.Tiers[i].Error = errMsg
|
||||
si.mu.Unlock()
|
||||
|
||||
si.logIndexJob(jobs.LevelError, name+": "+errMsg)
|
||||
si.emitStatus()
|
||||
|
||||
return
|
||||
@@ -691,6 +715,10 @@ func (si *SearchIndex) emitStatus() {
|
||||
si.mu.RUnlock()
|
||||
|
||||
runtime.EventsEmit(si.runtimeCtx, events.IndexStatusChanged, status)
|
||||
|
||||
// Mirror into the shared job registry. Every status mutation goes
|
||||
// through emitStatus, so hooking here covers all update paths.
|
||||
si.syncIndexJob(status)
|
||||
}
|
||||
|
||||
// GetPopularity returns the cached popularity (listen count) for
|
||||
|
||||
@@ -0,0 +1,795 @@
|
||||
// Package jobs provides a central registry for long-running background
|
||||
// work — library scans, search index builds, and anything else that runs
|
||||
// while the user is doing something else. Producers report progress
|
||||
// through a Handle; the registry coalesces those updates into a single
|
||||
// JobsChanged event so the frontend can render one indicator, one job
|
||||
// list, and one log viewer regardless of which subsystem is working.
|
||||
package jobs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
|
||||
"yellowjacket/backend/events"
|
||||
)
|
||||
|
||||
// Kind identifies the subsystem that owns a job. The frontend uses it
|
||||
// to pick an icon and to route "view details" to the right panel.
|
||||
type Kind string
|
||||
|
||||
// Job kinds.
|
||||
const (
|
||||
KindLibraryScan Kind = "library-scan"
|
||||
KindIndexBuild Kind = "index-build"
|
||||
)
|
||||
|
||||
// State is the lifecycle position of a job.
|
||||
type State string
|
||||
|
||||
// Job states. Queued, Running, Paused and Pausing are live; Complete,
|
||||
// Cancelled and Error are terminal.
|
||||
const (
|
||||
StateQueued State = "queued"
|
||||
StateRunning State = "running"
|
||||
StatePausing State = "pausing"
|
||||
StatePaused State = "paused"
|
||||
StateCancelling State = "cancelling"
|
||||
StateComplete State = "complete"
|
||||
StateCancelled State = "cancelled"
|
||||
StateError State = "error"
|
||||
)
|
||||
|
||||
// IsTerminal reports whether the state means the job will not progress
|
||||
// further without being started again from scratch.
|
||||
func (s State) IsTerminal() bool {
|
||||
return s == StateComplete || s == StateCancelled || s == StateError
|
||||
}
|
||||
|
||||
// Level is the severity of a job log entry.
|
||||
type Level string
|
||||
|
||||
// Log levels.
|
||||
const (
|
||||
LevelInfo Level = "info"
|
||||
LevelWarn Level = "warn"
|
||||
LevelError Level = "error"
|
||||
)
|
||||
|
||||
// maxLogEntries bounds the per-job log ring buffer. Scans can emit a
|
||||
// warning per unreadable file, so the buffer is a tail, not an archive.
|
||||
const maxLogEntries = 500
|
||||
|
||||
// emitInterval is how often a dirty registry is flushed to the frontend.
|
||||
// Progress tickers run at 300ms, so this keeps re-render cost bounded
|
||||
// without making the UI feel laggy.
|
||||
const emitInterval = 250 * time.Millisecond
|
||||
|
||||
// finishedRetention is how long terminal jobs stay in the registry so
|
||||
// the user can read their logs after the fact.
|
||||
const finishedRetention = 30 * time.Minute
|
||||
|
||||
// maxFinished caps how many terminal jobs are retained regardless of age.
|
||||
const maxFinished = 25
|
||||
|
||||
// Caps describes which controls a job supports. The frontend renders
|
||||
// buttons from these rather than switching on Kind, so a job that gains
|
||||
// pause support later needs no frontend change.
|
||||
type Caps struct {
|
||||
Pausable bool `json:"pausable"`
|
||||
Cancellable bool `json:"cancellable"`
|
||||
}
|
||||
|
||||
// Stage is one named sub-step of a multi-stage job, such as an index
|
||||
// build tier. Jobs with a single linear phase leave Stages empty.
|
||||
type Stage struct {
|
||||
Name string `json:"name"`
|
||||
State string `json:"state"` // pending, running, complete, error, skipped
|
||||
Current int64 `json:"current"`
|
||||
Total int64 `json:"total"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// Stat is a display-only key/value pair shown in the job detail panel
|
||||
// (e.g. "Added" / "1,204").
|
||||
type Stat struct {
|
||||
Label string `json:"label"`
|
||||
Value string `json:"value"`
|
||||
}
|
||||
|
||||
// LogEntry is one line of a job's output log.
|
||||
type LogEntry struct {
|
||||
Time int64 `json:"time"` // unix milliseconds
|
||||
Level Level `json:"level"`
|
||||
Message string `json:"message"`
|
||||
Detail string `json:"detail,omitempty"`
|
||||
}
|
||||
|
||||
// Job is the frontend-facing snapshot of a single background job.
|
||||
type Job struct {
|
||||
ID string `json:"id"`
|
||||
Kind Kind `json:"kind"`
|
||||
Title string `json:"title"`
|
||||
Subtitle string `json:"subtitle,omitempty"`
|
||||
|
||||
State State `json:"state"`
|
||||
Phase string `json:"phase,omitempty"`
|
||||
|
||||
// Current/Total drive the progress bar. Total == 0 means the job
|
||||
// is indeterminate and the frontend should render a spinner.
|
||||
Current int64 `json:"current"`
|
||||
Total int64 `json:"total"`
|
||||
|
||||
Caps Caps `json:"caps"`
|
||||
Stages []Stage `json:"stages"`
|
||||
Stats []Stat `json:"stats"`
|
||||
Error string `json:"error,omitempty"`
|
||||
|
||||
StartedAt int64 `json:"startedAt"` // unix milliseconds
|
||||
UpdatedAt int64 `json:"updatedAt"`
|
||||
EndedAt int64 `json:"endedAt,omitempty"`
|
||||
|
||||
LogCount int `json:"logCount"`
|
||||
WarnCount int `json:"warnCount"`
|
||||
ErrorCount int `json:"errorCount"`
|
||||
}
|
||||
|
||||
// Controls holds the callbacks the registry invokes when the user asks
|
||||
// for a job to be paused, resumed, or cancelled. All three are optional;
|
||||
// a nil callback means the corresponding capability is unavailable.
|
||||
//
|
||||
// Callbacks are invoked on a dedicated goroutine, so implementations may
|
||||
// block (StopBuild waits for its build goroutine to exit, for instance)
|
||||
// without stalling the Wails call dispatcher.
|
||||
type Controls struct {
|
||||
Pause func()
|
||||
Resume func()
|
||||
Cancel func()
|
||||
}
|
||||
|
||||
// Spec describes a job at registration time.
|
||||
type Spec struct {
|
||||
ID string
|
||||
Kind Kind
|
||||
Title string
|
||||
Subtitle string
|
||||
Total int64
|
||||
State State
|
||||
Caps Caps
|
||||
Controls Controls
|
||||
|
||||
// Durable marks a job whose paused state should survive an app
|
||||
// restart. On the next launch the owning subsystem adopts it back
|
||||
// into the registry as paused instead of silently resuming.
|
||||
Durable bool
|
||||
}
|
||||
|
||||
// Handle is a producer's write side of a registered job. Every mutator
|
||||
// marks the registry dirty; the emitter coalesces those into one event.
|
||||
type Handle struct {
|
||||
reg *Registry
|
||||
id string
|
||||
|
||||
mu sync.Mutex
|
||||
job Job
|
||||
controls Controls
|
||||
durable bool
|
||||
log []LogEntry
|
||||
}
|
||||
|
||||
// Registry owns every known job and pushes coalesced snapshots to the
|
||||
// frontend. It is safe for concurrent use.
|
||||
type Registry struct {
|
||||
logger *slog.Logger
|
||||
store *Store
|
||||
|
||||
mu sync.RWMutex
|
||||
ctx context.Context
|
||||
jobs map[string]*Handle
|
||||
order []string
|
||||
|
||||
dirty atomic.Bool
|
||||
}
|
||||
|
||||
// NewRegistry creates a registry. Pass a nil store to disable
|
||||
// pause-across-restart persistence (tests do this).
|
||||
func NewRegistry(logger *slog.Logger, store *Store) *Registry {
|
||||
return &Registry{
|
||||
logger: logger,
|
||||
store: store,
|
||||
jobs: make(map[string]*Handle),
|
||||
}
|
||||
}
|
||||
|
||||
// SetContext injects the Wails runtime context and starts the coalescing
|
||||
// emitter. Until it is called, updates are recorded but not pushed.
|
||||
func (r *Registry) SetContext(ctx context.Context) {
|
||||
r.mu.Lock()
|
||||
r.ctx = ctx
|
||||
r.mu.Unlock()
|
||||
|
||||
go r.emitLoop(ctx)
|
||||
}
|
||||
|
||||
// emitLoop flushes the registry to the frontend whenever it is dirty.
|
||||
func (r *Registry) emitLoop(ctx context.Context) {
|
||||
ticker := time.NewTicker(emitInterval)
|
||||
defer ticker.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
if r.dirty.Swap(false) {
|
||||
r.emit()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// emit pushes a full snapshot to the frontend. A full snapshot (rather
|
||||
// than a delta) means a component that mounts mid-scan is correct from
|
||||
// the first event it receives.
|
||||
func (r *Registry) emit() {
|
||||
r.mu.RLock()
|
||||
ctx := r.ctx
|
||||
r.mu.RUnlock()
|
||||
|
||||
if ctx == nil {
|
||||
return
|
||||
}
|
||||
|
||||
runtime.EventsEmit(ctx, events.JobsChanged, r.Snapshot())
|
||||
}
|
||||
|
||||
// touch marks the registry dirty so the next emitter tick publishes it.
|
||||
func (r *Registry) touch() {
|
||||
r.dirty.Store(true)
|
||||
}
|
||||
|
||||
// flush publishes immediately. Used for state transitions, where a
|
||||
// quarter-second of lag would make a button press feel unresponsive.
|
||||
func (r *Registry) flush() {
|
||||
r.dirty.Store(false)
|
||||
r.emit()
|
||||
}
|
||||
|
||||
// Start registers a job and returns its handle. Re-registering an
|
||||
// existing ID reuses the handle and its log, which is what happens when
|
||||
// a queued scan is popped off the queue and actually begins.
|
||||
func (r *Registry) Start(spec Spec) *Handle {
|
||||
now := nowMillis()
|
||||
|
||||
state := spec.State
|
||||
if state == "" {
|
||||
state = StateRunning
|
||||
}
|
||||
|
||||
r.mu.Lock()
|
||||
|
||||
h, existing := r.jobs[spec.ID]
|
||||
if !existing {
|
||||
h = &Handle{reg: r, id: spec.ID}
|
||||
r.jobs[spec.ID] = h
|
||||
r.order = append(r.order, spec.ID)
|
||||
}
|
||||
|
||||
r.mu.Unlock()
|
||||
|
||||
h.mu.Lock()
|
||||
|
||||
if !existing {
|
||||
h.job = Job{
|
||||
ID: spec.ID,
|
||||
StartedAt: now,
|
||||
Stages: []Stage{},
|
||||
Stats: []Stat{},
|
||||
}
|
||||
}
|
||||
|
||||
h.job.Kind = spec.Kind
|
||||
h.job.Title = spec.Title
|
||||
h.job.Subtitle = spec.Subtitle
|
||||
h.job.State = state
|
||||
h.job.Caps = spec.Caps
|
||||
h.job.Total = spec.Total
|
||||
h.job.UpdatedAt = now
|
||||
h.job.EndedAt = 0
|
||||
h.job.Error = ""
|
||||
h.controls = spec.Controls
|
||||
h.durable = spec.Durable
|
||||
h.mu.Unlock()
|
||||
|
||||
r.persistPause(spec.ID, state)
|
||||
r.pruneFinished()
|
||||
r.flush()
|
||||
|
||||
return h
|
||||
}
|
||||
|
||||
// Get returns the handle for an ID, or nil when unknown.
|
||||
func (r *Registry) Get(id string) *Handle {
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
|
||||
return r.jobs[id]
|
||||
}
|
||||
|
||||
// Snapshot returns every known job, oldest registration first.
|
||||
func (r *Registry) Snapshot() []Job {
|
||||
r.mu.RLock()
|
||||
|
||||
out := make([]Job, 0, len(r.order))
|
||||
handles := make([]*Handle, 0, len(r.order))
|
||||
|
||||
for _, id := range r.order {
|
||||
if h, ok := r.jobs[id]; ok {
|
||||
handles = append(handles, h)
|
||||
}
|
||||
}
|
||||
|
||||
r.mu.RUnlock()
|
||||
|
||||
for _, h := range handles {
|
||||
out = append(out, h.Snapshot())
|
||||
}
|
||||
|
||||
return out
|
||||
}
|
||||
|
||||
// Logs returns the retained log tail for a job, oldest entry first.
|
||||
func (r *Registry) Logs(id string) []LogEntry {
|
||||
h := r.Get(id)
|
||||
if h == nil {
|
||||
return []LogEntry{}
|
||||
}
|
||||
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
|
||||
out := make([]LogEntry, len(h.log))
|
||||
copy(out, h.log)
|
||||
|
||||
return out
|
||||
}
|
||||
|
||||
// HasActive reports whether any job is in a non-terminal state.
|
||||
func (r *Registry) HasActive() bool {
|
||||
for _, j := range r.Snapshot() {
|
||||
if !j.State.IsTerminal() {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// Pause asks the owning subsystem to pause a job. The job moves to
|
||||
// "pausing" immediately for UI feedback; the producer confirms the
|
||||
// transition to "paused" when it actually stops.
|
||||
func (r *Registry) Pause(id string) {
|
||||
h := r.Get(id)
|
||||
if h == nil {
|
||||
return
|
||||
}
|
||||
|
||||
h.mu.Lock()
|
||||
pause := h.controls.Pause
|
||||
pausable := h.job.Caps.Pausable
|
||||
live := !h.job.State.IsTerminal()
|
||||
h.mu.Unlock()
|
||||
|
||||
if pause == nil || !pausable || !live {
|
||||
return
|
||||
}
|
||||
|
||||
h.SetState(StatePausing)
|
||||
h.Logf(LevelInfo, "Pause requested")
|
||||
|
||||
go pause()
|
||||
}
|
||||
|
||||
// Resume asks the owning subsystem to continue a paused job.
|
||||
func (r *Registry) Resume(id string) {
|
||||
h := r.Get(id)
|
||||
if h == nil {
|
||||
return
|
||||
}
|
||||
|
||||
h.mu.Lock()
|
||||
resume := h.controls.Resume
|
||||
paused := h.job.State == StatePaused || h.job.State == StatePausing
|
||||
h.mu.Unlock()
|
||||
|
||||
if resume == nil || !paused {
|
||||
return
|
||||
}
|
||||
|
||||
h.Logf(LevelInfo, "Resume requested")
|
||||
|
||||
go resume()
|
||||
}
|
||||
|
||||
// Cancel asks the owning subsystem to abandon a job.
|
||||
func (r *Registry) Cancel(id string) {
|
||||
h := r.Get(id)
|
||||
if h == nil {
|
||||
return
|
||||
}
|
||||
|
||||
h.mu.Lock()
|
||||
cancel := h.controls.Cancel
|
||||
cancellable := h.job.Caps.Cancellable
|
||||
live := !h.job.State.IsTerminal()
|
||||
h.mu.Unlock()
|
||||
|
||||
if cancel == nil || !cancellable || !live {
|
||||
return
|
||||
}
|
||||
|
||||
h.SetState(StateCancelling)
|
||||
h.Logf(LevelInfo, "Cancel requested")
|
||||
|
||||
go cancel()
|
||||
}
|
||||
|
||||
// Remove drops a job from the registry entirely, discarding its log.
|
||||
func (r *Registry) Remove(id string) {
|
||||
r.mu.Lock()
|
||||
|
||||
delete(r.jobs, id)
|
||||
|
||||
for i, existing := range r.order {
|
||||
if existing == id {
|
||||
r.order = append(r.order[:i], r.order[i+1:]...)
|
||||
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
r.mu.Unlock()
|
||||
|
||||
if r.store != nil {
|
||||
r.store.ClearPaused(id)
|
||||
}
|
||||
|
||||
r.flush()
|
||||
}
|
||||
|
||||
// ClearFinished drops every terminal job. Bound to the "clear" action
|
||||
// in the jobs panel.
|
||||
func (r *Registry) ClearFinished() {
|
||||
r.mu.Lock()
|
||||
|
||||
kept := r.order[:0]
|
||||
|
||||
for _, id := range r.order {
|
||||
h, ok := r.jobs[id]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
|
||||
h.mu.Lock()
|
||||
terminal := h.job.State.IsTerminal()
|
||||
h.mu.Unlock()
|
||||
|
||||
if terminal {
|
||||
delete(r.jobs, id)
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
kept = append(kept, id)
|
||||
}
|
||||
|
||||
r.order = kept
|
||||
r.mu.Unlock()
|
||||
|
||||
r.flush()
|
||||
}
|
||||
|
||||
// pruneFinished evicts terminal jobs that are older than the retention
|
||||
// window, and trims the oldest when too many have accumulated.
|
||||
func (r *Registry) pruneFinished() {
|
||||
cutoff := nowMillis() - finishedRetention.Milliseconds()
|
||||
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
|
||||
var finished []string
|
||||
|
||||
for _, id := range r.order {
|
||||
h, ok := r.jobs[id]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
|
||||
h.mu.Lock()
|
||||
terminal := h.job.State.IsTerminal()
|
||||
ended := h.job.EndedAt
|
||||
h.mu.Unlock()
|
||||
|
||||
if terminal && ended > 0 && ended < cutoff {
|
||||
delete(r.jobs, id)
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
if terminal {
|
||||
finished = append(finished, id)
|
||||
}
|
||||
}
|
||||
|
||||
// Trim the oldest terminal jobs beyond the cap.
|
||||
if excess := len(finished) - maxFinished; excess > 0 {
|
||||
for _, id := range finished[:excess] {
|
||||
delete(r.jobs, id)
|
||||
}
|
||||
}
|
||||
|
||||
kept := r.order[:0]
|
||||
|
||||
for _, id := range r.order {
|
||||
if _, ok := r.jobs[id]; ok {
|
||||
kept = append(kept, id)
|
||||
}
|
||||
}
|
||||
|
||||
r.order = kept
|
||||
}
|
||||
|
||||
// persistPause writes or clears the durable pause record for a job so a
|
||||
// paused job comes back paused after a restart instead of silently
|
||||
// resuming (or silently never running again).
|
||||
func (r *Registry) persistPause(id string, state State) {
|
||||
if r.store == nil {
|
||||
return
|
||||
}
|
||||
|
||||
h := r.Get(id)
|
||||
if h == nil {
|
||||
return
|
||||
}
|
||||
|
||||
h.mu.Lock()
|
||||
durable := h.durable
|
||||
job := h.job
|
||||
h.mu.Unlock()
|
||||
|
||||
if !durable {
|
||||
return
|
||||
}
|
||||
|
||||
if state != StatePaused {
|
||||
r.store.ClearPaused(id)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
r.store.SetPaused(Persisted{
|
||||
ID: job.ID,
|
||||
Kind: job.Kind,
|
||||
Title: job.Title,
|
||||
Subtitle: job.Subtitle,
|
||||
})
|
||||
}
|
||||
|
||||
// PausedEntries returns the jobs of the given kind that were paused when
|
||||
// the app last shut down. Subsystems call this during startup and adopt
|
||||
// each entry back into the registry with its controls attached.
|
||||
func (r *Registry) PausedEntries(kind Kind) []Persisted {
|
||||
if r.store == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
return r.store.PausedEntries(kind)
|
||||
}
|
||||
|
||||
// IsPersistentlyPaused reports whether the given job ID was paused when
|
||||
// the app last shut down. Subsystems check this before auto-starting
|
||||
// work at launch, so a paused job stays paused.
|
||||
func (r *Registry) IsPersistentlyPaused(id string) bool {
|
||||
if r.store == nil {
|
||||
return false
|
||||
}
|
||||
|
||||
return r.store.IsPaused(id)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Handle
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// Snapshot returns a copy of the job's current state.
|
||||
func (h *Handle) Snapshot() Job {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
|
||||
job := h.job
|
||||
|
||||
job.Stages = make([]Stage, len(h.job.Stages))
|
||||
copy(job.Stages, h.job.Stages)
|
||||
|
||||
job.Stats = make([]Stat, len(h.job.Stats))
|
||||
copy(job.Stats, h.job.Stats)
|
||||
|
||||
return job
|
||||
}
|
||||
|
||||
// State returns the job's current state.
|
||||
func (h *Handle) State() State {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
|
||||
return h.job.State
|
||||
}
|
||||
|
||||
// SetState moves the job to a new state. Terminal states stamp EndedAt.
|
||||
// Transitions flush immediately so controls feel responsive.
|
||||
func (h *Handle) SetState(state State) {
|
||||
h.mu.Lock()
|
||||
|
||||
if h.job.State == state {
|
||||
h.mu.Unlock()
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
h.job.State = state
|
||||
h.job.UpdatedAt = nowMillis()
|
||||
|
||||
if state.IsTerminal() {
|
||||
h.job.EndedAt = h.job.UpdatedAt
|
||||
} else {
|
||||
h.job.EndedAt = 0
|
||||
}
|
||||
|
||||
h.mu.Unlock()
|
||||
|
||||
h.reg.persistPause(h.id, state)
|
||||
h.reg.flush()
|
||||
}
|
||||
|
||||
// SetPhase records the human-readable phase label ("Scanning files").
|
||||
func (h *Handle) SetPhase(phase string) {
|
||||
h.mu.Lock()
|
||||
|
||||
changed := h.job.Phase != phase
|
||||
h.job.Phase = phase
|
||||
h.job.UpdatedAt = nowMillis()
|
||||
h.mu.Unlock()
|
||||
|
||||
if changed {
|
||||
h.reg.flush()
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
h.reg.touch()
|
||||
}
|
||||
|
||||
// SetProgress updates the progress numerator and denominator. Pass a
|
||||
// total of zero to render the job as indeterminate.
|
||||
func (h *Handle) SetProgress(current, total int64) {
|
||||
h.mu.Lock()
|
||||
h.job.Current = current
|
||||
h.job.Total = total
|
||||
h.job.UpdatedAt = nowMillis()
|
||||
h.mu.Unlock()
|
||||
|
||||
h.reg.touch()
|
||||
}
|
||||
|
||||
// SetSubtitle updates the secondary line shown under the job title.
|
||||
func (h *Handle) SetSubtitle(subtitle string) {
|
||||
h.mu.Lock()
|
||||
h.job.Subtitle = subtitle
|
||||
h.job.UpdatedAt = nowMillis()
|
||||
h.mu.Unlock()
|
||||
|
||||
h.reg.touch()
|
||||
}
|
||||
|
||||
// SetStats replaces the job's display statistics.
|
||||
func (h *Handle) SetStats(stats []Stat) {
|
||||
h.mu.Lock()
|
||||
h.job.Stats = stats
|
||||
h.job.UpdatedAt = nowMillis()
|
||||
h.mu.Unlock()
|
||||
|
||||
h.reg.touch()
|
||||
}
|
||||
|
||||
// SetStages replaces the job's stage list. Used by multi-tier jobs such
|
||||
// as the index build.
|
||||
func (h *Handle) SetStages(stages []Stage) {
|
||||
h.mu.Lock()
|
||||
h.job.Stages = stages
|
||||
h.job.UpdatedAt = nowMillis()
|
||||
h.mu.Unlock()
|
||||
|
||||
h.reg.touch()
|
||||
}
|
||||
|
||||
// SetCaps updates which controls the job currently supports.
|
||||
func (h *Handle) SetCaps(caps Caps) {
|
||||
h.mu.Lock()
|
||||
h.job.Caps = caps
|
||||
h.mu.Unlock()
|
||||
|
||||
h.reg.touch()
|
||||
}
|
||||
|
||||
// Logf appends a line to the job's log ring buffer.
|
||||
func (h *Handle) Logf(level Level, message string) {
|
||||
h.logEntry(level, message, "")
|
||||
}
|
||||
|
||||
// LogDetail appends a log line carrying a secondary detail string, such
|
||||
// as the file path a warning refers to.
|
||||
func (h *Handle) LogDetail(level Level, message, detail string) {
|
||||
h.logEntry(level, message, detail)
|
||||
}
|
||||
|
||||
func (h *Handle) logEntry(level Level, message, detail string) {
|
||||
h.mu.Lock()
|
||||
|
||||
if len(h.log) >= maxLogEntries {
|
||||
// Drop the oldest entry. Log volume is low enough (phase
|
||||
// transitions and per-file warnings) that the copy is cheaper
|
||||
// than maintaining an explicit ring index.
|
||||
h.log = append(h.log[:0], h.log[1:]...)
|
||||
}
|
||||
|
||||
h.log = append(h.log, LogEntry{
|
||||
Time: nowMillis(),
|
||||
Level: level,
|
||||
Message: message,
|
||||
Detail: detail,
|
||||
})
|
||||
|
||||
h.job.LogCount++
|
||||
|
||||
switch level {
|
||||
case LevelWarn:
|
||||
h.job.WarnCount++
|
||||
case LevelError:
|
||||
h.job.ErrorCount++
|
||||
case LevelInfo:
|
||||
}
|
||||
|
||||
h.mu.Unlock()
|
||||
|
||||
h.reg.touch()
|
||||
}
|
||||
|
||||
// Complete marks the job finished successfully.
|
||||
func (h *Handle) Complete() {
|
||||
h.SetPhase("")
|
||||
h.SetState(StateComplete)
|
||||
}
|
||||
|
||||
// Cancelled marks the job as abandoned at the user's request.
|
||||
func (h *Handle) Cancelled() {
|
||||
h.SetPhase("")
|
||||
h.SetState(StateCancelled)
|
||||
}
|
||||
|
||||
// Fail marks the job as errored and records the message.
|
||||
func (h *Handle) Fail(err error) {
|
||||
h.mu.Lock()
|
||||
h.job.Error = err.Error()
|
||||
h.mu.Unlock()
|
||||
|
||||
h.Logf(LevelError, err.Error())
|
||||
h.SetState(StateError)
|
||||
}
|
||||
|
||||
func nowMillis() int64 {
|
||||
return time.Now().UnixMilli()
|
||||
}
|
||||
@@ -0,0 +1,326 @@
|
||||
package jobs
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"log/slog"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
var errBoom = errors.New("boom")
|
||||
|
||||
func testRegistry() *Registry {
|
||||
return NewRegistry(slog.New(slog.DiscardHandler), nil)
|
||||
}
|
||||
|
||||
func TestStartRegistersJob(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
r := testRegistry()
|
||||
|
||||
h := r.Start(Spec{
|
||||
ID: "scan:1",
|
||||
Kind: KindLibraryScan,
|
||||
Title: "Scanning Music",
|
||||
Caps: Caps{Pausable: true, Cancellable: true},
|
||||
})
|
||||
|
||||
if h == nil {
|
||||
t.Fatal("expected a handle")
|
||||
}
|
||||
|
||||
snap := r.Snapshot()
|
||||
if len(snap) != 1 {
|
||||
t.Fatalf("expected 1 job, got %d", len(snap))
|
||||
}
|
||||
|
||||
if snap[0].State != StateRunning {
|
||||
t.Errorf("expected default state running, got %q", snap[0].State)
|
||||
}
|
||||
|
||||
if snap[0].Title != "Scanning Music" {
|
||||
t.Errorf("unexpected title %q", snap[0].Title)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStartReusesHandleAndLog(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
r := testRegistry()
|
||||
|
||||
h := r.Start(Spec{ID: "scan:1", Kind: KindLibraryScan, State: StateQueued})
|
||||
h.Logf(LevelInfo, "queued")
|
||||
|
||||
// A queued scan being popped off the queue re-registers the same ID.
|
||||
again := r.Start(Spec{ID: "scan:1", Kind: KindLibraryScan})
|
||||
if again != h {
|
||||
t.Fatal("expected the same handle to be reused")
|
||||
}
|
||||
|
||||
if got := len(r.Logs("scan:1")); got != 1 {
|
||||
t.Errorf("expected the log to survive re-registration, got %d entries", got)
|
||||
}
|
||||
|
||||
if again.State() != StateRunning {
|
||||
t.Errorf("expected state running after restart, got %q", again.State())
|
||||
}
|
||||
|
||||
if len(r.Snapshot()) != 1 {
|
||||
t.Error("re-registering should not duplicate the job")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLogRingIsBounded(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
r := testRegistry()
|
||||
h := r.Start(Spec{ID: "scan:1", Kind: KindLibraryScan})
|
||||
|
||||
for range maxLogEntries + 50 {
|
||||
h.Logf(LevelWarn, "warning")
|
||||
}
|
||||
|
||||
logs := r.Logs("scan:1")
|
||||
if len(logs) != maxLogEntries {
|
||||
t.Errorf("expected log capped at %d, got %d", maxLogEntries, len(logs))
|
||||
}
|
||||
|
||||
// LogCount keeps counting past the ring so the UI can show that
|
||||
// entries were dropped.
|
||||
if got := h.Snapshot().LogCount; got != maxLogEntries+50 {
|
||||
t.Errorf("expected LogCount %d, got %d", maxLogEntries+50, got)
|
||||
}
|
||||
|
||||
if got := h.Snapshot().WarnCount; got != maxLogEntries+50 {
|
||||
t.Errorf("expected WarnCount %d, got %d", maxLogEntries+50, got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTerminalStatesStampEndedAt(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
apply func(*Handle)
|
||||
want State
|
||||
}{
|
||||
{"complete", func(h *Handle) { h.Complete() }, StateComplete},
|
||||
{"cancelled", func(h *Handle) { h.Cancelled() }, StateCancelled},
|
||||
{"failed", func(h *Handle) { h.Fail(errBoom) }, StateError},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
r := testRegistry()
|
||||
h := r.Start(Spec{ID: "scan:1", Kind: KindLibraryScan})
|
||||
tt.apply(h)
|
||||
|
||||
snap := h.Snapshot()
|
||||
if snap.State != tt.want {
|
||||
t.Errorf("expected state %q, got %q", tt.want, snap.State)
|
||||
}
|
||||
|
||||
if !snap.State.IsTerminal() {
|
||||
t.Error("expected a terminal state")
|
||||
}
|
||||
|
||||
if snap.EndedAt == 0 {
|
||||
t.Error("expected EndedAt to be stamped")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFailRecordsErrorMessage(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
r := testRegistry()
|
||||
h := r.Start(Spec{ID: "index:build", Kind: KindIndexBuild})
|
||||
h.Fail(errBoom)
|
||||
|
||||
if got := h.Snapshot().Error; got != "boom" {
|
||||
t.Errorf("expected error %q, got %q", "boom", got)
|
||||
}
|
||||
|
||||
if got := h.Snapshot().ErrorCount; got != 1 {
|
||||
t.Errorf("expected the failure to be logged, got ErrorCount %d", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPauseInvokesControlAndMarksPausing(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
r := testRegistry()
|
||||
|
||||
var wg sync.WaitGroup
|
||||
|
||||
wg.Add(1)
|
||||
r.Start(Spec{
|
||||
ID: "scan:1",
|
||||
Kind: KindLibraryScan,
|
||||
Caps: Caps{Pausable: true},
|
||||
Controls: Controls{Pause: wg.Done},
|
||||
})
|
||||
|
||||
r.Pause("scan:1")
|
||||
wg.Wait()
|
||||
|
||||
// The producer confirms StatePaused; the registry only promises
|
||||
// the intermediate "pausing" state.
|
||||
if got := r.Get("scan:1").State(); got != StatePausing {
|
||||
t.Errorf("expected state pausing, got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestControlsRespectCapabilities(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
r := testRegistry()
|
||||
|
||||
called := false
|
||||
|
||||
r.Start(Spec{
|
||||
ID: "scan:1",
|
||||
Kind: KindLibraryScan,
|
||||
Caps: Caps{Pausable: false, Cancellable: false},
|
||||
Controls: Controls{Pause: func() { called = true }, Cancel: func() { called = true }},
|
||||
})
|
||||
|
||||
r.Pause("scan:1")
|
||||
r.Cancel("scan:1")
|
||||
|
||||
if called {
|
||||
t.Error("controls must not fire for a job that declares no capability")
|
||||
}
|
||||
|
||||
if got := r.Get("scan:1").State(); got != StateRunning {
|
||||
t.Errorf("expected state to be unchanged, got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestControlsIgnoreTerminalJobs(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
r := testRegistry()
|
||||
|
||||
called := false
|
||||
h := r.Start(Spec{
|
||||
ID: "scan:1",
|
||||
Kind: KindLibraryScan,
|
||||
Caps: Caps{Pausable: true, Cancellable: true},
|
||||
Controls: Controls{Pause: func() { called = true }, Cancel: func() { called = true }},
|
||||
})
|
||||
h.Complete()
|
||||
|
||||
r.Pause("scan:1")
|
||||
r.Cancel("scan:1")
|
||||
|
||||
if called {
|
||||
t.Error("controls must not fire for a finished job")
|
||||
}
|
||||
}
|
||||
|
||||
func TestControlsOnUnknownJobAreNoOps(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
r := testRegistry()
|
||||
|
||||
// Stale IDs arrive from a frontend holding an old snapshot.
|
||||
r.Pause("scan:404")
|
||||
r.Resume("scan:404")
|
||||
r.Cancel("scan:404")
|
||||
|
||||
if got := len(r.Logs("scan:404")); got != 0 {
|
||||
t.Errorf("expected no logs for an unknown job, got %d", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClearFinishedKeepsActiveJobs(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
r := testRegistry()
|
||||
|
||||
done := r.Start(Spec{ID: "scan:1", Kind: KindLibraryScan})
|
||||
done.Complete()
|
||||
r.Start(Spec{ID: "scan:2", Kind: KindLibraryScan})
|
||||
|
||||
r.ClearFinished()
|
||||
|
||||
snap := r.Snapshot()
|
||||
if len(snap) != 1 {
|
||||
t.Fatalf("expected 1 job to survive, got %d", len(snap))
|
||||
}
|
||||
|
||||
if snap[0].ID != "scan:2" {
|
||||
t.Errorf("expected the active job to survive, kept %q", snap[0].ID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHasActive(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
r := testRegistry()
|
||||
|
||||
if r.HasActive() {
|
||||
t.Error("an empty registry has no active jobs")
|
||||
}
|
||||
|
||||
h := r.Start(Spec{ID: "scan:1", Kind: KindLibraryScan})
|
||||
|
||||
if !r.HasActive() {
|
||||
t.Error("expected the running job to count as active")
|
||||
}
|
||||
|
||||
h.Complete()
|
||||
|
||||
if r.HasActive() {
|
||||
t.Error("a completed job is not active")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSnapshotIsADeepCopy(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
r := testRegistry()
|
||||
h := r.Start(Spec{ID: "index:build", Kind: KindIndexBuild})
|
||||
h.SetStages([]Stage{{Name: "Catalog Import", State: "running"}})
|
||||
|
||||
snap := h.Snapshot()
|
||||
snap.Stages[0].State = "mutated"
|
||||
|
||||
if got := h.Snapshot().Stages[0].State; got != "running" {
|
||||
t.Errorf("mutating a snapshot leaked into the job: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConcurrentUpdatesAreSafe(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
r := testRegistry()
|
||||
h := r.Start(Spec{ID: "scan:1", Kind: KindLibraryScan})
|
||||
|
||||
var wg sync.WaitGroup
|
||||
|
||||
for i := range 8 {
|
||||
wg.Add(1)
|
||||
|
||||
go func(n int) {
|
||||
defer wg.Done()
|
||||
|
||||
for range 100 {
|
||||
h.SetProgress(int64(n), 100)
|
||||
h.Logf(LevelWarn, "concurrent")
|
||||
|
||||
_ = r.Snapshot()
|
||||
}
|
||||
}(i)
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
|
||||
if got := h.Snapshot().WarnCount; got != 800 {
|
||||
t.Errorf("expected 800 warnings, got %d", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package jobs
|
||||
|
||||
// Service is the Wails-bound facade over the registry. It deliberately
|
||||
// exposes only the read and control surface — producers get a *Handle
|
||||
// through the registry instead, so the frontend cannot invent jobs.
|
||||
type Service struct {
|
||||
reg *Registry
|
||||
}
|
||||
|
||||
// NewService wraps a registry for frontend binding.
|
||||
func NewService(reg *Registry) *Service {
|
||||
return &Service{reg: reg}
|
||||
}
|
||||
|
||||
// GetJobs returns every known job — active first by registration order,
|
||||
// including recently finished ones so the panel can show outcomes.
|
||||
func (s *Service) GetJobs() []Job {
|
||||
return s.reg.Snapshot()
|
||||
}
|
||||
|
||||
// GetJobLog returns the retained log tail for one job.
|
||||
func (s *Service) GetJobLog(id string) []LogEntry {
|
||||
return s.reg.Logs(id)
|
||||
}
|
||||
|
||||
// PauseJob asks the owning subsystem to pause a job. Returns
|
||||
// immediately; the job reports "paused" once it actually stops.
|
||||
func (s *Service) PauseJob(id string) {
|
||||
s.reg.Pause(id)
|
||||
}
|
||||
|
||||
// ResumeJob continues a paused job.
|
||||
func (s *Service) ResumeJob(id string) {
|
||||
s.reg.Resume(id)
|
||||
}
|
||||
|
||||
// CancelJob abandons a job.
|
||||
func (s *Service) CancelJob(id string) {
|
||||
s.reg.Cancel(id)
|
||||
}
|
||||
|
||||
// DismissJob removes a single finished job from the list.
|
||||
func (s *Service) DismissJob(id string) {
|
||||
s.reg.Remove(id)
|
||||
}
|
||||
|
||||
// ClearFinishedJobs removes every terminal job from the list.
|
||||
func (s *Service) ClearFinishedJobs() {
|
||||
s.reg.ClearFinished()
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
package jobs
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"yellowjacket/backend/database"
|
||||
)
|
||||
|
||||
// Persisted is a job whose paused state outlived the process that
|
||||
// created it. The owning subsystem adopts these back into the registry
|
||||
// during startup, re-attaching the controls needed to resume.
|
||||
type Persisted struct {
|
||||
ID string `json:"id"`
|
||||
Kind Kind `json:"kind"`
|
||||
Title string `json:"title"`
|
||||
Subtitle string `json:"subtitle"`
|
||||
}
|
||||
|
||||
// Store persists durable job state to the job_state table.
|
||||
type Store struct {
|
||||
db *database.DB
|
||||
logger *slog.Logger
|
||||
}
|
||||
|
||||
// NewStore creates a job state store backed by the application database.
|
||||
func NewStore(db *database.DB, logger *slog.Logger) *Store {
|
||||
return &Store{db: db, logger: logger}
|
||||
}
|
||||
|
||||
// SetPaused records that a job is paused.
|
||||
func (s *Store) SetPaused(p Persisted) {
|
||||
if s == nil || s.db == nil {
|
||||
return
|
||||
}
|
||||
|
||||
if _, err := s.db.ExecContext(
|
||||
`INSERT OR REPLACE INTO job_state`+
|
||||
` (id, kind, title, subtitle, paused_at)`+
|
||||
` VALUES (?, ?, ?, ?, ?)`,
|
||||
p.ID, string(p.Kind), p.Title, p.Subtitle,
|
||||
time.Now().UTC().Format(time.RFC3339),
|
||||
); err != nil {
|
||||
s.logger.Warn("jobs: could not persist paused job",
|
||||
"id", p.ID, "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
// ClearPaused removes a job's durable pause record.
|
||||
func (s *Store) ClearPaused(id string) {
|
||||
if s == nil || s.db == nil {
|
||||
return
|
||||
}
|
||||
|
||||
if _, err := s.db.ExecContext(
|
||||
"DELETE FROM job_state WHERE id = ?", id,
|
||||
); err != nil {
|
||||
s.logger.Warn("jobs: could not clear paused job",
|
||||
"id", id, "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
// PausedEntries returns every persisted paused job of the given kind.
|
||||
func (s *Store) PausedEntries(kind Kind) []Persisted {
|
||||
if s == nil || s.db == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
rows, err := s.db.QueryContext(
|
||||
`SELECT id, kind, title, subtitle FROM job_state`+
|
||||
` WHERE kind = ? ORDER BY paused_at`,
|
||||
string(kind),
|
||||
)
|
||||
if err != nil {
|
||||
s.logger.Warn("jobs: could not read paused jobs",
|
||||
"kind", kind, "err", err)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
defer func() { _ = rows.Close() }()
|
||||
|
||||
var out []Persisted
|
||||
|
||||
for rows.Next() {
|
||||
var (
|
||||
p Persisted
|
||||
kindText string
|
||||
)
|
||||
|
||||
if scanErr := rows.Scan(
|
||||
&p.ID, &kindText, &p.Title, &p.Subtitle,
|
||||
); scanErr != nil {
|
||||
s.logger.Warn("jobs: could not scan paused job", "err", scanErr)
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
p.Kind = Kind(kindText)
|
||||
out = append(out, p)
|
||||
}
|
||||
|
||||
return out
|
||||
}
|
||||
|
||||
// IsPaused reports whether the given job ID has a durable pause record.
|
||||
// Subsystems check this before auto-starting work at launch.
|
||||
func (s *Store) IsPaused(id string) bool {
|
||||
if s == nil || s.db == nil {
|
||||
return false
|
||||
}
|
||||
|
||||
rows, err := s.db.QueryContext(
|
||||
"SELECT 1 FROM job_state WHERE id = ?", id,
|
||||
)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
defer func() { _ = rows.Close() }()
|
||||
|
||||
return rows.Next()
|
||||
}
|
||||
+42
-20
@@ -23,6 +23,7 @@ import (
|
||||
"yellowjacket/backend/database"
|
||||
"yellowjacket/backend/database/sql/sqlcgen"
|
||||
"yellowjacket/backend/events"
|
||||
"yellowjacket/backend/jobs"
|
||||
"yellowjacket/backend/metadata"
|
||||
"yellowjacket/backend/system"
|
||||
)
|
||||
@@ -106,6 +107,10 @@ type Library struct {
|
||||
scanPaused bool
|
||||
scanPauseCh chan struct{}
|
||||
|
||||
// jobs is the background job registry. Nil in tests that do not
|
||||
// exercise progress reporting; every use site must nil-check.
|
||||
jobs *jobs.Registry
|
||||
|
||||
// Scan queue fields — protected by mu.
|
||||
scanQueue []scanQueueEntry
|
||||
currentScanLibraryID int64
|
||||
@@ -218,6 +223,25 @@ func (l *Library) scanInternal(
|
||||
metrics.LibraryName = libraryName
|
||||
scanStart := time.Now()
|
||||
|
||||
// Register the background job before any work starts so the UI
|
||||
// indicator appears immediately, even during the pre-walk count.
|
||||
jobHandle := l.startScanJob(scanQueueEntry{
|
||||
libraryID: libraryID,
|
||||
libraryName: libraryName,
|
||||
libraryPath: libraryPath,
|
||||
})
|
||||
|
||||
// Stream non-fatal issues into the job log as they happen rather
|
||||
// than dumping them all at completion — the point of the log pane
|
||||
// is to answer "what is it doing right now".
|
||||
metrics.onWarning = func(w ScanWarning) {
|
||||
if jobHandle == nil {
|
||||
return
|
||||
}
|
||||
|
||||
jobHandle.LogDetail(jobs.LevelWarn, w.Phase+": "+w.Err, w.FilePath)
|
||||
}
|
||||
|
||||
scanCtx, scanCancel := context.WithCancel(l.ctx)
|
||||
defer scanCancel()
|
||||
|
||||
@@ -281,6 +305,14 @@ func (l *Library) scanInternal(
|
||||
}
|
||||
}
|
||||
|
||||
// emitProgress publishes one progress update to both consumers: the
|
||||
// legacy LibraryScanProgress event and the shared job registry.
|
||||
// Routing everything through here keeps the two from drifting.
|
||||
emitProgress := func(p ScanProgress) {
|
||||
runtime.EventsEmit(l.ctx, events.LibraryScanProgress, p)
|
||||
reportScanProgress(jobHandle, p)
|
||||
}
|
||||
|
||||
runtime.EventsEmit(l.ctx, events.LibraryScanStarted, map[string]any{
|
||||
"libraryId": libraryID,
|
||||
"libraryName": libraryName,
|
||||
@@ -289,9 +321,7 @@ func (l *Library) scanInternal(
|
||||
basePath := libraryPath
|
||||
|
||||
// --- Pre-walk: count audio files for progress reporting ---
|
||||
runtime.EventsEmit(l.ctx, events.LibraryScanProgress,
|
||||
mkProgress("counting", 0, 0, 0, 0, 0),
|
||||
)
|
||||
emitProgress(mkProgress("counting", 0, 0, 0, 0, 0))
|
||||
|
||||
totalFiles := countAudioFiles(basePath)
|
||||
|
||||
@@ -488,14 +518,10 @@ func (l *Library) scanInternal(
|
||||
s := skipped.Load()
|
||||
u := updated.Load()
|
||||
|
||||
runtime.EventsEmit(
|
||||
l.ctx,
|
||||
events.LibraryScanProgress,
|
||||
mkProgress(
|
||||
"scanning", totalFiles,
|
||||
a+s+u, a, s, u,
|
||||
),
|
||||
)
|
||||
emitProgress(mkProgress(
|
||||
"scanning", totalFiles,
|
||||
a+s+u, a, s, u,
|
||||
))
|
||||
case <-stopProgress:
|
||||
return
|
||||
}
|
||||
@@ -618,18 +644,14 @@ func (l *Library) scanInternal(
|
||||
s := skipped.Load()
|
||||
u := updated.Load()
|
||||
|
||||
runtime.EventsEmit(l.ctx, events.LibraryScanProgress,
|
||||
mkProgress("scanning", totalFiles, a+s+u, a, s, u),
|
||||
)
|
||||
emitProgress(mkProgress("scanning", totalFiles, a+s+u, a, s, u))
|
||||
|
||||
// Close thumbnail channel and wait for all thumbnail workers
|
||||
// to finish. The DB writer has stopped sending work at this
|
||||
// point so it is safe to close.
|
||||
thumbStart := time.Now()
|
||||
|
||||
runtime.EventsEmit(l.ctx, events.LibraryScanProgress,
|
||||
mkProgress("thumbnails", totalFiles, a+s+u, a, s, u),
|
||||
)
|
||||
emitProgress(mkProgress("thumbnails", totalFiles, a+s+u, a, s, u))
|
||||
|
||||
close(thumbChan)
|
||||
thumbWg.Wait()
|
||||
@@ -648,9 +670,7 @@ func (l *Library) scanInternal(
|
||||
l.logger.Info("scan cancelled, skipping orphan cleanup")
|
||||
} else {
|
||||
// --- Phase 5: orphan cleanup ---
|
||||
runtime.EventsEmit(l.ctx, events.LibraryScanProgress,
|
||||
mkProgress("orphans", totalFiles, a+s+u, a, s, u),
|
||||
)
|
||||
emitProgress(mkProgress("orphans", totalFiles, a+s+u, a, s, u))
|
||||
|
||||
orphanStart := time.Now()
|
||||
|
||||
@@ -753,6 +773,8 @@ func (l *Library) scanInternal(
|
||||
"total", metrics.Total,
|
||||
)
|
||||
|
||||
finishScanJob(jobHandle, metrics, cancelled)
|
||||
|
||||
if cancelled {
|
||||
runtime.EventsEmit(
|
||||
l.ctx, events.LibraryScanCancelled, metrics,
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package library
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
@@ -59,6 +61,11 @@ type ScanMetrics struct {
|
||||
|
||||
// Non-fatal issues encountered during scanning.
|
||||
Warnings []ScanWarning `json:"warnings"`
|
||||
|
||||
// onWarning, when set, receives each warning as it is recorded so
|
||||
// the scan's job log can show problems live instead of only in the
|
||||
// completion payload. Invoked outside the metrics lock.
|
||||
onWarning func(ScanWarning) `json:"-"`
|
||||
}
|
||||
|
||||
// ScanProgress is the payload emitted periodically during a scan to
|
||||
@@ -82,6 +89,59 @@ type ScanWarning struct {
|
||||
Err string `json:"err"`
|
||||
}
|
||||
|
||||
// timingBreakdown renders the full per-phase timing profile as plain
|
||||
// text for the job log. This replaces the metrics table that used to
|
||||
// live on the settings page: same numbers, but attached to the scan
|
||||
// that produced them and copyable from the job's output pane.
|
||||
func (m *ScanMetrics) timingBreakdown() string {
|
||||
var b strings.Builder
|
||||
|
||||
line := func(label string, d time.Duration) {
|
||||
b.WriteString(label)
|
||||
b.WriteString(": ")
|
||||
b.WriteString(d.Round(time.Millisecond).String())
|
||||
b.WriteString("\n")
|
||||
}
|
||||
|
||||
line("Total", m.Total)
|
||||
|
||||
// Full-rescan-only phases; zero on an incremental scan.
|
||||
if m.ClearQueue > 0 || m.ClearDatabase > 0 || m.ClearCoverFiles > 0 {
|
||||
line(" Clear queue", m.ClearQueue)
|
||||
line(" Clear database", m.ClearDatabase)
|
||||
line(" Clear cover files", m.ClearCoverFiles)
|
||||
}
|
||||
|
||||
line(" Load existing files", m.LoadExisting)
|
||||
line(" Directory walk", m.WalkDuration)
|
||||
line(" Metadata extraction (wall clock)", m.ExtractionWallClock)
|
||||
line(" Tag extraction (cumulative)", m.TagExtraction)
|
||||
line(" Duration extraction (cumulative)", m.DurationExtraction)
|
||||
|
||||
for format, ms := range m.FormatExtraction {
|
||||
b.WriteString(" ")
|
||||
b.WriteString(format)
|
||||
b.WriteString(" (")
|
||||
b.WriteString(strconv.FormatInt(m.FormatCount[format], 10))
|
||||
b.WriteString(" files): ")
|
||||
b.WriteString((time.Duration(ms) * time.Millisecond).String())
|
||||
b.WriteString("\n")
|
||||
}
|
||||
|
||||
line(" DB writes (wall clock)", m.DBWritesWallClock)
|
||||
line(" Batch commits", m.BatchCommits)
|
||||
line(" Save cover originals", m.CoverArtSave)
|
||||
line(" Thumbnails (wall clock)", m.ThumbnailWallClock)
|
||||
line(" Cumulative CPU time", m.ThumbnailGeneration)
|
||||
line(" Small", m.ThumbnailSmall)
|
||||
line(" Medium", m.ThumbnailMedium)
|
||||
line(" Large", m.ThumbnailLarge)
|
||||
line(" Orphan cleanup", m.OrphanCleanup)
|
||||
line(" Post-scan variants", m.PostScanVariants)
|
||||
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func newScanMetrics() *ScanMetrics {
|
||||
return &ScanMetrics{
|
||||
FormatExtraction: make(map[string]int64),
|
||||
@@ -113,14 +173,22 @@ func (m *ScanMetrics) addCoverArtSave(d time.Duration) {
|
||||
|
||||
// addWarning records a non-fatal scan issue. Safe for concurrent use.
|
||||
func (m *ScanMetrics) addWarning(filePath, phase string, err error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
|
||||
m.Warnings = append(m.Warnings, ScanWarning{
|
||||
warning := ScanWarning{
|
||||
FilePath: filePath,
|
||||
Phase: phase,
|
||||
Err: err.Error(),
|
||||
})
|
||||
}
|
||||
|
||||
m.mu.Lock()
|
||||
m.Warnings = append(m.Warnings, warning)
|
||||
notify := m.onWarning
|
||||
m.mu.Unlock()
|
||||
|
||||
// Called outside the lock: the job registry takes its own locks and
|
||||
// must never be able to deadlock against a scan worker.
|
||||
if notify != nil {
|
||||
notify(warning)
|
||||
}
|
||||
}
|
||||
|
||||
// addThumbnailTier records the time spent generating a single
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
|
||||
"yellowjacket/backend/events"
|
||||
"yellowjacket/backend/jobs"
|
||||
)
|
||||
|
||||
// CancelScan cancels an in-progress scan. Returns immediately;
|
||||
@@ -27,31 +28,66 @@ func (l *Library) CancelScan() {
|
||||
// next pause checkpoint until ResumeScan is called.
|
||||
func (l *Library) PauseScan() {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
|
||||
if !l.scanActive || l.scanPaused {
|
||||
l.mu.Unlock()
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
l.scanPaused = true
|
||||
l.scanPauseCh = make(chan struct{})
|
||||
pausedID := l.currentScanLibraryID
|
||||
reg := l.jobs
|
||||
l.mu.Unlock()
|
||||
|
||||
runtime.EventsEmit(l.ctx, events.LibraryScanPaused)
|
||||
|
||||
// Confirm the pause on the job — the registry moved it to "pausing"
|
||||
// when the request came in. Writing the durable pause record is a
|
||||
// side effect of reaching StatePaused, so a scan paused now comes
|
||||
// back paused after a restart. Done after releasing l.mu: this
|
||||
// writes to the database, and workers take l.mu on every pause
|
||||
// checkpoint.
|
||||
if reg == nil {
|
||||
return
|
||||
}
|
||||
|
||||
if h := reg.Get(scanJobID(pausedID)); h != nil {
|
||||
h.SetState(jobs.StatePaused)
|
||||
h.SetPhase("Paused")
|
||||
h.Logf(jobs.LevelInfo, "Scan paused")
|
||||
}
|
||||
}
|
||||
|
||||
// ResumeScan unblocks a paused scan.
|
||||
func (l *Library) ResumeScan() {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
|
||||
if !l.scanPaused {
|
||||
l.mu.Unlock()
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
l.scanPaused = false
|
||||
close(l.scanPauseCh) // unblocks all waiting workers
|
||||
resumedID := l.currentScanLibraryID
|
||||
reg := l.jobs
|
||||
l.mu.Unlock()
|
||||
|
||||
runtime.EventsEmit(l.ctx, events.LibraryScanResumed)
|
||||
|
||||
// Clears the durable pause record as a side effect of leaving
|
||||
// StatePaused.
|
||||
if reg == nil {
|
||||
return
|
||||
}
|
||||
|
||||
if h := reg.Get(scanJobID(resumedID)); h != nil {
|
||||
h.SetState(jobs.StateRunning)
|
||||
h.Logf(jobs.LevelInfo, "Scan resumed")
|
||||
}
|
||||
}
|
||||
|
||||
// IsScanActive returns whether a scan is currently running.
|
||||
|
||||
@@ -0,0 +1,348 @@
|
||||
package library
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"yellowjacket/backend/jobs"
|
||||
)
|
||||
|
||||
// scanJobPrefix namespaces library scan jobs in the shared registry.
|
||||
const scanJobPrefix = "scan:"
|
||||
|
||||
// scanPhaseLabels maps internal scan phase identifiers to the labels
|
||||
// shown in the jobs UI.
|
||||
var scanPhaseLabels = map[string]string{
|
||||
"counting": "Counting files",
|
||||
"scanning": "Reading metadata",
|
||||
"thumbnails": "Generating thumbnails",
|
||||
"orphans": "Cleaning up removed files",
|
||||
}
|
||||
|
||||
// SetJobRegistry wires the background job registry so scans report
|
||||
// progress, logs, and pause/cancel controls to the frontend.
|
||||
func (l *Library) SetJobRegistry(reg *jobs.Registry) {
|
||||
l.mu.Lock()
|
||||
l.jobs = reg
|
||||
l.mu.Unlock()
|
||||
}
|
||||
|
||||
// jobRegistry returns the registry, or nil when none is wired.
|
||||
func (l *Library) jobRegistry() *jobs.Registry {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
|
||||
return l.jobs
|
||||
}
|
||||
|
||||
// scanJobID returns the stable registry ID for a library's scan job.
|
||||
// It is stable across restarts so a durable pause can be matched back
|
||||
// to the library it belongs to.
|
||||
func scanJobID(libraryID int64) string {
|
||||
return scanJobPrefix + strconv.FormatInt(libraryID, 10)
|
||||
}
|
||||
|
||||
// libraryIDFromJobID parses a library ID back out of a scan job ID.
|
||||
func libraryIDFromJobID(id string) (int64, bool) {
|
||||
if len(id) <= len(scanJobPrefix) || id[:len(scanJobPrefix)] != scanJobPrefix {
|
||||
return 0, false
|
||||
}
|
||||
|
||||
parsed, err := strconv.ParseInt(id[len(scanJobPrefix):], 10, 64)
|
||||
if err != nil {
|
||||
return 0, false
|
||||
}
|
||||
|
||||
return parsed, true
|
||||
}
|
||||
|
||||
// scanJobSpec builds the registry spec for a library scan. Controls are
|
||||
// bound to the library ID rather than "the current scan" so that a
|
||||
// control arriving for a queued or stale job cannot disturb a different
|
||||
// library's scan.
|
||||
func (l *Library) scanJobSpec(
|
||||
entry scanQueueEntry,
|
||||
state jobs.State,
|
||||
) jobs.Spec {
|
||||
return jobs.Spec{
|
||||
ID: scanJobID(entry.libraryID),
|
||||
Kind: jobs.KindLibraryScan,
|
||||
Title: "Scanning " + entry.libraryName,
|
||||
Subtitle: entry.libraryPath,
|
||||
State: state,
|
||||
Caps: jobs.Caps{
|
||||
Pausable: true,
|
||||
Cancellable: true,
|
||||
},
|
||||
Durable: true,
|
||||
Controls: jobs.Controls{
|
||||
Pause: func() { l.pauseScanForLibrary(entry.libraryID) },
|
||||
Resume: func() { l.resumeScanForLibrary(entry) },
|
||||
Cancel: func() { l.cancelScanForLibrary(entry.libraryID) },
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// registerQueuedScanJob records a library that is waiting behind another
|
||||
// scan, so the user can see the whole pipeline rather than just the head.
|
||||
func (l *Library) registerQueuedScanJob(entry scanQueueEntry) {
|
||||
reg := l.jobRegistry()
|
||||
if reg == nil {
|
||||
return
|
||||
}
|
||||
|
||||
h := reg.Start(l.scanJobSpec(entry, jobs.StateQueued))
|
||||
h.SetPhase("Waiting for other scans")
|
||||
h.Logf(jobs.LevelInfo, "Queued behind an in-progress scan")
|
||||
}
|
||||
|
||||
// startScanJob registers (or re-registers, for a queued job now starting)
|
||||
// the running job for a scan and returns its handle.
|
||||
func (l *Library) startScanJob(entry scanQueueEntry) *jobs.Handle {
|
||||
reg := l.jobRegistry()
|
||||
if reg == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
h := reg.Start(l.scanJobSpec(entry, jobs.StateRunning))
|
||||
h.SetProgress(0, 0)
|
||||
h.Logf(jobs.LevelInfo, "Scan started for "+entry.libraryPath)
|
||||
|
||||
return h
|
||||
}
|
||||
|
||||
// reportScanProgress mirrors a ScanProgress payload into the job
|
||||
// registry. Called from the same places that emit LibraryScanProgress
|
||||
// so the two views never disagree.
|
||||
func reportScanProgress(h *jobs.Handle, p ScanProgress) {
|
||||
if h == nil {
|
||||
return
|
||||
}
|
||||
|
||||
label, ok := scanPhaseLabels[p.Phase]
|
||||
if !ok {
|
||||
label = p.Phase
|
||||
}
|
||||
|
||||
h.SetPhase(label)
|
||||
|
||||
// The counting pre-walk has no denominator to report against, so
|
||||
// leave the job indeterminate until the total is known.
|
||||
if p.Phase == "counting" {
|
||||
h.SetProgress(0, 0)
|
||||
} else {
|
||||
h.SetProgress(p.Processed, p.Total)
|
||||
}
|
||||
|
||||
h.SetStats([]jobs.Stat{
|
||||
{Label: "Added", Value: strconv.FormatInt(p.Added, 10)},
|
||||
{Label: "Updated", Value: strconv.FormatInt(p.Updated, 10)},
|
||||
{Label: "Skipped", Value: strconv.FormatInt(p.Skipped, 10)},
|
||||
})
|
||||
}
|
||||
|
||||
// finishScanJob applies the terminal state and summary for a completed,
|
||||
// cancelled, or paused-then-abandoned scan.
|
||||
func finishScanJob(h *jobs.Handle, m *ScanMetrics, cancelled bool) {
|
||||
if h == nil {
|
||||
return
|
||||
}
|
||||
|
||||
h.SetStats([]jobs.Stat{
|
||||
{Label: "Added", Value: strconv.FormatInt(m.Added, 10)},
|
||||
{Label: "Updated", Value: strconv.FormatInt(m.Updated, 10)},
|
||||
{Label: "Skipped", Value: strconv.FormatInt(m.Skipped, 10)},
|
||||
{Label: "Removed", Value: strconv.FormatInt(m.Removed, 10)},
|
||||
{Label: "Duration", Value: m.Total.Round(time.Millisecond).String()},
|
||||
{Label: "Walk", Value: m.WalkDuration.Round(time.Millisecond).String()},
|
||||
{Label: "Metadata", Value: m.ExtractionWallClock.Round(time.Millisecond).String()},
|
||||
{Label: "DB writes", Value: m.DBWritesWallClock.Round(time.Millisecond).String()},
|
||||
{Label: "Thumbnails", Value: m.ThumbnailWallClock.Round(time.Millisecond).String()},
|
||||
})
|
||||
|
||||
// The full timing breakdown goes into the log rather than the stats
|
||||
// grid: it is a profiling aid, wanted rarely and in full, and the
|
||||
// log pane already has a copy-to-clipboard button.
|
||||
h.LogDetail(jobs.LevelInfo, "Timing breakdown", m.timingBreakdown())
|
||||
|
||||
if cancelled {
|
||||
h.Logf(jobs.LevelInfo, "Scan cancelled")
|
||||
h.Cancelled()
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
h.Logf(jobs.LevelInfo,
|
||||
"Scan complete — "+
|
||||
strconv.FormatInt(m.Added, 10)+" added, "+
|
||||
strconv.FormatInt(m.Updated, 10)+" updated, "+
|
||||
strconv.FormatInt(m.Removed, 10)+" removed",
|
||||
)
|
||||
h.Complete()
|
||||
}
|
||||
|
||||
// pauseScanForLibrary pauses the running scan, but only when the library
|
||||
// asking is the one currently being scanned.
|
||||
func (l *Library) pauseScanForLibrary(libraryID int64) {
|
||||
l.mu.Lock()
|
||||
current := l.currentScanLibraryID
|
||||
l.mu.Unlock()
|
||||
|
||||
if current != libraryID {
|
||||
return
|
||||
}
|
||||
|
||||
l.PauseScan()
|
||||
}
|
||||
|
||||
// cancelScanForLibrary cancels a scan for one library. A queued library
|
||||
// is dropped from the queue; the running one is cancelled outright.
|
||||
func (l *Library) cancelScanForLibrary(libraryID int64) {
|
||||
l.mu.Lock()
|
||||
|
||||
current := l.currentScanLibraryID
|
||||
|
||||
if current != libraryID {
|
||||
// Not running — drop it from the queue if it is waiting there.
|
||||
kept := l.scanQueue[:0]
|
||||
|
||||
for _, entry := range l.scanQueue {
|
||||
if entry.libraryID != libraryID {
|
||||
kept = append(kept, entry)
|
||||
}
|
||||
}
|
||||
|
||||
l.scanQueue = kept
|
||||
l.mu.Unlock()
|
||||
|
||||
if reg := l.jobRegistry(); reg != nil {
|
||||
if h := reg.Get(scanJobID(libraryID)); h != nil {
|
||||
h.Cancelled()
|
||||
}
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
cancel := l.scanCancel
|
||||
paused := l.scanPaused
|
||||
pauseCh := l.scanPauseCh
|
||||
|
||||
// Unblock paused workers so they observe the cancelled context
|
||||
// instead of sitting on the pause channel forever.
|
||||
if paused {
|
||||
l.scanPaused = false
|
||||
|
||||
if pauseCh != nil {
|
||||
close(pauseCh)
|
||||
}
|
||||
|
||||
l.scanPauseCh = nil
|
||||
}
|
||||
|
||||
l.mu.Unlock()
|
||||
|
||||
if cancel != nil {
|
||||
cancel()
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// No live scan goroutine — this is a scan that was paused before a
|
||||
// restart and never resumed. Retire the adopted job directly.
|
||||
if reg := l.jobRegistry(); reg != nil {
|
||||
if h := reg.Get(scanJobID(libraryID)); h != nil {
|
||||
h.Cancelled()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// resumeScanForLibrary continues a paused scan. When the scan goroutine
|
||||
// is still alive it is simply unblocked. When the pause outlived the
|
||||
// process, a fresh scan is queued instead: scans are incremental, so
|
||||
// already-imported files are skipped on the second pass and the effect
|
||||
// is a resume rather than a restart.
|
||||
func (l *Library) resumeScanForLibrary(entry scanQueueEntry) {
|
||||
l.mu.Lock()
|
||||
live := l.scanActive && l.currentScanLibraryID == entry.libraryID
|
||||
l.mu.Unlock()
|
||||
|
||||
if live {
|
||||
l.ResumeScan()
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if reg := l.jobRegistry(); reg != nil {
|
||||
if h := reg.Get(scanJobID(entry.libraryID)); h != nil {
|
||||
h.Logf(jobs.LevelInfo,
|
||||
"Resuming from a previous session — already-imported "+
|
||||
"files are skipped")
|
||||
}
|
||||
}
|
||||
|
||||
// Clear the durable pause record before restarting, otherwise
|
||||
// RestorePausedScans would adopt it again on the next launch.
|
||||
if reg := l.jobRegistry(); reg != nil {
|
||||
reg.Remove(scanJobID(entry.libraryID))
|
||||
}
|
||||
|
||||
if err := l.ScanLibrary(entry.libraryID); err != nil {
|
||||
l.logger.Warn("could not resume scan",
|
||||
"libraryID", entry.libraryID, "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
// RestorePausedScans adopts scans that were paused when the app last
|
||||
// shut down back into the job registry, still paused. Call during
|
||||
// startup before SoftScanAllLibraries so the soft scan does not restart
|
||||
// a library the user deliberately paused.
|
||||
func (l *Library) RestorePausedScans() {
|
||||
reg := l.jobRegistry()
|
||||
if reg == nil {
|
||||
return
|
||||
}
|
||||
|
||||
for _, p := range reg.PausedEntries(jobs.KindLibraryScan) {
|
||||
libraryID, ok := libraryIDFromJobID(p.ID)
|
||||
if !ok {
|
||||
reg.Remove(p.ID)
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
lib, err := l.db.Queries.GetLibrary(l.ctx, libraryID)
|
||||
if err != nil {
|
||||
// The library was removed while the scan was paused.
|
||||
l.logger.Info("dropping paused scan for missing library",
|
||||
"libraryID", libraryID)
|
||||
reg.Remove(p.ID)
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
entry := scanQueueEntry{
|
||||
libraryID: lib.ID,
|
||||
libraryName: lib.Name,
|
||||
libraryPath: lib.Path,
|
||||
}
|
||||
|
||||
h := reg.Start(l.scanJobSpec(entry, jobs.StatePaused))
|
||||
h.SetPhase("Paused")
|
||||
h.Logf(jobs.LevelInfo, "Paused in a previous session — resume to continue")
|
||||
|
||||
l.logger.Info("restored paused library scan",
|
||||
"libraryID", lib.ID, "libraryName", lib.Name)
|
||||
}
|
||||
}
|
||||
|
||||
// isScanPausedPersistently reports whether a library's scan was left
|
||||
// paused by a previous session.
|
||||
func (l *Library) isScanPausedPersistently(libraryID int64) bool {
|
||||
reg := l.jobRegistry()
|
||||
if reg == nil {
|
||||
return false
|
||||
}
|
||||
|
||||
return reg.IsPersistentlyPaused(scanJobID(libraryID))
|
||||
}
|
||||
@@ -26,16 +26,19 @@ func (l *Library) ScanLibrary(id int64) error {
|
||||
}
|
||||
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
|
||||
// Silent dedup: already scanning this library.
|
||||
if l.currentScanLibraryID == id {
|
||||
l.mu.Unlock()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Silent dedup: already queued.
|
||||
for _, entry := range l.scanQueue {
|
||||
if entry.libraryID == id {
|
||||
l.mu.Unlock()
|
||||
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -50,6 +53,7 @@ func (l *Library) ScanLibrary(id int64) error {
|
||||
l.scanActive = true
|
||||
l.currentScanLibraryID = entry.libraryID
|
||||
l.currentScanLibraryName = entry.libraryName
|
||||
l.mu.Unlock()
|
||||
|
||||
go l.startScan(entry)
|
||||
|
||||
@@ -58,13 +62,19 @@ func (l *Library) ScanLibrary(id int64) error {
|
||||
|
||||
// A scan is already running — queue this library.
|
||||
l.scanQueue = append(l.scanQueue, entry)
|
||||
queueLength := len(l.scanQueue)
|
||||
l.mu.Unlock()
|
||||
|
||||
runtime.EventsEmit(l.ctx, events.LibraryScanQueued, map[string]any{
|
||||
"libraryId": lib.ID,
|
||||
"libraryName": lib.Name,
|
||||
"queueLength": len(l.scanQueue),
|
||||
"queueLength": queueLength,
|
||||
})
|
||||
|
||||
// Registering the queued job takes l.mu again, so it must happen
|
||||
// after the unlock above.
|
||||
l.registerQueuedScanJob(entry)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -127,6 +137,20 @@ func (l *Library) SoftScanAllLibraries() error {
|
||||
}
|
||||
|
||||
for _, lib := range libs {
|
||||
// A scan the user paused stays paused across restarts — the
|
||||
// soft scan must not quietly start it again behind their back.
|
||||
// RestorePausedScans has already surfaced it in the jobs panel
|
||||
// with a resume button.
|
||||
if l.isScanPausedPersistently(lib.ID) {
|
||||
l.logger.Info(
|
||||
"soft scan: library scan is paused, skipping",
|
||||
"libraryID", lib.ID,
|
||||
"libraryName", lib.Name,
|
||||
)
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
dbCount, countErr := l.db.Queries.CountAudioFilesByLibrary(
|
||||
l.ctx, lib.ID,
|
||||
)
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/user"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
)
|
||||
|
||||
@@ -22,14 +23,15 @@ const (
|
||||
dirTypeData dirType = "data"
|
||||
)
|
||||
|
||||
// envHomeOverride is the environment variable that, when set, relocates
|
||||
// all YellowJacket config and data under a single base directory. It
|
||||
// exists so a development build can run against an isolated sandbox
|
||||
// without touching the current user's real config.toml or yj.db.
|
||||
const envHomeOverride = "YJ_HOME"
|
||||
|
||||
// getUserDirPath returns and creates the path for a user directory.
|
||||
func getUserDirPath(dt dirType) (string, error) {
|
||||
currentUser, err := user.Current()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("could not get current user: %w", err)
|
||||
}
|
||||
|
||||
path, err := buildUserDirPath(currentUser.Username, dt)
|
||||
path, err := resolveUserDirPath(dt)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
@@ -50,6 +52,22 @@ func getUserDirPath(dt dirType) (string, error) {
|
||||
return path, nil
|
||||
}
|
||||
|
||||
// resolveUserDirPath picks the base path for a user directory. When
|
||||
// YJ_HOME is set it wins for every OS, mapping to <YJ_HOME>/<dirType>;
|
||||
// otherwise the standard OS-specific location is used.
|
||||
func resolveUserDirPath(dt dirType) (string, error) {
|
||||
if home := os.Getenv(envHomeOverride); home != "" {
|
||||
return filepath.Join(home, string(dt)), nil
|
||||
}
|
||||
|
||||
currentUser, err := user.Current()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("could not get current user: %w", err)
|
||||
}
|
||||
|
||||
return buildUserDirPath(currentUser.Username, dt)
|
||||
}
|
||||
|
||||
// buildUserDirPath constructs the OS-specific path for a user directory.
|
||||
func buildUserDirPath(username string, dt dirType) (string, error) {
|
||||
// Map directory types to their Unix subdirectory paths
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
package system
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestResolveUserDirPath_HomeOverride(t *testing.T) {
|
||||
home := t.TempDir()
|
||||
t.Setenv(envHomeOverride, home)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
dt dirType
|
||||
want string
|
||||
}{
|
||||
{name: "config", dt: dirTypeConfig, want: filepath.Join(home, "config")},
|
||||
{name: "data", dt: dirTypeData, want: filepath.Join(home, "data")},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got, err := resolveUserDirPath(tt.dt)
|
||||
if err != nil {
|
||||
t.Fatalf("resolveUserDirPath(%q) returned error: %v", tt.dt, err)
|
||||
}
|
||||
|
||||
if got != tt.want {
|
||||
t.Errorf("resolveUserDirPath(%q) = %q, want %q", tt.dt, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveUserDirPath_NoOverrideUsesOSPath(t *testing.T) {
|
||||
t.Setenv(envHomeOverride, "")
|
||||
|
||||
got, err := resolveUserDirPath(dirTypeConfig)
|
||||
if err != nil {
|
||||
t.Fatalf("resolveUserDirPath returned error: %v", err)
|
||||
}
|
||||
|
||||
// Without the override the path must fall back to the OS-specific
|
||||
// yellowjacket location, not a bare "<home>/config" base dir.
|
||||
if !filepath.IsAbs(got) || !strings.HasSuffix(got, "yellowjacket") {
|
||||
t.Errorf(
|
||||
"resolveUserDirPath fallback = %q, want absolute path ending in %q",
|
||||
got, "yellowjacket",
|
||||
)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user