Files
uberbringer/internal/pkg/jobstore/store_test.go
T
57_WolveandClaude Opus 5.5 5ae323b570 Keep unique jobs' references in the SQLite job store
The queue answers a repeated ntfy message or digest with its earlier
job, by the source and reference of unique jobs. For that check to
outlive a restart, the store keeps those references too.

Add, for a unique job, stores its source and reference with its job
ID in refs, in the insert's commit, and drops those of the source
beyond the newest 512, in the order they were kept, as the queue
forgets them. Job IDs do not give that order: one minted after the
clock was set back, as on a host whose clock does not run while it is
off, sorts before those kept, and pruning by ID would drop the new
reference and keep the oldest. A reference the store still holds for
an earlier job is dropped and kept again for the new one, as the
newest of its source; a plain insert would fail and stop the daemon.
Pruning statuses leaves refs alone. Load returns the references by
source, the first kept first, and reads a job as unique while its
reference is kept.

A test runs the same calls against this store and the memory store
and finds the same records, references, content and refusals. Another
keeps 512 references and then one whose job ID sorts before them all,
and finds that one kept and the first gone.

Part of stage 1d of docs/plans/job-store.md (decision 10).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 16:37:45 -06:00

649 lines
23 KiB
Go

package jobstore
import (
"bytes"
"context"
"database/sql"
"errors"
"fmt"
"os"
"path/filepath"
"reflect"
"slices"
"strings"
"testing"
"time"
"go.jetify.com/typeid"
"uberbringer/internal/pkg/printqueue"
)
func newJobID(t *testing.T) printqueue.JobID {
t.Helper()
id, err := typeid.New[printqueue.JobID]()
if err != nil {
t.Fatal(err)
}
return id
}
// at returns a time on the test day with nanoseconds, which a store must
// keep.
func at(second, nanos int) time.Time {
return time.Date(2026, 12, 1, 12, 0, second, nanos, time.UTC)
}
// record returns job seq with one queued delivery per printer, numbered
// from seq*10.
func record(t *testing.T, seq uint64, printers ...string) printqueue.Record {
t.Helper()
r := printqueue.Record{
Seq: seq, ID: newJobID(t), Source: "print", Ref: fmt.Sprintf("req_%d", seq),
CreatedAt: at(0, 100+int(seq)),
}
for i, p := range printers {
r.Deliveries = append(r.Deliveries,
printqueue.Delivery{Seq: seq*10 + uint64(i), Printer: p, State: printqueue.StoredQueued})
}
return r
}
// add stores r with content job, without a sync.
func add(t *testing.T, s *Store, r printqueue.Record, job string) {
t.Helper()
if err := s.Add(context.Background(), r, []byte(job), false); err != nil {
t.Fatal(err)
}
}
func load(t *testing.T, s printqueue.Store) printqueue.Loaded {
t.Helper()
loaded, err := s.Load(context.Background())
if err != nil {
t.Fatal(err)
}
return loaded
}
// Every field of a job and of its deliveries survives a close and a
// reopen, also for a job with three deliveries.
func TestRecordsSurviveAReopen(t *testing.T) {
ctx := context.Background()
s := openStore(t, t.TempDir())
one := record(t, 1, "default")
one.Source, one.Ref, one.Sequence, one.Unique = "ntfy:home", "msg1", "alerts/seq1", true
three := record(t, 2, "default", "kitchen", "bar")
add(t, s, one, `{"elements":[{"type":"text","text":"one"}]}`)
add(t, s, three, `{"elements":[]}`)
failed := three.Deliveries[0]
failed.State, failed.Attempts, failed.Error = printqueue.StoredFailed, 3, "dial tcp: refused"
failed.StartedAt, failed.SentAt, failed.FinishedAt = at(1, 1), at(1, 2), at(1, 3)
if err := s.Finish(ctx, failed, printqueue.Prune{}, true); err != nil {
t.Fatal(err)
}
sending := three.Deliveries[2]
sending.Printer, sending.Attempts, sending.StartedAt, sending.SentAt = "spare", 2, at(2, 4), at(2, 5)
if err := s.Sending(ctx, sending); err != nil {
t.Fatal(err)
}
loaded := load(t, reopen(t, s))
if len(loaded.Records) != 2 {
t.Fatalf("loaded %d records, want 2", len(loaded.Records))
}
wantOne := one
wantOne.Size = int64(len(`{"elements":[{"type":"text","text":"one"}]}`))
checkRecord(t, loaded.Records[0], wantOne)
got := loaded.Records[1]
if got.Deliveries[2].FinishedAt.IsZero() {
t.Error("the interrupted send has no finish time")
}
got.Deliveries[2].FinishedAt = time.Time{}
wantThree := three
wantThree.Size = int64(len(`{"elements":[]}`))
sending.State, sending.Error = printqueue.StoredUncertain, printqueue.InterruptedSend
wantThree.Deliveries = []printqueue.Delivery{failed, three.Deliveries[1], sending}
checkRecord(t, got, wantThree)
if len(loaded.Refs) != 1 || loaded.Refs[0] != (printqueue.UniqueRef{Source: "ntfy:home", Ref: "msg1", ID: one.ID}) {
t.Errorf("refs %+v, want job 1's", loaded.Refs)
}
}
// checkRecord compares every field, times by ==, so a lost nanosecond or
// location shows.
func checkRecord(t *testing.T, got, want printqueue.Record) {
t.Helper()
if got.Seq != want.Seq || got.ID != want.ID || got.Source != want.Source || got.Ref != want.Ref ||
got.Sequence != want.Sequence || got.Unique != want.Unique || got.CreatedAt != want.CreatedAt ||
got.Size != want.Size || len(got.Deliveries) != len(want.Deliveries) {
t.Fatalf("job %d:\n got %+v\nwant %+v", want.Seq, got, want)
}
for i := range want.Deliveries {
if got.Deliveries[i] != want.Deliveries[i] {
t.Errorf("job %d delivery %d:\n got %+v\nwant %+v", want.Seq, i, got.Deliveries[i], want.Deliveries[i])
}
}
}
// Job returns a job's content as it was added, and ErrContentGone for one
// it does not keep.
func TestJobReturnsTheContent(t *testing.T) {
ctx := context.Background()
s := openStore(t, t.TempDir())
add(t, s, record(t, 1, "default"), `{"elements":[{"type":"text","text":"Grüße"}]}`)
content, err := s.Job(ctx, 1)
if err != nil || string(content) != `{"elements":[{"type":"text","text":"Grüße"}]}` {
t.Errorf("Job(1) = %q, %v", content, err)
}
if _, err := s.Job(ctx, 2); !errors.Is(err, printqueue.ErrContentGone) {
t.Errorf("Job(2) = %v, want ErrContentGone", err)
}
}
// Idle checkpoints only once enough commits have gathered, not each time
// the queue empties. The log holds every write until a checkpoint copies it
// into the database, so the database file grows only at a checkpoint.
func TestIdleCheckpointsOnceCommitsGather(t *testing.T) {
ctx := context.Background()
dir := t.TempDir()
s := openStore(t, dir)
size := func() int64 {
t.Helper()
info, err := os.Stat(filepath.Join(dir, FileName))
if err != nil {
t.Fatal(err)
}
return info.Size()
}
before := size()
seq := uint64(1)
for ; seq <= idleCheckpointCommits/2; seq++ {
add(t, s, record(t, seq, "default"), `{"elements":[]}`)
if err := s.Idle(ctx); err != nil {
t.Fatal(err)
}
if size() != before {
t.Fatalf("Idle checkpointed after %d jobs, want it to wait for %d commits", seq, idleCheckpointCommits)
}
}
for ; size() == before && seq <= 2*idleCheckpointCommits; seq++ {
add(t, s, record(t, seq, "default"), `{"elements":[]}`)
if err := s.Idle(ctx); err != nil {
t.Fatal(err)
}
}
if size() == before {
t.Errorf("Idle never checkpointed in %d commits", 2*idleCheckpointCommits)
}
}
// Open's schema step commits at synchronous FULL, and its one write, as a
// reopen's, at NORMAL.
func TestOpenSyncsTheSchemaStep(t *testing.T) {
ctx := context.Background()
path := filepath.Join(t.TempDir(), FileName)
for _, want := range [][]commit{{{full, 0}, {normal, 0}}, {{normal, 0}}} {
s, err := connect(ctx, path)
if err != nil {
t.Fatal(err)
}
commits := recordCommits(t, s)
if err := s.prepare(ctx); err != nil {
t.Fatal(err)
}
if got := commits(); !slices.Equal(got, want) {
t.Errorf("Open committed %+v, want %+v", got, want)
}
if err := s.Close(); err != nil {
t.Fatal(err)
}
}
}
// commit is what the test hook saw in one transaction.
type commit struct {
synchronous int // 2 is FULL, 1 NORMAL
changes int64 // rows the transaction changed
}
const (
normal = 1
full = 2
)
// recordCommits makes s report each transaction it commits from now on;
// the returned func hands over those seen since its last call.
func recordCommits(t *testing.T, s *Store) func() []commit {
t.Helper()
ctx := context.Background()
var commits []commit
var last int64
if err := s.conn.QueryRowContext(ctx, "SELECT total_changes()").Scan(&last); err != nil {
t.Fatal(err)
}
s.commitHook = func(ctx context.Context, tx *sql.Tx) error {
var c commit
var total int64
if err := tx.QueryRowContext(ctx, "PRAGMA synchronous").Scan(&c.synchronous); err != nil {
return err
}
if err := tx.QueryRowContext(ctx, "SELECT total_changes()").Scan(&total); err != nil {
return err
}
c.changes, last = total-last, total
commits = append(commits, c)
return nil
}
return func() []commit {
seen := commits
commits = nil
return seen
}
}
// Sending, failures and unique inserts commit at synchronous FULL, every
// other commit at NORMAL; Sending, and a Finish that drops nothing, change
// only the delivery's row.
func TestSyncedCommits(t *testing.T) {
ctx := context.Background()
s := openStore(t, t.TempDir())
commits := recordCommits(t, s)
check := func(step string, want ...commit) {
t.Helper()
if got := commits(); !slices.Equal(got, want) {
t.Errorf("%s committed %+v, want %+v", step, got, want)
}
}
r := record(t, 1, "default")
add(t, s, r, `{}`)
check("an insert", commit{normal, 3})
u := record(t, 2, "default")
u.Source, u.Unique = "ntfy:home", true
if err := s.Add(ctx, u, []byte(`{}`), true); err != nil {
t.Fatal(err)
}
check("a unique insert", commit{full, 4})
d := r.Deliveries[0]
d.Attempts, d.StartedAt, d.SentAt = 1, at(1, 0), at(1, 1)
if err := s.Sending(ctx, d); err != nil {
t.Fatal(err)
}
check("Sending", commit{full, 1})
d.State, d.FinishedAt = printqueue.StoredDone, at(2, 0)
if err := s.Finish(ctx, d, printqueue.Prune{}, false); err != nil {
t.Fatal(err)
}
check("done", commit{normal, 1})
f := u.Deliveries[0]
f.State, f.Error, f.FinishedAt = printqueue.StoredFailed, "rendering: bad image", at(3, 0)
if err := s.Finish(ctx, f, printqueue.Prune{}, true); err != nil {
t.Fatal(err)
}
check("failed", commit{full, 1})
load(t, s)
check("Load", commit{normal, 0})
// A synced commit that fails leaves the connection at NORMAL too.
if err := s.Sending(ctx, printqueue.Delivery{Seq: 99, State: printqueue.StoredSending}); err == nil {
t.Error("an unknown delivery was marked sending")
}
var level int
if err := s.conn.QueryRowContext(ctx, "PRAGMA synchronous").Scan(&level); err != nil || level != normal {
t.Errorf("synchronous is %d (%v) after a failed synced commit, want NORMAL", level, err)
}
}
// Finish records the final state and drops exactly the jobs, deliveries
// and contents it is given, in the same commit.
func TestFinishPrunesInOneCommit(t *testing.T) {
ctx := context.Background()
s := openStore(t, t.TempDir())
for seq := uint64(1); seq <= 3; seq++ {
add(t, s, record(t, seq, "default", "kitchen"), `{"n":1}`)
}
commits := recordCommits(t, s)
var inCommit [3]int
hook := s.commitHook
s.commitHook = func(ctx context.Context, tx *sql.Tx) error {
for i, table := range []string{"jobs", "deliveries", "content"} {
if err := tx.QueryRowContext(ctx, "SELECT count(*) FROM "+table).Scan(&inCommit[i]); err != nil {
return err
}
}
return hook(ctx, tx)
}
done := printqueue.Delivery{Seq: 30, Printer: "default", State: printqueue.StoredDone, Attempts: 1, FinishedAt: at(2, 0)}
p := printqueue.Prune{Jobs: []uint64{1}, Deliveries: []uint64{10, 11, 21}, Content: []uint64{1, 2}}
if err := s.Finish(ctx, done, p, false); err != nil {
t.Fatal(err)
}
if got := commits(); !slices.Equal(got, []commit{{normal, 7}}) {
t.Errorf("Finish committed %+v, want one commit of 7 rows", got)
}
if inCommit != [3]int{2, 3, 1} {
t.Errorf("inside the commit: %v jobs, deliveries and contents, want them dropped already", inCommit)
}
for name, err := range map[string]error{
"a finished delivery": s.Finish(ctx, done, printqueue.Prune{}, false),
"a state that is not final": s.Finish(ctx, printqueue.Delivery{Seq: 31, State: printqueue.StoredSending}, printqueue.Prune{}, false),
"a delivery of a dropped job": s.Finish(ctx, printqueue.Delivery{Seq: 10, State: printqueue.StoredDone}, printqueue.Prune{}, false),
"sending a finished delivery": s.Sending(ctx, done),
} {
if err == nil {
t.Errorf("%s was accepted", name)
}
}
loaded := load(t, s)
if len(loaded.Records) != 2 || loaded.Records[0].Seq != 2 {
t.Fatalf("records %+v, want jobs 2 and 3", loaded.Records)
}
if r := loaded.Records[0]; r.Size != 0 || len(r.Deliveries) != 1 || r.Deliveries[0].Seq != 20 {
t.Errorf("job 2 %+v, want no content and only delivery 20", r)
}
if r := loaded.Records[1]; r.Size == 0 || r.Deliveries[0] != done {
t.Errorf("job 3 %+v, want its content and delivery 30 done", r)
}
for _, seq := range []uint64{1, 2} {
if _, err := s.Job(ctx, seq); !errors.Is(err, printqueue.ErrContentGone) {
t.Errorf("Job(%d) = %v, want ErrContentGone", seq, err)
}
}
}
// Load turns every delivery in sending into uncertain in one commit,
// leaves the other deliveries of its job alone, and turns none the second
// time.
func TestLoadEndsSendsUncertainOnce(t *testing.T) {
ctx := context.Background()
s := openStore(t, t.TempDir())
r := record(t, 1, "default", "kitchen")
add(t, s, r, `{"elements":[]}`)
sending := r.Deliveries[1]
sending.Attempts, sending.StartedAt, sending.SentAt = 2, at(1, 5), at(2, 6)
if err := s.Sending(ctx, sending); err != nil {
t.Fatal(err)
}
commits := recordCommits(t, s)
loaded := load(t, s)
if got := commits(); !slices.Equal(got, []commit{{normal, 1}}) {
t.Errorf("Load committed %+v, want one commit that changes one row", got)
}
if !slices.Equal(loaded.Uncertain, []uint64{11}) {
t.Errorf("uncertain %v, want delivery 11", loaded.Uncertain)
}
if size := loaded.Records[0].Size; size != int64(len(`{"elements":[]}`)) {
t.Errorf("size %d, want the content's length", size)
}
ds := loaded.Records[0].Deliveries
if ds[0] != r.Deliveries[0] {
t.Errorf("delivery 10 %+v, want it still queued", ds[0])
}
d := ds[1]
if d.State != printqueue.StoredUncertain || d.Error != printqueue.InterruptedSend || d.FinishedAt.IsZero() ||
d.Attempts != 2 || d.StartedAt != sending.StartedAt || d.SentAt != sending.SentAt {
t.Errorf("delivery 11 %+v, want it uncertain with its attempt", d)
}
again := load(t, s)
if len(again.Uncertain) != 0 || again.Records[0].Deliveries[1] != d {
t.Errorf("second load %+v, want nothing turned again", again)
}
if got := commits(); !slices.Equal(got, []commit{{normal, 0}}) {
t.Errorf("the second Load committed %+v, want no change", got)
}
if err := s.Sending(ctx, d); err == nil {
t.Error("an uncertain delivery was marked sending again")
}
}
// The references of unique jobs are kept, the newest KeptRefs of each
// source, apart from the jobs, whose pruning leaves them.
func TestRefsKeepTheNewestPerSource(t *testing.T) {
ctx := context.Background()
s := openStore(t, t.TempDir())
var third printqueue.UniqueRef
for seq := uint64(1); seq <= printqueue.KeptRefs+2; seq++ {
r := record(t, seq, "default")
r.Source, r.Ref, r.Unique = "ntfy:home", fmt.Sprintf("msg%d", seq), true
if seq == 3 {
third = printqueue.UniqueRef{Source: r.Source, Ref: r.Ref, ID: r.ID}
}
add(t, s, r, `{}`)
done := r.Deliveries[0]
done.State = printqueue.StoredDone
p := printqueue.Prune{Jobs: []uint64{seq}, Deliveries: []uint64{done.Seq}, Content: []uint64{seq}}
if err := s.Finish(ctx, done, p, false); err != nil {
t.Fatal(err)
}
}
other := record(t, 1000, "default")
other.Source, other.Ref, other.Unique = "ntfy:work", "msg1", true
add(t, s, other, `{}`)
add(t, s, record(t, 1001, "default"), `{}`)
loaded := load(t, s)
if len(loaded.Records) != 2 {
t.Errorf("%d records, want only the last two jobs", len(loaded.Records))
}
if len(loaded.Refs) != printqueue.KeptRefs+1 {
t.Fatalf("%d refs, want %d for ntfy:home and 1 for ntfy:work", len(loaded.Refs), printqueue.KeptRefs+1)
}
if loaded.Refs[0] != third || loaded.Refs[printqueue.KeptRefs] != (printqueue.UniqueRef{Source: "ntfy:work", Ref: "msg1", ID: other.ID}) {
t.Errorf("refs start with %+v and end with %+v", loaded.Refs[0], loaded.Refs[printqueue.KeptRefs])
}
// A reference kept for an earlier job is taken over by a new one.
again := record(t, 1002, "default")
again.Source, again.Ref, again.Unique = "ntfy:home", "msg5", true
add(t, s, again, `{}`)
refs := load(t, s).Refs
if i := slices.IndexFunc(refs, func(r printqueue.UniqueRef) bool { return r.Ref == "msg5" }); i < 0 || refs[i].ID != again.ID {
t.Errorf("msg5 is not kept for the new job: %+v", refs)
}
if len(refs) != printqueue.KeptRefs+1 {
t.Errorf("%d refs, want %d", len(refs), printqueue.KeptRefs+1)
}
}
// References are kept in the order they were kept, not by job ID: one
// whose job was minted after the clock went back, so that its ID sorts
// before every kept one, is kept, and the first kept goes.
func TestRefsKeepTheNewestWhateverTheJobID(t *testing.T) {
s := openStore(t, t.TempDir())
for seq := uint64(1); seq <= printqueue.KeptRefs; seq++ {
r := record(t, seq, "default")
r.Source, r.Ref, r.Unique = "ntfy:home", fmt.Sprintf("msg%d", seq), true
add(t, s, r, `{}`)
}
early, err := printqueue.ParseJobID("job_00000000000000000000000000")
if err != nil {
t.Fatal(err)
}
late := record(t, 1000, "default")
late.ID, late.Source, late.Ref, late.Unique = early, "ntfy:home", "after the clock went back", true
add(t, s, late, `{}`)
refs := load(t, s).Refs
if len(refs) != printqueue.KeptRefs {
t.Fatalf("%d refs, want %d", len(refs), printqueue.KeptRefs)
}
if newest := refs[len(refs)-1]; newest.Ref != late.Ref || newest.ID != early {
t.Errorf("newest ref %+v, want the one kept last", newest)
}
if refs[0].Ref != "msg2" {
t.Errorf("oldest ref %+v, want msg2, msg1 having gone", refs[0])
}
}
// The log grows by a bounded number of pages per job: an insert, a synced
// sending mark, and done with the pruning of the job ten before it. The
// bound has headroom; the number is logged.
func TestWALFramesPerJob(t *testing.T) {
ctx := context.Background()
dir := t.TempDir()
s := openStore(t, dir)
if _, err := s.conn.ExecContext(ctx, "PRAGMA wal_autocheckpoint = 0"); err != nil {
t.Fatal(err)
}
frames := func() int64 {
t.Helper()
info, err := os.Stat(filepath.Join(dir, FileName+"-wal"))
if err != nil {
t.Fatal(err)
}
const header, frame = 32, 24 + 4096
return (info.Size() - header) / frame
}
body := `{"elements":[{"type":"text","text":"` + strings.Repeat("Grüße ", 245) + `"}]}`
const jobs, history = 30, 10
before := frames()
for seq := uint64(1); seq <= jobs; seq++ {
r := record(t, seq, "default")
add(t, s, r, body)
d := r.Deliveries[0]
d.Attempts, d.StartedAt, d.SentAt = 1, time.Now().UTC(), time.Now().UTC()
if err := s.Sending(ctx, d); err != nil {
t.Fatal(err)
}
d.State, d.FinishedAt = printqueue.StoredDone, time.Now().UTC()
var p printqueue.Prune
if old := seq - history; seq > history {
p = printqueue.Prune{Jobs: []uint64{old}, Deliveries: []uint64{old * 10}, Content: []uint64{old}}
}
if err := s.Finish(ctx, d, p, false); err != nil {
t.Fatal(err)
}
}
perJob := float64(frames()-before) / jobs
t.Logf("WAL frames per job of %d bytes: %.2f", len(body), perJob)
if perJob > 16 {
t.Errorf("%.2f WAL frames per job, want at most 16", perJob)
}
if _, err := os.Stat(filepath.Join(dir, FileName+"-shm")); !errors.Is(err, os.ErrNotExist) {
t.Errorf("a -shm file exists (%v); exclusive locking keeps the log's index in memory", err)
}
}
// The store answers as the memory store does: the same records, references
// and content after the same calls, and an error for the same calls.
func TestBehavesAsTheMemoryStore(t *testing.T) {
ctx := context.Background()
disk := openStore(t, t.TempDir())
memory := printqueue.NewMemoryStore()
one := record(t, 1, "default", "kitchen")
two := record(t, 2, "default")
two.Source, two.Ref, two.Sequence, two.Unique = "ntfy:home", "m1", "alerts/s1", true
clash := record(t, 3, "default")
clash.Deliveries[0].Seq = 10
four := record(t, 4, "default")
four.Source, four.Ref, four.Unique = "ntfy:home", "m2", true
sending := one.Deliveries[1]
sending.Attempts, sending.StartedAt, sending.SentAt = 1, at(1, 1), at(1, 2)
failed := two.Deliveries[0]
failed.State, failed.Error, failed.Attempts, failed.FinishedAt = printqueue.StoredFailed, "giving up", 4, at(2, 3)
done := one.Deliveries[0]
done.State, done.Attempts, done.FinishedAt = printqueue.StoredDone, 1, at(3, 4)
steps := []struct {
name string
call func(printqueue.Store) error
}{
{"add one", func(s printqueue.Store) error { return s.Add(ctx, one, []byte(`{"a":1}`), false) }},
{"add two without content", func(s printqueue.Store) error { return s.Add(ctx, two, nil, true) }},
{"add one again", func(s printqueue.Store) error { return s.Add(ctx, one, []byte(`{}`), false) }},
{"add a job whose delivery is stored", func(s printqueue.Store) error { return s.Add(ctx, clash, []byte(`{}`), false) }},
{"sending", func(s printqueue.Store) error { return s.Sending(ctx, sending) }},
{"sending an unknown delivery", func(s printqueue.Store) error { return s.Sending(ctx, printqueue.Delivery{Seq: 99}) }},
{"failed", func(s printqueue.Store) error { return s.Finish(ctx, failed, printqueue.Prune{}, true) }},
{"failed again", func(s printqueue.Store) error { return s.Finish(ctx, failed, printqueue.Prune{}, true) }},
{"finish in a state that is not final", func(s printqueue.Store) error { return s.Finish(ctx, sending, printqueue.Prune{}, false) }},
{"done, dropping two's content", func(s printqueue.Store) error {
return s.Finish(ctx, done, printqueue.Prune{Content: []uint64{2}}, false)
}},
{"add four", func(s printqueue.Store) error { return s.Add(ctx, four, []byte(`{"b":2}`), true) }},
{"load", func(s printqueue.Store) error { _, err := s.Load(ctx); return err }},
{"sending an uncertain delivery", func(s printqueue.Store) error { return s.Sending(ctx, sending) }},
}
for _, step := range steps {
diskErr, memoryErr := step.call(disk), step.call(memory)
if (diskErr == nil) != (memoryErr == nil) {
t.Errorf("%s: the store returned %v, the memory store %v", step.name, diskErr, memoryErr)
}
}
got, want := withoutLoadTimes(load(t, disk)), withoutLoadTimes(load(t, memory))
if !reflect.DeepEqual(got, want) {
t.Errorf("loaded\n%+v\nwant, as the memory store,\n%+v", got, want)
}
for seq := uint64(1); seq <= 4; seq++ {
diskJob, diskErr := disk.Job(ctx, seq)
memoryJob, memoryErr := memory.Job(ctx, seq)
if !bytes.Equal(diskJob, memoryJob) || !errors.Is(diskErr, memoryErr) {
t.Errorf("Job(%d) = %q, %v; the memory store's %q, %v", seq, diskJob, diskErr, memoryJob, memoryErr)
}
}
}
// withoutLoadTimes clears the finish time that Load gives the deliveries it
// finds sending, which is the time of that Load.
func withoutLoadTimes(loaded printqueue.Loaded) printqueue.Loaded {
for i := range loaded.Records {
for j := range loaded.Records[i].Deliveries {
if d := &loaded.Records[i].Deliveries[j]; d.Error == printqueue.InterruptedSend {
d.FinishedAt = time.Time{}
}
}
}
return loaded
}
// Errors name the operation and sequence numbers, never what a job prints
// or where it came from.
func TestErrorsNeverQuoteTheJob(t *testing.T) {
ctx := context.Background()
s := openStore(t, t.TempDir())
r := record(t, 1, "default")
r.Source, r.Ref, r.Sequence, r.Unique = "ntfy:private-source", "private-ref", "private-topic/1", true
const content = `{"elements":[{"type":"text","text":"private text"}]}`
add(t, s, r, content)
d := r.Deliveries[0]
d.State, d.Error = printqueue.StoredFailed, "private error"
if err := s.Finish(ctx, d, printqueue.Prune{}, true); err != nil {
t.Fatal(err)
}
errs := []error{
s.Add(ctx, r, []byte(content), true),
s.Sending(ctx, d),
s.Finish(ctx, d, printqueue.Prune{}, true),
}
if err := s.Close(); err != nil {
t.Fatal(err)
}
_, jobErr := s.Job(ctx, 1)
_, loadErr := s.Load(ctx)
errs = append(errs, jobErr, loadErr, s.Add(ctx, record(t, 2, "default"), []byte(content), false))
for i, err := range errs {
if err == nil {
t.Errorf("call %d succeeded", i)
continue
}
if strings.Contains(err.Error(), "private") {
t.Errorf("call %d: %v quotes the job", i, err)
}
}
}