Leave unsent jobs queued when a durable store stops

A stop and a start are a restart too, so with a store that outlives the
process a stop now treats waiting jobs as a crash would: they stay
queued and print at the next start. The job in hand stays queued as
well while nothing of it has been sent: rendering and connecting end
with the daemon, and an attempt whose connection opens once the stop
has begun writes nothing. Only a write that has begun runs on, so the
stop takes at most printer.write_timeout and two commits. A job waiting
to retry after an attempt reached the printer fails, as before, and its
sent_at shows that bytes went out.

A store error that stops the queue now ends the job's context the same
way, so a rendering, a dial or a wait between retries stops at once
rather than running on to a job that can write nothing.

With the memory store, which the process forgets, a stop is unchanged:
the job in hand finishes, rendering included, and waiting jobs fail.

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:46:13 -06:00
1 parent 45b57ab196
commit 4ef6d21258
3 files changed
+480 -17

No files matched your search

+81 -17
View File
@@ -110,7 +110,9 @@ type Renderer interface {
// Sender delivers bytes to the printer. It calls beforeWrite, if not nil, // Sender delivers bytes to the printer. It calls beforeWrite, if not nil,
// once it can write and before the first byte, and writes nothing when // once it can write and before the first byte, and writes nothing when
// beforeWrite fails. // beforeWrite fails. Cancelling ctx stops the wait for the printer and
// the dial, but not a write that has begun; ctx's deadline still bounds
// it.
type Sender interface { type Sender interface {
Send(ctx context.Context, data []byte, beforeWrite func() error) error Send(ctx context.Context, data []byte, beforeWrite func() error) error
} }
@@ -197,6 +199,11 @@ type Queue struct {
// wake tells the worker that a delivery is waiting or the queue // wake tells the worker that a delivery is waiting or the queue
// stopped. // stopped.
wake chan struct{} wake chan struct{}
// halted ends once a store error has stopped the queue, and with it
// the context of the job in hand.
halted context.Context
halt context.CancelFunc
} }
// New returns a Queue that keeps its jobs in store. Call Run to start // New returns a Queue that keeps its jobs in store. Call Run to start
@@ -212,6 +219,7 @@ func New(renderer Renderer, sender Sender, store Store, logger *slog.Logger, opt
options.RetryDelay = time.Second options.RetryDelay = time.Second
} }
options.History = max(options.History, 0) options.History = max(options.History, 0)
halted, halt := context.WithCancel(context.Background())
return &Queue{ return &Queue{
renderer: renderer, renderer: renderer,
sender: sender, sender: sender,
@@ -220,6 +228,8 @@ func New(renderer Renderer, sender Sender, store Store, logger *slog.Logger, opt
options: options, options: options,
jobs: make(map[JobID]*entry), jobs: make(map[JobID]*entry),
wake: make(chan struct{}, 1), wake: make(chan struct{}, 1),
halted: halted,
halt: halt,
} }
} }
@@ -373,9 +383,13 @@ func (q *Queue) Restore(ctx context.Context) error {
return nil return nil
} }
// Run prints jobs until ctx is cancelled. A job that is printing when ctx is // Run prints jobs until ctx is cancelled, then returns nil, or the store
// cancelled is finished; jobs still waiting are marked failed. Run returns // error that stopped the queue. With the memory store, a job that is
// nil then, or the store error that stopped the queue. // printing when ctx is cancelled is finished, and jobs still waiting are
// marked failed. With a durable store, a job finishes only if its write
// has begun, and every job that sent nothing stays queued for the next
// start; a job waiting to retry after an attempt reached the printer
// fails.
func (q *Queue) Run(ctx context.Context) error { func (q *Queue) Run(ctx context.Context) error {
for { for {
d, err := q.next(ctx) d, err := q.next(ctx)
@@ -435,11 +449,22 @@ func (q *Queue) next(ctx context.Context) (*delivery, error) {
// process prints delivery d and records how that ended. It returns only a // process prints delivery d and records how that ended. It returns only a
// store error. // store error.
func (q *Queue) process(ctx context.Context, d *delivery) error { func (q *Queue) process(ctx context.Context, d *delivery) error {
// Detach from shutdown so a receipt that has started is not cut short, // With the memory store, the job is detached from shutdown so a
// but keep a bound so a stuck printer cannot hold the worker forever. // receipt that has started is not cut short, rendering included, since
// Store calls are detached too: a commit that has begun finishes. // the process forgets it anyway. With a durable store, rendering and
jobCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), jobTimeout) // connecting end with the daemon and the job stays queued for the
// next start; only a write that has begun runs on, since the sender
// ignores the context's cancellation once it writes. Either way a
// bound keeps a stuck printer from holding the worker forever, and a
// store error that stops the queue ends the job's context too. Store
// calls are detached: a commit that has begun finishes.
parent := context.WithoutCancel(ctx)
if q.store.Durable() {
parent = ctx
}
jobCtx, cancel := context.WithTimeout(parent, jobTimeout)
defer cancel() defer cancel()
defer context.AfterFunc(q.halted, cancel)()
storeCtx := context.WithoutCancel(ctx) storeCtx := context.WithoutCancel(ctx)
rec := d.job.rec rec := d.job.rec
@@ -466,6 +491,10 @@ func (q *Queue) process(ctx context.Context, d *delivery) error {
q.release(d) q.release(d)
return storeErr return storeErr
} }
if err != nil && q.abandoned(ctx, d) {
logger.Info("job left queued: the daemon is stopping and nothing was sent")
return nil
}
if err != nil { if err != nil {
return q.fail(storeCtx, d, attempts, err, logger) return q.fail(storeCtx, d, attempts, err, logger)
} }
@@ -499,6 +528,20 @@ func (q *Queue) releaseLocked(d *delivery) {
} }
} }
// abandoned reports whether d, which did not print, stays queued: with a
// durable store, once ctx is done, if no attempt reached the printer.
// Nothing is written then, and d reads as queued again, as the store has
// it.
func (q *Queue) abandoned(ctx context.Context, d *delivery) bool {
q.mu.Lock()
defer q.mu.Unlock()
if !q.store.Durable() || ctx.Err() == nil || !d.SentAt.IsZero() {
return false
}
q.releaseLocked(d)
return true
}
// fail records d as failed after attempts, logs it and reports it. // 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 { 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 { if err := q.finish(ctx, d, attempts, cause); err != nil {
@@ -513,39 +556,55 @@ func (q *Queue) fail(ctx context.Context, d *delivery, attempts int, cause error
// print renders job once and sends it, retrying failed sends with backoff. // print renders job once and sends it, retrying failed sends with backoff.
// Each attempt records d as sending once the printer's connection is open // Each attempt records d as sending once the printer's connection is open
// and before the first byte. Retries stop early when runCtx is cancelled. // and before the first byte; with a durable store, an attempt whose
// It returns the attempts made and why the job failed, or the store error // connection opens once runCtx is done writes nothing. Retries stop early
// that stopped it, in which case nothing was written. logger carries the // when runCtx is cancelled. It returns the attempts made and why the job
// job's fields. // failed, or the store error that stopped it, in which case nothing was
// written. logger carries the job's fields.
func (q *Queue) print(runCtx, jobCtx context.Context, d *delivery, job receipt.Job, logger *slog.Logger) (attempts int, err, storeErr error) { func (q *Queue) print(runCtx, jobCtx context.Context, d *delivery, job receipt.Job, logger *slog.Logger) (attempts int, err, storeErr error) {
data, err := q.renderer.Render(jobCtx, job) data, err := q.renderer.Render(jobCtx, job)
if err != nil { if err != nil {
return 0, fmt.Errorf("rendering: %w", err), nil return 0, fmt.Errorf("rendering: %w", err), nil
} }
storeCtx := context.WithoutCancel(runCtx) storeCtx := context.WithoutCancel(runCtx)
durable := q.store.Durable()
delay := q.options.RetryDelay delay := q.options.RetryDelay
var last error
for attempt := 1; ; attempt++ { for attempt := 1; ; attempt++ {
stopping := false
err := q.sender.Send(jobCtx, data, func() error { err := q.sender.Send(jobCtx, data, func() error {
if storeErr = q.stopped(); storeErr != nil { if storeErr = q.stopped(); storeErr != nil {
return storeErr return storeErr
} }
if durable && runCtx.Err() != nil {
stopping = true
return errShuttingDown
}
storeErr = q.sending(storeCtx, d, attempt) storeErr = q.sending(storeCtx, d, attempt)
return storeErr return storeErr
}) })
switch { switch {
case storeErr != nil: case storeErr != nil:
return attempt, nil, storeErr return attempt, nil, storeErr
case stopping && last == nil:
return attempt - 1, errShuttingDown, nil
case stopping:
return attempt - 1, fmt.Errorf("server shutting down after %d attempts: %w", attempt-1, last), nil
case err == nil: case err == nil:
return attempt, nil, nil return attempt, nil, nil
case attempt > q.options.Retries: case attempt > q.options.Retries:
return attempt, err, nil return attempt, err, nil
} }
last = err
logger.Warn("send failed, retrying", "attempt", attempt, "retry_in", delay, "err", err) logger.Warn("send failed, retrying", "attempt", attempt, "retry_in", delay, "err", err)
select { select {
case <-time.After(delay): case <-time.After(delay):
case <-runCtx.Done(): case <-runCtx.Done():
return attempt, fmt.Errorf("server shutting down after %d attempts: %w", attempt, err), nil return attempt, fmt.Errorf("server shutting down after %d attempts: %w", attempt, err), nil
case <-jobCtx.Done(): case <-jobCtx.Done():
if runCtx.Err() != nil {
return attempt, fmt.Errorf("server shutting down after %d attempts: %w", attempt, err), nil
}
return attempt, fmt.Errorf("giving up after %d attempts: %w", attempt, err), nil return attempt, fmt.Errorf("giving up after %d attempts: %w", attempt, err), nil
} }
delay *= 2 delay *= 2
@@ -668,6 +727,7 @@ func (q *Queue) stop(err error) error {
} }
q.closed = true q.closed = true
q.mu.Unlock() q.mu.Unlock()
q.halt()
q.signal() q.signal()
return err return err
} }
@@ -680,15 +740,19 @@ func (q *Queue) signal() {
} }
} }
// shutdown stops accepting jobs and fails those still waiting. It returns // shutdown stops accepting jobs. With a durable store, the jobs still
// the store error that stopped the queue, if one did: recording a failure // waiting stay queued for the next start, as after a crash. With the
// can meet one, and so can a Submit whose insert shutdown waited for. // memory store, which the process forgets, they fail. It returns 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 { func (q *Queue) shutdown(ctx context.Context) error {
q.submitMu.Lock() q.submitMu.Lock()
q.mu.Lock() q.mu.Lock()
q.closed = true q.closed = true
waiting := q.waiting var waiting []*delivery
q.waiting = nil if !q.store.Durable() {
waiting, q.waiting = q.waiting, nil
}
q.mu.Unlock() q.mu.Unlock()
q.submitMu.Unlock() q.submitMu.Unlock()
+5
View File
@@ -88,6 +88,11 @@ func discardLogger() *slog.Logger {
return slog.New(slog.NewTextHandler(io.Discard, nil)) return slog.New(slog.NewTextHandler(io.Discard, nil))
} }
// slogTo returns a logger that writes text lines to b.
func slogTo(b *lockedBuffer) *slog.Logger {
return slog.New(slog.NewTextHandler(b, nil))
}
func newQueue(r printqueue.Renderer, s printqueue.Sender, opts printqueue.Options) *printqueue.Queue { func newQueue(r printqueue.Renderer, s printqueue.Sender, opts printqueue.Options) *printqueue.Queue {
return newQueueOn(printqueue.NewMemoryStore(), r, s, discardLogger(), opts) return newQueueOn(printqueue.NewMemoryStore(), r, s, discardLogger(), opts)
} }
+394
View File
@@ -0,0 +1,394 @@
package printqueue_test
import (
"context"
"errors"
"fmt"
"slices"
"strings"
"sync"
"testing"
"time"
"uberbringer/internal/pkg/printqueue"
"uberbringer/internal/pkg/receipt"
)
// blockingRenderer tells started when it begins, then renders once
// release closes, or fails once its context ends.
type blockingRenderer struct {
started chan struct{}
release chan struct{}
}
func newBlockingRenderer() blockingRenderer {
return blockingRenderer{started: make(chan struct{}, 10), release: make(chan struct{})}
}
func (r blockingRenderer) Render(ctx context.Context, job receipt.Job) ([]byte, error) {
r.started <- struct{}{}
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-r.release:
return []byte(job.Elements[0].Text), nil
}
}
// slotSender stands for a printer whose one connection another client
// holds: it tells waiting, then waits for its context to end, before any
// dial.
type slotSender struct{ waiting chan struct{} }
func (s slotSender) Send(ctx context.Context, _ []byte, _ func() error) error {
s.waiting <- struct{}{}
<-ctx.Done()
return fmt.Errorf("waiting for printer: %w", ctx.Err())
}
// writingSender calls beforeWrite, tells writing, and finishes its write
// once release closes, whatever its context does.
type writingSender struct {
writing chan struct{}
release chan struct{}
mu sync.Mutex
sent []string
}
func (s *writingSender) Send(_ context.Context, data []byte, beforeWrite func() error) error {
if err := beforeWrite(); err != nil {
return err
}
s.writing <- struct{}{}
<-s.release
s.mu.Lock()
defer s.mu.Unlock()
s.sent = append(s.sent, string(data))
return nil
}
// restartAndPrint starts a queue on store as after a restart and waits for
// each of ids to print. It returns what was sent, in order.
func restartAndPrint(t *testing.T, store printqueue.Store, ids ...printqueue.JobID) []string {
t.Helper()
sender := &fakeSender{}
q := newQueueOn(store, fakeRenderer{}, sender, discardLogger(), printqueue.Options{})
if err := q.Restore(context.Background()); err != nil {
t.Fatal(err)
}
for _, id := range ids {
if st, _ := q.Status(id); st.State != printqueue.StateQueued || st.StartedAt != nil || st.Attempts != 0 {
t.Errorf("job %s after the restart: %+v, want queued", id, st)
}
}
startQueue(t, q)
for _, id := range ids {
waitForState(t, q, id, printqueue.StateDone)
}
return sender.Sent()
}
// With a durable store, a stop leaves every job that sent nothing queued:
// one rendering, one waiting for the printer, one between failed dials,
// and the jobs waiting behind it. After the restart each prints once.
func TestDurableShutdownLeavesUnsentJobsQueued(t *testing.T) {
cases := []struct {
name string
setup func(t *testing.T) (printqueue.Renderer, printqueue.Sender, printqueue.Options, chan struct{})
}{
{
name: "rendering",
setup: func(*testing.T) (printqueue.Renderer, printqueue.Sender, printqueue.Options, chan struct{}) {
r := newBlockingRenderer()
return r, &fakeSender{}, printqueue.Options{}, r.started
},
},
{
name: "waiting for the printer",
setup: func(*testing.T) (printqueue.Renderer, printqueue.Sender, printqueue.Options, chan struct{}) {
s := slotSender{waiting: make(chan struct{}, 10)}
return fakeRenderer{}, s, printqueue.Options{}, s.waiting
},
},
{
name: "between failed dials",
setup: func(*testing.T) (printqueue.Renderer, printqueue.Sender, printqueue.Options, chan struct{}) {
return fakeRenderer{}, &fakeSender{failures: 100}, printqueue.Options{Retries: 10, RetryDelay: time.Hour}, nil
},
},
}
for _, tt := range cases {
t.Run(tt.name, func(t *testing.T) {
inner := printqueue.NewDurableMemoryStore()
store := newTestStore(inner)
renderer, sender, opts, reached := tt.setup(t)
var logs lockedBuffer
q := newQueueOn(store, renderer, sender, slogTo(&logs), opts)
first, _ := q.Submit(job("first"), printqueue.Meta{})
second, _ := q.Submit(job("second"), printqueue.Meta{})
stop, _ := runQueue(t, q)
if reached != nil {
waitClosed(t, reached, "the job getting there")
} else {
waitFor(t, func() bool { return strings.Contains(logs.String(), "send failed, retrying") })
}
if err := stop(); err != nil {
t.Fatalf("Run = %v at the stop", err)
}
for _, id := range []printqueue.JobID{first.ID, second.ID} {
if st, _ := q.Status(id); st.State != printqueue.StateQueued {
t.Errorf("job %s at the stop: %+v, want queued", id, st)
}
}
for _, c := range store.Commits() {
if c.op != "add" {
t.Errorf("commit %+v at the stop, want none but the inserts", c)
}
}
if !strings.Contains(logs.String(), "job left queued") {
t.Errorf("log %q, want the job in hand left queued", logs.String())
}
if sent := restartAndPrint(t, inner, first.ID, second.ID); !slices.Equal(sent, []string{"first", "second"}) {
t.Errorf("sent %v after the restart, want each job once, in order", sent)
}
})
}
}
// With a durable store, a job whose write has begun finishes at a stop,
// and the jobs behind it stay queued.
func TestDurableShutdownFinishesAWrite(t *testing.T) {
inner := printqueue.NewDurableMemoryStore()
sender := &writingSender{writing: make(chan struct{}, 1), release: make(chan struct{})}
q := newQueueOn(inner, fakeRenderer{}, sender, discardLogger(), printqueue.Options{})
first, _ := q.Submit(job("first"), printqueue.Meta{})
second, _ := q.Submit(job("second"), printqueue.Meta{})
stop, done := runQueue(t, q)
<-sender.writing
stopped := make(chan error, 1)
go func() { stopped <- stop() }()
select {
case <-done:
t.Fatal("Run returned while a write was under way")
case <-time.After(20 * time.Millisecond):
}
close(sender.release)
if err := <-stopped; err != nil {
t.Fatalf("Run = %v at the stop", err)
}
if st, _ := q.Status(first.ID); st.State != printqueue.StateDone {
t.Errorf("job in its write %+v, want done", st)
}
if st, _ := q.Status(second.ID); st.State != printqueue.StateQueued {
t.Errorf("waiting job %+v, want queued", st)
}
if sent := restartAndPrint(t, inner, second.ID); !slices.Equal(sent, []string{"second"}) {
t.Errorf("sent %v after the restart, want only the waiting job", sent)
}
}
// With a durable store, a job waiting to retry after an attempt reached
// the printer fails at a stop, with sent_at, and is not sent again.
func TestDurableShutdownFailsAJobThatReachedThePrinter(t *testing.T) {
inner := printqueue.NewDurableMemoryStore()
store := newTestStore(inner)
q := newQueueOn(store, fakeRenderer{}, &fakeSender{writeFailures: 1}, discardLogger(),
printqueue.Options{Retries: 5, RetryDelay: time.Hour})
st, _ := q.Submit(job("x"), printqueue.Meta{})
stop, _ := runQueue(t, q)
waitFor(t, func() bool {
return slices.ContainsFunc(store.Commits(), func(c commit) bool { return c.op == "sending" })
})
if err := stop(); err != nil {
t.Fatalf("Run = %v at the stop", err)
}
got, _ := q.Status(st.ID)
if got.State != printqueue.StateFailed || got.SentAt == nil || got.Attempts != 1 || !strings.Contains(got.Error, "shutting down") {
t.Errorf("status %+v, want failed with sent_at after 1 attempt", got)
}
if c := store.Commits(); c[len(c)-1] != (commit{op: "finish", seq: 1, state: printqueue.StoredFailed, synced: true}) {
t.Errorf("commits %+v, want the failure synced last", c)
}
after := newQueueOn(inner, fakeRenderer{}, &fakeSender{}, discardLogger(), printqueue.Options{})
if err := after.Restore(context.Background()); err != nil {
t.Fatal(err)
}
if again, _ := after.Status(st.ID); again.State != printqueue.StateFailed || after.Pending() != 0 {
t.Errorf("status after the restart %+v, pending %d; want it failed", again, after.Pending())
}
}
// With the memory store, the job in hand finishes at a stop, its
// rendering included, and the jobs waiting fail, recorded with a sync.
func TestMemoryShutdownFinishesARendering(t *testing.T) {
store := newTestStore(printqueue.NewMemoryStore())
renderer := newBlockingRenderer()
sender := &fakeSender{}
q := newQueueOn(store, renderer, sender, discardLogger(), printqueue.Options{})
first, _ := q.Submit(job("first"), printqueue.Meta{})
second, _ := q.Submit(job("second"), printqueue.Meta{})
stop, _ := runQueue(t, q)
<-renderer.started
stopped := make(chan error, 1)
go func() { stopped <- stop() }()
time.Sleep(20 * time.Millisecond)
close(renderer.release)
if err := <-stopped; err != nil {
t.Fatalf("Run = %v at the stop", err)
}
if st, _ := q.Status(first.ID); st.State != printqueue.StateDone {
t.Errorf("job in hand %+v, want done", st)
}
if st, _ := q.Status(second.ID); st.State != printqueue.StateFailed || !strings.Contains(st.Error, "shutting down") {
t.Errorf("waiting job %+v, want failed", st)
}
if c := store.Commits(); c[len(c)-1] != (commit{op: "finish", seq: 2, state: printqueue.StoredFailed, synced: true}) {
t.Errorf("commits %+v, want the waiting job's failure synced last", c)
}
}
// lateSender opens its connection, tells connected, and waits for proceed
// before it calls beforeWrite, as a connection that opens just as the
// daemon stops. With writeFirst, its first send writes and fails before
// that, so an earlier attempt has reached the printer.
type lateSender struct {
writeFirst bool
connected chan struct{}
proceed chan struct{}
mu sync.Mutex
calls int
}
func (s *lateSender) Send(_ context.Context, _ []byte, beforeWrite func() error) error {
s.mu.Lock()
s.calls++
first := s.calls == 1
s.mu.Unlock()
if s.writeFirst && first {
if err := beforeWrite(); err != nil {
return err
}
return errors.New("connection reset")
}
s.connected <- struct{}{}
<-s.proceed
return beforeWrite()
}
// With a durable store, an attempt whose connection opens once the stop
// has begun writes nothing: the job stays queued if nothing was sent
// before, and fails with sent_at if an earlier attempt reached the
// printer.
func TestDurableShutdownStopsALateConnection(t *testing.T) {
for _, tt := range []struct {
name string
writeFirst bool
}{
{"nothing sent before", false},
{"an earlier attempt reached the printer", true},
} {
t.Run(tt.name, func(t *testing.T) {
inner := printqueue.NewDurableMemoryStore()
store := newTestStore(inner)
sender := &lateSender{writeFirst: tt.writeFirst, connected: make(chan struct{}, 1), proceed: make(chan struct{})}
q := newQueueOn(store, fakeRenderer{}, sender, discardLogger(),
printqueue.Options{Retries: 3, RetryDelay: time.Millisecond})
st, _ := q.Submit(job("x"), printqueue.Meta{})
ctx, cancel := context.WithCancel(context.Background())
ran := make(chan error, 1)
go func() { ran <- q.Run(ctx) }()
waitClosed(t, sender.connected, "the late connection")
cancel()
close(sender.proceed)
if err := <-ran; err != nil {
t.Fatalf("Run = %v at the stop", err)
}
got, _ := q.Status(st.ID)
var marks int
for _, c := range store.Commits() {
if c.op == "sending" {
marks++
}
}
if !tt.writeFirst {
if got.State != printqueue.StateQueued || marks != 0 {
t.Errorf("status %+v after %d sending marks, want queued and none", got, marks)
}
if sent := restartAndPrint(t, inner, st.ID); !slices.Equal(sent, []string{"x"}) {
t.Errorf("sent %v after the restart, want the job once", sent)
}
return
}
if got.State != printqueue.StateFailed || got.SentAt == nil || got.Attempts != 1 || marks != 1 ||
!strings.Contains(got.Error, "shutting down after 1 attempts") {
t.Errorf("status %+v after %d sending marks, want failed with sent_at after the first", got, marks)
}
})
}
}
// Once a store error in Submit has stopped the queue, the job in hand
// writes nothing more to the store: its rendering, or its wait between
// failed dials, ends at once, it stays queued as the store has it, and it
// prints once after the restart.
func TestStoreFailureStopsTheJobInHand(t *testing.T) {
for _, tt := range []struct {
name string
setup func() (printqueue.Renderer, printqueue.Sender, printqueue.Options)
reached func(t *testing.T, r printqueue.Renderer)
}{
{
name: "rendering",
setup: func() (printqueue.Renderer, printqueue.Sender, printqueue.Options) {
return newBlockingRenderer(), &fakeSender{}, printqueue.Options{}
},
reached: func(t *testing.T, r printqueue.Renderer) {
waitClosed(t, r.(blockingRenderer).started, "the rendering")
},
},
{
name: "between failed dials",
setup: func() (printqueue.Renderer, printqueue.Sender, printqueue.Options) {
return fakeRenderer{}, &fakeSender{failures: 100}, printqueue.Options{Retries: 10, RetryDelay: time.Hour}
},
},
} {
t.Run(tt.name, func(t *testing.T) {
inner := printqueue.NewDurableMemoryStore()
store := newTestStore(inner)
renderer, sender, opts := tt.setup()
var logs lockedBuffer
q := newQueueOn(store, renderer, sender, slogTo(&logs), opts)
first, _ := q.Submit(job("first"), printqueue.Meta{})
stop, done := runQueue(t, q)
if tt.reached != nil {
tt.reached(t, renderer)
} else {
waitFor(t, func() bool { return strings.Contains(logs.String(), "send failed, retrying") })
}
store.failNext("add", errDisk)
if _, err := q.Submit(job("second"), printqueue.Meta{}); !errors.Is(err, errDisk) {
t.Fatalf("Submit = %v, want the store's error", err)
}
waitClosed(t, done, "Run's return")
if err := stop(); !errors.Is(err, errDisk) {
t.Errorf("Run = %v, want the store's error", err)
}
for _, c := range store.Commits() {
if c.op != "add" {
t.Errorf("commit %+v after the store failed", c)
}
}
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)
}
if sent := restartAndPrint(t, inner, first.ID); !slices.Equal(sent, []string{"first"}) {
t.Errorf("sent %v after the restart, want the job once", sent)
}
})
}
}