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>
This commit is contained in:
57_WolveandClaude Opus 5.5 committed 2026-12-01 21:28:38 -06:00
1 parent 9376653e1a
commit d3c3025e64
19 files changed
+429 -68

No files matched your search

+49
View File
@@ -17,6 +17,7 @@ import (
"go.jetify.com/typeid"
"uberbringer/internal/pkg/config"
"uberbringer/internal/pkg/escpos"
"uberbringer/internal/pkg/jobstore"
"uberbringer/internal/pkg/printqueue"
)
@@ -154,6 +155,54 @@ func seedSending(t *testing.T, dir, text string) string {
return id.String()
}
// A printer that answers that it is ready, then takes a job but never
// confirms it, leaves the job uncertain, sent once and never again.
func TestServeUnconfirmedJobReadsUncertain(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = ln.Close() })
connections := make(chan struct{}, 10)
go func() {
for {
conn, err := ln.Accept()
if err != nil {
return
}
connections <- struct{}{}
go func() {
defer conn.Close()
ready := make([]byte, len(escpos.StatusRequest(escpos.StatusPrinter))+
len(escpos.AutomaticStatusOff())+len(escpos.TransmitStatusRequest()))
if _, err := io.ReadFull(conn, ready); err != nil {
return
}
_, _ = conn.Write([]byte{0x12, 0x00})
online := make([]byte, len(escpos.StatusRequest(escpos.StatusPrinter)))
if _, err := io.ReadFull(conn, online); err != nil {
return
}
_, _ = conn.Write([]byte{0x12})
_, _ = io.Copy(io.Discard, conn)
}()
}
}()
cfg := testConfig(ln.Addr().(*net.TCPAddr).Port)
cfg.Printer.WriteTimeout = 300 * time.Millisecond
d := startDaemon(t, cfg)
id := d.print(t, "never confirmed")
var st jobStatus
waitFor(t, func() bool { st = d.status(t, id); return st.Status == "uncertain" })
if !strings.Contains(st.Error, "did not confirm") {
t.Errorf("error %q, want it to say the printer did not confirm", st.Error)
}
d.stop(t)
if n := len(connections); n != 1 {
t.Errorf("the printer got %d connections, want the job sent once", n)
}
}
// A job store that cannot be opened stops the start with an error naming
// its file, rather than starting empty.
func TestRunRefusesAStoreItCannotOpen(t *testing.T) {
+1 -1
View File
@@ -95,7 +95,7 @@ func run(ctx context.Context, cfg *config.Config, build BuildInfo, out io.Writer
renderer := receipt.NewRenderer(options, fetcher)
printerClient := printer.NewClient(
net.JoinHostPort(cfg.Printer.Address, strconv.Itoa(cfg.Printer.Port)),
cfg.Printer.DialTimeout, cfg.Printer.WriteTimeout)
cfg.Printer.DialTimeout, cfg.Printer.WriteTimeout, printer.Confirm(cfg.Printer.Confirm))
queue := printqueue.New(renderer, printerClient, store, logger, printqueue.Options{
Size: cfg.Queue.Size,
History: cfg.Queue.History,
+22 -2
View File
@@ -19,11 +19,16 @@ import (
"time"
"uberbringer/internal/pkg/config"
"uberbringer/internal/pkg/escpos"
"uberbringer/internal/pkg/printqueue"
"uberbringer/internal/pkg/receipt"
)
// fakePrinter records everything sent to it.
// fakePrinter records everything sent to it, and answers as an online
// printer with paper does: each DLE EOT 1, which the daemon asks at the
// start of a connection and again before each job, and each GS r 1, which
// it sends before and after each job, in that order within what one read
// brings.
type fakePrinter struct {
mu sync.Mutex
data bytes.Buffer
@@ -52,7 +57,22 @@ func startFakePrinterOn(t *testing.T, addr string) *fakePrinter {
}
go func() {
defer conn.Close()
data, _ := io.ReadAll(conn)
var data []byte
online, ready := 0, 0
buf := make([]byte, 4096)
for {
n, err := conn.Read(buf)
data = append(data, buf[:n]...)
for ; online < bytes.Count(data, escpos.StatusRequest(escpos.StatusPrinter)); online++ {
_, _ = conn.Write([]byte{0x12})
}
for ; ready < bytes.Count(data, escpos.TransmitStatusRequest()); ready++ {
_, _ = conn.Write([]byte{0x00})
}
if err != nil {
break
}
}
p.mu.Lock()
defer p.mu.Unlock()
p.data.Write(data)
+3 -2
View File
@@ -252,8 +252,9 @@ func (s *Server) handleHealth(c fiber.Ctx) error {
resp.Printer = printerHealth{Reachable: boolPtr(true), Status: "unknown"}
case errors.Is(err, context.DeadlineExceeded):
// The printer did not answer within healthTimeout, typically because
// it is still taking in a large job. Its state is unknown, so do not
// claim it is healthy.
// a job holds its connection while it prints or waits for the
// printer to be ready. Its state is unknown, so do not claim it is
// healthy.
s.logger.Warn("printer health check timed out", "err", err)
resp.Status = "unavailable"
resp.Printer = printerHealth{Status: "timeout"}
+13
View File
@@ -122,6 +122,18 @@ type PrinterConfig struct {
DialTimeout time.Duration `mapstructure:"dial_timeout"`
WriteTimeout time.Duration `mapstructure:"write_timeout"`
// Confirm makes each send wait, within WriteTimeout and up to 2 s more
// for the check that the printer is online, for the printer to answer
// GS r 1 before the job, which the TM-T88IV does only while it
// can print, and to confirm with its answer to GS r 1 after the job that
// it ran it; a job it does not confirm ends uncertain. It also sends
// GS a 0, which turns the printer's automatic status off, and DLE EOT 1,
// which the printer must answer on receipt, and it needs GS r answers
// with bits 4 and 7 clear. Off sends none of these and records a job done
// once the operating system has taken its bytes, for a printer that
// does not answer so.
Confirm bool `mapstructure:"confirm"`
// Retries is how many times a failed send is retried before the job is
// marked failed.
Retries int `mapstructure:"retries"`
@@ -394,6 +406,7 @@ func Default() Config {
CutFeed: 3,
DialTimeout: 5 * time.Second,
WriteTimeout: 30 * time.Second,
Confirm: true,
Retries: 3,
RetryDelay: time.Second,
},
+8 -1
View File
@@ -63,6 +63,9 @@ func TestLoadInstallScriptConfigGetsDefaults(t *testing.T) {
t.Errorf("defaults not applied: max_lines %d, box_line_spacing %d, cut_feed %d",
cfg.Format.MaxLines, cfg.Printer.BoxLineSpacing, cfg.Printer.CutFeed)
}
if !cfg.Printer.Confirm {
t.Error("printer.confirm must be on by default")
}
if cfg.Format.Timezone != "Local" || cfg.Format.TimeLayout != "02 Jan 15:04" {
t.Errorf("format defaults not applied: timezone %q, time_layout %q", cfg.Format.Timezone, cfg.Format.TimeLayout)
}
@@ -408,7 +411,7 @@ func TestExampleConfigLoads(t *testing.T) {
if def := config.Default(); cfg.WebServer.RateLimit != def.WebServer.RateLimit ||
cfg.Images.MaxBytes != def.Images.MaxBytes || cfg.Printer.Model != def.Printer.Model ||
cfg.Format.MaxLines != def.Format.MaxLines || cfg.Printer.BoxLineSpacing != def.Printer.BoxLineSpacing ||
cfg.Printer.CutFeed != def.Printer.CutFeed ||
cfg.Printer.CutFeed != def.Printer.CutFeed || cfg.Printer.Confirm != def.Printer.Confirm ||
cfg.Format.Timezone != def.Format.Timezone || cfg.Format.TimeLayout != def.Format.TimeLayout ||
cfg.Ntfy.Format != def.Ntfy.Format || len(cfg.Ntfy.Markers) != 0 ||
cfg.State != def.State || cfg.Queue != def.Queue || len(cfg.Ntfy.Subscriptions) != 0 {
@@ -494,11 +497,15 @@ retries = 2
t.Setenv("UBERBRINGER_WEBSERVER_TRUSTED_PROXIES", "10.0.0.1, 172.18.0.0/16")
t.Setenv("UBERBRINGER_NOT_A_KEY", "ignored")
t.Setenv("UBERBRINGER_PRINTER_RETRIES", "")
t.Setenv("UBERBRINGER_PRINTER_CONFIRM", "false")
cfg, err := config.Load(path)
if err != nil {
t.Fatalf("Load: %v", err)
}
if cfg.Printer.Confirm {
t.Error("printer.confirm is on, want the environment's false")
}
if cfg.Printer.Address != "env.lan" {
t.Errorf("Address = %q, want the environment's value", cfg.Printer.Address)
}
+48 -20
View File
@@ -69,7 +69,8 @@ const (
StateFailed State = "failed"
// StateUncertain is a job that was being sent when the daemon stopped,
// so it may have printed. It is never sent again.
// or one the printer did not confirm, so it may have printed. It is
// never sent again.
StateUncertain State = "uncertain"
)
@@ -77,9 +78,12 @@ const (
type Status struct {
// ID identifies the job.
ID JobID `json:"id"`
// State is where the job is in its lifecycle. uncertain is a job that
// was being sent to the printer when the daemon stopped: it may have
// printed, and it is never sent again.
// State is where the job is in its lifecycle. done is a job the printer
// confirmed it ran, or with printer.confirm off, one written to it in
// full. uncertain is a job that was being sent to the
// printer when the daemon stopped, or that the printer did not confirm:
// it may have printed in full, in part or not at all, and it is never
// sent again.
State State `json:"status" jsonschema:"enum=queued,enum=printing,enum=done,enum=failed,enum=uncertain"`
// Source says where the job came from: print for POST /api/v1/print,
// module:<name> for a module route, e.g. module:ntfy, or
@@ -98,8 +102,7 @@ type Status struct {
// A failed job with sent_at reached the printer, and part of it may have
// printed; one without it never reached the printer.
SentAt *time.Time `json:"sent_at,omitempty"`
// FinishedAt is when the job was done or failed, or when a start found
// it uncertain.
// FinishedAt is when the job was done, failed or found uncertain.
FinishedAt *time.Time `json:"finished_at,omitempty"`
}
@@ -112,11 +115,24 @@ type Renderer interface {
// once it can write and before the first byte, and writes nothing when
// beforeWrite fails. Cancelling ctx stops the wait for the printer and
// the dial, but not a write that has begun; ctx's deadline still bounds
// it.
// it. An error with an Unconfirmed method that reports true means every
// byte was written but the printer did not confirm the job: it may have
// printed in full, in part or not at all, and it is not sent again.
type Sender interface {
Send(ctx context.Context, data []byte, beforeWrite func() error) error
}
// unconfirmedSend is the end of the error of a job the printer did not
// confirm.
const unconfirmedSend = "it may have printed in full, in part or not at all, and it is not sent again"
// unconfirmed reports whether err says a job was written in full but not
// confirmed by the printer.
func unconfirmed(err error) bool {
var u interface{ Unconfirmed() bool }
return errors.As(err, &u) && u.Unconfirmed()
}
// Options configures a Queue.
type Options struct {
// Size is how many jobs may wait.
@@ -570,10 +586,18 @@ func (q *Queue) process(ctx context.Context, d *delivery) error {
logger.Info("job left queued: the daemon is stopping and nothing was sent")
return nil
}
if unconfirmed(err) {
if err := q.finish(storeCtx, d, StoredUncertain, attempts, err); err != nil {
return err
}
logger.Warn("job may not have printed in full: the printer did not confirm it; it is not sent again",
"printer", d.Printer, "attempts", attempts, "err", err)
return nil
}
if err != nil {
return q.fail(storeCtx, d, attempts, err, logger)
}
if err := q.finish(storeCtx, d, attempts, nil); err != nil {
if err := q.finish(storeCtx, d, StoredDone, attempts, nil); err != nil {
return err
}
logger.Info("job printed", "attempts", attempts)
@@ -619,7 +643,7 @@ func (q *Queue) abandoned(ctx context.Context, d *delivery) bool {
// fail records d as failed after attempts, logs it and reports it.
func (q *Queue) fail(ctx context.Context, d *delivery, attempts int, cause error, logger *slog.Logger) error {
if err := q.finish(ctx, d, attempts, cause); err != nil {
if err := q.finish(ctx, d, StoredFailed, attempts, cause); err != nil {
return err
}
logger.Error("job failed", "attempts", attempts, "err", cause)
@@ -667,7 +691,7 @@ func (q *Queue) print(runCtx, jobCtx context.Context, d *delivery, job receipt.J
return attempt - 1, fmt.Errorf("server shutting down after %d attempts: %w", attempt-1, last), nil
case err == nil:
return attempt, nil, nil
case attempt > q.options.Retries:
case unconfirmed(err) || attempt > q.options.Retries:
return attempt, err, nil
}
last = err
@@ -705,12 +729,13 @@ func (q *Queue) sending(ctx context.Context, d *delivery, attempt int) error {
return nil
}
// finish records d as done after attempts, or as failed with cause, and
// drops in the same commit the jobs that retention lets go of. A failure
// is synced, since a failed job rolled back to queued would print after a
// restart. Once a store error has stopped the queue it writes nothing and
// returns that error.
func (q *Queue) finish(ctx context.Context, d *delivery, attempts int, cause error) error {
// finish records d in state, a final one, after attempts: done, failed
// with cause, or uncertain, unconfirmed with cause. It drops in the same
// commit the jobs that retention lets go of. A failure is synced, since a
// failed job rolled back to queued would print after a restart. Once a
// store error has stopped the queue it writes nothing and returns that
// error.
func (q *Queue) finish(ctx context.Context, d *delivery, state StoredState, attempts int, cause error) error {
if err := q.stopped(); err != nil {
q.release(d)
return err
@@ -718,9 +743,12 @@ func (q *Queue) finish(ctx context.Context, d *delivery, attempts int, cause err
q.mu.Lock()
next := d.Delivery
q.mu.Unlock()
next.State, next.Attempts, next.FinishedAt = StoredDone, attempts, time.Now().UTC()
if cause != nil {
next.State, next.Error = StoredFailed, cause.Error()
next.State, next.Attempts, next.FinishedAt = state, attempts, time.Now().UTC()
switch {
case state == StoredUncertain && cause != nil:
next.Error = cause.Error() + "; " + unconfirmedSend
case cause != nil:
next.Error = cause.Error()
}
q.mu.Lock()
@@ -868,7 +896,7 @@ func (q *Queue) shutdown(ctx context.Context) error {
storeCtx := context.WithoutCancel(ctx)
for _, d := range waiting {
if err := q.finish(storeCtx, d, 0, errShuttingDown); err != nil {
if err := q.finish(storeCtx, d, StoredFailed, 0, errShuttingDown); err != nil {
return q.stop(err)
}
}
+65 -1
View File
@@ -5,6 +5,7 @@ import (
"errors"
"io"
"log/slog"
"slices"
"strings"
"sync"
"testing"
@@ -23,10 +24,18 @@ func (f fakeRenderer) Render(_ context.Context, job receipt.Job) ([]byte, error)
return []byte(job.Elements[0].Text), nil
}
// unconfirmedError is what a Sender returns for a job it wrote in full
// that the printer did not confirm.
type unconfirmedError struct{}
func (unconfirmedError) Error() string { return "the printer did not confirm the job: i/o timeout" }
func (unconfirmedError) Unconfirmed() bool { return true }
// fakeSender fails the first failures sends as a failed dial does, before
// beforeWrite. Then it calls beforeWrite, fails the next writeFailures
// sends as a failed write does, and records data. script, while it lasts,
// says how each send ends instead: "dial" or "write" fails it there, and
// says how each send ends instead: "dial" or "write" fails it there,
// "unconfirmed" records data and returns an unconfirmedError, and
// anything else goes on as above.
type fakeSender struct {
mu sync.Mutex
@@ -71,6 +80,9 @@ func (f *fakeSender) Send(_ context.Context, data []byte, beforeWrite func() err
return errors.New("connection reset")
}
f.sent = append(f.sent, string(data))
if step == "unconfirmed" {
return unconfirmedError{}
}
return nil
}
@@ -264,6 +276,58 @@ func TestFailsAfterRetries(t *testing.T) {
}
}
// A job written in full that the printer does not confirm ends uncertain:
// it is not retried, not reported as a failure, logged at WARN, and its
// commit is not synced. After a restart it is still uncertain and is not
// sent again.
func TestUnconfirmedSendEndsUncertain(t *testing.T) {
var logs lockedBuffer
reported := make(chan printqueue.JobID, 1)
inner := printqueue.NewDurableMemoryStore()
store := newTestStore(inner)
sender := &fakeSender{script: []string{"unconfirmed"}}
q := newQueueOn(store, fakeRenderer{}, sender, slogTo(&logs), printqueue.Options{
Retries: 3,
OnFailure: func(id printqueue.JobID, _ error) { reported <- id },
})
cancel, wait := startQueue(t, q)
submitted, _ := q.Submit(job("x"), printqueue.Meta{})
st := waitForState(t, q, submitted.ID, printqueue.StateUncertain)
cancel()
wait()
if st.Attempts != 1 || st.SentAt == nil || st.FinishedAt == nil ||
!strings.Contains(st.Error, "did not confirm") || !strings.Contains(st.Error, "not sent again") {
t.Errorf("status %+v, want one attempt, sent, finished, and an error saying it may have printed", st)
}
if sent := sender.Sent(); len(sent) != 1 {
t.Errorf("sent %q, want one send", sent)
}
if len(reported) != 0 {
t.Error("an unconfirmed job was reported as a failure")
}
want := []commit{
{op: "add", seq: 1, state: printqueue.StoredQueued},
{op: "sending", seq: 1, state: printqueue.StoredSending, synced: true},
{op: "finish", seq: 1, state: printqueue.StoredUncertain},
}
if got := store.Commits(); !slices.Equal(got, want) {
t.Errorf("commits\n%+v\nwant\n%+v", got, want)
}
if !strings.Contains(logs.String(), "level=WARN") || !strings.Contains(logs.String(), "did not confirm") {
t.Errorf("log %q, want a WARN line", logs.String())
}
again := &fakeSender{}
restarted := newQueueOn(inner, fakeRenderer{}, again, discardLogger(), printqueue.Options{})
if err := restarted.Restore(context.Background()); err != nil {
t.Fatal(err)
}
if st, err := restarted.Status(submitted.ID); err != nil || st.State != printqueue.StateUncertain || restarted.Pending() != 0 {
t.Errorf("after a restart: %+v, %v, %d waiting; want it uncertain, not waiting", st, err, restarted.Pending())
}
}
func TestRenderFailureIsNotRetried(t *testing.T) {
sender := &fakeSender{}
q := newQueue(fakeRenderer{err: errors.New("image blocked")}, sender, printqueue.Options{Retries: 3})
+3 -2
View File
@@ -27,8 +27,9 @@ const (
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: 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"
)