Restore stored jobs at start, ending interrupted sends uncertain

Breaking: job status can be "uncertain", a new status value. Clients
that switch on status must handle it.

The queue loads what its store keeps before the worker, the server and
the subscriptions start. Queued deliveries wait again in submission
order, ahead of any new job, even beyond queue.size: Submit answers
queue_full until the backlog falls below it. Restored statuses answer
at once, and the sequence continues from the highest stored.

A delivery found in sending at start may have reached the printer, so
the store ends it uncertain, a new terminal state, and it is never sent
again; a person checks the paper and sends it again if it is missing.
Each one is logged once at WARN by its job's ID, printer, source and
reference. A job's status is uncertain once all its deliveries have
finished and any is, over failed over done.

With the memory store there is nothing to restore, so the daemon
behaves as before; a store on disk comes in stage 1d. Part of stage 1c
of docs/plans/job-store.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
57_WolveandClaude Opus 5.5 committed 2026-12-01 13:45:07 -06:00
1 parent 9b25c1bfd3
commit 45b57ab196
9 files changed
+405 -21

No files matched your search

+88 -11
View File
@@ -67,19 +67,26 @@ const (
StatePrinting State = "printing"
StateDone State = "done"
StateFailed State = "failed"
// StateUncertain is a job that was being sent when the daemon stopped,
// so it may have printed. It is never sent again.
StateUncertain State = "uncertain"
)
// Status describes a job.
type Status struct {
// ID identifies the job.
ID JobID `json:"id"`
// State is where the job is in its lifecycle.
State State `json:"status" jsonschema:"enum=queued,enum=printing,enum=done,enum=failed"`
// State is where the job is in its lifecycle. uncertain is a job that
// was being sent to the printer when the daemon stopped: it may have
// printed, and it is never sent again.
State State `json:"status" jsonschema:"enum=queued,enum=printing,enum=done,enum=failed,enum=uncertain"`
// Source says where the job came from: print for POST /api/v1/print,
// module:<name> for a module route, e.g. module:ntfy, or
// ntfy:<subscription> for an ntfy subscription in the config.
Source string `json:"source,omitempty"`
// Error says why a failed job failed.
// Error says why a failed job failed, or that an uncertain one may
// have printed.
Error string `json:"error,omitempty"`
// Attempts is how many times the job was sent to the printer.
Attempts int `json:"attempts,omitempty"`
@@ -91,7 +98,8 @@ type Status struct {
// A failed job with sent_at reached the printer, and part of it may have
// printed; one without it never reached the printer.
SentAt *time.Time `json:"sent_at,omitempty"`
// FinishedAt is when the job was done or failed.
// FinishedAt is when the job was done or failed, or when a start found
// it uncertain.
FinishedAt *time.Time `json:"finished_at,omitempty"`
}
@@ -304,6 +312,67 @@ func (q *Queue) Pending() int {
return len(q.waiting)
}
// Restore loads the jobs the store keeps, before Run and before the first
// Submit. Their queued deliveries wait again, in submission order and
// ahead of any new job, even beyond Size, and their statuses answer at
// once. Each delivery the load turned uncertain is logged at WARN by its
// job's ID, source and reference; it is never sent again.
func (q *Queue) Restore(ctx context.Context) error {
q.submitMu.Lock()
defer q.submitMu.Unlock()
q.mu.Lock()
started := len(q.jobs) > 0 || q.nextJob > 0
q.mu.Unlock()
if started {
return errors.New("restoring the print queue: jobs were already queued")
}
loaded, err := q.store.Load(ctx)
if err != nil {
return fmt.Errorf("loading the job store: %w", err)
}
uncertain := make(map[uint64]bool, len(loaded.Uncertain))
for _, seq := range loaded.Uncertain {
uncertain[seq] = true
}
type turned struct {
rec Record
printer string
}
var warn []turned
q.mu.Lock()
for _, r := range loaded.Records {
q.nextJob = max(q.nextJob, r.Seq)
e := q.keep(r)
e.finished = true
for _, d := range e.deliveries {
q.nextDelivery = max(q.nextDelivery, d.Seq)
e.finished = e.finished && d.State.Finished()
if d.State == StoredQueued {
q.waiting = append(q.waiting, d)
}
if uncertain[d.Seq] {
warn = append(warn, turned{rec: e.rec, printer: d.Printer})
}
}
if e.finished {
q.finished = append(q.finished, e)
}
}
waiting := len(q.waiting)
q.mu.Unlock()
for _, w := range warn {
q.logger.Warn("job was being sent when the daemon stopped; it may have printed and is not sent again",
"job_id", w.rec.ID.String(), "printer", w.printer, "source", w.rec.Source, "ref", w.rec.Ref)
}
if len(loaded.Records) > 0 {
q.logger.Info("print queue restored", "jobs", len(loaded.Records), "waiting", waiting, "uncertain", len(warn))
}
q.signal()
return nil
}
// Run prints jobs until ctx is cancelled. A job that is printing when ctx is
// cancelled is finished; jobs still waiting are marked failed. Run returns
// nil then, or the store error that stopped the queue.
@@ -632,8 +701,10 @@ func (q *Queue) shutdown(ctx context.Context) error {
return q.stopped()
}
// status returns the job's status, derived from its deliveries. The
// caller holds the queue's mu.
// status returns the job's status, derived from its deliveries: their
// attempts summed, their earliest start and first send, and their latest
// finish once all have finished. The error is an uncertain delivery's,
// else a failed one's. The caller holds the queue's mu.
func (e *entry) status() Status {
st := Status{
ID: e.rec.ID,
@@ -644,7 +715,7 @@ func (e *entry) status() Status {
var started, sent, finished time.Time
for _, d := range e.deliveries {
st.Attempts += d.Attempts
if st.Error == "" {
if d.Error != "" && (st.Error == "" || d.State == StoredUncertain) {
st.Error = d.Error
}
started = earliest(started, d.StartedAt)
@@ -662,18 +733,22 @@ func (e *entry) status() Status {
// jobState derives a job's state from its deliveries': queued while every
// one waits, untaken; printing while any is unfinished once one is taken
// or finished; once every one has finished, failed if any failed, and
// done otherwise.
// or finished; once every one has finished, uncertain if any is, since a
// receipt may have printed, then failed if any failed, and done
// otherwise.
func jobState(ds []*delivery) State {
var waiting, finished, failed int
var waiting, finished, failed, uncertain int
for _, d := range ds {
switch {
case d.State == StoredQueued && !d.taken:
waiting++
case d.State.Finished():
finished++
if d.State == StoredFailed {
switch d.State {
case StoredFailed:
failed++
case StoredUncertain:
uncertain++
}
}
}
@@ -682,6 +757,8 @@ func jobState(ds []*delivery) State {
return StateQueued
case finished < len(ds):
return StatePrinting
case uncertain > 0:
return StateUncertain
case failed > 0:
return StateFailed
}