Files
uberbringer/internal/pkg/printqueue/store.go
T
57_WolveandClaude Opus 5.5 d3c3025e64 Record a job done only once the printer confirms it
Breaking: a job reads done only once the printer has confirmed that it
ran it, and holds the printer's connection until then. A job written in
full that the printer does not confirm within printer.write_timeout now
reads uncertain and is not sent again; before, it read done. Before
each job, nothing is sent until the printer answers that it can print,
so with its cover open or no paper a job is retried and fails, with no
sent_at, as when the printer is unreachable, where before it read done.
Receipts that take longer than write_timeout to print need a larger
one. With confirmation the daemon also turns the printer's automatic
status off (GS a 0) before each job and before its confirmation, so
another client that relies on automatic status from the same printer
stops getting it. printer.confirm = false keeps the old meaning of done
and sends none of this.

The third paper check of the job store showed why: with the
TM-T88IV's cover open, Windows took all of a 128 KB receipt into its
send buffer, so the job read done; the daemon stopped, and once the
cover closed only the first third printed, without its cut. The printer
was then left inside the image command, waiting for the rest, until it
was switched off and on.

The daemon now turns on the printer client's confirmation. The queue
treats an unconfirmed send as written but unknown: it records the
delivery uncertain, with an error that says the printer did not confirm
it and that it may have printed in full, in part or not at all, logs it
at WARN with the printer, and neither retries it nor reports it as a
failure. Its commit is not synced: lost, it rolls back to sending,
which the next start turns uncertain too. A printer that is not ready
gives a plain error before the sending mark, which the queue retries as
a failed dial.

The new key printer.confirm, on by default, turns confirmation off for
a printer that does not answer GS r with bits 4 and 7 clear, or does not
answer DLE EOT on receipt; only the TM-T88IV is checked. The key's
comments in config.go and the example config say what it sends and
needs. docs/api.md warns that raw bytes which make the printer answer
can be taken for the confirmation, and says that /healthz answers 503
timeout while a job holds the connection. It and design.md say that
each job waits about 200 ms for answers still owed, for DLE EOT 1 to
say that the printer is online, and for no answer to come late.
design.md says why each connection opens with DLE EOT 1, GS a 0 and
GS r 1, and names what stays open: a raw job holding a command answered
with bits 4 and 7 clear, such as GS r, GS I, ESC v or ESC u 0, with
printing after it, and an answer taken for the ready answer that is not
it, one still queued when the fence arrived or one owed from before a
late DLE EOT answer that stood in for the fence, followed by a pause of
more than 100 ms while the printer reads online, as might happen during
the TM-m50II's feed and cut at cover close. It relies on the printer
answering DLE EOT on receipt and running GS a 0 in order,
unverified beyond the TM-T88IV until stage 4a's raw-byte probe, and now
says a send that fails part-way can print a whole receipt twice. The
unit and install.md give the stop timeout with and without state.dir:
without it the job being sent runs on from its rendering, image fetches
included, up to the job's 2-minute cap, so such hosts keep systemd's
default or set state.dir. configuration.md says the online check can
add 2 s to write_timeout. The printers plan says what Send now does
before a job, and its table of what a failed send can mean gains the
ready wait and the confirmation.

The tests' fake printers answer DLE EOT 1 and GS r 1 as an online
printer with paper does; a test runs the daemon against one that
answers that it is ready but never confirms the job. On paper, a
receipt read done 884 ms after it was written, when the printer
answered, and a receipt whose daemon was killed while it waited, with
the cover open, read uncertain after the restart and printed once, cut
short. With GS a 0 and DLE EOT 1, a receipt printed once with nothing
extra and read done 888 ms after it was written; after a power cycle,
with /healthz polled every 250 ms, one sent with the cover open waited
15.7 s with nothing sent and printed once, cut once, when the cover
closed. With the fence, a receipt printed once with nothing extra and
read done 921 ms after it was written.

Part of stage 1d of docs/plans/job-store.md.

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

351 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, or written in full
// without the printer confirming it, 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
}