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

+21
View File
@@ -13,6 +13,27 @@ version may break callers; such changes are listed under **Breaking**.
while it was sending the job to the printer, so the receipt may have while it was sending the job to the printer, so the receipt may have
printed. Such a job is never sent again. Clients that switch on `status` printed. Such a job is never sent again. Clients that switch on `status`
must handle it. must handle it.
- A job is `done` only once the printer confirms it ran it: after each job
the daemon sends `GS r 1`, which the printer answers only after every
byte before it, and holds the connection until the answer. A job written
in full that the printer does not confirm within `printer.write_timeout`
is `uncertain` and is not sent again; before, it read `done` even when
the operating system still held part of it, and a stop could lose that
part. Before each job the daemon also asks `DLE EOT 1` and `GS r 1`
first, drops whatever the printer sent before it answered the
`DLE EOT 1`, and sends nothing until the printer answers the `GS r 1`,
which the TM-T88IV does only while it can print: with the cover open or
no paper, a job is retried and fails as when the printer is unreachable,
instead of reading `done`. That wait drops the answers still owed to
earlier requests and then checks with `DLE EOT 1` that the printer is
online, so each job takes about 200 ms more. The daemon also turns the
printer's automatic status off (`GS a 0`) before each job and before
each confirmation, so another client that relies on automatic status
from the same printer stops getting it. Raise `write_timeout` for
receipts that take longer than 30 seconds to print.
`printer.confirm = false` restores the old meaning of `done`, and sends
none of this, for a printer that does not answer `GS r` with bits 4 and
7 clear, or `DLE EOT` on receipt.
- With `state.dir` set, jobs still waiting when the daemon stops print - With `state.dir` set, jobs still waiting when the daemon stops print
after the next start, in order and however old, instead of being marked after the next start, in order and however old, instead of being marked
failed; after a crash they print too, instead of being forgotten. A failed; after a crash they print too, instead of being forgotten. A
+6
View File
@@ -129,6 +129,12 @@ main. A change is done when the gate passes and the docs under `docs/` (or
problem while it cuts or feeds. A status read cut short by our own deadline problem while it cuts or feeds. A status read cut short by our own deadline
is a timeout, never a printer fault. Anything that acts on status re-checks is a timeout, never a printer fault. Anything that acts on status re-checks
first, as `/healthz` does. first, as `/healthz` does.
- A write that returned proves only that the operating system holds the
bytes. A job is `done` only once the printer answers the `GS r 1` sent
after it (`printer.confirm`); one written in full without that answer is
`uncertain` and never sent again. Nothing of a job is sent until the
printer has answered a `GS r 1` asked alone, which also drops late
answers to earlier requests.
- Every refusal is an `apiError` with a code from `server/errors.go`. A code is - Every refusal is an `apiError` with a code from `server/errors.go`. A code is
part of the API: never rename one, and add a new code to the table in part of the API: never rename one, and add a new code to the table in
`docs/api.md`. `docs/api.md`.
+11
View File
@@ -68,7 +68,18 @@
cut_feed = 3 cut_feed = 3
dial_timeout = "5s" dial_timeout = "5s"
# How long sending a job may take, with confirm also the wait for the
# printer to be ready and to confirm the job once it has printed.
write_timeout = "30s" write_timeout = "30s"
# Ask the printer (GS r 1) before each job whether it can print, and send
# nothing until it answers; after each job, wait for it to confirm the job
# before it reads done. One it does not confirm within write_timeout reads
# uncertain and is not sent again. This 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 needs GS r answers with bits 4 and 7 clear.
# false, for a printer that does not answer so, sends none of these and
# reads done once the operating system has the job's bytes.
confirm = true
retries = 3 # resend attempts when the printer is unreachable retries = 3 # resend attempts when the printer is unreachable
retry_delay = "1s" # doubles after each attempt retry_delay = "1s" # doubles after each attempt
+40 -14
View File
@@ -123,17 +123,33 @@ curl -H @"$HOME/.uberbringer-auth" https://printer.example.com/api/v1/jobs/job_0
} }
``` ```
`status` is `queued`, `printing`, `done`, `failed` or `uncertain`. A failed job `status` is `queued`, `printing`, `done`, `failed` or `uncertain`. A job is
includes an `error` field. `uncertain` means the daemon stopped while it was `done` once the printer has confirmed that it ran it: after each job the
sending the job to the printer, so the receipt may have printed; its `error` daemon asks the printer for its status, which it answers only once every
says so. Such a job is never sent again: if the paper shows it missing, send byte before the question has run (with `printer.confirm = false`, `done`
it again. `sent_at` is when the first attempt was about to write to the means only that the job was written to the printer's connection). The
printer. A failed job with `sent_at` reached the printer, and part of it may answer names no job, so before each job the daemon drops the answers
have printed; one without it never reached the printer. the printer still owed to earlier questions: those it sent before its
`source` says where the job came from: `print` for answer to a real-time question asked first, and those that come within
`/api/v1/print`, `module:<name>` for a [module](#modules) route, or 100 ms of each other after it. It then checks with `DLE EOT 1` that the
`ntfy:<name>` for an [ntfy subscription](ntfy.md) printer is online, and if another answer comes it sends nothing and
in the config. The last `queue.history` finished jobs are kept. tries again; each job waits about 200 ms for these checks. A
[`raw`](#raw) element can still let a job read `done` before it has
printed; docs/design.md describes the one other case, where the printer,
still reporting online, pauses more than 100 ms between two answers,
which is unverified.
A failed job includes an `error` field. `uncertain` means
the receipt may have printed in full, in part or not at all: the daemon
stopped while it was sending the job, or the printer did not confirm it
within `printer.write_timeout`, as when its cover is open; its `error`
says which. Such a job is never sent again: if the paper shows it missing,
send it again. `sent_at` is when the first attempt was about to write
to the printer. A failed job with `sent_at` reached the printer, and
part of it may have printed; one without it never reached the printer.
`source` says where the job came from: `print` for `/api/v1/print`,
`module:<name>` for a [module](#modules) route, or `ntfy:<name>` for an
[ntfy subscription](ntfy.md) in the config. The last `queue.history`
finished jobs are kept.
With [`state.dir`](configuration.md#state) set, jobs are kept on disk, so With [`state.dir`](configuration.md#state) set, jobs are kept on disk, so
a job's status answers after a restart as before it, and a job still a job's status answers after a restart as before it, and a job still
@@ -250,9 +266,11 @@ Details:
- **Brief problems are re-checked.** A printer that looks not ready is read - **Brief problems are re-checked.** A printer that looks not ready is read
again 750 ms later, and only a problem that is still there gives `503`. again 750 ms later, and only a problem that is still there gives `503`.
While cutting or feeding, a printer can report a problem for a moment. While cutting or feeding, a printer can report a problem for a moment.
- **Timeouts.** The printer accepts one connection at a time. While it is still - **Timeouts.** The printer accepts one connection at a time, and a job holds
taking in a large job, the 3-second health check can run out of time. That it until the printer has printed it and confirmed so (`printer.confirm`),
gives `503` with printer status `"timeout"`, because the printer's state is or, while the printer cannot print, as the job waits for it to be ready.
When that takes longer than the 3-second health check, the check gives
`503` with printer status `"timeout"`, because the printer's state is
unknown. unknown.
- **The cover flag** is only reported while the printer is offline. Epson - **The cover flag** is only reported while the printer is offline. Epson
printers always go offline when the cover opens. printers always go offline when the cover opens.
@@ -408,6 +426,14 @@ or link-local addresses (including cloud metadata endpoints) are refused unless
|-------|--------| |-------|--------|
| `hex` | ESC/POS bytes as hex, spaces allowed, e.g. `"1B 61 01"` | | `hex` | ESC/POS bytes as hex, spaces allowed, e.g. `"1B 61 01"` |
Bytes that make the printer answer with a byte whose bits 4 and 7 are
clear, such as `GS r`, `GS I`, `ESC v` or `ESC u 0`, can be taken for the
printer's confirmation of the job (`printer.confirm`) when printing follows
them, so the job can read `done` before it has printed, or `uncertain`
though it printed. Answers they leave owed can do the same to the next
job: before each job the daemon drops the answers still owed to earlier
requests, but only those that come within 100 ms of each other.
The bytes are sent as given, so a job with a `raw` element prints only with The bytes are sent as given, so a job with a `raw` element prints only with
a token issued with `uberbringer token --raw`; any other token gets `403` a token issued with `uberbringer token --raw`; any other token gets `403`
`token_scope`. Previewing one needs no such token. `token_scope`. Previewing one needs no such token.
+7 -1
View File
@@ -87,7 +87,8 @@ so on a host it set up, re-run it after changing them
| `columns` | from the width | Font A characters per line, for word wrap; overrides the model | | `columns` | from the width | Font A characters per line, for word wrap; overrides the model |
| `box_line_spacing` | `0` | The line spacing, in motion units (ESC 3, 0–255), used while a box prints. Lines of box drawing leave small gaps in the vertical borders at the printer's default spacing; a value checked on paper closes them. `0` keeps the default | | `box_line_spacing` | `0` | The line spacing, in motion units (ESC 3, 0–255), used while a box prints. Lines of box drawing leave small gaps in the vertical borders at the printer's default spacing; a value checked on paper closes them. `0` keeps the default |
| `cut_feed` | `3` | Blank lines, 0–255, fed before every cut, the one after each copy and `cut` elements alike, so that the last printed line does not sit right at the cut. They show in previews and count toward `format.max_lines` | | `cut_feed` | `3` | Blank lines, 0–255, fed before every cut, the one after each copy and `cut` elements alike, so that the last printed line does not sit right at the cut. They show in previews and count toward `format.max_lines` |
| `dial_timeout`, `write_timeout` | `"5s"`, `"30s"` | How long connecting to the printer, and sending it a job, may take | | `dial_timeout`, `write_timeout` | `"5s"`, `"30s"` | How long connecting to the printer, and sending it a job, may take. With `confirm`, `write_timeout` also bounds the wait for the printer to be ready before a job, which the check that it is online can extend by up to 2 s, and the wait for its confirmation after it, which comes once the job has printed: raise it for receipts that take longer to print, and the stop timeout with it. A job's whole run is capped at 2 minutes, so a larger value changes nothing |
| `confirm` | `true` | Ask the printer for its status with `GS r 1`, which it answers only once it has run every byte before it, and, on the TM-T88IV, only while it can print. Before each job, ask `DLE EOT 1`, which the printer answers at once, then `GS r 1`, drop whatever the printer sent before the `DLE EOT` answer, and wait up to `write_timeout` for the answer to `GS r 1`: without it, as with the cover open or no paper, nothing is sent and the job is retried, then fails, as when the printer is unreachable. Before each job, also turn the printer's automatic status off (`GS a 0`) and, once it has answered, check with `DLE EOT 1` again that it is online and that no answer comes late. These checks take about 200 ms per job. After each job, turn automatic status off again and ask again, and mark the job `done` only on the answer; one the printer does not confirm within `write_timeout` is `uncertain` and is not sent again. Checked on the TM-T88IV. `false`, for a printer that does not answer `GS r` with bits 4 and 7 clear or does not answer `DLE EOT` on receipt, sends none of these and marks a job `done` once the operating system has taken its bytes, which a stop or a crash can still lose |
| `retries` | `3` | How many times a failed send is retried before the job fails | | `retries` | `3` | How many times a failed send is retried before the job fails |
| `retry_delay` | `"1s"` | The wait before the first retry; it doubles after each | | `retry_delay` | `"1s"` | The wait before the first retry; it doubles after each |
@@ -261,6 +262,11 @@ Request bodies and the `Authorization` header are never sent to Sentry.
so check the paper. A job that a stop catches before it reached the so check the paper. A job that a stop catches before it reached the
printer is logged at INFO as `job left queued` and prints after the printer is logged at INFO as `job left queued` and prints after the
start. start.
- A job written to the printer in full that it does not confirm is logged
at WARN, as `job may not have printed in full`, with the printer's
error; it reads `uncertain` and is not sent again. If its receipt was cut
short, the printer may still be waiting for the rest of an image and
print the next receipt as noise: switch it off and on.
- Each [ntfy subscription](ntfy.md) logs with its `subscription` name, - Each [ntfy subscription](ntfy.md) logs with its `subscription` name,
never with what a message says or its topic. It logs at WARN when its never with what a message says or its topic. It logs at WARN when its
connection is lost, when its credentials are refused and while the queue connection is lost, when its credentials are refused and while the queue
+106 -9
View File
@@ -47,8 +47,102 @@ client ─HTTPS─▶ Caddy ─▶ server ── validate ──▶ printqueue (
`ref`. It is never sent again; a person checks the paper, and a `ref`. It is never sent again; a person checks the paper, and a
reprint is a new request. A crash between the mark and the write reprint is a new request. A crash between the mark and the write
leaves an `uncertain` receipt that never printed, the safe direction. leaves an `uncertain` receipt that never printed, the safe direction.
`queued` never reached the printer, `done` was written in full, and a `queued` never reached the printer, and a `failed` job reached it only
`failed` job reached it only if `sent_at` is set. if `sent_at` is set.
- **Done means the printer confirmed it (owner, 2026-12-01).** A write
that returned says only that the operating system holds the bytes. On
the TM-T88IV with its cover open, Windows took a whole 128 KB receipt
into its send buffer at once; the daemon stopped, and once the cover
closed only the receipt's first third printed, uncut, and the printer
waited for the rest of the image, so the next receipt would have
printed as noise until it was switched off and on. So the client asks
with `GS r 1`, which the printer answers only once it has run every
byte before it, and, on the TM-T88IV, only while it can print
(`printer.confirm`):
- Before the `sending` mark it sends `DLE EOT 1`, `GS a 0` and `GS r 1`
in one write. The printer answers `DLE EOT` on receipt, ahead of
anything it receives after it, so that answer is a fence: everything
before it left the printer before the request reached it, and is
dropped, however long a lost segment holds the request back. That
takes care of answers owed to requests the printer ran earlier, on
an earlier connection or for an earlier run of the daemon, and of the
last bytes of an automatic status block whose header went to an
earlier connection. A late answer to an earlier connection's
`DLE EOT` looks like the fence's and can stand in for it; the last
check below catches what follows from that. It then waits, up to
`printer.write_timeout`, for an answer to `GS r 1` after the fence.
Without it, as with the cover open, paper out or a printer stuck
inside a cut-short image, nothing is sent, and the job retries as
after a failed dial and fails with no `sent_at`. Requests still
queued in the printer ahead of this one are answered first, and the
answers carry nothing that tells them apart, so the wait reads every
answer until 100 ms have passed since the last and drops them all.
Only answers keep the wait open, and one that the deadline or the
connection's end cuts short counts as not ready. A printer may run
`GS r 1` while offline, as the TM-m50II's settings may allow, so it
then asks `DLE EOT 1` again, for up to 2 s beyond
`printer.write_timeout`, and sends the job only if the printer
answers that it is online. Last, it reads on for 100 ms. Once the
answers have settled none is owed, so an answer to `GS r 1` during
the online check or after it means that one taken for the ready
answer was not, as when a late `DLE EOT` answer stood in for the
fence and an owed answer followed it; then nothing is sent, and the
job is tried again. Each job waits about 200 ms for these checks.
- After the job it sends `GS a 0` and `GS r 1` again, and the job is
`done` only on that answer. Without it within
`printer.write_timeout`, the job is `uncertain`, with a WARN line,
and never sent again. A receipt that takes longer to print than that
reads `uncertain` though it printed, and the job's 2-minute bound
caps the timeout.
- Automatic status blocks: the UB-E02 and UB-E03 boards turn them on
at power-on, and a job's `ESC @` turns them off, but not on a
TM-T88VII with DIP switch 2-1 on. A block's last three bytes have the
`GS r` answer's fixed bits, and the board can send them on the next
connection. So the client sends `GS a 0` before each `GS r 1`; the
printer runs it in order, so no block follows the answer on that
connection. Bytes of blocks before the fence are dropped with the
rest; blocks after it are passed over by their header's fixed bits,
a block split across reads included, and after the confirmation the
client reads on for up to 100 ms for the rest of a block it ended
inside. `Status` sends no `GS a 0`, which the printer does not run
while offline; before it closes, it reads what has come, to the end
of any block.
- Not `DLE EOT` for the confirmation: it is answered at once, and an
image's bytes can hold it, which the printer answers too; such
answers are told from the `GS r` answer by their fixed bits (bits 4
and 7 clear). The TM-T88IV answers `0x00`; Epson's pages also give a
form with bit 4 set, which a model must not use unless it runs with
`printer.confirm = false`, unchecked on the TM-T88VII and TM-m50II.
`printer.confirm` also needs a printer that answers `DLE EOT` on
receipt.
- What remains open, which an acknowledgement that names the job,
`GS ( H` fn 48 (phase 5), would close:
- A `raw` job holding a command the printer answers with a byte
whose bits 4 and 7 are clear, such as `GS r`, `GS I`, `ESC v` or
`ESC u 0`, with printing after it, is confirmed by that answer
before it has printed. Answers it leaves owed, far enough apart,
can do the same to the next job. Only a token issued with `--raw`
can send one.
- An answer taken for the ready answer that is not it: the answer to
a request still queued in the printer when the fence arrived, or,
when a late `DLE EOT` answer stood in for the fence while this
connection's request was held back, one the printer owed from
before. The printer runs queued requests back to back, so the real
ready answer follows within the settle, which drops both, or
within 100 ms of the online answer, which sends nothing, unless
printing comes between them, which only a `raw` job puts there, or
the printer pauses longer while it reports online. The TM-m50II
feeds and cuts when its cover closes; if it reports online before
it has run the queued requests and pauses between them, the late
ready answer confirms the job before it has printed.
- The client relies on the printer answering `DLE EOT` on receipt,
ahead of the `GS r 1` sent just before it, and running `GS a 0` in
order, and on how the board routes bytes across connections. The
TM-T88IV answers `DLE EOT`; the rest is unverified, and stage 4a's
raw-byte probe (docs/plans/printers.md) checks it.
- A job holds the printer's connection until it has printed, so
`/healthz` answers `503` `timeout` during a receipt that takes more
than 3 seconds.
- **Deliveries.** A job has one delivery per printer, one for `default` - **Deliveries.** A job has one delivery per printer, one for `default`
until several printers are configured, each with its own state, until several printers are configured, each with its own state,
attempts and times. A job's `status` derives from them: `queued` while attempts and times. A job's `status` derives from them: `queued` while
@@ -141,10 +235,11 @@ client ─HTTPS─▶ Caddy ─▶ server ── validate ──▶ printqueue (
untested on ARM hardware: the owner has none, modernc's CI names no untested on ARM hardware: the owner has none, modernc's CI names no
ARMv6 target, and older SIGSEGV reports for linux/arm exist. CI ARMv6 target, and older SIGSEGV reports for linux/arm exist. CI
cross-compiles them on every push. cross-compiles them on every push.
- **Acknowledgement.** Epson documents one, `GS ( H` fn 48, answered - **Acknowledgement with an ID.** Epson also documents `GS ( H` fn 48,
once a job has printed, which would turn most `uncertain` jobs into answered with an ID of the host's choosing once a job has printed,
confirmed prints. Whether the TM-T88IV's network board passes it to which would tell one job's answer from another's even across
port 9100 is unverified, so it waits for a paper test connections. Whether the TM-T88IV's network board passes it to port
9100 is unverified, so it waits for a paper test
(docs/plans/job-store.md, phase 5). The state machine is safe without (docs/plans/job-store.md, phase 5). The state machine is safe without
it. it.
- **Render, then send.** The handler validates the whole job, and a `400` - **Render, then send.** The handler validates the whole job, and a `400`
@@ -153,8 +248,9 @@ client ─HTTPS─▶ Caddy ─▶ server ── validate ──▶ printqueue (
sends that stream over one connection. A failure before the send, such as a sends that stream over one connection. A failure before the send, such as a
broken image, costs no paper and leaves no half-printed receipt. A retry broken image, costs no paper and leaves no half-printed receipt. A retry
resends the same bytes and does not render again. A send that fails resends the same bytes and does not render again. A send that fails
part-way can print part of a receipt twice. That is accepted, because part-way can print a receipt, or part of one, twice. That is accepted,
retries are what let a job survive a printer that is briefly offline. because retries are what let a job survive a printer that is briefly
offline.
- **Blank paper before the cut (owner, 2026-11-30).** The cut, `GS V 66 0`, - **Blank paper before the cut (owner, 2026-11-30).** The cut, `GS V 66 0`,
feeds the last printed line just past the cutter, so the cut fell right feeds the last printed line just past the cutter, so the cut fell right
under it. `printer.cut_feed` blank lines (3) now feed before every cut. under it. `printer.cut_feed` blank lines (3) now feed before every cut.
@@ -579,7 +675,8 @@ before anything is built. They come in this order.
the owner accepted every proposed default, 2026-12-01). The store is the owner accepted every proposed default, 2026-12-01). The store is
built (Decisions, "Jobs survive a restart"); what is left: built (Decisions, "Jobs survive a restart"); what is left:
- `GET /api/v1/jobs` lists the history, job status shows `ref`, and - `GET /api/v1/jobs` lists the history, job status shows `ref`, and
`/healthz` counts the jobs found `uncertain` at the latest start. `/healthz` counts the jobs that became `uncertain` since the latest
start, at it or during the run.
- `DELETE /api/v1/jobs/{id}` cancels a waiting job, for full tokens. An - `DELETE /api/v1/jobs/{id}` cancels a waiting job, for full tokens. An
ntfy `message_delete` cancels the waiting receipts of its ntfy `message_delete` cancels the waiting receipts of its
notification (`Queue.Cancel`); `message_clear` does not, and the notification (`Queue.Cancel`); `message_clear` does not, and the
+6 -3
View File
@@ -44,9 +44,12 @@ sudo UBERBRINGER_VERSION=v0.2.0 ./install.sh <domain> <acme-email> <printer-addr
- The unit keeps systemd's stop timeout, 90 seconds, so a receipt that is - The unit keeps systemd's stop timeout, 90 seconds, so a receipt that is
being written to the printer when the service stops can finish. If you being written to the printer when the service stops can finish. If you
lower it with `systemctl edit`, keep it above `printer.write_timeout` lower it with `systemctl edit` and have `state.dir` set, keep it above
plus 10 seconds (40 at the defaults); a stop that kills the write leaves `printer.write_timeout` plus 10 seconds (40 at the defaults); a stop that
the job `uncertain`. kills the write leaves the job `uncertain`. Without `state.dir`, the job
being sent runs on from its rendering, image fetches included, through
its dial and the wait for the printer to be ready, up to the job's
2-minute cap, so keep the 90-second default there, or set `state.dir`.
- Change the systemd unit with `systemctl edit uberbringer`. - Change the systemd unit with `systemctl edit uberbringer`.
- The install log is `/var/log/uberbringer-install.log`. - The install log is `/var/log/uberbringer-install.log`.
+11 -6
View File
@@ -153,13 +153,13 @@ For stage 3:
- A write error after which `Write` had taken nothing counts as nothing sent and fails over at once. That needs `Send` to report what it wrote, which it discards today. The printer stays in `sent_to` all the same: over-reporting is the safe direction, and dropping it would cost one more store write. - A write error after which `Write` had taken nothing counts as nothing sent and fails over at once. That needs `Send` to report what it wrote, which it discards today. The printer stays in `sent_to` all the same: over-reporting is the safe direction, and dropping it would cost one more store write.
- `attempts` counts every attempt on every printer, and each mark's attempt number goes on from the last. - `attempts` counts every attempt on every printer, and each mark's attempt number goes on from the last.
- The risk: the next printer prints the whole receipt. A first printer that took all of it before the error, or buffered it and prints it once its fault clears, prints it too. - The risk: the next printer prints the whole receipt. A first printer that took all of it before the error, or buffered it and prints it once its fault clears, prints it too.
- Some sends that will not print show no error at all. `Write` returns once the kernel holds the bytes, so a printer that goes offline after taking them, or one that another host holds, takes the receipt without a word, and no failover happens (Investigation findings, WHAT "THE PRINTER FAILED" CAN MEAN). - With `printer.confirm`, the default, `Send` opens each connection with `DLE EOT 1`, `GS a 0` and `GS r 1` and writes nothing without an answer to that `GS r 1`, after the `DLE EOT` answer, and a second `DLE EOT 1` that says online, so a printer that is offline, has its cover open or is held by another host gets no byte, and the delivery counts as nothing sent. A printer that takes the job and then does not confirm it leaves the delivery `uncertain`, which never fails over. With `printer.confirm = false`, `Write` returns once the kernel holds the bytes, so such sends show no error at all, and no failover happens (Investigation findings, WHAT "THE PRINTER FAILED" CAN MEAN).
- docs/plans/remote-printers.md decision 17 builds on this: a remote `partial` outcome is today's write error, and `nothing` matches `NothingWritten`. - docs/plans/remote-printers.md decision 17 builds on this: a remote `partial` outcome is today's write error, and `nothing` matches `NothingWritten`.
23. **A status check before an anycast send.** After the dial and before the `sending` mark, on the same connection and inside the printer's slot, anycast reads `DLE EOT`. It reads a not-ready answer again 750 ms later, as `/healthz` does. 23. **A status check before an anycast send.** After the dial and before the `sending` mark, on the same connection and inside the printer's slot, anycast reads `DLE EOT`. It reads a not-ready answer again 750 ms later, as `/healthz` does.
- The read runs over the connection already open, so it never waits on its own slot. - The read runs over the connection already open, so it never waits on its own slot.
- It reads `DLE EOT` only. Stage 4a's `GS r 1` is not real-time, adds up to 500 ms, and could close the connection the job is about to be written on (decision 28). Near-end never decides a failover. - It reads `DLE EOT` only, before `Send`'s ready wait. Stage 4a's `GS r 1` is not real-time, adds up to 500 ms, and could close the connection the job is about to be written on (decision 28). Near-end never decides a failover.
- A printer still not ready (offline, cover open, paper out, an error) counts as nothing sent. It is marked down (decision 24), and the delivery fails over at once. - A printer still not ready (offline, cover open, paper out, an error) counts as nothing sent. It is marked down (decision 24), and the delivery fails over at once.
- A timeout or no answer sends anyway: a timeout is never a printer fault, and a printer busy with an earlier job may answer late. - A timeout or no answer goes on to the send: a timeout is never a printer fault, and a printer busy with an earlier job may answer late. With `printer.confirm`, the send then writes nothing until the printer answers `GS r 1` and says it is online to `DLE EOT 1`, and anything less counts as nothing sent, as a failed dial does.
- Unicast and multicast do not check, as today, so a job for a printer that is briefly offline is still buffered for it. The check and `/healthz` share one settle function, moved from the server to `printer`, which takes the read to use. - Unicast and multicast do not check, as today, so a job for a printer that is briefly offline is still buffered for it. The check and `/healthz` share one settle function, moved from the server to `printer`, which takes the read to use.
- Without the check, a printer out of paper most likely still takes the connection and the bytes, so the main anycast case would fall into decision 22's path. That is an inference, and a paper check tests it before stage 3 starts. With the owner's OK, one short receipt goes unicast to the TM-T88IV with its paper out (or its cover open). Does the printer take the connection and the bytes, and print the receipt once the paper is loaded? - Without the check, a printer out of paper most likely still takes the connection and the bytes, so the main anycast case would fall into decision 22's path. That is an inference, and a paper check tests it before stage 3 starts. With the owner's OK, one short receipt goes unicast to the TM-T88IV with its paper out (or its cover open). Does the printer take the connection and the bytes, and print the receipt once the paper is loaded?
- docs/plans/remote-printers.md decision 19 reads a remote printer's status through the same settle function at the agent, and this paper check decides the anycast check there too. - docs/plans/remote-printers.md decision 19 reads a remote printer's status through the same settle function at the agent, and this paper check decides the anycast check there too.
@@ -326,7 +326,7 @@ REAL-TIME STATUS (`DLE EOT`) PER MODEL
- `GS r 1` reports near-end on all three, but it is not real-time: it is answered after the printing before it has finished, and at paper end the TM-T88IV to VII go offline and do not run it. Its fixed bits differ from `DLE EOT`'s (bit 4 is 0, where `DLE EOT` has 1), so `Status.Apply` would refuse it; Epson's page also says to accept `0xx1xx10`, contradicting its own table. - `GS r 1` reports near-end on all three, but it is not real-time: it is answered after the printing before it has finished, and at paper end the TM-T88IV to VII go offline and do not run it. Its fixed bits differ from `DLE EOT`'s (bit 4 is 0, where `DLE EOT` has 1), so `Status.Apply` would refuse it; Epson's page also says to accept `0xx1xx10`, contradicting its own table.
WHAT "THE PRINTER FAILED" CAN MEAN WHAT "THE PRINTER FAILED" CAN MEAN
"Sent" means bytes the kernel took from `Write`. Whether they printed is unknowable without an acknowledgement (job-store phase 5). A text receipt of a few KB is usually taken whole at once, so a write error mostly shows on large image jobs or blocked or reset connections (an inference). "Sent" means bytes the kernel took from `Write`. With `printer.confirm = false`, whether they printed is unknowable without an acknowledgement (job-store phase 5). With `printer.confirm`, the default, the printer's answer to the `GS r 1` after the job says that it ran every byte, though the answer names no job, so design.md's residuals remain. A text receipt of a few KB is usually taken whole at once, so a write error mostly shows on large image jobs or blocked or reset connections (an inference).
| Signal | Bytes of the job sent | Printer at fault | | Signal | Bytes of the job sent | Printer at fault |
|---|---|---| |---|---|---|
@@ -336,10 +336,15 @@ WHAT "THE PRINTER FAILED" CAN MEAN
| A status check before the first byte (proposed), read again: offline, cover open, paper out, an error | none | yes | | A status check before the first byte (proposed), read again: offline, cover open, paper out, an error | none | yes |
| The same check shows near-end only | none | no: it still prints | | The same check shows near-end only | none | no: it still prints |
| The same check times out, or gets no or a malformed answer | none | unknown; a timeout is never a fault | | The same check times out, or gets no or a malformed answer | none | unknown; a timeout is never a fault |
| `printer.confirm`: no answer to the ready request (`DLE EOT 1`, `GS a 0`, `GS r 1`) within `write_timeout` (cover open, paper out, another host holding the printer, a printer stuck inside an earlier job) | none | yes, or held elsewhere |
| `printer.confirm`: the ready wait cut short by its deadline or the connection's end after an answer | none | unknown |
| `printer.confirm`: `DLE EOT 1` after the ready answer reports the printer offline, or goes unanswered | none | yes |
| `Write` fails having taken nothing | none | depends | | `Write` fails having taken nothing | none | depends |
| `Write` times out, or the connection resets, after part of the job | part | unknown, or yes | | `Write` times out, or the connection resets, after part of the job | part | unknown, or yes |
| The dial succeeds while another host holds the printer; a small job's `Write` returns | all, held | unknown: it may print when the other host lets go | | The dial succeeds while another host holds the printer; a small job's `Write` returns | all, held | unknown: it may print when the other host lets go |
| `Write` returns, then the printer goes offline (cover, paper end); the data prints when the cause clears | all | yes, but failing over prints it twice | | `Write` returns, then the printer goes offline (cover, paper end); the data prints when the cause clears | all | yes, but failing over prints it twice |
| `printer.confirm`: the job written in full, then the answer to the `GS r 1` after it | all, run by the printer | no |
| `printer.confirm`: the job written in full, but no answer before the write deadline, or the connection fails | all; it may have printed in full, in part or not at all | unknown: the delivery is `uncertain`, neither retried nor failed over |
| A render error | none | no: a fault of the job, unless that printer's options cause it | | A render error | none | no: a fault of the job, unless that printer's options cause it |
WHERE THE REPORTS DISAGREE OR ARE UNSURE WHERE THE REPORTS DISAGREE OR ARE UNSURE
@@ -969,7 +974,7 @@ internal/app/uberbringer/server
internal/pkg/printer internal/pkg/printer
- printer.go: - printer.go:
- `readStatus(ctx, conn)`: the `DLE EOT` reads on an open connection. `Status` calls it after `connect`; the checked send calls it on its own connection, so it never waits on its own slot. `GS r 1`, once stage 4a adds it, belongs to `Status` alone. - `readStatus(ctx, conn)`: the `DLE EOT` reads on an open connection. `Status` calls it after `connect`; the checked send calls it on its own connection, so it never waits on its own slot. `GS r 1` belongs to `Send`'s ready wait and confirmation and, once stage 4a adds its near-end read, to `Status`; the checked send never asks it.
- `Settle(ctx, read, delay)` (name assumed): the read again of a not-ready answer, moved from server/handlers.go's `settledPrinterStatus`. `/healthz` passes `Client.Status` and its `HealthRecheckDelay`; the checked send passes a read over its own connection, and the 750-ms delay internal/app gives each lane. - `Settle(ctx, read, delay)` (name assumed): the read again of a not-ready answer, moved from server/handlers.go's `settledPrinterStatus`. `/healthz` passes `Client.Status` and its `HealthRecheckDelay`; the checked send passes a read over its own connection, and the 750-ms delay internal/app gives each lane.
- The checked send: after the dial and before `beforeWrite`, the settled read of decision 23. - The checked send: after the dial and before `beforeWrite`, the settled read of decision 23.
- `Send` returns an error type (`SendError`, name assumed) holding the count `Write` took, with a method `NothingWritten() bool`. - `Send` returns an error type (`SendError`, name assumed) holding the count `Write` took, with a method `NothingWritten() bool`.
@@ -1065,7 +1070,7 @@ First, before any code, with the owner's OK. These are status reads only, nothin
internal/pkg/escpos internal/pkg/escpos
- profile.go: `Model` and the status capabilities (decision 27); `LookupProfile` keeps the exact name. - profile.go: `Model` and the status capabilities (decision 27); `LookupProfile` keeps the exact name.
- status.go: the `GS r 1` request and its decoder (decision 28); decision 29's bits in `Status`, `Normalized()` and `Ready()`; the comment on the TM-T88VII. - status.go: the decoder of the `GS r 1` reply (decision 28), whose request is `escpos.TransmitStatusRequest`, as `Send` asks it. `Status` reads the reply through its connection's `line`, so a status block split across reads stays skipped, and leaves a missed answer to `Send`'s ready wait, which drops it with everything before its fence, or with its own answer; decision 29's bits in `Status`, `Normalized()` and `Ready()`; the comment on the TM-T88VII.
internal/pkg/printer internal/pkg/printer
- printer.go: `Status` sends `GS r 1` last when the profile says so, only when online and ready, under its own deadline, and closes the connection after a missed answer. If stage 3 has shipped, `readStatus`, which the checked send uses, stays `DLE EOT` only. - printer.go: `Status` sends `GS r 1` last when the profile says so, only when online and ready, under its own deadline, and closes the connection after a missed answer. If stage 3 has shipped, `readStatus`, which the checked send uses, stays `DLE EOT` only.
+2 -2
View File
@@ -401,7 +401,7 @@
"type": "string" "type": "string"
}, },
"finished_at": { "finished_at": {
"description": "finished_at is when the job was done or failed, or when a start found it uncertain.", "description": "finished_at is when the job was done, failed or found uncertain.",
"format": "date-time", "format": "date-time",
"type": "string" "type": "string"
}, },
@@ -428,7 +428,7 @@
"type": "string" "type": "string"
}, },
"status": { "status": {
"description": "status 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.", "description": "status 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.",
"enum": [ "enum": [
"queued", "queued",
"printing", "printing",
+49
View File
@@ -17,6 +17,7 @@ import (
"go.jetify.com/typeid" "go.jetify.com/typeid"
"uberbringer/internal/pkg/config" "uberbringer/internal/pkg/config"
"uberbringer/internal/pkg/escpos"
"uberbringer/internal/pkg/jobstore" "uberbringer/internal/pkg/jobstore"
"uberbringer/internal/pkg/printqueue" "uberbringer/internal/pkg/printqueue"
) )
@@ -154,6 +155,54 @@ func seedSending(t *testing.T, dir, text string) string {
return id.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 // A job store that cannot be opened stops the start with an error naming
// its file, rather than starting empty. // its file, rather than starting empty.
func TestRunRefusesAStoreItCannotOpen(t *testing.T) { 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) renderer := receipt.NewRenderer(options, fetcher)
printerClient := printer.NewClient( printerClient := printer.NewClient(
net.JoinHostPort(cfg.Printer.Address, strconv.Itoa(cfg.Printer.Port)), 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{ queue := printqueue.New(renderer, printerClient, store, logger, printqueue.Options{
Size: cfg.Queue.Size, Size: cfg.Queue.Size,
History: cfg.Queue.History, History: cfg.Queue.History,
+22 -2
View File
@@ -19,11 +19,16 @@ import (
"time" "time"
"uberbringer/internal/pkg/config" "uberbringer/internal/pkg/config"
"uberbringer/internal/pkg/escpos"
"uberbringer/internal/pkg/printqueue" "uberbringer/internal/pkg/printqueue"
"uberbringer/internal/pkg/receipt" "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 { type fakePrinter struct {
mu sync.Mutex mu sync.Mutex
data bytes.Buffer data bytes.Buffer
@@ -52,7 +57,22 @@ func startFakePrinterOn(t *testing.T, addr string) *fakePrinter {
} }
go func() { go func() {
defer conn.Close() 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() p.mu.Lock()
defer p.mu.Unlock() defer p.mu.Unlock()
p.data.Write(data) 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"} resp.Printer = printerHealth{Reachable: boolPtr(true), Status: "unknown"}
case errors.Is(err, context.DeadlineExceeded): case errors.Is(err, context.DeadlineExceeded):
// The printer did not answer within healthTimeout, typically because // The printer did not answer within healthTimeout, typically because
// it is still taking in a large job. Its state is unknown, so do not // a job holds its connection while it prints or waits for the
// claim it is healthy. // 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) s.logger.Warn("printer health check timed out", "err", err)
resp.Status = "unavailable" resp.Status = "unavailable"
resp.Printer = printerHealth{Status: "timeout"} resp.Printer = printerHealth{Status: "timeout"}
+13
View File
@@ -122,6 +122,18 @@ type PrinterConfig struct {
DialTimeout time.Duration `mapstructure:"dial_timeout"` DialTimeout time.Duration `mapstructure:"dial_timeout"`
WriteTimeout time.Duration `mapstructure:"write_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 // Retries is how many times a failed send is retried before the job is
// marked failed. // marked failed.
Retries int `mapstructure:"retries"` Retries int `mapstructure:"retries"`
@@ -394,6 +406,7 @@ func Default() Config {
CutFeed: 3, CutFeed: 3,
DialTimeout: 5 * time.Second, DialTimeout: 5 * time.Second,
WriteTimeout: 30 * time.Second, WriteTimeout: 30 * time.Second,
Confirm: true,
Retries: 3, Retries: 3,
RetryDelay: time.Second, 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", t.Errorf("defaults not applied: max_lines %d, box_line_spacing %d, cut_feed %d",
cfg.Format.MaxLines, cfg.Printer.BoxLineSpacing, cfg.Printer.CutFeed) 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" { 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) 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 || if def := config.Default(); cfg.WebServer.RateLimit != def.WebServer.RateLimit ||
cfg.Images.MaxBytes != def.Images.MaxBytes || cfg.Printer.Model != def.Printer.Model || 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.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.Format.Timezone != def.Format.Timezone || cfg.Format.TimeLayout != def.Format.TimeLayout ||
cfg.Ntfy.Format != def.Ntfy.Format || len(cfg.Ntfy.Markers) != 0 || cfg.Ntfy.Format != def.Ntfy.Format || len(cfg.Ntfy.Markers) != 0 ||
cfg.State != def.State || cfg.Queue != def.Queue || len(cfg.Ntfy.Subscriptions) != 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_WEBSERVER_TRUSTED_PROXIES", "10.0.0.1, 172.18.0.0/16")
t.Setenv("UBERBRINGER_NOT_A_KEY", "ignored") t.Setenv("UBERBRINGER_NOT_A_KEY", "ignored")
t.Setenv("UBERBRINGER_PRINTER_RETRIES", "") t.Setenv("UBERBRINGER_PRINTER_RETRIES", "")
t.Setenv("UBERBRINGER_PRINTER_CONFIRM", "false")
cfg, err := config.Load(path) cfg, err := config.Load(path)
if err != nil { if err != nil {
t.Fatalf("Load: %v", err) 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" { if cfg.Printer.Address != "env.lan" {
t.Errorf("Address = %q, want the environment's value", cfg.Printer.Address) t.Errorf("Address = %q, want the environment's value", cfg.Printer.Address)
} }
+48 -20
View File
@@ -69,7 +69,8 @@ const (
StateFailed State = "failed" StateFailed State = "failed"
// StateUncertain is a job that was being sent when the daemon stopped, // 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" StateUncertain State = "uncertain"
) )
@@ -77,9 +78,12 @@ const (
type Status struct { type Status struct {
// ID identifies the job. // ID identifies the job.
ID JobID `json:"id"` ID JobID `json:"id"`
// State is where the job is in its lifecycle. uncertain is a job that // State is where the job is in its lifecycle. done is a job the printer
// was being sent to the printer when the daemon stopped: it may have // confirmed it ran, or with printer.confirm off, one written to it in
// printed, and it is never sent again. // 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"` 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, // Source says where the job came from: print for POST /api/v1/print,
// module:<name> for a module route, e.g. module:ntfy, or // 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 // A failed job with sent_at reached the printer, and part of it may have
// printed; one without it never reached the printer. // printed; one without it never reached the printer.
SentAt *time.Time `json:"sent_at,omitempty"` SentAt *time.Time `json:"sent_at,omitempty"`
// FinishedAt is when the job was done or failed, or when a start found // FinishedAt is when the job was done, failed or found uncertain.
// it uncertain.
FinishedAt *time.Time `json:"finished_at,omitempty"` 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 // once it can write and before the first byte, and writes nothing when
// beforeWrite fails. Cancelling ctx stops the wait for the printer and // 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 // 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 { type Sender interface {
Send(ctx context.Context, data []byte, beforeWrite func() error) error 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. // Options configures a Queue.
type Options struct { type Options struct {
// Size is how many jobs may wait. // 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") logger.Info("job left queued: the daemon is stopping and nothing was sent")
return nil 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 { if err != nil {
return q.fail(storeCtx, d, attempts, err, logger) 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 return err
} }
logger.Info("job printed", "attempts", attempts) 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. // 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 { 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 return err
} }
logger.Error("job failed", "attempts", attempts, "err", cause) 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 return attempt - 1, fmt.Errorf("server shutting down after %d attempts: %w", attempt-1, last), nil
case err == nil: case err == nil:
return attempt, nil, nil return attempt, nil, nil
case attempt > q.options.Retries: case unconfirmed(err) || attempt > q.options.Retries:
return attempt, err, nil return attempt, err, nil
} }
last = err last = err
@@ -705,12 +729,13 @@ func (q *Queue) sending(ctx context.Context, d *delivery, attempt int) error {
return nil return nil
} }
// finish records d as done after attempts, or as failed with cause, and // finish records d in state, a final one, after attempts: done, failed
// drops in the same commit the jobs that retention lets go of. A failure // with cause, or uncertain, unconfirmed with cause. It drops in the same
// is synced, since a failed job rolled back to queued would print after a // commit the jobs that retention lets go of. A failure is synced, since a
// restart. Once a store error has stopped the queue it writes nothing and // failed job rolled back to queued would print after a restart. Once a
// returns that error. // store error has stopped the queue it writes nothing and returns that
func (q *Queue) finish(ctx context.Context, d *delivery, attempts int, cause error) error { // error.
func (q *Queue) finish(ctx context.Context, d *delivery, state StoredState, attempts int, cause error) error {
if err := q.stopped(); err != nil { if err := q.stopped(); err != nil {
q.release(d) q.release(d)
return err return err
@@ -718,9 +743,12 @@ func (q *Queue) finish(ctx context.Context, d *delivery, attempts int, cause err
q.mu.Lock() q.mu.Lock()
next := d.Delivery next := d.Delivery
q.mu.Unlock() q.mu.Unlock()
next.State, next.Attempts, next.FinishedAt = StoredDone, attempts, time.Now().UTC() next.State, next.Attempts, next.FinishedAt = state, attempts, time.Now().UTC()
if cause != nil { switch {
next.State, next.Error = StoredFailed, cause.Error() case state == StoredUncertain && cause != nil:
next.Error = cause.Error() + "; " + unconfirmedSend
case cause != nil:
next.Error = cause.Error()
} }
q.mu.Lock() q.mu.Lock()
@@ -868,7 +896,7 @@ func (q *Queue) shutdown(ctx context.Context) error {
storeCtx := context.WithoutCancel(ctx) storeCtx := context.WithoutCancel(ctx)
for _, d := range waiting { 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) return q.stop(err)
} }
} }
+65 -1
View File
@@ -5,6 +5,7 @@ import (
"errors" "errors"
"io" "io"
"log/slog" "log/slog"
"slices"
"strings" "strings"
"sync" "sync"
"testing" "testing"
@@ -23,10 +24,18 @@ func (f fakeRenderer) Render(_ context.Context, job receipt.Job) ([]byte, error)
return []byte(job.Elements[0].Text), nil 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 // fakeSender fails the first failures sends as a failed dial does, before
// beforeWrite. Then it calls beforeWrite, fails the next writeFailures // beforeWrite. Then it calls beforeWrite, fails the next writeFailures
// sends as a failed write does, and records data. script, while it lasts, // 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. // anything else goes on as above.
type fakeSender struct { type fakeSender struct {
mu sync.Mutex mu sync.Mutex
@@ -71,6 +80,9 @@ func (f *fakeSender) Send(_ context.Context, data []byte, beforeWrite func() err
return errors.New("connection reset") return errors.New("connection reset")
} }
f.sent = append(f.sent, string(data)) f.sent = append(f.sent, string(data))
if step == "unconfirmed" {
return unconfirmedError{}
}
return nil 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) { func TestRenderFailureIsNotRetried(t *testing.T) {
sender := &fakeSender{} sender := &fakeSender{}
q := newQueue(fakeRenderer{err: errors.New("image blocked")}, sender, printqueue.Options{Retries: 3}) 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" StoredDone StoredState = "done"
// StoredFailed: given up; reached the printer only if SentAt is set. // StoredFailed: given up; reached the printer only if SentAt is set.
StoredFailed StoredState = "failed" StoredFailed StoredState = "failed"
// StoredUncertain: found in StoredSending at a start, so it may have // StoredUncertain: found in StoredSending at a start, or written in full
// printed. It is never sent again. // without the printer confirming it, so it may have printed. It is never
// sent again.
StoredUncertain StoredState = "uncertain" StoredUncertain StoredState = "uncertain"
) )
+7 -4
View File
@@ -21,10 +21,13 @@ Restart=on-failure
RestartSec=5 RestartSec=5
LimitNOFILE=4096 LimitNOFILE=4096
# TimeoutStopSec= stays at systemd's default, 90 s. A stop lets a receipt # TimeoutStopSec= stays at systemd's default, 90 s. A stop lets a receipt
# already being written to the printer finish, which takes up to # already being written to the printer finish. With state.dir set, that takes
# printer.write_timeout (30 s) and two commits; keep any lower timeout above # up to printer.write_timeout (30 s) and two commits: keep any lower timeout
# write_timeout plus 10 s, or the stop kills the write and leaves its job # above write_timeout plus 10 s, or the stop kills the write and leaves its job
# uncertain. # uncertain. Without state.dir, the job being sent runs on from its rendering,
# image fetches included, through its dial and the wait for the printer to be
# ready, up to the job's 2-minute cap: keep the default there, or set
# state.dir.
# ── Privileges ──────────────────────────────────────────────────────────────── # ── Privileges ────────────────────────────────────────────────────────────────
# The daemon binds an unprivileged port, dials the printer over TCP and fetches # The daemon binds an unprivileged port, dials the printer over TCP and fetches