From f6323aa854d627eede9c69844fb92b8bf47016ea Mon Sep 17 00:00:00 2001 From: William Gill Date: Tue, 1 Dec 2026 14:34:57 -0600 Subject: [PATCH] Keep print jobs in the SQLite job store The job store now implements printqueue.Store on its one connection, so the queue can keep jobs on disk. A mutex serialises every call, since a transaction and the synchronous setting belong to the connection. - Add inserts the job, its deliveries and its content in one transaction. - Sending updates the delivery's row alone, at synchronous FULL, so the mark is on disk before the first byte goes to the printer. - Finish updates the delivery's row and drops exactly the jobs, deliveries and contents the queue names, in one transaction, synced when the queue asks, as it does for a failure. - Load turns every delivery in sending into uncertain and reads the jobs and deliveries, in one commit. It reads each content's length, not the content, and refuses a delivery whose job is gone or whose state this binary does not know; its errors name the file. - Job reads one job's content. - Idle runs a passive checkpoint while the queue has nothing to do, once 64 commits, about 20 jobs, have gathered since the last. The queue is idle after nearly every job when receipts come one at a time, and a checkpoint syncs the log and the database, and the next commit the log's header: checkpointing each time would turn a job's one sync into four. A synced commit sets synchronous FULL, commits, and returns to NORMAL even when the commit failed. Times are stored as Unix nanoseconds, so they read back to the nanosecond in UTC. Errors name the operation and the job's or delivery's sequence number, never a value. A test hook runs inside each commit and reads PRAGMA synchronous and total_changes(), so the tests see which commits are synced, the schema step included, and that Sending, and a Finish that drops nothing, change one row. With automatic checkpoints off, a job of 2 KB appended 8.6 WAL frames on the workstation; the test holds it to at most 16. Unique jobs' references are kept in the next commit. Nothing uses the store yet. Part of stage 1d of docs/plans/job-store.md. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 3 + internal/pkg/jobstore/open.go | 25 +- internal/pkg/jobstore/store.go | 301 +++++++++++++++++ internal/pkg/jobstore/store_test.go | 488 ++++++++++++++++++++++++++++ 4 files changed, 815 insertions(+), 2 deletions(-) create mode 100644 internal/pkg/jobstore/store.go create mode 100644 internal/pkg/jobstore/store_test.go diff --git a/CLAUDE.md b/CLAUDE.md index c04e602..4a8a84d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -57,6 +57,7 @@ modules from `go list`. The module path is the bare - server → modules, printqueue, receipt, printer, escpos - modules → receipt, ntfy - printqueue → receipt +- jobstore → printqueue - receipt → escpos, raster - printer → escpos - internal/app → docs, server and the libraries @@ -64,6 +65,8 @@ modules from `go list`. The module path is the bare Only `internal/app` reads config or wires in safehttp. Packages under `internal/pkg` take plain values, and escpos knows nothing of JSON or HTTP. +printqueue defines its `Store` and imports no database; jobstore implements +it on SQLite, so the server and tools/genopenapi never compile SQLite. ## Gate diff --git a/internal/pkg/jobstore/open.go b/internal/pkg/jobstore/open.go index f004c23..9163166 100644 --- a/internal/pkg/jobstore/open.go +++ b/internal/pkg/jobstore/open.go @@ -1,5 +1,5 @@ // Package jobstore keeps print jobs in a SQLite database on disk, so that -// they outlive the process. +// they outlive the process. Its Store implements printqueue.Store. // // The database is one file, FileName, with SQLite's write-ahead log beside // it. A Store holds one connection for its life, in exclusive locking @@ -108,6 +108,13 @@ type Store struct { mu sync.Mutex conn *sql.Conn closed bool + + // commits counts the commits since Idle last checkpointed. + commits int + + // commitHook, which only tests set, runs in each transaction just + // before it commits. + commitHook func(ctx context.Context, tx *sql.Tx) error } // Open opens the job store in dir, creating it if it is missing, and @@ -272,6 +279,11 @@ func setVersion(ctx context.Context, tx *sql.Tx, version int) error { return err } +// Durable reports true: jobs outlive the process. +func (s *Store) Durable() bool { + return true +} + // Close checkpoints the log into the database and releases the file and // its lock. Calls after the first do nothing. func (s *Store) Close() error { @@ -311,5 +323,14 @@ func (s *Store) update(ctx context.Context, sync bool, fn func(*sql.Tx) error) ( if err := fn(tx); err != nil { return errors.Join(err, tx.Rollback()) } - return tx.Commit() + if s.commitHook != nil { + if err := s.commitHook(ctx, tx); err != nil { + return errors.Join(err, tx.Rollback()) + } + } + if err := tx.Commit(); err != nil { + return err + } + s.commits++ + return nil } diff --git a/internal/pkg/jobstore/store.go b/internal/pkg/jobstore/store.go new file mode 100644 index 0000000..142901d --- /dev/null +++ b/internal/pkg/jobstore/store.go @@ -0,0 +1,301 @@ +package jobstore + +import ( + "context" + "database/sql" + "errors" + "fmt" + "slices" + "time" + + "uberbringer/internal/pkg/printqueue" +) + +var _ printqueue.Store = (*Store)(nil) + +// errNotOpen is a delivery that is not stored, or has finished already. +var errNotOpen = errors.New("not stored, or already finished") + +// Load implements printqueue.Store. It turns every delivery in sending into +// uncertain, and reads the jobs, in one commit. A record's Size is its +// content's length, read without the content. +func (s *Store) Load(ctx context.Context) (printqueue.Loaded, error) { + s.mu.Lock() + defer s.mu.Unlock() + var loaded printqueue.Loaded + err := s.update(ctx, false, func(tx *sql.Tx) error { + var err error + if loaded.Uncertain, err = endSends(ctx, tx, time.Now().UTC()); err != nil { + return fmt.Errorf("ending interrupted sends: %w", err) + } + loaded.Records, err = readRecords(ctx, tx) + return err + }) + if err != nil { + return printqueue.Loaded{}, fmt.Errorf("loading jobs from %s: %w", s.path, err) + } + return loaded, nil +} + +// endSends turns every delivery in sending into uncertain, finished at +// now, and returns their sequence numbers in order. +func endSends(ctx context.Context, tx *sql.Tx, now time.Time) ([]uint64, error) { + rows, err := tx.QueryContext(ctx, + `UPDATE deliveries SET state = ?, error = ?, finished_at = ? WHERE state = ? RETURNING seq`, + printqueue.StoredUncertain, printqueue.InterruptedSend, now.UnixNano(), printqueue.StoredSending) + if err != nil { + return nil, err + } + var turned []uint64 + for rows.Next() { + var seq uint64 + if err := rows.Scan(&seq); err != nil { + return nil, errors.Join(err, rows.Close()) + } + turned = append(turned, seq) + } + if err := errors.Join(rows.Err(), rows.Close()); err != nil { + return nil, err + } + slices.Sort(turned) + return turned, nil +} + +// readRecords returns every job in sequence order, each with its +// deliveries in sequence order. +func readRecords(ctx context.Context, tx *sql.Tx) ([]printqueue.Record, error) { + rows, err := tx.QueryContext(ctx, ` + SELECT j.seq, j.id, j.source, j.ref, j.sequence, j.created_at, COALESCE(length(c.job), 0) + FROM jobs j LEFT JOIN content c ON c.seq = j.seq + ORDER BY j.seq`) + if err != nil { + return nil, fmt.Errorf("reading jobs: %w", err) + } + var records []printqueue.Record + index := make(map[uint64]int) + for rows.Next() { + var r printqueue.Record + var id string + var created int64 + if err := rows.Scan(&r.Seq, &id, &r.Source, &r.Ref, &r.Sequence, &created, &r.Size); err != nil { + return nil, errors.Join(fmt.Errorf("reading jobs: %w", err), rows.Close()) + } + if r.ID, err = printqueue.ParseJobID(id); err != nil { + return nil, errors.Join(fmt.Errorf("reading job %d: its ID: %w", r.Seq, err), rows.Close()) + } + r.CreatedAt = time.Unix(0, created).UTC() + index[r.Seq] = len(records) + records = append(records, r) + } + if err := errors.Join(rows.Err(), rows.Close()); err != nil { + return nil, fmt.Errorf("reading jobs: %w", err) + } + + rows, err = tx.QueryContext(ctx, ` + SELECT seq, job_seq, printer, state, attempts, error, started_at, sent_at, finished_at + FROM deliveries ORDER BY seq`) + if err != nil { + return nil, fmt.Errorf("reading deliveries: %w", err) + } + for rows.Next() { + var d printqueue.Delivery + var jobSeq uint64 + var started, sent, finished sql.NullInt64 + if err := rows.Scan(&d.Seq, &jobSeq, &d.Printer, &d.State, &d.Attempts, &d.Error, &started, &sent, &finished); err != nil { + return nil, errors.Join(fmt.Errorf("reading deliveries: %w", err), rows.Close()) + } + i, ok := index[jobSeq] + if !ok { + return nil, errors.Join(fmt.Errorf("reading delivery %d: its job %d is not stored", d.Seq, jobSeq), rows.Close()) + } + if !known(d.State) { + return nil, errors.Join(fmt.Errorf("reading delivery %d: unknown state", d.Seq), rows.Close()) + } + d.StartedAt, d.SentAt, d.FinishedAt = fromNanos(started), fromNanos(sent), fromNanos(finished) + records[i].Deliveries = append(records[i].Deliveries, d) + } + if err := errors.Join(rows.Err(), rows.Close()); err != nil { + return nil, fmt.Errorf("reading deliveries: %w", err) + } + return records, nil +} + +// known reports whether a stored delivery's state is one this binary +// handles. A state from a newer binary would leave its job in no state the +// queue can finish. +func known(state printqueue.StoredState) bool { + return state == printqueue.StoredQueued || state == printqueue.StoredSending || state.Finished() +} + +// Add implements printqueue.Store: the job, its deliveries and its content, +// in one commit. +func (s *Store) Add(ctx context.Context, r printqueue.Record, job []byte, sync bool) error { + s.mu.Lock() + defer s.mu.Unlock() + if job == nil { + // A nil slice would be stored as NULL. + job = []byte{} + } + err := s.update(ctx, sync, func(tx *sql.Tx) error { + if _, err := tx.ExecContext(ctx, + `INSERT INTO jobs (seq, id, source, ref, sequence, created_at) VALUES (?, ?, ?, ?, ?, ?)`, + r.Seq, r.ID.String(), r.Source, r.Ref, r.Sequence, r.CreatedAt.UnixNano()); err != nil { + return err + } + for _, d := range r.Deliveries { + if _, err := tx.ExecContext(ctx, + `INSERT INTO deliveries (seq, job_seq, printer, state, attempts, error, started_at, sent_at, finished_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, + d.Seq, r.Seq, d.Printer, d.State, d.Attempts, d.Error, + nanos(d.StartedAt), nanos(d.SentAt), nanos(d.FinishedAt)); err != nil { + return fmt.Errorf("delivery %d: %w", d.Seq, err) + } + } + if _, err := tx.ExecContext(ctx, `INSERT INTO content (seq, job) VALUES (?, ?)`, r.Seq, job); err != nil { + return fmt.Errorf("its content: %w", err) + } + return nil + }) + if err != nil { + return fmt.Errorf("adding job %d: %w", r.Seq, err) + } + return nil +} + +// Sending implements printqueue.Store, with a synced commit that changes +// only d's row. +func (s *Store) Sending(ctx context.Context, d printqueue.Delivery) error { + s.mu.Lock() + defer s.mu.Unlock() + err := s.update(ctx, true, func(tx *sql.Tx) error { + res, err := tx.ExecContext(ctx, + `UPDATE deliveries SET state = ?, printer = ?, attempts = ?, started_at = ?, sent_at = ? + WHERE seq = ? AND state IN (?, ?)`, + printqueue.StoredSending, d.Printer, d.Attempts, nanos(d.StartedAt), nanos(d.SentAt), + d.Seq, printqueue.StoredQueued, printqueue.StoredSending) + if err != nil { + return err + } + return oneRow(res) + }) + if err != nil { + return fmt.Errorf("recording delivery %d as sending: %w", d.Seq, err) + } + return nil +} + +// Finish implements printqueue.Store: d's row, then exactly the rows p +// names, in one commit. +func (s *Store) Finish(ctx context.Context, d printqueue.Delivery, p printqueue.Prune, sync bool) error { + if !d.State.Finished() { + return fmt.Errorf("finishing delivery %d: %q is not a final state", d.Seq, d.State) + } + s.mu.Lock() + defer s.mu.Unlock() + err := s.update(ctx, sync, func(tx *sql.Tx) error { + res, err := tx.ExecContext(ctx, + `UPDATE deliveries SET printer = ?, state = ?, attempts = ?, error = ?, + started_at = ?, sent_at = ?, finished_at = ? + WHERE seq = ? AND state IN (?, ?)`, + d.Printer, d.State, d.Attempts, d.Error, nanos(d.StartedAt), nanos(d.SentAt), nanos(d.FinishedAt), + d.Seq, printqueue.StoredQueued, printqueue.StoredSending) + if err != nil { + return err + } + if err := oneRow(res); err != nil { + return err + } + return prune(ctx, tx, p) + }) + if err != nil { + return fmt.Errorf("finishing delivery %d: %w", d.Seq, err) + } + return nil +} + +// prune deletes the jobs, deliveries and contents p names. +func prune(ctx context.Context, tx *sql.Tx, p printqueue.Prune) error { + for _, table := range []struct { + name string + seqs []uint64 + }{{"jobs", p.Jobs}, {"deliveries", p.Deliveries}, {"content", p.Content}} { + for _, seq := range table.seqs { + // The table name is one of the three above, never input. + if _, err := tx.ExecContext(ctx, `DELETE FROM `+table.name+` WHERE seq = ?`, seq); err != nil { + return fmt.Errorf("dropping %s %d: %w", table.name, seq, err) + } + } + } + return nil +} + +// oneRow checks that res changed exactly one row: the delivery it named +// was stored and open. +func oneRow(res sql.Result) error { + n, err := res.RowsAffected() + if err != nil { + return err + } + if n != 1 { + return errNotOpen + } + return nil +} + +// Job implements printqueue.Store. +func (s *Store) Job(ctx context.Context, seq uint64) ([]byte, error) { + s.mu.Lock() + defer s.mu.Unlock() + var job []byte + err := s.conn.QueryRowContext(ctx, `SELECT job FROM content WHERE seq = ?`, seq).Scan(&job) + switch { + case errors.Is(err, sql.ErrNoRows): + return nil, printqueue.ErrContentGone + case err != nil: + return nil, fmt.Errorf("reading the content of job %d: %w", seq, err) + } + return job, nil +} + +// idleCheckpointCommits is how many commits Idle lets the log gather before +// it checkpoints. A checkpoint syncs the log and the database, and the +// first commit after it syncs the log's header as the log starts over. The +// queue is idle after nearly every job when receipts come one at a time, +// so checkpointing each time would add three syncs to a job's one. At +// about three commits a job, this checkpoints every twenty-odd jobs, long +// before the log reaches the 1,000 pages of SQLite's own checkpoint. +const idleCheckpointCommits = 64 + +// Idle implements printqueue.Store. Once idleCheckpointCommits commits have +// gathered since it last did, it copies the log into the database while +// nothing waits, so that SQLite's own checkpoint seldom lands on a commit a +// job waits for. +func (s *Store) Idle(ctx context.Context) error { + s.mu.Lock() + defer s.mu.Unlock() + if s.commits < idleCheckpointCommits { + return nil + } + var busy, frames, copied int + if err := s.conn.QueryRowContext(ctx, "PRAGMA wal_checkpoint(PASSIVE)").Scan(&busy, &frames, &copied); err != nil { + return fmt.Errorf("checkpointing: %w", err) + } + s.commits = 0 + return nil +} + +// nanos returns t as Unix nanoseconds, or NULL for the zero time. +func nanos(t time.Time) sql.NullInt64 { + if t.IsZero() { + return sql.NullInt64{} + } + return sql.NullInt64{Int64: t.UnixNano(), Valid: true} +} + +// fromNanos is the inverse of nanos, in UTC. +func fromNanos(n sql.NullInt64) time.Time { + if !n.Valid { + return time.Time{} + } + return time.Unix(0, n.Int64).UTC() +} diff --git a/internal/pkg/jobstore/store_test.go b/internal/pkg/jobstore/store_test.go new file mode 100644 index 0000000..ba73e13 --- /dev/null +++ b/internal/pkg/jobstore/store_test.go @@ -0,0 +1,488 @@ +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) + } + } +}