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 <noreply@anthropic.com>
This commit is contained in:
57_WolveandClaude Opus 5.5 committed 2026-12-01 16:34:51 -06:00
1 parent 6e47cb713e
commit f6323aa854
4 files changed
+815 -2

No files matched your search

+301
View File
@@ -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()
}