Keep print jobs in the job store
The queue now keeps its jobs in a Store, the memory store for now, so that a store on disk can take its place. Submit stores the job as JSON before it answers, and the worker reads it back and decodes it when it takes it, so what prints is what was stored. Each job has one delivery, for the printer "default", and its status derives from its deliveries: queued while all wait, printing while any is unfinished, then failed over done once all have finished. Every change is committed to the store first and made in memory after, so a status never shows what the store lacks. Once the printer's connection is open and before the first byte, the worker records the attempt as sending; a failed dial records nothing. A failure is committed with a sync, since one rolled back to queued would print after a restart. A job's content goes in the commit that finishes it, as it went from memory before, and statuses past queue.history leave the store in the commit that finishes the job pushing them out. A job whose stored content no longer decodes fails without its content in the logs. A submit lock covers the capacity check, the insert and the append to the waiting list; the status lock is never held across a store call, so Status and Pending answer during a commit. A store error is returned, by Submit with nothing queued, or by Run, which ends; shutdown is 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:
1 parent
dbfabd1613
commit
14c5e86ab6
5 files changed
+914
-104
No files matched your search
@@ -0,0 +1,394 @@
|
||||
package printqueue_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"reflect"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"uberbringer/internal/pkg/printqueue"
|
||||
"uberbringer/internal/pkg/receipt"
|
||||
)
|
||||
|
||||
// commit is one write a testStore committed.
|
||||
type commit struct {
|
||||
op string // add, sending or finish
|
||||
seq uint64 // the job's for add, the delivery's otherwise
|
||||
state printqueue.StoredState
|
||||
synced bool
|
||||
}
|
||||
|
||||
// testStore wraps a Store. It records each commit and whether it was
|
||||
// synced, fails the next call of a method on demand, holds the calls of a
|
||||
// method while blocked, and can rewrite the content Job returns.
|
||||
type testStore struct {
|
||||
printqueue.Store
|
||||
|
||||
mu sync.Mutex
|
||||
commits []commit
|
||||
fail map[string]error
|
||||
block map[string]*gate
|
||||
content func([]byte) []byte
|
||||
}
|
||||
|
||||
// gate holds the calls of a blocked method: entered gets a value as each
|
||||
// call arrives, and open closes to let them through.
|
||||
type gate struct {
|
||||
entered chan struct{}
|
||||
open chan struct{}
|
||||
}
|
||||
|
||||
func newTestStore(s printqueue.Store) *testStore {
|
||||
return &testStore{Store: s, fail: make(map[string]error), block: make(map[string]*gate)}
|
||||
}
|
||||
|
||||
// failNext makes the next call of op (add, sending, finish, job, idle or
|
||||
// load) fail with err.
|
||||
func (s *testStore) failNext(op string, err error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.fail[op] = err
|
||||
}
|
||||
|
||||
// blockOn holds every call of op until release is called. entered gets a
|
||||
// value as each call arrives.
|
||||
func (s *testStore) blockOn(op string) (entered <-chan struct{}, release func()) {
|
||||
g := &gate{entered: make(chan struct{}, 10), open: make(chan struct{})}
|
||||
s.mu.Lock()
|
||||
s.block[op] = g
|
||||
s.mu.Unlock()
|
||||
return g.entered, sync.OnceFunc(func() {
|
||||
s.mu.Lock()
|
||||
delete(s.block, op)
|
||||
s.mu.Unlock()
|
||||
close(g.open)
|
||||
})
|
||||
}
|
||||
|
||||
// before waits while op is blocked, then returns the error its call is to
|
||||
// fail with, if any.
|
||||
func (s *testStore) before(op string) error {
|
||||
s.mu.Lock()
|
||||
err := s.fail[op]
|
||||
delete(s.fail, op)
|
||||
g := s.block[op]
|
||||
s.mu.Unlock()
|
||||
if g != nil {
|
||||
g.entered <- struct{}{}
|
||||
<-g.open
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *testStore) record(c commit) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.commits = append(s.commits, c)
|
||||
}
|
||||
|
||||
// Commits returns the commits so far, in order.
|
||||
func (s *testStore) Commits() []commit {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return slices.Clone(s.commits)
|
||||
}
|
||||
|
||||
func (s *testStore) Load(ctx context.Context) (printqueue.Loaded, error) {
|
||||
if err := s.before("load"); err != nil {
|
||||
return printqueue.Loaded{}, err
|
||||
}
|
||||
return s.Store.Load(ctx)
|
||||
}
|
||||
|
||||
func (s *testStore) Add(ctx context.Context, r printqueue.Record, job []byte, sync bool) error {
|
||||
if err := s.before("add"); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.Store.Add(ctx, r, job, sync); err != nil {
|
||||
return err
|
||||
}
|
||||
s.record(commit{op: "add", seq: r.Seq, state: printqueue.StoredQueued, synced: sync})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *testStore) Sending(ctx context.Context, d printqueue.Delivery) error {
|
||||
if err := s.before("sending"); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.Store.Sending(ctx, d); err != nil {
|
||||
return err
|
||||
}
|
||||
s.record(commit{op: "sending", seq: d.Seq, state: printqueue.StoredSending, synced: true})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *testStore) Finish(ctx context.Context, d printqueue.Delivery, p printqueue.Prune, sync bool) error {
|
||||
if err := s.before("finish"); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.Store.Finish(ctx, d, p, sync); err != nil {
|
||||
return err
|
||||
}
|
||||
s.record(commit{op: "finish", seq: d.Seq, state: d.State, synced: sync})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *testStore) Job(ctx context.Context, seq uint64) ([]byte, error) {
|
||||
if err := s.before("job"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
data, err := s.Store.Job(ctx, seq)
|
||||
s.mu.Lock()
|
||||
rewrite := s.content
|
||||
s.mu.Unlock()
|
||||
if err == nil && rewrite != nil {
|
||||
data = rewrite(data)
|
||||
}
|
||||
return data, err
|
||||
}
|
||||
|
||||
func (s *testStore) Idle(ctx context.Context) error {
|
||||
if err := s.before("idle"); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.Store.Idle(ctx)
|
||||
}
|
||||
|
||||
// runQueue runs q in the background. stop cancels Run's context and
|
||||
// returns what Run returned; done is closed once Run has returned.
|
||||
func runQueue(t *testing.T, q *printqueue.Queue) (stop func() error, done <-chan struct{}) {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
finished := make(chan struct{})
|
||||
var err error
|
||||
go func() {
|
||||
defer close(finished)
|
||||
err = q.Run(ctx)
|
||||
}()
|
||||
stop = func() error {
|
||||
cancel()
|
||||
<-finished
|
||||
return err
|
||||
}
|
||||
t.Cleanup(func() { _ = stop() })
|
||||
return stop, finished
|
||||
}
|
||||
|
||||
// waitClosed waits for done to close or to give a value.
|
||||
func waitClosed(t *testing.T, done <-chan struct{}, what string) {
|
||||
t.Helper()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatalf("%s did not happen", what)
|
||||
}
|
||||
}
|
||||
|
||||
var errDisk = errors.New("disk I/O error")
|
||||
|
||||
// The sending mark and a failure are synced; the insert of a job from the
|
||||
// routes and its done are not. A failed dial writes no sending mark.
|
||||
func TestCommitsAndSyncs(t *testing.T) {
|
||||
store := newTestStore(printqueue.NewMemoryStore())
|
||||
sender := &fakeSender{failures: 1}
|
||||
q := newQueueOn(store, fakeRenderer{}, sender, discardLogger(), printqueue.Options{Retries: 1})
|
||||
startQueue(t, q)
|
||||
|
||||
first, _ := q.Submit(job("first"), printqueue.Meta{})
|
||||
waitForState(t, q, first.ID, printqueue.StateDone)
|
||||
sender.mu.Lock()
|
||||
sender.failures = 2
|
||||
sender.mu.Unlock()
|
||||
second, _ := q.Submit(job("second"), printqueue.Meta{})
|
||||
if st := waitForState(t, q, second.ID, printqueue.StateFailed); st.Attempts != 2 {
|
||||
t.Errorf("second job %+v, want 2 attempts", st)
|
||||
}
|
||||
|
||||
want := []commit{
|
||||
{op: "add", seq: 1, state: printqueue.StoredQueued},
|
||||
{op: "sending", seq: 1, state: printqueue.StoredSending, synced: true},
|
||||
{op: "finish", seq: 1, state: printqueue.StoredDone},
|
||||
{op: "add", seq: 2, state: printqueue.StoredQueued},
|
||||
{op: "finish", seq: 2, state: printqueue.StoredFailed, synced: true},
|
||||
}
|
||||
if got := store.Commits(); !slices.Equal(got, want) {
|
||||
t.Errorf("commits\n%+v\nwant\n%+v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// The job the worker renders is the job submitted, read back from the
|
||||
// store.
|
||||
func TestJobRoundTripsThroughTheStore(t *testing.T) {
|
||||
var submitted receipt.Job
|
||||
body := `{"elements": [{"type": "text", "text": "Grüße", "align": "center", "bold": true, "size": 2},
|
||||
{"type": "kv", "pairs": [{"key": "Total", "value": "£12.50", "bold": true}]},
|
||||
{"type": "qr", "data": "https://example.com", "size": 6},
|
||||
{"type": "box", "title": "T", "children": [{"type": "text", "text": "in a box"}]}], "copies": 2}`
|
||||
if err := json.Unmarshal([]byte(body), &submitted); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rendered := make(chan receipt.Job, 1)
|
||||
renderer := rendererFunc(func(job receipt.Job) ([]byte, error) {
|
||||
rendered <- job
|
||||
return []byte("x"), nil
|
||||
})
|
||||
q := newQueue(renderer, &fakeSender{}, printqueue.Options{})
|
||||
startQueue(t, q)
|
||||
if _, err := q.Submit(submitted, printqueue.Meta{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
select {
|
||||
case got := <-rendered:
|
||||
if !reflect.DeepEqual(got, submitted) {
|
||||
t.Errorf("rendered %+v\nwant %+v", got, submitted)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("the job was not rendered")
|
||||
}
|
||||
}
|
||||
|
||||
// rendererFunc is a Renderer.
|
||||
type rendererFunc func(receipt.Job) ([]byte, error)
|
||||
|
||||
func (f rendererFunc) Render(_ context.Context, job receipt.Job) ([]byte, error) {
|
||||
return f(job)
|
||||
}
|
||||
|
||||
// While a commit is held, Status and Pending still answer.
|
||||
func TestStatusAnswersDuringACommit(t *testing.T) {
|
||||
store := newTestStore(printqueue.NewMemoryStore())
|
||||
sender := &fakeSender{}
|
||||
q := newQueueOn(store, fakeRenderer{}, sender, discardLogger(), printqueue.Options{})
|
||||
startQueue(t, q)
|
||||
|
||||
inFinish, releaseFinish := store.blockOn("finish")
|
||||
defer releaseFinish()
|
||||
first, _ := q.Submit(job("first"), printqueue.Meta{})
|
||||
waitClosed(t, inFinish, "the finish commit")
|
||||
|
||||
inAdd, releaseAdd := store.blockOn("add")
|
||||
defer releaseAdd()
|
||||
submitted := make(chan struct{})
|
||||
go func() {
|
||||
defer close(submitted)
|
||||
_, _ = q.Submit(job("second"), printqueue.Meta{})
|
||||
}()
|
||||
waitClosed(t, inAdd, "the second insert")
|
||||
|
||||
answered := make(chan struct{})
|
||||
go func() {
|
||||
defer close(answered)
|
||||
if st, err := q.Status(first.ID); err != nil || st.State != printqueue.StatePrinting {
|
||||
t.Errorf("status %+v, %v during the held finish", st, err)
|
||||
}
|
||||
_ = q.Pending()
|
||||
}()
|
||||
waitClosed(t, answered, "Status and Pending answering")
|
||||
releaseAdd()
|
||||
waitClosed(t, submitted, "the second Submit")
|
||||
releaseFinish()
|
||||
waitForState(t, q, first.ID, printqueue.StateDone)
|
||||
waitFor(t, func() bool { return q.Pending() == 0 && len(sender.Sent()) == 2 })
|
||||
}
|
||||
|
||||
// A stored job that no longer decodes fails, logged by ID and never with
|
||||
// its content.
|
||||
func TestUndecodableJobFails(t *testing.T) {
|
||||
var logs lockedBuffer
|
||||
store := newTestStore(printqueue.NewMemoryStore())
|
||||
store.content = func([]byte) []byte {
|
||||
return []byte(`{"elements": [{"type": "text", "text": "secret words"}], "renamed_field": 1}`)
|
||||
}
|
||||
sender := &fakeSender{}
|
||||
q := newQueueOn(store, fakeRenderer{}, sender, slog.New(slog.NewTextHandler(&logs, nil)), printqueue.Options{})
|
||||
startQueue(t, q)
|
||||
st, _ := q.Submit(job("secret words"), printqueue.Meta{Source: "print", Ref: "req_1"})
|
||||
failed := waitForState(t, q, st.ID, printqueue.StateFailed)
|
||||
if !strings.Contains(failed.Error, "no longer decodes") || len(sender.Sent()) != 0 {
|
||||
t.Errorf("status %+v, sent %v", failed, sender.Sent())
|
||||
}
|
||||
out := logs.String()
|
||||
if !strings.Contains(out, "job_id="+st.ID.String()) || !strings.Contains(out, "no longer decodes") {
|
||||
t.Errorf("log %q, want the failure with the job's ID", out)
|
||||
}
|
||||
if strings.Contains(out, "secret") || strings.Contains(out, "renamed_field") {
|
||||
t.Errorf("log %q quotes the stored job", out)
|
||||
}
|
||||
}
|
||||
|
||||
// Statuses beyond History go from the store with their deliveries in the
|
||||
// commit that finishes the job pushing them out, and a job's content goes
|
||||
// in the commit that finishes it.
|
||||
func TestHistoryPrunesTheStore(t *testing.T) {
|
||||
inner := printqueue.NewMemoryStore()
|
||||
q := newQueueOn(inner, fakeRenderer{}, &fakeSender{}, discardLogger(), printqueue.Options{History: 2})
|
||||
startQueue(t, q)
|
||||
var ids []printqueue.JobID
|
||||
for range 4 {
|
||||
st, _ := q.Submit(job("x"), printqueue.Meta{})
|
||||
ids = append(ids, st.ID)
|
||||
waitForState(t, q, st.ID, printqueue.StateDone)
|
||||
}
|
||||
loaded, err := inner.Load(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var kept []printqueue.JobID
|
||||
for _, r := range loaded.Records {
|
||||
kept = append(kept, r.ID)
|
||||
}
|
||||
if !slices.Equal(kept, ids[2:]) {
|
||||
t.Errorf("store keeps %v, want the last two, %v", kept, ids[2:])
|
||||
}
|
||||
for seq := uint64(1); seq <= 4; seq++ {
|
||||
if _, err := inner.Job(context.Background(), seq); !errors.Is(err, printqueue.ErrContentGone) {
|
||||
t.Errorf("content of job %d: %v, want ErrContentGone", seq, err)
|
||||
}
|
||||
}
|
||||
if r := loaded.Records[1]; r.Size != 0 {
|
||||
t.Errorf("job 4 keeps %d bytes of content", r.Size)
|
||||
}
|
||||
}
|
||||
|
||||
// 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()
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for !cond() {
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal("condition not met")
|
||||
}
|
||||
time.Sleep(2 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user