vcom/internal/jobs/manager.go
vrubelroman f08467d63b feat(jobs): add background job manager (stage 4)
A Manager independent of Bubble Tea: FIFO queue limited to maxParallel
jobs, latest-value progress published at most 10 times a second by a
ticker, events delivered in order by a dispatcher so a slow notify never
blocks a job. Ask blocks only the asking job; Cancel, panics, holds and
Shutdown are handled on every path without leaking goroutines.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 04:08:13 +03:00

436 lines
10 KiB
Go

// Package jobs runs background operations (copy, delete, archive, connect,
// ...) independently of the UI framework (design §6, D4).
//
// A Manager runs at most maxParallel jobs at once and queues the rest. Jobs
// report progress with Handle.SetProgress ("latest value wins"); the Manager
// publishes changes at most 10 times per second, so a job copying thousands
// of small files never waits for the UI. Questions to the user
// (Handle.Ask) block only the asking job. Every goroutine recovers panics:
// a panicking job ends as Failed instead of taking the process down.
//
// Events reach the notify callback from a single dispatcher goroutine in
// order. notify may block (Bubble Tea's Send does until the program reads
// it); that delays later events but never a job.
package jobs
import (
"context"
"errors"
"fmt"
"log/slog"
"runtime/debug"
"sort"
"sync"
"time"
)
// DefaultMaxParallel is used when New gets maxParallel <= 0.
const DefaultMaxParallel = 2
// tickInterval bounds ProgressTick to 10 Hz.
var tickInterval = 100 * time.Millisecond
// keepFinished is how many finished jobs Snapshot keeps for the job list.
const keepFinished = 100
// ErrShutdown is the Err of a job started after Shutdown.
var ErrShutdown = errors.New("job manager is shut down")
// Releaser is something a job holds while it runs (a connection lease, a
// mounted archive). The Manager calls Release exactly once when the job
// ends, whatever the outcome.
type Releaser interface{ Release() }
// Func is a job body. It must return soon after ctx is cancelled.
type Func func(ctx context.Context, h *Handle) (result any, err error)
type job struct {
id ID
kind Kind
title string
state State
progress Progress
dirty bool
started time.Time
background bool
result any
err error
asking int
fn Func
holds []Releaser
ctx context.Context
cancel context.CancelFunc
}
type pending struct {
q Question
ch chan any
j *job
}
// Manager runs jobs. It is safe for concurrent use.
type Manager struct {
notify func(Event)
maxParallel int
mu sync.Mutex
nextID ID
nextQID uint64
jobs map[ID]*job
finished []ID // finished job IDs, oldest first
queue []*job
running int // Running or Waiting
questions map[uint64]*pending
shutdown bool
events []Event
dispatching bool
ticking bool
changed chan struct{} // closed and replaced on every idle-relevant change
}
// New creates a Manager. notify receives every Event (main forwards them
// with program.Send); nil discards them.
func New(notify func(Event), maxParallel int) *Manager {
if maxParallel <= 0 {
maxParallel = DefaultMaxParallel
}
if notify == nil {
notify = func(Event) {}
}
return &Manager{
notify: notify,
maxParallel: maxParallel,
jobs: map[ID]*job{},
questions: map[uint64]*pending{},
changed: make(chan struct{}),
}
}
// broadcastLocked wakes Shutdown waiters.
func (m *Manager) broadcastLocked() {
close(m.changed)
m.changed = make(chan struct{})
}
// safeGo runs fn in a goroutine that logs and swallows panics.
func safeGo(what string, fn func()) {
go func() {
defer func() {
if r := recover(); r != nil {
slog.Error("jobs: panic", "in", what, "panic", r, "stack", string(debug.Stack()))
}
}()
fn()
}()
}
// emitLocked queues e for the dispatcher; m.mu is held.
func (m *Manager) emitLocked(e Event) {
m.events = append(m.events, e)
if !m.dispatching {
m.dispatching = true
safeGo("dispatch", m.dispatch)
}
}
func (m *Manager) dispatch() {
defer func() {
// notify panicked: keep delivering on a fresh goroutine.
if r := recover(); r != nil {
slog.Error("jobs: notify panicked", "panic", r, "stack", string(debug.Stack()))
m.mu.Lock()
m.dispatching = false
if len(m.events) > 0 {
m.dispatching = true
safeGo("dispatch", m.dispatch)
}
m.broadcastLocked()
m.mu.Unlock()
}
}()
for {
m.mu.Lock()
if len(m.events) == 0 {
m.dispatching = false
m.broadcastLocked()
m.mu.Unlock()
return
}
batch := m.events
m.events = nil
m.mu.Unlock()
for i, e := range batch {
func() {
defer func() {
if r := recover(); r != nil {
m.mu.Lock()
m.events = append(batch[i+1:len(batch):len(batch)], m.events...)
m.mu.Unlock()
panic(r)
}
}()
m.notify(e)
}()
}
}
}
func (j *job) snapshot() Snapshot {
return Snapshot{
ID: j.id, Kind: j.kind, Title: j.title, State: j.state, Progress: j.progress,
Started: j.started, Background: j.background, Result: j.result, Err: j.err,
}
}
// Start queues a job and returns its ID. holds are released when the job
// ends (also when it is cancelled before running, or started after
// Shutdown).
func (m *Manager) Start(k Kind, title string, fn Func, holds ...Releaser) ID {
ctx, cancel := context.WithCancel(context.Background())
m.mu.Lock()
defer m.mu.Unlock()
m.nextID++
j := &job{
id: m.nextID, kind: k, title: title, state: Queued, started: time.Now(),
fn: fn, holds: holds, ctx: ctx, cancel: cancel,
}
m.jobs[j.id] = j
if m.shutdown {
m.emitLocked(Started{Snapshot: j.snapshot()})
m.finishLocked(j, Cancelled, nil, ErrShutdown)
return j.id
}
m.queue = append(m.queue, j)
m.scheduleLocked()
m.emitLocked(Started{Snapshot: j.snapshot()})
return j.id
}
// scheduleLocked starts queued jobs while slots are free.
func (m *Manager) scheduleLocked() {
for m.running < m.maxParallel && len(m.queue) > 0 {
j := m.queue[0]
m.queue = m.queue[1:]
m.running++
j.state = Running
j.dirty = true
m.startTickerLocked()
safeGo("job", func() { m.run(j) })
}
}
func (m *Manager) run(j *job) {
var (
res any
err error
)
func() {
defer func() {
if r := recover(); r != nil {
slog.Error("jobs: job panicked", "job", j.id, "kind", j.kind, "panic", r, "stack", string(debug.Stack()))
err = fmt.Errorf("job %q panicked: %v", j.title, r)
res = nil
}
}()
res, err = j.fn(j.ctx, &Handle{m: m, j: j})
}()
state := Done
switch {
case err == nil:
case errors.Is(err, context.Canceled):
state = Cancelled
default:
state = Failed
}
m.mu.Lock()
defer m.mu.Unlock()
m.running--
m.finishLocked(j, state, res, err)
m.scheduleLocked()
}
// finishLocked moves j to a terminal state, releases its holds and emits
// Finished.
func (m *Manager) finishLocked(j *job, s State, res any, err error) {
j.state, j.result, j.err, j.dirty = s, res, err, false
j.cancel()
for qid, p := range m.questions {
if p.j == j {
delete(m.questions, qid)
m.emitLocked(Unasked{Question: p.q})
}
}
for _, h := range j.holds {
release(h)
}
j.holds = nil
j.fn = nil
m.emitLocked(Finished{Snapshot: j.snapshot()})
m.finished = append(m.finished, j.id)
if len(m.finished) > keepFinished {
delete(m.jobs, m.finished[0])
m.finished = m.finished[1:]
}
m.broadcastLocked()
}
func release(h Releaser) {
defer func() {
if r := recover(); r != nil {
slog.Error("jobs: Release panicked", "panic", r, "stack", string(debug.Stack()))
}
}()
h.Release()
}
// startTickerLocked runs the progress ticker while jobs are active.
func (m *Manager) startTickerLocked() {
if m.ticking {
return
}
m.ticking = true
safeGo("ticker", m.tick)
}
func (m *Manager) tick() {
t := time.NewTicker(tickInterval)
defer t.Stop()
for range t.C {
m.mu.Lock()
var snaps []Snapshot
for _, j := range m.jobs {
if j.dirty && !j.state.Finished() {
j.dirty = false
snaps = append(snaps, j.snapshot())
}
}
if len(snaps) > 0 {
sort.Slice(snaps, func(a, b int) bool { return snaps[a].ID < snaps[b].ID })
m.emitLocked(ProgressTick{Snapshots: snaps})
}
if m.running == 0 && len(m.queue) == 0 {
m.ticking = false
m.broadcastLocked()
m.mu.Unlock()
return
}
m.mu.Unlock()
}
}
// Answer delivers the user's answer to question qid. Unknown or already
// withdrawn questions are ignored.
func (m *Manager) Answer(qid uint64, answer any) {
m.mu.Lock()
defer m.mu.Unlock()
p := m.questions[qid]
if p == nil {
return
}
delete(m.questions, qid)
p.ch <- answer // buffered, never blocks
}
// Cancel cancels a job: a queued job ends at once as Cancelled, a running
// one gets its ctx cancelled (and any pending Ask returns).
func (m *Manager) Cancel(id ID) {
m.mu.Lock()
defer m.mu.Unlock()
j := m.jobs[id]
if j == nil || j.state.Finished() {
return
}
if j.state == Queued {
m.dequeueLocked(j)
m.finishLocked(j, Cancelled, nil, context.Canceled)
return
}
j.cancel()
}
func (m *Manager) dequeueLocked(j *job) {
for i, q := range m.queue {
if q == j {
m.queue = append(m.queue[:i], m.queue[i+1:]...)
return
}
}
}
// SetBackground marks a job as running in the background (the UI closes its
// progress dialog).
func (m *Manager) SetBackground(id ID, bg bool) {
m.mu.Lock()
defer m.mu.Unlock()
if j := m.jobs[id]; j != nil && j.background != bg {
j.background = bg
if !j.state.Finished() {
j.dirty = true
}
}
}
// Snapshot returns all known jobs (active and the last finished ones) by ID.
func (m *Manager) Snapshot() []Snapshot {
m.mu.Lock()
defer m.mu.Unlock()
out := make([]Snapshot, 0, len(m.jobs))
for _, j := range m.jobs {
out = append(out, j.snapshot())
}
sort.Slice(out, func(a, b int) bool { return out[a].ID < out[b].ID })
return out
}
// Get returns one job's snapshot.
func (m *Manager) Get(id ID) (Snapshot, bool) {
m.mu.Lock()
defer m.mu.Unlock()
j := m.jobs[id]
if j == nil {
return Snapshot{}, false
}
return j.snapshot(), true
}
// Active counts queued, running and waiting jobs.
func (m *Manager) Active() int {
m.mu.Lock()
defer m.mu.Unlock()
return m.running + len(m.queue)
}
// Shutdown cancels every job, refuses new ones and waits until running jobs
// have returned (so they can remove temp files) and all events have been
// delivered, or until ctx is done.
func (m *Manager) Shutdown(ctx context.Context) error {
m.mu.Lock()
m.shutdown = true
for len(m.queue) > 0 {
j := m.queue[0]
m.queue = m.queue[1:]
m.finishLocked(j, Cancelled, nil, context.Canceled)
}
for _, j := range m.jobs {
if !j.state.Finished() {
j.cancel()
}
}
m.mu.Unlock()
for {
m.mu.Lock()
idle := m.running == 0 && !m.dispatching && !m.ticking
ch := m.changed
m.mu.Unlock()
if idle {
return nil
}
select {
case <-ch:
case <-ctx.Done():
return ctx.Err()
}
}
}