Files
uberbringer/internal/pkg/printqueue/store.go
T
57_WolveandClaude Opus 5.5 888470bbdc Add the job store interface and its memory store
The print queue is to keep its jobs in a store that can outlive the
process. printqueue now defines that Store: a job is a Record with one
or more deliveries, one per printer, each with a stored state (queued,
sending, done, failed or uncertain), its attempts, error and times. Add,
Sending and Finish commit each change; Finish also drops the jobs,
deliveries and content retention lets go of, in the same commit. Load
turns every delivery found in sending into uncertain and says which.

MemoryStore implements it in memory, for when no state directory is
set. It refuses to mark a finished delivery again, so a bug that would
resend a job shows up as an error. The references of unique jobs are
kept per source, the newest 512, apart from the jobs themselves, for
the duplicate check to come.

Nothing uses the store yet. Part of stage 1c of docs/plans/job-store.md.

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

350 lines
9.7 KiB
Go

package printqueue
import (
"bytes"
"cmp"
"context"
"errors"
"fmt"
"maps"
"slices"
"sync"
"time"
)
// StoredState is a delivery's state as a Store records it. A delivery the
// worker has taken but not yet marked sending is still StoredQueued: being
// taken is never stored.
type StoredState string
// Stored states of a delivery.
const (
// StoredQueued: waiting, or taken but nothing sent yet.
StoredQueued StoredState = "queued"
// StoredSending: an attempt was about to write to the printer.
StoredSending StoredState = "sending"
// StoredDone: written in full to the printer.
StoredDone StoredState = "done"
// StoredFailed: given up; reached the printer only if SentAt is set.
StoredFailed StoredState = "failed"
// StoredUncertain: found in StoredSending at a start, so it may have
// printed. It is never sent again.
StoredUncertain StoredState = "uncertain"
)
// Finished reports whether s is a final state.
func (s StoredState) Finished() bool {
switch s {
case StoredDone, StoredFailed, StoredUncertain:
return true
}
return false
}
// DefaultPrinter names the printer of every delivery while the daemon
// drives one printer.
const DefaultPrinter = "default"
// KeptRefs is how many references of unique jobs are kept per source, for
// the duplicate check, whatever happens to their statuses.
const KeptRefs = 512
// InterruptedSend is the error of a delivery that Load found in
// StoredSending.
const InterruptedSend = "the daemon stopped while the receipt was being sent to the printer, so it may have printed; " +
"it is not sent again"
// ErrContentGone is returned by Store.Job for a job whose content is no
// longer kept.
var ErrContentGone = errors.New("job content no longer kept")
// Record is one job as a Store keeps it, with its deliveries.
type Record struct {
// Seq is the job's place in submission order.
Seq uint64
ID JobID
Source string
Ref string
// Sequence is the ntfy notification a card came from,
// "<topic>/<sequence ID>"; empty for other jobs.
Sequence string
// Unique marks Ref as unique at Source, for the duplicate check.
Unique bool
CreatedAt time.Time
// Size is the bytes of stored content; 0 once the content is dropped.
Size int64
// Deliveries are the job's deliveries, one per printer, in Seq order.
Deliveries []Delivery
}
// Delivery is a job on one printer.
type Delivery struct {
// Seq is the delivery's own place in submission order.
Seq uint64
// Printer is the printer used, or the one to try first.
Printer string
State StoredState
Attempts int
Error string
StartedAt time.Time
// SentAt is when the first attempt was about to write to the printer.
SentAt time.Time
FinishedAt time.Time
}
// UniqueRef is the source and reference of a unique job, with its ID.
type UniqueRef struct {
Source string
Ref string
ID JobID
}
// Loaded is what Store.Load returns.
type Loaded struct {
// Records are every stored job, in Seq order, without content.
Records []Record
// Refs are the kept references of unique jobs, oldest first within
// each source.
Refs []UniqueRef
// Uncertain are the deliveries this Load turned from StoredSending
// into StoredUncertain.
Uncertain []uint64
}
// Prune names what a Store drops in the commit of Store.Finish, by Seq:
// jobs, deliveries and contents. A job that goes is listed with each of its
// deliveries and with its content, if it still has it, so that a Store
// drops exactly what is listed.
type Prune struct {
Jobs []uint64
Deliveries []uint64
Content []uint64
}
// Store keeps jobs, and with a durable Store they outlive the process.
// Every method that writes commits before it returns; with sync, or for
// Sending, the commit is durable then. A Store never calls back into the
// queue.
type Store interface {
// Durable reports whether records outlive the process.
Durable() bool
// Load turns every delivery in StoredSending into StoredUncertain, with
// the error InterruptedSend, in one commit, then returns the records,
// the kept references and the deliveries it turned.
Load(ctx context.Context) (Loaded, error)
// Add stores a new job, its queued deliveries and its content, the job
// as JSON. A unique job's reference is kept too, and the oldest of its
// source beyond KeptRefs is dropped.
Add(ctx context.Context, r Record, job []byte, sync bool) error
// Sending records d, an attempt about to write to its printer, in
// StoredSending: its printer, attempts, StartedAt and SentAt. It
// returns once that is durable.
Sending(ctx context.Context, d Delivery) error
// Finish records d in its final state and drops what p names, in one
// commit.
Finish(ctx context.Context, d Delivery, p Prune, sync bool) error
// Job returns the content of job seq, or ErrContentGone.
Job(ctx context.Context, seq uint64) ([]byte, error)
// Idle is called when the queue has nothing to do.
Idle(ctx context.Context) error
// Close releases the store.
Close() error
}
// MemoryStore is a Store that keeps jobs in memory only, so they end with
// the process. It is safe for concurrent use.
type MemoryStore struct {
durable bool
// mu guards the fields below.
mu sync.Mutex
jobs map[uint64]*Record
deliveries map[uint64]uint64 // delivery Seq to job Seq
content map[uint64][]byte
refs map[string][]UniqueRef // per source, oldest first
}
// NewMemoryStore returns an empty MemoryStore.
func NewMemoryStore() *MemoryStore {
return &MemoryStore{
jobs: make(map[uint64]*Record),
deliveries: make(map[uint64]uint64),
content: make(map[uint64][]byte),
refs: make(map[string][]UniqueRef),
}
}
// Durable reports false, unless a test made the store report itself
// durable to stand for a store on disk.
func (s *MemoryStore) Durable() bool {
return s.durable
}
// Load implements Store.
func (s *MemoryStore) Load(context.Context) (Loaded, error) {
s.mu.Lock()
defer s.mu.Unlock()
var loaded Loaded
now := time.Now().UTC()
for _, seq := range slices.Sorted(maps.Keys(s.jobs)) {
r := s.jobs[seq]
for i := range r.Deliveries {
if d := &r.Deliveries[i]; d.State == StoredSending {
d.State, d.Error, d.FinishedAt = StoredUncertain, InterruptedSend, now
loaded.Uncertain = append(loaded.Uncertain, d.Seq)
}
}
loaded.Records = append(loaded.Records, cloneRecord(*r))
}
for _, source := range slices.Sorted(maps.Keys(s.refs)) {
loaded.Refs = append(loaded.Refs, s.refs[source]...)
}
return loaded, nil
}
// Add implements Store.
func (s *MemoryStore) Add(_ context.Context, r Record, job []byte, _ bool) error {
s.mu.Lock()
defer s.mu.Unlock()
if _, ok := s.jobs[r.Seq]; ok {
return fmt.Errorf("adding job %d: already stored", r.Seq)
}
for _, d := range r.Deliveries {
if _, ok := s.deliveries[d.Seq]; ok {
return fmt.Errorf("adding job %d: delivery %d already stored", r.Seq, d.Seq)
}
}
r = cloneRecord(r)
slices.SortFunc(r.Deliveries, func(a, b Delivery) int { return cmp.Compare(a.Seq, b.Seq) })
r.Size = int64(len(job))
s.jobs[r.Seq] = &r
s.content[r.Seq] = bytes.Clone(job)
for _, d := range r.Deliveries {
s.deliveries[d.Seq] = r.Seq
}
if r.Unique {
refs := append(s.refs[r.Source], UniqueRef{Source: r.Source, Ref: r.Ref, ID: r.ID})
if extra := len(refs) - KeptRefs; extra > 0 {
refs = slices.Delete(refs, 0, extra)
}
s.refs[r.Source] = refs
}
return nil
}
// Sending implements Store.
func (s *MemoryStore) Sending(_ context.Context, d Delivery) error {
s.mu.Lock()
defer s.mu.Unlock()
stored, err := s.delivery(d.Seq)
if err != nil {
return fmt.Errorf("recording delivery %d as sending: %w", d.Seq, err)
}
stored.State, stored.Printer, stored.Attempts = StoredSending, d.Printer, d.Attempts
stored.StartedAt, stored.SentAt = d.StartedAt, d.SentAt
return nil
}
// Finish implements Store.
func (s *MemoryStore) Finish(_ context.Context, d Delivery, p Prune, _ bool) error {
s.mu.Lock()
defer s.mu.Unlock()
if !d.State.Finished() {
return fmt.Errorf("finishing delivery %d: %q is not a final state", d.Seq, d.State)
}
stored, err := s.delivery(d.Seq)
if err != nil {
return fmt.Errorf("finishing delivery %d: %w", d.Seq, err)
}
*stored = d
for _, seq := range p.Jobs {
if r, ok := s.jobs[seq]; ok {
for _, d := range r.Deliveries {
delete(s.deliveries, d.Seq)
}
}
delete(s.jobs, seq)
delete(s.content, seq)
}
for _, seq := range p.Deliveries {
if jobSeq, ok := s.deliveries[seq]; ok {
r := s.jobs[jobSeq]
r.Deliveries = slices.DeleteFunc(r.Deliveries, func(d Delivery) bool { return d.Seq == seq })
delete(s.deliveries, seq)
}
}
for _, seq := range p.Content {
delete(s.content, seq)
if r, ok := s.jobs[seq]; ok {
r.Size = 0
}
}
return nil
}
// Job implements Store.
func (s *MemoryStore) Job(_ context.Context, seq uint64) ([]byte, error) {
s.mu.Lock()
defer s.mu.Unlock()
job, ok := s.content[seq]
if !ok {
return nil, ErrContentGone
}
return bytes.Clone(job), nil
}
// Idle implements Store; there is nothing to do.
func (s *MemoryStore) Idle(context.Context) error {
return nil
}
// Close implements Store; there is nothing to release.
func (s *MemoryStore) Close() error {
return nil
}
// delivery returns the stored delivery seq, which must not be finished.
// The caller holds s.mu.
func (s *MemoryStore) delivery(seq uint64) (*Delivery, error) {
jobSeq, ok := s.deliveries[seq]
if !ok {
return nil, errors.New("not stored")
}
r := s.jobs[jobSeq]
for i := range r.Deliveries {
if d := &r.Deliveries[i]; d.Seq == seq {
if d.State.Finished() {
return nil, fmt.Errorf("already %s", d.State)
}
return d, nil
}
}
return nil, errors.New("not stored")
}
// cloneRecord returns r with deliveries of its own.
func cloneRecord(r Record) Record {
r.Deliveries = slices.Clone(r.Deliveries)
return r
}