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:
1 parent
45b57ab196
commit
4ef6d21258
3 files changed
+480
-17
No files matched your search
@@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user