Keep print jobs on disk in state.dir

Breaking: with state.dir set, jobs still waiting when the daemon stops
or crashes print after the next start, in order and however old,
instead of being marked failed or forgotten; a client that resends such
jobs must stop. The Docker image sets state.dir, so a container keeps
its jobs in /var/lib/uberbringer, and loses them with the container
unless a volume is mounted there.

The owner decided that jobs survive a restart and that a restart never
prints a receipt twice. When state.dir is set, the daemon now opens the
SQLite job store there, jobs.db, and the queue restores it before the
subscriptions are made and before anything is served, so restored jobs
go ahead of new ones and a second daemon on the directory stops before
it reads the subscriptions' state. Without state.dir the queue keeps its
jobs in memory, as before. The store closes once the queue has stopped.

A job's sending mark is synced before its first byte, so one caught mid
write reads uncertain after the restart and is never sent again; a job
that had not reached the printer prints once. A store that cannot be
opened stops the start with an error naming the file, rather than
starting empty and forgetting which receipts are in doubt.

The unit gains UMask=0077, so the store's files are its user's alone,
and says why systemd's 90 s stop timeout is enough; the Dockerfile and
docs/docker.md ask for --stop-timeout 40. design.md replaces "The queue
lives in memory" with the store, the state machine, the sync policy,
store failures, stage 1a's numbers, and that the ARM builds ship the
store untested on ARM hardware. install.md and docker.md say how to set
aside a store that will not open; configuration.md, api.md, cli.md and
ntfy.md say what survives a restart. The license notices gain the
driver's modules.

TestServeRestart runs the daemon twice on one directory: jobs queued
when the first run stops, its printer refusing connections, print in
order after the restart, ahead of a new job, and a job seeded in sending
between the runs reads uncertain and never reaches the printer.

Part of stage 1d of docs/plans/job-store.md (decisions 14 and 15).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
57_WolveandClaude Opus 5.5 committed 2026-12-01 16:48:57 -06:00
1 parent 341353f702
commit 5cc4614ad7
20 files changed
+5144 -93

No files matched your search

+133 -44
View File
@@ -10,11 +10,12 @@ in docs/ describe how to use it.
Scripts and services on the owner's network send short JSON jobs, and one
Epson receipt printer prints them. The daemon replaces the 0.1 one on the
same endpoint, `POST /api/v1/print` behind a TLS reverse proxy, and 0.1
installs are deployed. It is one static binary with no database, sized for
receipt rates on one printer.
installs are deployed. It is one static binary, which keeps its jobs in a
SQLite file of its own, sized for receipt rates on one printer.
```text
client ─HTTPS─▶ Caddy ─▶ server ── validate ──▶ printqueue (memory, 1 worker)
client ─HTTPS─▶ Caddy ─▶ server ── validate ──▶ printqueue (1 worker) ◀──▶ jobstore
│ │ (SQLite, state.dir)
│ │ receipt.Render: whole job
│ │ to bytes, images via safehttp
│ ▼
@@ -29,13 +30,123 @@ client ─HTTPS─▶ Caddy ─▶ server ── validate ──▶ printqueue (
second printer means a second instance with its own config and port.
The planned TM-T88VII and TM-m50II (owner, 2026-11-29) have the same
geometry as the TM-T88IV, so a single profile default covers all three.
- **The queue lives in memory, on purpose.** ESC/POS gives no
acknowledgement of what has printed. A queue replayed after a crash could
therefore print a receipt twice. A lost job, by contrast, shows as failed
or unknown, and the client can send it again. Waiting jobs are marked
failed at shutdown. After a crash their IDs answer `job_not_found`. One
worker keeps jobs in submission order, and the history is capped by
`queue.history`.
- **Jobs survive a restart, and a restart never prints a receipt twice
(owner, 2026-11-30).** With `state.dir` set, the queue keeps its jobs in
`jobs.db` there; without it, they stay in memory, and waiting jobs fail
at shutdown. One worker prints them in submission order, and statuses are
kept for the last `queue.history` finished jobs.
- **What can be known.** A TCP write returns once the kernel has the
bytes, not once they print, so no store can record a receipt as
printed. Each attempt therefore commits its `sending` mark, synced,
after the printer's connection opens and before the first byte; if
that commit fails, the connection closes with nothing written. A dial
failure writes nothing, so a job retried while the printer is offline
stays safe to retry. At start, every delivery found in `sending` ends
`uncertain`, a status of its own, with an error saying it may have
printed, and one WARN line by its `job_id`, `printer`, `source` and
`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
leaves an `uncertain` receipt that never printed, the safe direction.
`queued` never reached the printer, `done` was written in full, and a
`failed` job reached it only if `sent_at` is set.
- **Deliveries.** A job has one delivery per printer, one for `default`
until several printers are configured, each with its own state,
attempts and times. A job's `status` derives from them: `queued` while
each waits untaken; `printing` while any is unfinished once one is
taken or finished; once all have finished, `uncertain` if any is, else
`failed` if any is, else `done`.
- **The sync policy.** The `sending` mark, a failure and the insert of
an ntfy job commit at `synchronous=FULL`; everything else commits at
NORMAL, and the next synced commit, since the log is appended in
order, or the kernel's writeback within about 30 s makes it durable. A
lost lazy write only weakens a status: a `done` rolled back to
`sending` reads `uncertain`, and a lost insert loses a job never sent.
`failed` is synced because, rolled back to `queued`, it would print
after its client was told it failed. A job from the HTTP routes may be
lost to a power cut within about 30 s of its `202`, but never prints
twice; syncing its insert would cost a second fsync per job. An ntfy
job's insert is synced, because the subscriber records its message as
handled within a second. So a job costs one fsync, plus one per
failure and per ntfy job.
- **Measured.** On leil-rig's test VM (AlmaLinux 9, xfs on a virtual
disk, the unit's sandbox), a text job of 1.5 KB took 1.04 device
flushes, 11.5 WAL frames and about 54 KiB of device writes, some 26 MiB
a day at 500 jobs. A synced commit took 2.9 ms (median, with
fdatasync; 5.0 ms with fsync) and a lazy one about 0.6 ms; an
automatic checkpoint came every 87 jobs. SD cards, ext4 and ARM are
unmeasured. A jobstore test logs the WAL frames per job and holds them
to a bound.
- **The store.** SQLite through `modernc.org/sqlite`, which is pure Go,
so release builds keep `CGO_ENABLED=0`, and `database/sql` with
hand-written statements. Not GORM: its pure-Go dialector has had no
release since 2024 and pulls in an older SQLite, its default logger
prints SQL with its values, which would log print contents, and it
adds about 10 MB to the binary where the driver adds 4 MB. A
home-grown journal would write fewer bytes, but SQLite handles torn
writes and recovery itself. bbolt rewrites whole pages with two
fdatasyncs per commit and cannot leave a commit unsynced safely, and
BadgerDB maps gigabytes and never syncs on Windows.
- One connection, held for the daemon's life, in WAL mode with
`locking_mode=EXCLUSIVE`: no `-shm` file and no memory map, and a
second daemon on the same directory fails at start. No other
process, the `sqlite3` CLI included, can read the file while the
daemon runs. Further pragmas: `temp_store=MEMORY`,
`journal_size_limit` 4 MiB, `secure_delete=FAST`, and
`auto_vacuum=NONE`, so the file levels off at its high-water mark.
Commits sync with fdatasync on Linux.
- `jobs` is written once per job; `deliveries` holds one row per
printer, the only rows a status change rewrites; `content` holds the
validated `receipt.Job` as JSON, never rendered bytes or a token,
apart from the statuses; `refs` holds the duplicate check's
references, pruned in the order they were kept, since job IDs need
not sort in that order once the clock is set back. Jobs,
deliveries and content are looked up by sequence number only, so
they have no indexes; `refs` has one, on its source and reference.
Statuses live in memory, loaded at start; the worker reads a job's
content when it takes it, and a stored job that no longer decodes
fails, logged by its ID.
- The store checkpoints while the queue is empty, once 64 commits,
about 20 jobs, have gathered since its last checkpoint, so SQLite's
own, at 1,000 pages, seldom delays a `sending` mark. Not after every
job: a checkpoint syncs the log and the database, and the next commit
syncs the log's header, three syncs more on a job that should cost
one.
- Open checks every page (`quick_check`), since SQLite would otherwise
meet a damaged page only mid-run, and refuses a schema newer than
the binary's.
- **Shutdown.** With the store, waiting jobs stay queued and print after
the next start, in order, however old. A job that has not reached
`sending`, still rendering, dialling or waiting to retry, stops and
stays queued. A write already under way finishes, so the stop timeout
must exceed `printer.write_timeout` plus about 10 s: systemd's 90 s
default does, and docs/docker.md asks for `--stop-timeout 40`. A kill
mid-write leaves its job `uncertain`. A job waiting to retry after an
attempt reached `sending` fails, its `sent_at` showing bytes went out.
- **Store failures (owner, 2026-12-01).** A store that cannot be opened
stops the daemon with an error naming the file. Starting empty would
forget the waiting jobs and which receipts are in doubt, so the
operator moves `jobs.db` and `jobs.db-wal` aside together
(docs/install.md, docs/docker.md). A damaged ntfy state file, by
contrast, means a fresh start with a warning. A store write that fails
once the daemon runs stops the queue and the daemon, logged and
reported to Sentry once; nothing is retried. Memory changes only after
a commit, so a job keeps the state the store last recorded, and one
that had not reached `sending` prints once after the restart.
- **Privacy.** Print contents now rest on disk: `jobs.db` and its log
are 0600 in a 0700 directory, the unit sets `UMask=0077`, and
`secure_delete=FAST` overwrites deleted rows where that costs no extra
writes; deleted content can still linger in free pages and the log
until they are reused. Content is kept by `queue.content_bytes`.
- **ARM.** The armv6, armv7 and arm64 release builds ship the store
untested on ARM hardware: the owner has none, modernc's CI names no
ARMv6 target, and older SIGSEGV reports for linux/arm exist. CI
cross-compiles them on every push.
- **Acknowledgement.** Epson documents one, `GS ( H` fn 48, answered
once a job has printed, which would turn most `uncertain` jobs into
confirmed prints. 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
it.
- **Render, then send.** The handler validates the whole job, and a `400`
lists every problem. The worker then renders the complete receipt, images
included, to one byte stream that starts with a printer reset (ESC @). It
@@ -382,8 +493,9 @@ client ─HTTPS─▶ Caddy ─▶ server ── validate ──▶ printqueue (
says to set the address it points to.
- The cursor moves past a message only once it is queued, held or
deliberately left out. A message queued but not yet printed when the
daemon stops is lost, as any waiting job is: the queue stays in
memory, because ESC/POS cannot say what printed.
daemon stops waits in the job store, which every subscription has,
since it needs `state.dir`, and prints after the restart; if the
restart replays it, the queue's duplicate check answers with its job.
- State is one JSON file per subscription in `state.dir`, written
atomically (temporary file, fsync, rename), mode 0600 since held
messages carry titles. A change a restart must see, such as a message
@@ -464,38 +576,15 @@ Each feature below has its own plan in `docs/plans/<feature>.md`, written
before anything is built. They come in this order.
1. **Job store and print previews**: `docs/plans/job-store.md` (written;
the owner accepted every proposed default, 2026-12-01).
- Jobs survive a restart in SQLite, through `modernc.org/sqlite` and
`database/sql`, not GORM: WAL mode, one connection, exclusive
locking. `jobs.db` lives in `[state] dir`, beside the ntfy state
files; empty keeps the queue in memory. modernc's exact
`modernc.org/libc` is the one exception to "latest stable", held by
a gate check.
- A job has one delivery per printer, each with its own state. A
delivery's `sending` mark is synced before its first byte, and one
found in `sending` at start ends `uncertain`, a new terminal status,
never sent again. Failures, cancels and ntfy jobs are synced too; an
insert from the HTTP routes is not, so a power cut can lose it but
never print it twice. A store write that fails mid-run stops the
daemon.
- Queued jobs print in order after a restart, however old. The store
keeps the validated job as JSON, never rendered bytes or tokens;
statuses are kept by `queue.history`, content within
`queue.content_bytes` (64 MiB).
- ntfy and webhook jobs are checked against the last 512 source and
reference pairs of their source, so a replay after a crash never
prints twice. A digest gets a reference of its own, saved before it
is submitted.
- A job's status derives from its deliveries: once all have finished,
`uncertain` over `failed` over `done`.
- The Docker image keeps a store in `/var/lib/uberbringer`
(**Breaking** for a container that cannot write there). CI builds
the ARM targets.
- `GET /api/v1/jobs` lists the history and `DELETE /api/v1/jobs/{id}`
cancels a waiting job, for full tokens. An ntfy `message_delete`
cancels the waiting receipts of its notification (`Queue.Cancel`);
`message_clear` does not, and the subscriber filters priorities
itself.
the owner accepted every proposed default, 2026-12-01). The store is
built (Decisions, "Jobs survive a restart"); what is left:
- `GET /api/v1/jobs` lists the history, job status shows `ref`, and
`/healthz` counts the jobs found `uncertain` at the latest start.
- `DELETE /api/v1/jobs/{id}` cancels a waiting job, for full tokens. An
ntfy `message_delete` cancels the waiting receipts of its
notification (`Queue.Cancel`); `message_clear` does not, and the
subscriber filters priorities itself. A cancel is synced, as a
failure is.
- A PNG preview draws the paper one pixel per dot, box drawing from
the cell geometry and other glyphs from a bitmap font. Stored jobs
preview by ID.