Stop the print queue when its store fails

A store write that fails after start, such as on a full disk or a
damaged page, must stop the daemon, and nothing is retried: a write
that failed once seldom succeeds a moment later. The queue now stops on
the first store error. Submit answers that error once and ErrClosed
after, the job in hand writes nothing more to the store and keeps the
state the store last recorded, so one not yet marked sending reads as
queued again, and Run returns the error. A failure that an insert meets
while shutdown waits for it is returned too.

Every store error that stops the queue is marked ErrStoreFailed. serve
logs it once at ERROR, reports it to Sentry once and stops the daemon.
A request whose job could not be stored answers 500 internal_error
without being logged or reported again, so the failure is reported
once whoever submitted the job. docs/configuration.md lists it under
Logs.

With the memory store nothing fails, so the daemon behaves as before.
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:44:43 -06:00
1 parent 14c5e86ab6
commit 7e6cda16f8
7 files changed
+349 -45

No files matched your search

+84 -17
View File
@@ -27,6 +27,10 @@ var (
// ErrClosed is returned by Submit once the queue has shut down.
ErrClosed = errors.New("print queue is shut down")
// ErrStoreFailed marks a store error that stopped the queue, as
// Submit and Run return it. Run's caller reports it, once.
ErrStoreFailed = errors.New("job store failed")
// ErrNotFound is returned by Status for unknown or expired job IDs.
ErrNotFound = errors.New("job not found")
@@ -152,8 +156,8 @@ type delivery struct {
//
// Every change to a job is committed to the store first and made in
// memory after, so a status never shows what the store lacks. A store
// error is returned: by Submit, which then queues nothing, or by Run,
// which then ends.
// error stops the queue: Submit then answers ErrClosed, and Run returns
// the error.
type Queue struct {
renderer Renderer
sender Sender
@@ -176,8 +180,10 @@ type Queue struct {
waiting []*delivery // in submission order
finished []*entry // oldest first, for history eviction
closed bool
failure error // the store error that stopped the queue
// wake tells the worker that a delivery is waiting.
// wake tells the worker that a delivery is waiting or the queue
// stopped.
wake chan struct{}
}
@@ -208,8 +214,8 @@ func New(renderer Renderer, sender Sender, store Store, logger *slog.Logger, opt
// Submit queues job, sent from where meta says. The job should already be
// validated so callers can report problems synchronously; it is validated
// again when rendered. The job is stored before Submit returns, whatever
// happens to the caller meanwhile. A store error is returned, and the job
// is not queued.
// happens to the caller meanwhile. A store error stops the queue and is
// returned, marked as ErrStoreFailed.
func (q *Queue) Submit(job receipt.Job, meta Meta) (Status, error) {
id, err := typeid.New[JobID]()
if err != nil {
@@ -238,7 +244,7 @@ func (q *Queue) Submit(job receipt.Job, meta Meta) (Status, error) {
},
}
if err := q.store.Add(context.Background(), rec, content, false); err != nil {
return Status{}, fmt.Errorf("storing job %s: %w", id, err)
return Status{}, q.stop(fmt.Errorf("storing job %s: %w", id, err))
}
rec.Size = int64(len(content))
@@ -296,7 +302,7 @@ func (q *Queue) Pending() int {
// 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 a store error, which ends it.
// nil then, or the store error that stopped the queue.
func (q *Queue) Run(ctx context.Context) error {
for {
d, err := q.next(ctx)
@@ -307,18 +313,23 @@ func (q *Queue) Run(ctx context.Context) error {
return q.shutdown(ctx)
}
if err := q.process(ctx, d); err != nil {
return err
return q.stop(err)
}
}
}
// next waits for a delivery and takes it. It returns nil once ctx is
// done. The store is told when there is nothing to do.
// done, and the store error that stopped the queue, if one did. The store
// is told when there is nothing to do.
func (q *Queue) next(ctx context.Context) (*delivery, error) {
idle := false
for {
q.mu.Lock()
switch {
case q.failure != nil:
err := q.failure
q.mu.Unlock()
return nil, err
case ctx.Err() != nil:
q.mu.Unlock()
return nil, nil
@@ -333,8 +344,11 @@ func (q *Queue) next(ctx context.Context) (*delivery, error) {
q.mu.Unlock()
if !idle {
idle = true
if err := q.stopped(); err != nil {
return nil, err
}
if err := q.store.Idle(context.WithoutCancel(ctx)); err != nil {
return nil, fmt.Errorf("job store while idle: %w", err)
return nil, q.stop(fmt.Errorf("job store while idle: %w", err))
}
continue
}
@@ -362,6 +376,7 @@ func (q *Queue) process(ctx context.Context, d *delivery) error {
case errors.Is(err, ErrContentGone):
return q.fail(storeCtx, d, 0, err, logger)
case err != nil:
q.release(d)
return fmt.Errorf("reading job %s: %w", rec.ID, err)
}
job, err := receipt.DecodeJob(content)
@@ -371,10 +386,11 @@ func (q *Queue) process(ctx context.Context, d *delivery) error {
logger.Info("printing job", "elements", len(job.Elements), "copies", max(job.Copies, 1))
attempts, err, storeErr := q.print(ctx, jobCtx, d, job, logger)
if storeErr == nil {
storeErr = q.stopped()
}
if storeErr != nil {
q.mu.Lock()
d.taken = false
q.mu.Unlock()
q.release(d)
return storeErr
}
if err != nil {
@@ -387,6 +403,29 @@ func (q *Queue) process(ctx context.Context, d *delivery) error {
return nil
}
// stopped returns the store error that stopped the queue, if one did.
func (q *Queue) stopped() error {
q.mu.Lock()
defer q.mu.Unlock()
return q.failure
}
// release gives back d, which the worker took and did not finish, in the
// state the store has: one never marked sending reads as queued again.
func (q *Queue) release(d *delivery) {
q.mu.Lock()
defer q.mu.Unlock()
q.releaseLocked(d)
}
// releaseLocked is release for a caller that holds q.mu.
func (q *Queue) releaseLocked(d *delivery) {
d.taken = false
if d.State == StoredQueued {
d.StartedAt = time.Time{}
}
}
// fail records d as failed after attempts, logs it and reports it.
func (q *Queue) fail(ctx context.Context, d *delivery, attempts int, cause error, logger *slog.Logger) error {
if err := q.finish(ctx, d, attempts, cause); err != nil {
@@ -414,6 +453,9 @@ func (q *Queue) print(runCtx, jobCtx context.Context, d *delivery, job receipt.J
delay := q.options.RetryDelay
for attempt := 1; ; attempt++ {
err := q.sender.Send(jobCtx, data, func() error {
if storeErr = q.stopped(); storeErr != nil {
return storeErr
}
storeErr = q.sending(storeCtx, d, attempt)
return storeErr
})
@@ -459,8 +501,13 @@ func (q *Queue) sending(ctx context.Context, d *delivery, attempt int) error {
// finish records d as done after attempts, or as failed with cause, and
// drops in the same commit the jobs that retention lets go of. A failure
// is synced, since a failed job rolled back to queued would print after a
// restart.
// restart. Once a store error has stopped the queue it writes nothing and
// returns that error.
func (q *Queue) finish(ctx context.Context, d *delivery, attempts int, cause error) error {
if err := q.stopped(); err != nil {
q.release(d)
return err
}
q.mu.Lock()
next := d.Delivery
q.mu.Unlock()
@@ -475,6 +522,7 @@ func (q *Queue) finish(ctx context.Context, d *delivery, attempts int, cause err
q.mu.Unlock()
if err := q.store.Finish(ctx, next, prune, next.State == StoredFailed); err != nil {
q.release(d)
return fmt.Errorf("recording job %s as %s: %w", d.job.rec.ID, next.State, err)
}
@@ -533,6 +581,24 @@ func (q *Queue) retention(e *entry, finishing bool) (Prune, []*entry) {
return p, drop
}
// stop stops the queue after a store error: Submit answers ErrClosed from
// then on, the job in hand writes nothing more to the store and stays as
// the store has it, and Run returns err. It returns err, marked as
// ErrStoreFailed.
func (q *Queue) stop(err error) error {
if !errors.Is(err, ErrStoreFailed) {
err = fmt.Errorf("%w: %w", ErrStoreFailed, err)
}
q.mu.Lock()
if q.failure == nil {
q.failure = err
}
q.closed = true
q.mu.Unlock()
q.signal()
return err
}
// signal wakes the worker, if it waits.
func (q *Queue) signal() {
select {
@@ -542,7 +608,8 @@ func (q *Queue) signal() {
}
// shutdown stops accepting jobs and fails those still waiting. It returns
// a store error, if recording a failure met one.
// the store error that stopped the queue, if one did: recording a failure
// can meet one, and so can a Submit whose insert shutdown waited for.
func (q *Queue) shutdown(ctx context.Context) error {
q.submitMu.Lock()
q.mu.Lock()
@@ -555,10 +622,10 @@ func (q *Queue) shutdown(ctx context.Context) error {
storeCtx := context.WithoutCancel(ctx)
for _, d := range waiting {
if err := q.finish(storeCtx, d, 0, errShuttingDown); err != nil {
return err
return q.stop(err)
}
}
return nil
return q.stopped()
}
// status returns the job's status, derived from its deliveries. The
+183 -25
View File
@@ -260,6 +260,189 @@ func (f rendererFunc) Render(_ context.Context, job receipt.Job) ([]byte, error)
return f(job)
}
// When Add fails, Submit returns the error, nothing is queued, the queue
// stops and Run returns the error; later jobs are refused as closed.
func TestStoreFailureOnAdd(t *testing.T) {
store := newTestStore(printqueue.NewMemoryStore())
sender := &fakeSender{}
q := newQueueOn(store, fakeRenderer{}, sender, discardLogger(), printqueue.Options{})
stop, done := runQueue(t, q)
store.failNext("add", errDisk)
if _, err := q.Submit(job("x"), printqueue.Meta{}); !errors.Is(err, errDisk) || !errors.Is(err, printqueue.ErrStoreFailed) {
t.Fatalf("Submit = %v, want the store's error marked ErrStoreFailed", err)
}
waitClosed(t, done, "Run's return")
if err := stop(); !errors.Is(err, errDisk) || !errors.Is(err, printqueue.ErrStoreFailed) {
t.Errorf("Run = %v, want the store's error marked ErrStoreFailed", err)
}
if q.Pending() != 0 || len(sender.Sent()) != 0 {
t.Errorf("pending %d, sent %v; want nothing", q.Pending(), sender.Sent())
}
if _, err := q.Submit(job("y"), printqueue.Meta{}); !errors.Is(err, printqueue.ErrClosed) {
t.Errorf("Submit after the failure = %v, want ErrClosed", err)
}
}
// When the sending mark fails, nothing is written, the job never reads
// failed and the queue stops.
func TestStoreFailureOnSending(t *testing.T) {
store := newTestStore(printqueue.NewMemoryStore())
sender := &fakeSender{}
q := newQueueOn(store, fakeRenderer{}, sender, discardLogger(), printqueue.Options{})
store.failNext("sending", errDisk)
st, err := q.Submit(job("x"), printqueue.Meta{})
if err != nil {
t.Fatal(err)
}
stop, done := runQueue(t, q)
waitClosed(t, done, "Run's return")
if err := stop(); !errors.Is(err, errDisk) || !errors.Is(err, printqueue.ErrStoreFailed) {
t.Errorf("Run = %v, want the store's error marked ErrStoreFailed", err)
}
if sent := sender.Sent(); len(sent) != 0 {
t.Errorf("sent %v after the mark failed", sent)
}
if got, _ := q.Status(st.ID); got.State != printqueue.StateQueued || got.Error != "" || got.StartedAt != nil {
t.Errorf("status %+v, want queued, as the store has it", got)
}
for _, c := range store.Commits() {
if c.op != "add" {
t.Errorf("commit %+v after the failed mark", c)
}
}
}
// When Finish fails, the job keeps the state the store last recorded and
// the queue stops.
func TestStoreFailureOnFinish(t *testing.T) {
store := newTestStore(printqueue.NewMemoryStore())
sender := &fakeSender{}
q := newQueueOn(store, fakeRenderer{}, sender, discardLogger(), printqueue.Options{})
store.failNext("finish", errDisk)
st, _ := q.Submit(job("x"), printqueue.Meta{})
second, _ := q.Submit(job("y"), printqueue.Meta{})
stop, done := runQueue(t, q)
waitClosed(t, done, "Run's return")
if err := stop(); !errors.Is(err, errDisk) {
t.Errorf("Run = %v, want the store's error", err)
}
if got, _ := q.Status(st.ID); got.State != printqueue.StatePrinting || got.FinishedAt != nil {
t.Errorf("status %+v, want printing, as the store has it", got)
}
if got, _ := q.Status(second.ID); got.State != printqueue.StateQueued {
t.Errorf("waiting job %+v, want it left queued", got)
}
if sent := sender.Sent(); !slices.Equal(sent, []string{"x"}) {
t.Errorf("sent %v, want only the first job", sent)
}
}
// A failed read of a job's content or a failed Idle stops the queue too.
func TestStoreFailureOnReadOrIdle(t *testing.T) {
for _, op := range []string{"job", "idle"} {
t.Run(op, func(t *testing.T) {
store := newTestStore(printqueue.NewMemoryStore())
q := newQueueOn(store, fakeRenderer{}, &fakeSender{}, discardLogger(), printqueue.Options{})
store.failNext(op, errDisk)
var st printqueue.Status
if op == "job" {
var err error
if st, err = q.Submit(job("x"), printqueue.Meta{}); err != nil {
t.Fatal(err)
}
}
stop, done := runQueue(t, q)
waitClosed(t, done, "Run's return")
if err := stop(); !errors.Is(err, errDisk) {
t.Errorf("Run = %v, want the store's error", err)
}
if got, _ := q.Status(st.ID); op == "job" && (got.State != printqueue.StateQueued || got.StartedAt != nil) {
t.Errorf("status %+v, want queued, as the store has it", got)
}
})
}
}
// Once a store error in Submit has stopped the queue, the job in hand
// writes nothing more to the store: it stays queued, as the store has it.
func TestStoreFailureLeavesTheJobInHandQueued(t *testing.T) {
store := newTestStore(printqueue.NewDurableMemoryStore())
started, release := make(chan struct{}, 1), make(chan struct{})
renderer := rendererFunc(func(j receipt.Job) ([]byte, error) {
started <- struct{}{}
<-release
return []byte(j.Elements[0].Text), nil
})
sender := &fakeSender{}
q := newQueueOn(store, renderer, sender, discardLogger(), printqueue.Options{})
first, _ := q.Submit(job("first"), printqueue.Meta{})
stop, done := runQueue(t, q)
waitClosed(t, started, "the rendering")
store.failNext("add", errDisk)
if _, err := q.Submit(job("second"), printqueue.Meta{}); !errors.Is(err, printqueue.ErrStoreFailed) {
t.Fatalf("Submit = %v, want the store's error marked ErrStoreFailed", err)
}
close(release)
waitClosed(t, done, "Run's return")
if err := stop(); !errors.Is(err, printqueue.ErrStoreFailed) {
t.Errorf("Run = %v, want the store's error marked ErrStoreFailed", err)
}
for _, c := range store.Commits() {
if c.op != "add" {
t.Errorf("commit %+v after the store failed", c)
}
}
if sent := sender.Sent(); len(sent) != 0 {
t.Errorf("sent %v after the store failed", sent)
}
if got, _ := q.Status(first.ID); got.State != printqueue.StateQueued || got.StartedAt != nil {
t.Errorf("job in hand %+v, want queued, as the store has it", got)
}
}
// An insert that fails while shutdown waits for it stops the queue, and
// Run returns its error, with the memory store and with a durable one.
func TestStoreFailureDuringShutdownIsReturned(t *testing.T) {
for _, tt := range []struct {
name string
store printqueue.Store
}{
{"memory store", printqueue.NewMemoryStore()},
{"durable store", printqueue.NewDurableMemoryStore()},
} {
t.Run(tt.name, func(t *testing.T) {
store := newTestStore(tt.store)
q := newQueueOn(store, fakeRenderer{}, &fakeSender{}, discardLogger(), printqueue.Options{})
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
ran := make(chan error, 1)
go func() { ran <- q.Run(ctx) }()
inAdd, releaseAdd := store.blockOn("add")
defer releaseAdd()
store.failNext("add", errDisk)
submitted := make(chan error, 1)
go func() {
_, err := q.Submit(job("x"), printqueue.Meta{})
submitted <- err
}()
waitClosed(t, inAdd, "the insert")
cancel()
// The worker reaches shutdown, which waits for the insert.
time.Sleep(20 * time.Millisecond)
releaseAdd()
if err := <-submitted; !errors.Is(err, printqueue.ErrStoreFailed) {
t.Errorf("Submit = %v, want the store's error marked ErrStoreFailed", err)
}
if err := <-ran; !errors.Is(err, errDisk) || !errors.Is(err, printqueue.ErrStoreFailed) {
t.Errorf("Run = %v, want the store's error marked ErrStoreFailed", err)
}
})
}
}
// While a commit is held, Status and Pending still answer.
func TestStatusAnswersDuringACommit(t *testing.T) {
store := newTestStore(printqueue.NewMemoryStore())
@@ -356,31 +539,6 @@ func TestHistoryPrunesTheStore(t *testing.T) {
}
}
// A store error is returned: by Submit, which then queues nothing, and by
// Run, after a sending mark that failed with nothing written.
func TestStoreErrorsAreReturned(t *testing.T) {
store := newTestStore(printqueue.NewMemoryStore())
sender := &fakeSender{}
q := newQueueOn(store, fakeRenderer{}, sender, discardLogger(), printqueue.Options{})
store.failNext("add", errDisk)
if _, err := q.Submit(job("x"), printqueue.Meta{}); !errors.Is(err, errDisk) || q.Pending() != 0 {
t.Fatalf("Submit = %v with %d pending, want the store's error and nothing queued", err, q.Pending())
}
store.failNext("sending", errDisk)
if _, err := q.Submit(job("y"), printqueue.Meta{}); err != nil {
t.Fatal(err)
}
stop, done := runQueue(t, q)
waitClosed(t, done, "Run's return")
if err := stop(); !errors.Is(err, errDisk) {
t.Errorf("Run = %v, want the store's error", err)
}
if sent := sender.Sent(); len(sent) != 0 {
t.Errorf("sent %v after the mark failed", sent)
}
}
// waitFor polls cond until it holds.
func waitFor(t *testing.T, cond func() bool) {
t.Helper()