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>
This commit is contained in:
vrubelroman 2026-11-01 04:07:51 +03:00
parent 9c898e862b
commit f08467d63b
5 changed files with 1091 additions and 0 deletions

105
internal/jobs/events.go Normal file
View file

@ -0,0 +1,105 @@
package jobs
import (
"fmt"
"time"
)
// ID identifies a job within a Manager.
type ID uint64
// Kind names what a job does ("copy", "move", "delete", "trash", "archive",
// "unpack", "mount", "dirsize", "connect", "edit-upload", ...).
type Kind string
// State of a job.
type State uint8
const (
Queued State = iota
Running // fn is executing
Waiting // blocked in Handle.Ask until the user answers
Done // fn returned nil
Failed // fn returned an error or panicked
Cancelled // cancelled (before start, or fn returned context.Canceled)
)
func (s State) String() string {
switch s {
case Queued:
return "queued"
case Running:
return "running"
case Waiting:
return "waiting"
case Done:
return "done"
case Failed:
return "failed"
case Cancelled:
return "cancelled"
}
return fmt.Sprintf("State(%d)", uint8(s))
}
// Finished reports whether s is terminal.
func (s State) Finished() bool { return s >= Done }
// Progress is the latest progress a job reported.
type Progress struct {
Phase string
FilesDone int
FilesTotal int
BytesDone int64
BytesTotal int64
Current string
}
// Snapshot is a copy of a job's state.
type Snapshot struct {
ID ID
Kind Kind
Title string
State State
Progress Progress
Started time.Time // when Start was called
Background bool
Result any // what fn returned (e.g. a transfer report), for Done/Failed/Cancelled
Err error // why it Failed or was Cancelled
}
// Question is something a job asks the user (conflict, item error, host
// key, password, ...). Payload is defined by the job's domain; the UI picks a
// dialog by its type and answers with Manager.Answer(QID, answer).
type Question struct {
Job ID
QID uint64
Payload any
}
// Event is delivered to the notify callback given to New.
type Event interface{ isEvent() }
// Started: a job was accepted (State Queued or Running).
type Started struct{ Snapshot Snapshot }
// ProgressTick carries the jobs whose progress or state changed since the
// previous tick. At most 10 per second.
type ProgressTick struct{ Snapshots []Snapshot }
// Asked: a job is waiting for an answer.
type Asked struct{ Question Question }
// Unasked: a question was withdrawn without an answer (the job or the Ask
// context was cancelled); close its dialog.
type Unasked struct{ Question Question }
// Finished: a job reached a terminal state. It is the last event for that
// job.
type Finished struct{ Snapshot Snapshot }
func (Started) isEvent() {}
func (ProgressTick) isEvent() {}
func (Asked) isEvent() {}
func (Unasked) isEvent() {}
func (Finished) isEvent() {}

82
internal/jobs/handle.go Normal file
View file

@ -0,0 +1,82 @@
package jobs
import (
"context"
)
// Handle is a job's view of the Manager. It is passed to the job function
// and valid only while it runs.
type Handle struct {
m *Manager
j *job
}
// ID of the job.
func (h *Handle) ID() ID { return h.j.id }
// SetProgress records the latest progress. It is O(1), never blocks on the
// UI and may be called as often as wanted: the Manager publishes at most 10
// ticks per second, each with the last value.
func (h *Handle) SetProgress(p Progress) {
h.m.mu.Lock()
h.j.progress = p
h.j.dirty = true
h.m.mu.Unlock()
}
// Ask publishes a question and blocks this job's goroutine (State Waiting)
// until Manager.Answer, the job's cancellation or ctx. Other jobs and the
// UI keep running.
func (h *Handle) Ask(ctx context.Context, payload any) (any, error) {
m, j := h.m, h.j
ans := make(chan any, 1)
m.mu.Lock()
m.nextQID++
q := Question{Job: j.id, QID: m.nextQID, Payload: payload}
m.questions[q.QID] = &pending{q: q, ch: ans, j: j}
j.asking++
j.state = Waiting
j.dirty = true
m.emitLocked(Asked{Question: q})
m.mu.Unlock()
var (
a any
err error
)
select {
case a = <-ans:
case <-ctx.Done():
err = ctx.Err()
case <-j.ctx.Done():
err = j.ctx.Err()
}
m.mu.Lock()
if err != nil {
if _, still := m.questions[q.QID]; still {
delete(m.questions, q.QID)
m.emitLocked(Unasked{Question: q})
} else {
// Answered concurrently with the cancellation: the answer wins
// only if the job itself is not cancelled.
select {
case a = <-ans:
if j.ctx.Err() == nil {
err = nil
}
default:
}
}
}
j.asking--
if j.asking == 0 && j.state == Waiting {
j.state = Running
j.dirty = true
}
m.mu.Unlock()
if err != nil {
return nil, err
}
return a, nil
}

436
internal/jobs/manager.go Normal file
View file

@ -0,0 +1,436 @@
// 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()
}
}
}

View file

@ -0,0 +1,447 @@
package jobs
import (
"context"
"errors"
"runtime"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
)
// noLeak runs fn as a subtest and checks the goroutine count returns to the
// baseline afterwards.
func noLeak(t *testing.T, fn func(t *testing.T)) {
t.Helper()
runtime.GC()
base := runtime.NumGoroutine()
t.Run("body", fn)
deadline := time.Now().Add(3 * time.Second)
var n int
for time.Now().Before(deadline) {
if n = runtime.NumGoroutine(); n <= base {
return
}
time.Sleep(10 * time.Millisecond)
}
buf := make([]byte, 1<<20)
t.Errorf("goroutines: base=%d after=%d\n%s", base, n, buf[:runtime.Stack(buf, true)])
}
// recorder collects events.
type recorder struct {
mu sync.Mutex
ev []Event
at []time.Time
}
func (r *recorder) notify(e Event) {
r.mu.Lock()
r.ev = append(r.ev, e)
r.at = append(r.at, time.Now())
r.mu.Unlock()
}
func (r *recorder) events() []Event {
r.mu.Lock()
defer r.mu.Unlock()
return append([]Event(nil), r.ev...)
}
func (r *recorder) finished(id ID) (Snapshot, bool) {
for _, e := range r.events() {
if f, ok := e.(Finished); ok && f.Snapshot.ID == id {
return f.Snapshot, true
}
}
return Snapshot{}, false
}
func (r *recorder) asked() []Question {
var qs []Question
for _, e := range r.events() {
if a, ok := e.(Asked); ok {
qs = append(qs, a.Question)
}
}
return qs
}
func waitFor(t *testing.T, what string, cond func() bool) {
t.Helper()
deadline := time.Now().Add(3 * time.Second)
for !cond() {
if time.Now().After(deadline) {
t.Fatalf("timed out waiting for %s", what)
}
time.Sleep(time.Millisecond)
}
}
func shutdown(t *testing.T, m *Manager) {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
if err := m.Shutdown(ctx); err != nil {
t.Fatalf("Shutdown: %v", err)
}
}
type hold struct{ n atomic.Int32 }
func (h *hold) Release() { h.n.Add(1) }
// U section 2: progress went through a 256-slot channel with a full View per
// file. 100k SetProgress must neither slow the job down (even if nobody
// reads events) nor produce more than ~10 ticks per second.
func TestProgressCoalesced(t *testing.T) {
t.Run("NoReader", func(t *testing.T) {
noLeak(t, func(t *testing.T) {
unblock := make(chan struct{})
m := New(func(Event) { <-unblock }, 2) // like an unread program.Send
done := make(chan time.Duration, 1)
m.Start("copy", "fast", func(ctx context.Context, h *Handle) (any, error) {
start := time.Now()
for i := 0; i < 100_000; i++ {
h.SetProgress(Progress{FilesDone: i, BytesDone: int64(i) * 10})
}
done <- time.Since(start)
return nil, nil
})
select {
case el := <-done:
if el > 100*time.Millisecond {
t.Errorf("100k SetProgress took %v", el)
}
case <-time.After(time.Second):
t.Fatal("job blocked by an unread notify")
}
waitFor(t, "job finished", func() bool { return m.Active() == 0 })
close(unblock)
shutdown(t, m)
})
})
t.Run("TickRate", func(t *testing.T) {
noLeak(t, func(t *testing.T) {
var rec recorder
m := New(rec.notify, 2)
id := m.Start("copy", "steady", func(ctx context.Context, h *Handle) (any, error) {
end := time.Now().Add(time.Second)
for i := 0; time.Now().Before(end); i++ {
h.SetProgress(Progress{FilesDone: i})
if i%100 == 0 {
runtime.Gosched()
}
}
h.SetProgress(Progress{FilesDone: -1, Phase: "final"})
return "ok", nil
})
waitFor(t, "finished", func() bool { _, ok := rec.finished(id); return ok })
shutdown(t, m)
ticks := 0
for _, e := range rec.events() {
if _, ok := e.(ProgressTick); ok {
ticks++
}
}
if ticks > 11 || ticks < 5 {
t.Errorf("%d ticks in ~1s, want 5..11", ticks)
}
// Finished is last for the job and carries the final progress.
evs := rec.events()
f, ok := evs[len(evs)-1].(Finished)
if !ok || f.Snapshot.Progress.Phase != "final" || f.Snapshot.State != Done || f.Snapshot.Result != "ok" {
t.Errorf("last event = %#v", evs[len(evs)-1])
}
})
})
}
func TestAskBlocksOnlyJob(t *testing.T) {
noLeak(t, func(t *testing.T) {
var rec recorder
m := New(rec.notify, 2)
got := make(chan any, 1)
asker := m.Start("copy", "asker", func(ctx context.Context, h *Handle) (any, error) {
a, err := h.Ask(ctx, "overwrite?")
got <- a
return a, err
})
waitFor(t, "question", func() bool { return len(rec.asked()) == 1 })
if s, _ := m.Get(asker); s.State != Waiting {
t.Errorf("asker state = %v", s.State)
}
other := m.Start("delete", "other", func(ctx context.Context, h *Handle) (any, error) { return 42, nil })
waitFor(t, "other job done while asker waits", func() bool { _, ok := rec.finished(other); return ok })
if m.Active() != 1 {
t.Errorf("Active = %d", m.Active())
}
q := rec.asked()[0]
if q.Job != asker || q.Payload != "overwrite?" {
t.Errorf("question = %+v", q)
}
m.Answer(q.QID, "yes")
m.Answer(q.QID, "again") // ignored
if a := <-got; a != "yes" {
t.Errorf("answer = %v", a)
}
waitFor(t, "asker done", func() bool { _, ok := rec.finished(asker); return ok })
if s, _ := rec.finished(asker); s.State != Done || s.Result != "yes" {
t.Errorf("asker = %+v", s)
}
shutdown(t, m)
})
}
func TestCancelWhileWaiting(t *testing.T) {
noLeak(t, func(t *testing.T) {
var rec recorder
m := New(rec.notify, 2)
h1 := &hold{}
askErr := make(chan error, 1)
id := m.Start("copy", "c", func(ctx context.Context, h *Handle) (any, error) {
_, err := h.Ask(ctx, "conflict")
askErr <- err
return nil, err
}, h1)
waitFor(t, "question", func() bool { return len(rec.asked()) == 1 })
m.Cancel(id)
select {
case err := <-askErr:
if !errors.Is(err, context.Canceled) {
t.Errorf("Ask err = %v", err)
}
case <-time.After(time.Second):
t.Fatal("Ask not released by Cancel")
}
waitFor(t, "finished", func() bool { _, ok := rec.finished(id); return ok })
s, _ := rec.finished(id)
if s.State != Cancelled || h1.n.Load() != 1 {
t.Errorf("state %v, releases %d", s.State, h1.n.Load())
}
unasked := false
for _, e := range rec.events() {
if u, ok := e.(Unasked); ok && u.Question.QID == rec.asked()[0].QID {
unasked = true
}
}
if !unasked {
t.Error("no Unasked event")
}
m.Answer(rec.asked()[0].QID, "late") // no-op, must not block or panic
// The Ask ctx alone withdraws the question; the job continues.
ctx, cancel := context.WithCancel(context.Background())
id2 := m.Start("copy", "c2", func(_ context.Context, h *Handle) (any, error) {
_, err := h.Ask(ctx, "q")
return "continued after " + err.Error(), nil
})
waitFor(t, "second question", func() bool { return len(rec.asked()) == 2 })
cancel()
waitFor(t, "second finished", func() bool { _, ok := rec.finished(id2); return ok })
if s, _ := rec.finished(id2); s.State != Done {
t.Errorf("job after Ask ctx cancel = %+v", s)
}
shutdown(t, m)
})
}
func TestPanicBecomesFailed(t *testing.T) {
noLeak(t, func(t *testing.T) {
var rec recorder
m := New(rec.notify, 1)
h1 := &hold{}
id := m.Start("copy", "boom", func(ctx context.Context, h *Handle) (any, error) {
var p *Progress
_ = p.Phase // nil dereference
return nil, nil
}, h1)
next := m.Start("copy", "next", func(ctx context.Context, h *Handle) (any, error) { return nil, nil })
waitFor(t, "both finished", func() bool {
_, a := rec.finished(id)
_, b := rec.finished(next)
return a && b
})
s, _ := rec.finished(id)
if s.State != Failed || s.Err == nil || !strings.Contains(s.Err.Error(), "panicked") || h1.n.Load() != 1 {
t.Errorf("panicking job = %+v, releases %d", s, h1.n.Load())
}
if s, _ := rec.finished(next); s.State != Done {
t.Errorf("next job = %+v", s)
}
// A panicking notify does not stop event delivery.
var calls atomic.Int32
m2 := New(func(e Event) {
if calls.Add(1) == 1 {
panic("ui bug")
}
}, 1)
m2.Start("copy", "x", func(ctx context.Context, h *Handle) (any, error) { return nil, nil })
waitFor(t, "events after notify panic", func() bool { return calls.Load() >= 2 })
shutdown(t, m2)
shutdown(t, m)
})
}
func TestHoldsReleasedOnAllPaths(t *testing.T) {
noLeak(t, func(t *testing.T) {
m := New(nil, 1)
var holds []*hold
h := func() *hold { x := &hold{}; holds = append(holds, x); return x }
block := make(chan struct{})
m.Start("copy", "ok", func(ctx context.Context, _ *Handle) (any, error) { return nil, nil }, h(), h())
m.Start("copy", "err", func(ctx context.Context, _ *Handle) (any, error) { return nil, errors.New("x") }, h())
m.Start("copy", "panic", func(ctx context.Context, _ *Handle) (any, error) { panic("p") }, h())
running := m.Start("copy", "cancel-running", func(ctx context.Context, _ *Handle) (any, error) {
close(block)
<-ctx.Done()
return nil, ctx.Err()
}, h())
queued := m.Start("copy", "cancel-queued", func(ctx context.Context, _ *Handle) (any, error) { return nil, nil }, h())
<-block
m.Cancel(queued)
m.Cancel(running)
m.Start("copy", "on-shutdown-queue", func(ctx context.Context, _ *Handle) (any, error) {
<-ctx.Done()
return nil, ctx.Err()
}, h())
shutdown(t, m)
after := m.Start("copy", "after-shutdown", func(ctx context.Context, _ *Handle) (any, error) {
t.Error("job ran after Shutdown")
return nil, nil
}, h())
if s, _ := m.Get(after); s.State != Cancelled || !errors.Is(s.Err, ErrShutdown) {
t.Errorf("after shutdown: %+v", s)
}
for i, x := range holds {
if n := x.n.Load(); n != 1 {
t.Errorf("hold %d released %d times", i, n)
}
}
want := map[string]State{"ok": Done, "err": Failed, "panic": Failed, "cancel-running": Cancelled,
"cancel-queued": Cancelled, "on-shutdown-queue": Cancelled, "after-shutdown": Cancelled}
for _, s := range m.Snapshot() {
if s.State != want[s.Title] {
t.Errorf("%s: state %v, want %v", s.Title, s.State, want[s.Title])
}
}
})
}
// U section 3: "Transfer is already running" — now jobs queue.
func TestQueueRespectsMaxParallel(t *testing.T) {
noLeak(t, func(t *testing.T) {
var rec recorder
m := New(rec.notify, 2)
var cur, peak atomic.Int32
var mu sync.Mutex
var order []int
var ids []ID
for i := 0; i < 6; i++ {
ids = append(ids, m.Start("copy", "j", func(ctx context.Context, _ *Handle) (any, error) {
mu.Lock()
order = append(order, i)
mu.Unlock()
n := cur.Add(1)
for {
p := peak.Load()
if n <= p || peak.CompareAndSwap(p, n) {
break
}
}
time.Sleep(20 * time.Millisecond)
cur.Add(-1)
return nil, nil
}))
}
if s, _ := m.Get(ids[5]); s.State != Queued {
t.Errorf("6th job state = %v, want queued", s.State)
}
waitFor(t, "all done", func() bool { return m.Active() == 0 })
shutdown(t, m)
if p := peak.Load(); p != 2 {
t.Errorf("peak parallel = %d, want 2", p)
}
if order[0] > 1 || order[5] < 4 {
t.Errorf("not FIFO: %v", order)
}
for _, id := range ids {
if s, ok := rec.finished(id); !ok || s.State != Done {
t.Errorf("job %d: %+v", id, s)
}
}
})
}
func TestShutdownWaitsCleanup(t *testing.T) {
noLeak(t, func(t *testing.T) {
var rec recorder
m := New(rec.notify, 2)
var cleaned atomic.Bool
id := m.Start("copy", "c", func(ctx context.Context, _ *Handle) (any, error) {
<-ctx.Done()
time.Sleep(100 * time.Millisecond) // remove temp files
cleaned.Store(true)
return nil, ctx.Err()
})
waitFor(t, "running", func() bool { s, _ := m.Get(id); return s.State == Running })
shutdown(t, m)
if !cleaned.Load() {
t.Error("Shutdown returned before the job cleaned up")
}
if _, ok := rec.finished(id); !ok {
t.Error("Finished not delivered before Shutdown returned")
}
// A job ignoring cancellation: Shutdown gives up at the deadline.
m2 := New(nil, 1)
release := make(chan struct{})
m2.Start("copy", "stubborn", func(ctx context.Context, _ *Handle) (any, error) {
<-release
return nil, nil
})
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
defer cancel()
start := time.Now()
if err := m2.Shutdown(ctx); !errors.Is(err, context.DeadlineExceeded) {
t.Errorf("Shutdown = %v", err)
}
if el := time.Since(start); el > 500*time.Millisecond {
t.Errorf("Shutdown waited %v", el)
}
close(release)
shutdown(t, m2)
})
}
func TestBackgroundAndSnapshot(t *testing.T) {
noLeak(t, func(t *testing.T) {
var rec recorder
m := New(rec.notify, 1)
stop := make(chan struct{})
id := m.Start("copy", "bg", func(ctx context.Context, h *Handle) (any, error) {
<-stop
return nil, nil
})
m.SetBackground(id, true)
waitFor(t, "tick with background flag", func() bool {
for _, e := range rec.events() {
if pt, ok := e.(ProgressTick); ok {
for _, s := range pt.Snapshots {
if s.ID == id && s.Background && s.State == Running {
return true
}
}
}
}
return false
})
close(stop)
shutdown(t, m)
if snaps := m.Snapshot(); len(snaps) != 1 || !snaps[0].Background || snaps[0].State != Done {
t.Errorf("snapshot = %+v", snaps)
}
})
}

View file

@ -133,3 +133,24 @@
`io.Copy` из `*os.File` идёт параллельно: 4 МиБ при RTT 20 мс — upload ≈ 0,13 с, download ≈ 0,19 с (было ~2,6 с).
- `Create(CreateExcl)` применяет `perm` через fsetstat; `CreateTrunc` режим существующего файла не меняет.
`Mkdir` делает chmod, только если `perm != 0755` (умолчание сервера).
## Этап 4 `internal/jobs`
- **Без зависимостей:** пакет импортирует только stdlib (никакого Bubble Tea и `transfer`). `Result any` и
`Question.Payload any` — как в §6; transfer-джоба будет адаптером в UI.
- **Доставка событий:** один dispatcher-goroutine на менеджер, запускается при первом событии и завершается, когда
очередь событий пуста (нет вечной goroutine — `noLeak` без `Shutdown` не нужен). `notify` может блокироваться
(как `program.Send`): события копятся в срезе менеджера, джобы не ждут. Порядок событий сохраняется;
`Finished` — последнее событие джобы (тик собирается под тем же mutex, что и `Finished`).
- **Тикер 10 Гц** живёт, только пока есть активные джобы; в тик попадают только изменившиеся (dirty) снапшоты.
Переход Queued → Running и `SetBackground` тоже помечают снапшот dirty и уходят ближайшим тиком.
- **Сверх §6:** `Snapshot.Err` (причина Failed/Cancelled), событие `Unasked{Question}` (вопрос снят без ответа —
UI закрывает диалог), `Manager.Get(id)`, `Handle.ID()`, `State.Finished()`, `ErrShutdown`. Завершённые джобы
хранятся для списка `B`, не больше 100 последних.
- **Семантика итога:** `err == nil` → Done; `errors.Is(err, context.Canceled)` → Cancelled; иначе Failed; паника
в fn → Failed с текстом паники (стек — в slog). Паника в `notify` или в `Release` логируется и не ломает
менеджер. `Ask` с отменённым собственным ctx снимает вопрос, а джоба продолжает работу; отмена джобы снимает все
её вопросы. `Answer` на неизвестный/снятый вопрос — no-op.
- **Shutdown(ctx):** отменяет очередь (holds освобождаются сразу) и работающие джобы, ждёт их возврата и доставки
всех событий; по дедлайну возвращает `ctx.Err()`. `Start` после Shutdown сразу даёт Cancelled с `ErrShutdown`
(holds освобождаются).