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>
This commit is contained in:
57_WolveandClaude Opus 5.5 committed 2026-12-01 12:32:37 -06:00
1 parent 50db21190b
commit 888470bbdc
3 files changed
+575

No files matched your search

+9
View File
@@ -0,0 +1,9 @@
package printqueue
// NewDurableMemoryStore returns a MemoryStore that reports itself durable,
// so that a second Queue on it stands for the daemon after a restart.
func NewDurableMemoryStore() *MemoryStore {
s := NewMemoryStore()
s.durable = true
return s
}
+349
View File
@@ -0,0 +1,349 @@
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
}
+217
View File
@@ -0,0 +1,217 @@
package printqueue_test
import (
"context"
"errors"
"fmt"
"slices"
"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
}
// 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: time.Date(2026, 12, 1, 12, 0, 0, int(seq), time.UTC),
}
for i, p := range printers {
r.Deliveries = append(r.Deliveries, printqueue.Delivery{Seq: seq*10 + uint64(i), Printer: p, State: printqueue.StoredQueued})
}
return r
}
func TestMemoryStoreKeepsRecordsAndContent(t *testing.T) {
ctx := context.Background()
s := printqueue.NewMemoryStore()
if s.Durable() || !printqueue.NewDurableMemoryStore().Durable() {
t.Error("only the test store reports itself durable")
}
r := record(t, 2, "default", "kitchen", "bar")
r.Sequence = "alerts/seq1"
if err := s.Add(ctx, r, []byte(`{"elements":[]}`), false); err != nil {
t.Fatal(err)
}
if err := s.Add(ctx, record(t, 1, "default"), []byte(`{}`), false); err != nil {
t.Fatal(err)
}
if err := s.Add(ctx, record(t, 2, "default"), nil, false); err == nil {
t.Error("a second job 2 was stored")
}
loaded, err := s.Load(ctx)
if err != nil {
t.Fatal(err)
}
if len(loaded.Records) != 2 || loaded.Records[0].Seq != 1 || len(loaded.Uncertain) != 0 {
t.Fatalf("loaded %+v, want both jobs in seq order", loaded)
}
got := loaded.Records[1]
want := r
want.Size = int64(len(`{"elements":[]}`))
if got.ID != want.ID || got.Sequence != want.Sequence || got.Size != want.Size || got.CreatedAt != want.CreatedAt ||
!slices.Equal(got.Deliveries, want.Deliveries) {
t.Errorf("record %+v, want %+v", got, want)
}
// The loaded record is a copy.
loaded.Records[1].Deliveries[0].State = printqueue.StoredDone
if again, _ := s.Load(ctx); again.Records[1].Deliveries[0].State != printqueue.StoredQueued {
t.Error("changing a loaded record changed the store")
}
content, err := s.Job(ctx, 2)
if err != nil || string(content) != `{"elements":[]}` {
t.Errorf("Job = %q, %v", content, err)
}
if _, err := s.Job(ctx, 9); !errors.Is(err, printqueue.ErrContentGone) {
t.Errorf("Job of an unknown seq: %v, want ErrContentGone", err)
}
}
// Load turns a delivery in sending into uncertain, once.
func TestMemoryStoreLoadEndsSendsUncertain(t *testing.T) {
ctx := context.Background()
s := printqueue.NewDurableMemoryStore()
r := record(t, 1, "default", "kitchen")
if err := s.Add(ctx, r, []byte(`{}`), false); err != nil {
t.Fatal(err)
}
started := time.Date(2026, 12, 1, 12, 0, 1, 0, time.UTC)
sending := r.Deliveries[1]
sending.Attempts, sending.StartedAt, sending.SentAt = 2, started, started.Add(time.Second)
if err := s.Sending(ctx, sending); err != nil {
t.Fatal(err)
}
loaded, err := s.Load(ctx)
if err != nil {
t.Fatal(err)
}
if !slices.Equal(loaded.Uncertain, []uint64{11}) {
t.Errorf("uncertain %v, want delivery 11", loaded.Uncertain)
}
ds := loaded.Records[0].Deliveries
if ds[0].State != printqueue.StoredQueued {
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 != started || d.SentAt != started.Add(time.Second) {
t.Errorf("delivery 11 %+v, want it uncertain with its attempt", d)
}
if again, _ := s.Load(ctx); len(again.Uncertain) != 0 || again.Records[0].Deliveries[1].State != printqueue.StoredUncertain {
t.Errorf("second load %+v, want nothing turned again", again)
}
if err := s.Sending(ctx, d); err == nil {
t.Error("an uncertain delivery was marked sending again")
}
}
// Finish records the final state and drops jobs, deliveries and content in
// the same call.
func TestMemoryStoreFinishPrunes(t *testing.T) {
ctx := context.Background()
s := printqueue.NewMemoryStore()
for seq := uint64(1); seq <= 3; seq++ {
if err := s.Add(ctx, record(t, seq, "default", "kitchen"), []byte(`{"n":1}`), false); err != nil {
t.Fatal(err)
}
}
done := printqueue.Delivery{Seq: 30, Printer: "default", State: printqueue.StoredDone, Attempts: 1,
FinishedAt: time.Date(2026, 12, 1, 12, 0, 2, 0, time.UTC)}
if err := s.Finish(ctx, done, printqueue.Prune{Jobs: []uint64{1}, Deliveries: []uint64{21}, Content: []uint64{2}}, false); err != nil {
t.Fatal(err)
}
if err := s.Finish(ctx, done, printqueue.Prune{}, false); err == nil {
t.Error("a finished delivery was finished again")
}
if err := s.Finish(ctx, printqueue.Delivery{Seq: 31, State: printqueue.StoredSending}, printqueue.Prune{}, false); err == nil {
t.Error("Finish took a state that is not final")
}
if err := s.Finish(ctx, printqueue.Delivery{Seq: 10, State: printqueue.StoredDone}, printqueue.Prune{}, false); err == nil {
t.Error("a delivery of a dropped job was finished")
}
loaded, _ := s.Load(ctx)
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)
}
if _, err := s.Job(ctx, 2); !errors.Is(err, printqueue.ErrContentGone) {
t.Errorf("Job(2) = %v, want ErrContentGone", err)
}
if _, err := s.Job(ctx, 1); !errors.Is(err, printqueue.ErrContentGone) {
t.Errorf("Job(1) = %v, want ErrContentGone", err)
}
}
// The references of unique jobs are kept, KeptRefs per source, apart from
// the jobs themselves.
func TestMemoryStoreKeepsRefsPerSource(t *testing.T) {
ctx := context.Background()
s := printqueue.NewMemoryStore()
var first printqueue.UniqueRef
for seq := uint64(1); seq <= printqueue.KeptRefs+2; seq++ {
r := record(t, seq, "default")
r.Source, r.Unique = "ntfy:home", true
if seq == 3 {
first = printqueue.UniqueRef{Source: r.Source, Ref: r.Ref, ID: r.ID}
}
if err := s.Add(ctx, r, nil, true); err != nil {
t.Fatal(err)
}
done := r.Deliveries[0]
done.State = printqueue.StoredDone
if err := s.Finish(ctx, done, printqueue.Prune{Jobs: []uint64{seq}}, false); err != nil {
t.Fatal(err)
}
}
other := record(t, 1000, "default")
other.Source, other.Unique = "ntfy:work", true
if err := s.Add(ctx, other, nil, true); err != nil {
t.Fatal(err)
}
if err := s.Add(ctx, record(t, 1001, "default"), nil, false); err != nil {
t.Fatal(err)
}
loaded, _ := s.Load(ctx)
if len(loaded.Refs) != printqueue.KeptRefs+1 {
t.Fatalf("%d refs, want %d for ntfy:home and 1 for ntfy:work", len(loaded.Refs), printqueue.KeptRefs+1)
}
if loaded.Refs[0] != first || loaded.Refs[printqueue.KeptRefs].Source != "ntfy:work" {
t.Errorf("refs start with %+v and end with %+v", loaded.Refs[0], loaded.Refs[printqueue.KeptRefs])
}
}
func TestStoredStateFinished(t *testing.T) {
for state, want := range map[printqueue.StoredState]bool{
printqueue.StoredQueued: false, printqueue.StoredSending: false,
printqueue.StoredDone: true, printqueue.StoredFailed: true, printqueue.StoredUncertain: true,
} {
if state.Finished() != want {
t.Errorf("%s.Finished() = %v", state, !want)
}
}
}