// maintenance.go — one lane for routine store upkeep.
//
// Cache warms, the file-history index, line counts and the search check
// are all work nobody is waiting for. Each used to start itself — at
// boot, on a moved tip, after a round — in a goroutine of its own, so a
// restart or a busy hour put all of them next to the requests they
// exist to speed up. They now ask this scheduler, which runs one at a
// time and starts a task only when the machine can spare it.
//
// Admission is by load, not by clock: a task waits while the store
// gate is crowded, memory is short, or a deploy or backup is running,
// and says which. It checks again every poll interval.
package main
import (
"context"
"errors"
"log"
"sort"
"sync"
"time"
"craftdesign.group/quarry/internal/obs"
"craftdesign.group/quarry/internal/work"
"craftdesign.group/quarry/internal/zitcli"
)
const (
// maintPoll is how often a waiting task re-reads the load.
maintPoll = 15 * time.Second
// maintOverdue is how long a task may wait before the page says so.
maintOverdue = 24 * time.Hour
// maintQueue bounds the lane's queue. Requests coalesce per store
// and task, so the true bound is stores times tasks; this is above it.
maintQueue = 4096
// maintForgetWait bounds how long removing a store waits for its
// running task to notice it was cancelled.
maintForgetWait = 30 * time.Second
)
type maintKey struct{ store, task string }
// maintEntry is one store's task: what is asked of it now and how it
// last ended. It stays after the run so the page can show the result.
type maintEntry struct {
key maintKey
// pending: requested and not yet started. A second request while
// pending is the same work.
pending bool
queuedAt time.Time
waitingOn []string // non-nil while admitted to the lane but held by load
running bool
startedAt time.Time
last *maintDone
// cancel ends this entry's job once it has left the queue.
cancel context.CancelFunc
ended chan struct{} // closed when that job is over
}
type maintDone struct {
at time.Time
duration time.Duration
err string
// aborted: a pack zit gave up because the store was written to.
// It is a result to retry, not a failure, so err stays empty.
aborted bool
pack *zitcli.MaintPack
}
type maintDetailKey struct{}
// reportPack records a pack's outcome on the run that ctx belongs to,
// for the page's last-run column. A ctx from outside the lane is ignored.
func reportPack(ctx context.Context, p zitcli.MaintPack) {
if d, ok := ctx.Value(maintDetailKey{}).(*maintDone); ok {
d.pack = &p
}
}
// maintenance owns the lane. A nil *maintenance runs requests at once,
// unadmitted, which is what a registrar built without one expects.
type maintenance struct {
ctx context.Context
lane *work.Lane
// load returns what the task must wait on; empty means go.
load func() []string
poll time.Duration
now func() time.Time
mu sync.Mutex
entries map[maintKey]*maintEntry
queue []maintJob
stopped bool
wake chan struct{}
wg sync.WaitGroup
}
type maintJob struct {
e *maintEntry
run func(context.Context) error
}
// newMaintenance builds the scheduler. ctx ends it: waiting and queued
// tasks are dropped, a running one is cancelled.
func newMaintenance(ctx context.Context, load func() []string) *maintenance {
return newMaintenanceAt(ctx, load, maintPoll, time.Now)
}
// newMaintenanceAt is newMaintenance with its poll interval and clock
// given, fixed before the worker starts.
func newMaintenanceAt(ctx context.Context, load func() []string, poll time.Duration, now func() time.Time) *maintenance {
m := &maintenance{
ctx: ctx, lane: work.NewLane("maintenance", 1, maintQueue), load: load,
poll: poll, now: now, entries: map[maintKey]*maintEntry{},
wake: make(chan struct{}, 1),
}
go m.loop()
return m
}
// Request asks for task on store. It reports false when the same task
// is already queued for that store (the request coalesces into it) or
// the scheduler has stopped. It never blocks.
func (m *maintenance) Request(store, task string, run func(context.Context) error) bool {
return m.request(store, task, false, run)
}
// RequestOnce is Request for work an operator asked for by name: it also
// refuses while the same task is running, so a second click cannot queue
// a second run behind the first.
func (m *maintenance) RequestOnce(store, task string, run func(context.Context) error) bool {
return m.request(store, task, true, run)
}
func (m *maintenance) request(store, task string, once bool, run func(context.Context) error) bool {
if m == nil {
go func() { _ = run(obs.WithReason(context.Background(), obs.ReasonMaint)) }()
return true
}
key := maintKey{store, task}
m.mu.Lock()
defer m.mu.Unlock()
if m.stopped {
return false
}
e := m.entries[key]
if e == nil {
e = &maintEntry{key: key}
m.entries[key] = e
}
if e.pending || (once && e.running) {
return false
}
e.pending, e.queuedAt = true, m.now()
m.queue = append(m.queue, maintJob{e, run})
m.wg.Add(1)
select {
case m.wake <- struct{}{}:
default:
}
return true
}
// loop is the one worker: it takes requests in the order they came and
// waits out the load for each before taking the lane's slot, so the lane
// reads as running only while a task actually is.
func (m *maintenance) loop() {
for {
m.mu.Lock()
if len(m.queue) == 0 {
if m.ctx.Err() != nil {
m.stopped = true
m.mu.Unlock()
return
}
m.mu.Unlock()
select {
case <-m.wake:
case <-m.ctx.Done():
}
continue
}
job := m.queue[0]
m.queue = m.queue[1:]
ctx, cancel := context.WithCancel(m.ctx)
job.e.cancel, job.e.ended = cancel, make(chan struct{})
m.mu.Unlock()
ran := false
if err := m.admit(ctx, job.e); err == nil {
err = m.lane.DoNamed(ctx, job.e.key.task, job.e.key.store, func() error { return m.execute(ctx, job.e, job.run, &ran) })
if err != nil && ctx.Err() == nil {
log.Printf("maintenance: %s %s: %v", job.e.key.store, job.e.key.task, err)
}
}
cancel()
// Whatever is still pending was this request, never started
// (stopped, forgotten, or the lane refused): release it.
m.mu.Lock()
if !ran {
job.e.pending = false
}
job.e.waitingOn, job.e.cancel = nil, nil
close(job.e.ended)
m.mu.Unlock()
m.wg.Done()
}
}
// admit waits, without holding the lane, until no load signal is up.
func (m *maintenance) admit(ctx context.Context, e *maintEntry) error {
for {
if err := ctx.Err(); err != nil {
return err
}
reasons := m.load()
if len(reasons) == 0 {
return nil
}
m.mu.Lock()
e.waitingOn = reasons
m.mu.Unlock()
if !sleepCtx(ctx, m.poll) {
return ctx.Err()
}
}
}
// execute runs the task in the lane's slot.
func (m *maintenance) execute(ctx context.Context, e *maintEntry, run func(context.Context) error, ran *bool) error {
if err := ctx.Err(); err != nil {
return err
}
*ran = true
start := m.now()
m.mu.Lock()
e.pending, e.waitingOn, e.running, e.startedAt = false, nil, true, start
m.mu.Unlock()
done := &maintDone{}
err := run(obs.WithReason(context.WithValue(ctx, maintDetailKey{}, done), obs.ReasonMaint))
done.at, done.duration = m.now(), m.now().Sub(start)
switch {
case errors.Is(err, zitcli.ErrPackAborted):
done.aborted = true
case err != nil:
done.err = err.Error()
}
m.mu.Lock()
e.running, e.last = false, done
m.mu.Unlock()
return nil
}
// Forget drops everything the scheduler holds for a store that is gone:
// its queued and waiting tasks never run, a running one is cancelled, and
// its rows leave the page. It returns once that running task has ended
// (or after maintForgetWait), so the caller may close the store.
func (m *maintenance) Forget(store string) {
if m == nil {
return
}
var ended []chan struct{}
m.mu.Lock()
kept := m.queue[:0]
for _, j := range m.queue {
if j.e.key.store == store {
j.e.pending = false
m.wg.Done()
continue
}
kept = append(kept, j)
}
m.queue = kept
for k, e := range m.entries {
if k.store != store {
continue
}
if e.cancel != nil {
e.cancel()
ended = append(ended, e.ended)
}
delete(m.entries, k)
}
m.mu.Unlock()
deadline := time.After(maintForgetWait)
for _, c := range ended {
select {
case <-c:
case <-deadline:
return
}
}
}
// Wait returns once every requested task has run or been dropped.
func (m *maintenance) Wait() {
if m != nil {
m.wg.Wait()
}
}
// Snapshot is every task the scheduler knows, for the ops page: running
// first, then waiting, then queued, then idle ones by store.
func (m *maintenance) Snapshot() []zitcli.MaintTask {
if m == nil {
return nil
}
now := m.now()
m.mu.Lock()
out := make([]zitcli.MaintTask, 0, len(m.entries))
for _, e := range m.entries {
t := zitcli.MaintTask{Store: e.key.store, Task: e.key.task, State: "idle"}
switch {
case e.running:
t.State, t.AgeMs = "running", now.Sub(e.startedAt).Milliseconds()
case e.waitingOn != nil:
t.State, t.WaitingOn = "waiting", append([]string(nil), e.waitingOn...)
t.AgeMs = now.Sub(e.queuedAt).Milliseconds()
case e.pending:
t.State, t.AgeMs = "queued", now.Sub(e.queuedAt).Milliseconds()
}
if e.pending && !e.running && now.Sub(e.queuedAt) > maintOverdue {
t.Overdue = true
}
if e.last != nil {
t.Last = &zitcli.MaintLast{AgoMs: now.Sub(e.last.at).Milliseconds(),
DurationMs: e.last.duration.Milliseconds(), Error: e.last.err,
Aborted: e.last.aborted, Pack: e.last.pack}
}
out = append(out, t)
}
m.mu.Unlock()
rank := map[string]int{"running": 0, "waiting": 1, "queued": 2, "idle": 3}
sort.Slice(out, func(i, j int) bool {
if rank[out[i].State] != rank[out[j].State] {
return rank[out[i].State] < rank[out[j].State]
}
if out[i].Store != out[j].Store {
return out[i].Store < out[j].Store
}
return out[i].Task < out[j].Task
})
return out
}
// Lane is the scheduler's lane, for the ops page's lane list.
func (m *maintenance) Lane() *work.Lane {
if m == nil {
return nil
}
return m.lane
}