package jobstore import ( "context" "database/sql" "errors" "fmt" "os" "path/filepath" "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 = "ntfy:home", "msg1", "alerts/seq1" 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) } // 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, 3}) 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 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) } } // 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) } } }