Files
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

361 lines
12 KiB
Go

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. A record reads as Unique
// while its source and reference are among those kept.
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)
}
if loaded.Records, err = readRecords(ctx, tx); err != nil {
return err
}
loaded.Refs, err = readRefs(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,
EXISTS (SELECT 1 FROM refs r WHERE r.source = j.source AND r.ref = j.ref AND r.id = j.id),
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.Unique, &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()
}
// readRefs returns the kept references of unique jobs, by source, the first
// kept first within each.
func readRefs(ctx context.Context, tx *sql.Tx) ([]printqueue.UniqueRef, error) {
rows, err := tx.QueryContext(ctx, `SELECT source, ref, id FROM refs ORDER BY source, kept`)
if err != nil {
return nil, fmt.Errorf("reading references: %w", err)
}
var refs []printqueue.UniqueRef
for rows.Next() {
var r printqueue.UniqueRef
var id string
if err := rows.Scan(&r.Source, &r.Ref, &id); err != nil {
return nil, errors.Join(fmt.Errorf("reading references: %w", err), rows.Close())
}
if r.ID, err = printqueue.ParseJobID(id); err != nil {
return nil, errors.Join(fmt.Errorf("reading references: a job ID: %w", err), rows.Close())
}
refs = append(refs, r)
}
if err := errors.Join(rows.Err(), rows.Close()); err != nil {
return nil, fmt.Errorf("reading references: %w", err)
}
return refs, nil
}
// Add implements printqueue.Store: the job, its deliveries, its content
// and, for a unique job, its reference, in one commit. The references of a
// source beyond printqueue.KeptRefs go in the same commit, the first kept
// first.
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)
}
if r.Unique {
return keepRef(ctx, tx, r)
}
return nil
})
if err != nil {
return fmt.Errorf("adding job %d: %w", r.Seq, err)
}
return nil
}
// keepRef keeps the source and reference of unique job r as the newest of
// its source, and drops the oldest beyond printqueue.KeptRefs, in the order
// they were kept, as the queue forgets them. A reference kept for an
// earlier job is dropped first, so that r's is the newest. 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.
func keepRef(ctx context.Context, tx *sql.Tx, r printqueue.Record) error {
if _, err := tx.ExecContext(ctx, `DELETE FROM refs WHERE source = ? AND ref = ?`, r.Source, r.Ref); err != nil {
return fmt.Errorf("its earlier reference: %w", err)
}
if _, err := tx.ExecContext(ctx,
`INSERT INTO refs (source, ref, id) VALUES (?, ?, ?)`, r.Source, r.Ref, r.ID.String()); err != nil {
return fmt.Errorf("its reference: %w", err)
}
if _, err := tx.ExecContext(ctx,
`DELETE FROM refs WHERE source = ?1 AND kept <
(SELECT kept FROM refs WHERE source = ?1 ORDER BY kept DESC LIMIT 1 OFFSET ?2)`,
r.Source, printqueue.KeptRefs-1); err != nil {
return fmt.Errorf("pruning references: %w", 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()
}