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

+4
View File
@@ -9,6 +9,10 @@ version may break callers; such changes are listed under **Breaking**.
### Breaking ### Breaking
- Job status can be `uncertain`, a new `status` value: the daemon stopped
while it was sending the job to the printer, so the receipt may have
printed. Such a job is never sent again. Clients that switch on `status`
must handle it.
- A job with a `raw` element prints only with a token issued with - A job with a `raw` element prints only with a token issued with
`uberbringer token --raw`. Every other token, every token issued so far `uberbringer token --raw`. Every other token, every token issued so far
included, gets `403` `token_scope` for it and keeps every other route. included, gets `403` `token_scope` for it and keeps every other route.
+5 -2
View File
@@ -123,8 +123,11 @@ curl -H @"$HOME/.uberbringer-auth" https://printer.example.com/api/v1/jobs/job_0
} }
``` ```
`status` is `queued`, `printing`, `done` or `failed`. A failed job includes an `status` is `queued`, `printing`, `done`, `failed` or `uncertain`. A failed job
`error` field. `sent_at` is when the first attempt was about to write to the includes an `error` field. `uncertain` means the daemon stopped while it was
sending the job to the printer, so the receipt may have printed; its `error`
says so. Such a job is never sent again: if the paper shows it missing, send
it again. `sent_at` is when the first attempt was about to write to the
printer. A failed job with `sent_at` reached the printer, and part of it may printer. A failed job with `sent_at` reached the printer, and part of it may
have printed; one without it never reached the printer. have printed; one without it never reached the printer.
`source` says where the job came from: `print` for `source` says where the job came from: `print` for
+5 -4
View File
@@ -397,11 +397,11 @@
"type": "string" "type": "string"
}, },
"error": { "error": {
"description": "error says why a failed job failed.", "description": "error says why a failed job failed, or that an uncertain one may have printed.",
"type": "string" "type": "string"
}, },
"finished_at": { "finished_at": {
"description": "finished_at is when the job was done or failed.", "description": "finished_at is when the job was done or failed, or when a start found it uncertain.",
"format": "date-time", "format": "date-time",
"type": "string" "type": "string"
}, },
@@ -428,12 +428,13 @@
"type": "string" "type": "string"
}, },
"status": { "status": {
"description": "status is where the job is in its lifecycle.", "description": "status 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.",
"enum": [ "enum": [
"queued", "queued",
"printing", "printing",
"done", "done",
"failed" "failed",
"uncertain"
], ],
"type": "string" "type": "string"
} }
+4
View File
@@ -96,6 +96,10 @@ func run(ctx context.Context, cfg *config.Config, build BuildInfo, out io.Writer
RetryDelay: cfg.Printer.RetryDelay, RetryDelay: cfg.Printer.RetryDelay,
OnFailure: reportJobFailure, OnFailure: reportJobFailure,
}) })
// Restored jobs go ahead of new ones, so nothing may submit before.
if err := queue.Restore(ctx); err != nil {
return err
}
srv := server.New(server.Config{ srv := server.New(server.Config{
Info: server.Info{ Info: server.Info{
Project: Project, Project: Project,
+88 -11
View File
@@ -67,19 +67,26 @@ const (
StatePrinting State = "printing" StatePrinting State = "printing"
StateDone State = "done" StateDone State = "done"
StateFailed State = "failed" 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. // Status describes a job.
type Status struct { type Status struct {
// ID identifies the job. // ID identifies the job.
ID JobID `json:"id"` ID JobID `json:"id"`
// State is where the job is in its lifecycle. // State is where the job is in its lifecycle. uncertain is a job that
State State `json:"status" jsonschema:"enum=queued,enum=printing,enum=done,enum=failed"` // 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, // Source says where the job came from: print for POST /api/v1/print,
// module:<name> for a module route, e.g. module:ntfy, or // module:<name> for a module route, e.g. module:ntfy, or
// ntfy:<subscription> for an ntfy subscription in the config. // ntfy:<subscription> for an ntfy subscription in the config.
Source string `json:"source,omitempty"` 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"` Error string `json:"error,omitempty"`
// Attempts is how many times the job was sent to the printer. // Attempts is how many times the job was sent to the printer.
Attempts int `json:"attempts,omitempty"` 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 // A failed job with sent_at reached the printer, and part of it may have
// printed; one without it never reached the printer. // printed; one without it never reached the printer.
SentAt *time.Time `json:"sent_at,omitempty"` 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"` FinishedAt *time.Time `json:"finished_at,omitempty"`
} }
@@ -304,6 +312,67 @@ func (q *Queue) Pending() int {
return len(q.waiting) 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 // 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 // cancelled is finished; jobs still waiting are marked failed. Run returns
// nil then, or the store error that stopped the queue. // 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() return q.stopped()
} }
// status returns the job's status, derived from its deliveries. The // status returns the job's status, derived from its deliveries: their
// caller holds the queue's mu. // 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 { func (e *entry) status() Status {
st := Status{ st := Status{
ID: e.rec.ID, ID: e.rec.ID,
@@ -644,7 +715,7 @@ func (e *entry) status() Status {
var started, sent, finished time.Time var started, sent, finished time.Time
for _, d := range e.deliveries { for _, d := range e.deliveries {
st.Attempts += d.Attempts st.Attempts += d.Attempts
if st.Error == "" { if d.Error != "" && (st.Error == "" || d.State == StoredUncertain) {
st.Error = d.Error st.Error = d.Error
} }
started = earliest(started, d.StartedAt) 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 // jobState derives a job's state from its deliveries': queued while every
// one waits, untaken; printing while any is unfinished once one is taken // one waits, untaken; printing while any is unfinished once one is taken
// or finished; once every one has finished, failed if any failed, and // or finished; once every one has finished, uncertain if any is, since a
// done otherwise. // receipt may have printed, then failed if any failed, and done
// otherwise.
func jobState(ds []*delivery) State { func jobState(ds []*delivery) State {
var waiting, finished, failed int var waiting, finished, failed, uncertain int
for _, d := range ds { for _, d := range ds {
switch { switch {
case d.State == StoredQueued && !d.taken: case d.State == StoredQueued && !d.taken:
waiting++ waiting++
case d.State.Finished(): case d.State.Finished():
finished++ finished++
if d.State == StoredFailed { switch d.State {
case StoredFailed:
failed++ failed++
case StoredUncertain:
uncertain++
} }
} }
} }
@@ -682,6 +757,8 @@ func jobState(ds []*delivery) State {
return StateQueued return StateQueued
case finished < len(ds): case finished < len(ds):
return StatePrinting return StatePrinting
case uncertain > 0:
return StateUncertain
case failed > 0: case failed > 0:
return StateFailed return StateFailed
} }
+4
View File
@@ -35,12 +35,16 @@ type fakeSender struct {
script []string script []string
sent []string sent []string
block chan struct{} // if set, Send waits for it to close block chan struct{} // if set, Send waits for it to close
gate chan struct{} // if set, each Send takes a value from it first
} }
func (f *fakeSender) Send(_ context.Context, data []byte, beforeWrite func() error) error { func (f *fakeSender) Send(_ context.Context, data []byte, beforeWrite func() error) error {
if f.block != nil { if f.block != nil {
<-f.block <-f.block
} }
if f.gate != nil {
<-f.gate
}
f.mu.Lock() f.mu.Lock()
step := "" step := ""
if len(f.script) > 0 { if len(f.script) > 0 {
+283
View File
@@ -0,0 +1,283 @@
package printqueue_test
import (
"context"
"encoding/json"
"errors"
"log/slog"
"slices"
"strings"
"testing"
"time"
"uberbringer/internal/pkg/printqueue"
"uberbringer/internal/pkg/receipt"
)
// crashSender stands for a daemon that dies between the sending mark and
// the write: it calls beforeWrite, then writes nothing and does not
// return until release closes.
type crashSender struct{ release chan struct{} }
func (c crashSender) Send(_ context.Context, _ []byte, beforeWrite func() error) error {
if err := beforeWrite(); err != nil {
return err
}
<-c.release
return errors.New("the process was gone")
}
// storeJob adds job seq to store as an earlier run would have, with one
// queued delivery per printer, numbered from seq*10.
func storeJob(t *testing.T, store printqueue.Store, seq uint64, id printqueue.JobID, j receipt.Job, printers ...string) printqueue.Record {
t.Helper()
r := printqueue.Record{Seq: seq, ID: id, Source: "print", Ref: "req", CreatedAt: time.Now().UTC()}
for i, p := range printers {
r.Deliveries = append(r.Deliveries, printqueue.Delivery{Seq: seq*10 + uint64(i), Printer: p, State: printqueue.StoredQueued})
}
content, err := json.Marshal(j)
if err != nil {
t.Fatal(err)
}
if err := store.Add(context.Background(), r, content, false); err != nil {
t.Fatal(err)
}
return r
}
// Queued jobs resume after a restart in sequence order, even when their
// IDs were minted in another order, and ahead of jobs submitted after it.
// Their statuses answer before the worker runs.
func TestRestoreResumesInOrder(t *testing.T) {
store := printqueue.NewDurableMemoryStore()
var ids []printqueue.JobID
for range 3 {
ids = append(ids, newJobID(t))
}
slices.Reverse(ids)
for i, text := range []string{"one", "two", "three"} {
storeJob(t, store, uint64(i+1), ids[i], job(text), printqueue.DefaultPrinter)
}
sender := &fakeSender{}
q := newQueueOn(store, fakeRenderer{}, sender, discardLogger(), printqueue.Options{})
if err := q.Restore(context.Background()); err != nil {
t.Fatal(err)
}
if st, err := q.Status(ids[0]); err != nil || st.State != printqueue.StateQueued {
t.Errorf("restored status %+v, %v; want queued", st, err)
}
late, err := q.Submit(job("late"), printqueue.Meta{})
if err != nil {
t.Fatal(err)
}
startQueue(t, q)
waitForState(t, q, late.ID, printqueue.StateDone)
if got := sender.Sent(); !slices.Equal(got, []string{"one", "two", "three", "late"}) {
t.Errorf("sent %v, want the restored jobs in order, then the new one", got)
}
if err := q.Restore(context.Background()); err == nil {
t.Error("a second Restore was accepted")
}
}
// A backlog larger than Size loads whole, and Submit answers ErrQueueFull
// until it falls below Size.
func TestRestoredBacklogBeyondSize(t *testing.T) {
store := printqueue.NewDurableMemoryStore()
before := newQueueOn(store, fakeRenderer{}, &fakeSender{}, discardLogger(), printqueue.Options{Size: 5})
for range 5 {
if _, err := before.Submit(job("old"), printqueue.Meta{}); err != nil {
t.Fatal(err)
}
}
sender := &fakeSender{gate: make(chan struct{})}
q := newQueueOn(store, fakeRenderer{}, sender, discardLogger(), printqueue.Options{Size: 2})
if err := q.Restore(context.Background()); err != nil {
t.Fatal(err)
}
if q.Pending() != 5 {
t.Fatalf("Pending = %d, want the whole backlog, 5", q.Pending())
}
startQueue(t, q)
defer close(sender.gate)
waitFor(t, func() bool { return q.Pending() == 4 })
if _, err := q.Submit(job("new"), printqueue.Meta{}); !errors.Is(err, printqueue.ErrQueueFull) {
t.Errorf("Submit with 4 waiting = %v, want ErrQueueFull", err)
}
sender.gate <- struct{}{}
sender.gate <- struct{}{}
waitFor(t, func() bool { return q.Pending() == 2 })
if _, err := q.Submit(job("new"), printqueue.Meta{}); !errors.Is(err, printqueue.ErrQueueFull) {
t.Errorf("Submit with 2 waiting = %v, want ErrQueueFull", err)
}
sender.gate <- struct{}{}
waitFor(t, func() bool { return q.Pending() == 1 })
if _, err := q.Submit(job("new"), printqueue.Meta{}); err != nil {
t.Errorf("Submit with 1 waiting = %v, want it queued", err)
}
}
// A job whose sending mark was committed when the daemon died is
// uncertain after the restart: logged once at WARN by its IDs, never with
// its content, and never sent again. A second restart logs nothing more.
func TestInterruptedSendEndsUncertain(t *testing.T) {
store := printqueue.NewDurableMemoryStore()
crash := crashSender{release: make(chan struct{})}
before := newQueueOn(store, fakeRenderer{}, crash, discardLogger(), printqueue.Options{})
st, _ := before.Submit(job("private text"), printqueue.Meta{Source: "ntfy:home", Ref: "msg1"})
runQueue(t, before)
t.Cleanup(func() { close(crash.release) })
waitFor(t, func() bool { got, _ := before.Status(st.ID); return got.SentAt != nil })
var logs lockedBuffer
sender := &fakeSender{}
q := newQueueOn(store, fakeRenderer{}, sender, slog.New(slog.NewTextHandler(&logs, nil)), printqueue.Options{})
if err := q.Restore(context.Background()); err != nil {
t.Fatal(err)
}
got, _ := q.Status(st.ID)
if got.State != printqueue.StateUncertain || got.Error != printqueue.InterruptedSend || got.SentAt == nil ||
got.FinishedAt == nil || got.Attempts != 1 {
t.Errorf("status %+v, want uncertain with its attempt", got)
}
stop, _ := runQueue(t, q)
other, _ := q.Submit(job("other"), printqueue.Meta{})
waitForState(t, q, other.ID, printqueue.StateDone)
if err := stop(); err != nil {
t.Fatal(err)
}
if sent := sender.Sent(); !slices.Equal(sent, []string{"other"}) {
t.Errorf("sent %v, want only the new job", sent)
}
var warns []string
for line := range strings.Lines(logs.String()) {
if strings.Contains(line, "level=WARN") {
warns = append(warns, line)
}
}
if len(warns) != 1 {
t.Fatalf("WARN lines %q, want one", warns)
}
for _, want := range []string{"job_id=" + st.ID.String(), "printer=default", "source=ntfy:home", "ref=msg1", "may have printed"} {
if !strings.Contains(warns[0], want) {
t.Errorf("WARN line lacks %s: %s", want, warns[0])
}
}
if strings.Contains(logs.String(), "private text") {
t.Error("the job's text reached the logs")
}
var again lockedBuffer
third := newQueueOn(store, fakeRenderer{}, &fakeSender{}, slog.New(slog.NewTextHandler(&again, nil)), printqueue.Options{})
if err := third.Restore(context.Background()); err != nil {
t.Fatal(err)
}
if got, _ := third.Status(st.ID); got.State != printqueue.StateUncertain {
t.Errorf("status after a second restart %+v, want uncertain", got)
}
if strings.Contains(again.String(), "level=WARN") {
t.Errorf("a second restart logged %q", again.String())
}
}
// A job whose sending mark failed to commit was never sent: after the
// restart it is queued and prints once.
func TestFailedMarkPrintsOnceAfterRestart(t *testing.T) {
inner := printqueue.NewDurableMemoryStore()
store := newTestStore(inner)
store.failNext("sending", errDisk)
first := &fakeSender{}
before := newQueueOn(store, fakeRenderer{}, first, discardLogger(), printqueue.Options{})
st, _ := before.Submit(job("x"), printqueue.Meta{})
stop, done := runQueue(t, before)
waitClosed(t, done, "Run's return")
if err := stop(); !errors.Is(err, errDisk) {
t.Fatalf("Run = %v, want the store's error", err)
}
second := &fakeSender{}
q := newQueueOn(inner, fakeRenderer{}, second, discardLogger(), printqueue.Options{})
if err := q.Restore(context.Background()); err != nil {
t.Fatal(err)
}
if got, _ := q.Status(st.ID); got.State != printqueue.StateQueued {
t.Errorf("status after the restart %+v, want queued", got)
}
startQueue(t, q)
waitForState(t, q, st.ID, printqueue.StateDone)
if a, b := first.Sent(), second.Sent(); len(a) != 0 || !slices.Equal(b, []string{"x"}) {
t.Errorf("sent %v before and %v after the restart, want it once after", a, b)
}
}
// Records with several deliveries come back whole: each job's status
// derives from all of them, and the queued ones print.
func TestRestoreJobsWithSeveralDeliveries(t *testing.T) {
ctx := context.Background()
store := printqueue.NewDurableMemoryStore()
at := time.Date(2026, 12, 1, 12, 0, 0, 0, time.UTC)
set := func(r printqueue.Record, i int, state printqueue.StoredState) {
t.Helper()
d := r.Deliveries[i]
d.Attempts, d.StartedAt, d.SentAt = 1, at, at.Add(time.Duration(i)*time.Second)
if err := store.Sending(ctx, d); err != nil {
t.Fatal(err)
}
if state == printqueue.StoredSending {
return
}
d.State, d.FinishedAt = state, at.Add(time.Minute)
if state == printqueue.StoredFailed {
d.Error = "printer offline"
}
if err := store.Finish(ctx, d, printqueue.Prune{}, false); err != nil {
t.Fatal(err)
}
}
uncertain := storeJob(t, store, 1, newJobID(t), job("a"), "default", "kitchen", "bar")
set(uncertain, 0, printqueue.StoredDone)
set(uncertain, 1, printqueue.StoredFailed)
set(uncertain, 2, printqueue.StoredSending)
partly := storeJob(t, store, 2, newJobID(t), job("b"), "default", "kitchen")
set(partly, 0, printqueue.StoredDone)
failed := storeJob(t, store, 3, newJobID(t), job("c"), "default", "kitchen")
set(failed, 0, printqueue.StoredFailed)
set(failed, 1, printqueue.StoredDone)
waiting := storeJob(t, store, 4, newJobID(t), job("d"), "default", "kitchen", "bar")
sender := &fakeSender{}
q := newQueueOn(store, fakeRenderer{}, sender, discardLogger(), printqueue.Options{})
if err := q.Restore(ctx); err != nil {
t.Fatal(err)
}
for _, tt := range []struct {
r printqueue.Record
state printqueue.State
}{
{uncertain, printqueue.StateUncertain},
{partly, printqueue.StatePrinting},
{failed, printqueue.StateFailed},
{waiting, printqueue.StateQueued},
} {
if got, _ := q.Status(tt.r.ID); got.State != tt.state {
t.Errorf("job %d: %s, want %s", tt.r.Seq, got.State, tt.state)
}
}
got, _ := q.Status(uncertain.ID)
if got.Attempts != 3 || got.Error != printqueue.InterruptedSend || *got.SentAt != at || got.FinishedAt == nil {
t.Errorf("uncertain job %+v, want its three deliveries summed", got)
}
if q.Pending() != 4 {
t.Errorf("Pending = %d, want the four queued deliveries", q.Pending())
}
startQueue(t, q)
waitForState(t, q, partly.ID, printqueue.StateDone)
waitForState(t, q, waiting.ID, printqueue.StateDone)
if sent := sender.Sent(); !slices.Equal(sent, []string{"b", "d", "d", "d"}) {
t.Errorf("sent %v, want each queued delivery once, in order", sent)
}
}
+11 -3
View File
@@ -19,18 +19,19 @@ var deliveryKinds = []deliveryKind{
{"sending", StoredSending, true}, {"sending", StoredSending, true},
{"done", StoredDone, false}, {"done", StoredDone, false},
{"failed", StoredFailed, false}, {"failed", StoredFailed, false},
{"uncertain", StoredUncertain, false},
} }
// A job's status follows from its deliveries': queued while every one // A job's status follows from its deliveries': queued while every one
// waits, printing while any is unfinished once one was taken or finished, // waits, printing while any is unfinished once one was taken or finished,
// and once all have finished, failed over done. Every mix of one, two and // and once all have finished, uncertain over failed over done. Every mix
// three deliveries is checked. // of one, two and three deliveries is checked.
func TestJobStateFromDeliveries(t *testing.T) { func TestJobStateFromDeliveries(t *testing.T) {
for n := 1; n <= 3; n++ { for n := 1; n <= 3; n++ {
for _, mix := range mixes(n) { for _, mix := range mixes(n) {
var ds []*delivery var ds []*delivery
var names []string var names []string
waiting, finished, failed := 0, 0, 0 waiting, finished, failed, uncertain := 0, 0, 0, 0
for _, k := range mix { for _, k := range mix {
ds = append(ds, &delivery{Delivery: Delivery{State: k.state}, taken: k.taken}) ds = append(ds, &delivery{Delivery: Delivery{State: k.state}, taken: k.taken})
names = append(names, k.name) names = append(names, k.name)
@@ -42,6 +43,9 @@ func TestJobStateFromDeliveries(t *testing.T) {
case "failed": case "failed":
finished++ finished++
failed++ failed++
case "uncertain":
finished++
uncertain++
} }
} }
want := StateDone want := StateDone
@@ -50,6 +54,8 @@ func TestJobStateFromDeliveries(t *testing.T) {
want = StateQueued want = StateQueued
case finished < n: case finished < n:
want = StatePrinting want = StatePrinting
case uncertain > 0:
want = StateUncertain
case failed > 0: case failed > 0:
want = StateFailed want = StateFailed
} }
@@ -67,6 +73,8 @@ func TestJobStateFromDeliveries(t *testing.T) {
{[]string{"waiting", "done"}, StatePrinting}, {[]string{"waiting", "done"}, StatePrinting},
{[]string{"failed", "waiting", "sending"}, StatePrinting}, {[]string{"failed", "waiting", "sending"}, StatePrinting},
{[]string{"done", "failed", "done"}, StateFailed}, {[]string{"done", "failed", "done"}, StateFailed},
{[]string{"failed", "uncertain", "done"}, StateUncertain},
{[]string{"uncertain", "taken"}, StatePrinting},
{[]string{"done", "done", "done"}, StateDone}, {[]string{"done", "done", "done"}, StateDone},
} { } {
var ds []*delivery var ds []*delivery
+1 -1
View File
@@ -225,7 +225,7 @@ func TestSchemasCarryComments(t *testing.T) {
if d, _ := status["description"].(string); !strings.HasPrefix(d, "status is ") { if d, _ := status["description"].(string); !strings.HasPrefix(d, "status is ") {
t.Errorf("JobStatus.status description = %q", d) t.Errorf("JobStatus.status description = %q", d)
} }
if enum, _ := status["enum"].([]any); len(enum) != 4 { if enum, _ := status["enum"].([]any); len(enum) != 5 {
t.Errorf("JobStatus.status enum = %v", status["enum"]) t.Errorf("JobStatus.status enum = %v", status["enum"])
} }
id := property(t, doc, "JobStatus", "id") id := property(t, doc, "JobStatus", "id")