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

+30 -4
View File
@@ -13,12 +13,18 @@ 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.
- The Docker image sets `state.dir`, and the daemon now checks at start - With `state.dir` set, jobs still waiting when the daemon stops print
that it can write there, with or without ntfy subscriptions, so a after the next start, in order and however old, instead of being marked
container that cannot write `/var/lib/uberbringer` no longer starts: failed; after a crash they print too, instead of being forgotten. A
client that sends a failed job again at shutdown, or after a restart,
must stop doing so, or the receipt prints twice. Without `state.dir`
nothing changes. `install.sh` writes `state.dir` into new configs.
- The Docker image keeps its job store in `/var/lib/uberbringer`, its
`state.dir`, so a container that cannot write there no longer starts:
one started with `--read-only` and no volume there, or with a bind mount one started with `--read-only` and no volume there, or with a bind mount
owned by root. Mount a named volume there, or a directory owned by owned by root. Mount a named volume there, or a directory owned by
`10001:10001` (`docs/docker.md`). `10001:10001`, and stop the container with `--stop-timeout 40` so a
receipt being written can finish (`docs/docker.md`).
- A job with a `raw` element prints only with a token issued with - A job with a `raw` element prints only with a token issued with
`uberbringer token --raw`. Every other token, every token issued so far `uberbringer token --raw`. Every other token, every token issued so far
included, gets `403` `token_scope` for it and keeps every other route. included, gets `403` `token_scope` for it and keeps every other route.
@@ -34,6 +40,26 @@ version may break callers; such changes are listed under **Breaking**.
### Added ### Added
- Jobs survive a restart. With `state.dir` set, every job is kept in a job
store there, `jobs.db`, a SQLite database through the pure-Go
`modernc.org/sqlite`, and every kept status answers after a restart.
- A restart never prints a receipt twice: each attempt is recorded on
disk before its first byte goes to the printer, and a job caught
sending reads `uncertain` and is never sent again. Each job costs one
synced write, plus one per failure and per ntfy job; a job accepted
over HTTP can be lost to a power cut within about 30 seconds of its
`202`, but is never printed twice.
- A store that cannot be opened stops the daemon with an error naming
the file; `docs/install.md` and `docs/docker.md` say how to set it
aside. Only one daemon can use a state directory.
- The store holds what the receipts print. Its files are readable by the
daemon's user only, and the systemd unit gains `UMask=0077`.
- The armv6, armv7 and arm64 release builds ship the store untested on
ARM hardware. CI now cross-compiles the ARM targets on every push.
- Going back to 0.2.0 needs every key added since removed from the
config, such as `[state]`, `queue.content_bytes`, `printer.cut_feed`
and the `ntfy` tables: 0.2.0 refuses them as unknown. It never reads
`jobs.db`, so the jobs waiting there do not print.
- Notifications: - Notifications:
- The `notify` module prints a card from - The `notify` module prints a card from
`{"title", "message", "priority", "tags"}`, with `topic`, `click`, `{"title", "message", "priority", "tags"}`, with `topic`, `click`,
+3 -2
View File
@@ -1,8 +1,9 @@
# Überbringer # Überbringer
Notes for agents working in this repository. Überbringer is a single Go Notes for agents working in this repository. Überbringer is a single Go
binary. It takes JSON print jobs over a REST API (Fiber v3) and queues them in binary. It takes JSON print jobs over a REST API (Fiber v3) and queues them,
memory. It renders each job to ESC/POS and sends it over TCP port 9100 to one in memory or, with a state directory, in a SQLite job store on disk. It
renders each job to ESC/POS and sends it over TCP port 9100 to one
Epson receipt printer. It ships in two forms: as release tarballs, which Epson receipt printer. It ships in two forms: as release tarballs, which
`install.sh` installs behind Caddy, and as the Alpine image built from the `install.sh` installs behind Caddy, and as the Alpine image built from the
root `Dockerfile`. root `Dockerfile`.
+11 -5
View File
@@ -17,9 +17,10 @@ RUN CGO_ENABLED=0 go build -trimpath \
FROM alpine:3.24 FROM alpine:3.24
# ca-certificates for fetching https images, tzdata for local log times. # ca-certificates for fetching https images, tzdata for local log times.
# The user and group have the fixed ID 10001, so that files mounted from the # The user and group have the fixed ID 10001, so that files mounted from the
# host, such as an ntfy token file, can be given to it. /var/lib/uberbringer # host, such as an ntfy token file or a state directory, can be given to it.
# holds the state of the ntfy subscriptions; a named volume mounted there # /var/lib/uberbringer holds the job store and the state of the ntfy
# takes over its owner, so the daemon can write to it. # subscriptions; a named volume mounted there takes over its owner, so the
# daemon can write to it.
RUN apk add --no-cache ca-certificates tzdata \ RUN apk add --no-cache ca-certificates tzdata \
&& addgroup -S -g 10001 uberbringer \ && addgroup -S -g 10001 uberbringer \
&& adduser -S -D -H -u 10001 -G uberbringer -h /etc/uberbringer uberbringer \ && adduser -S -D -H -u 10001 -G uberbringer -h /etc/uberbringer uberbringer \
@@ -34,8 +35,13 @@ WORKDIR /etc/uberbringer
# Plain HTTP for a reverse proxy in front, which terminates TLS. Mount # Plain HTTP for a reverse proxy in front, which terminates TLS. Mount
# config.toml at /etc/uberbringer/config.toml, or set UBERBRINGER_CONFIG to "" # config.toml at /etc/uberbringer/config.toml, or set UBERBRINGER_CONFIG to ""
# and give the settings as UBERBRINGER_* variables. Either way, bind_ip must be # and give the settings as UBERBRINGER_* variables. Either way, bind_ip must be
# 0.0.0.0 and trusted_proxies must hold the proxy's address. Mount a volume on # 0.0.0.0 and trusted_proxies must hold the proxy's address. The daemon keeps
# /var/lib/uberbringer to keep the subscriptions' state across containers. # its jobs in /var/lib/uberbringer and does not start if it cannot write
# there. Mount a volume on it to keep the jobs and the subscriptions' state
# across containers; there is no VOLUME, so a new container never starts on
# an empty anonymous one unnoticed. Stop the container with a timeout above
# printer.write_timeout plus 10 s (--stop-timeout 40), so a receipt being
# written can finish.
ENV UBERBRINGER_CONFIG=/etc/uberbringer/config.toml \ ENV UBERBRINGER_CONFIG=/etc/uberbringer/config.toml \
UBERBRINGER_STATE_DIR=/var/lib/uberbringer UBERBRINGER_STATE_DIR=/var/lib/uberbringer
EXPOSE 8080 EXPOSE 8080
+2
View File
@@ -5,6 +5,8 @@ REST API and prints them on an EPSON ESC/POS network receipt printer.
- Jobs return at once with an ID and print in order on a background worker, - Jobs return at once with an ID and print in order on a background worker,
with retries while the printer is offline. with retries while the printer is offline.
- With a state directory, jobs are kept on disk: waiting jobs print after a
restart, and a restart never prints a receipt twice.
- UTF-8 text is transcoded to the printer's code page and wraps at word - UTF-8 text is transcoded to the printer's code page and wraps at word
boundaries for the paper width. boundaries for the paper width.
- Text styles and sizes, QR codes, barcodes, images and raw ESC/POS. - Text styles and sizes, QR codes, barcodes, images and raw ESC/POS.
File diff suppressed because it is too large. Load diff
+6 -4
View File
@@ -141,10 +141,12 @@
content_bytes = 67108864 content_bytes = 67108864
[state] [state]
# The directory the ntfy subscriptions keep their state in, so that a # The directory of the job store, jobs.db, and of the ntfy subscriptions'
# restart neither prints a message twice nor loses one. Required with a # state, so that waiting jobs print after a restart, no receipt prints
# subscription. install.sh writes "/var/lib/uberbringer", and the Docker # twice, and a subscription neither prints a message twice nor loses one.
# image sets it with UBERBRINGER_STATE_DIR. # Empty keeps jobs in memory, and a stop fails the waiting ones. Required
# with a subscription. install.sh writes "/var/lib/uberbringer", and the
# Docker image sets it with UBERBRINGER_STATE_DIR.
dir = "" dir = ""
[images] [images]
+8 -1
View File
@@ -135,6 +135,13 @@ have printed; one without it never reached the printer.
`ntfy:<name>` for an [ntfy subscription](ntfy.md) `ntfy:<name>` for an [ntfy subscription](ntfy.md)
in the config. The last `queue.history` finished jobs are kept. in the config. The last `queue.history` finished jobs are kept.
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
waiting when the daemon stopped prints after it. A job that was being sent
to the printer when the daemon stopped reads `uncertain` from then on.
Without `state.dir`, jobs live in memory: a stop marks the waiting ones
failed, and after a restart every earlier ID answers `job_not_found`.
### Preview a receipt ### Preview a receipt
`POST /api/v1/preview` takes the same body as `/api/v1/print` and validates `POST /api/v1/preview` takes the same body as `/api/v1/print` and validates
@@ -283,7 +290,7 @@ Errors are JSON:
| 401 | `unauthorized` | `missing bearer token`, or `invalid or expired token`. Sent with `WWW-Authenticate` | | 401 | `unauthorized` | `missing bearer token`, or `invalid or expired token`. Sent with `WWW-Authenticate` |
| 403 | `token_scope` | The token does not allow the request: a token limited to modules on another route, e.g. `token is limited to modules ntfy, notify`, or a job with `raw` elements from a token issued without `--raw`, which lists them in `details`. See [tokens](#api) | | 403 | `token_scope` | The token does not allow the request: a token limited to modules on another route, e.g. `token is limited to modules ntfy, notify`, or a job with `raw` elements from a token issued without `--raw`, which lists them in `details`. See [tokens](#api) |
| 404 | `not_found` | Unknown route | | 404 | `not_found` | Unknown route |
| 404 | `job_not_found` | Unknown, expired or malformed job ID | | 404 | `job_not_found` | Unknown, expired or malformed job ID, or, without `state.dir`, one from before a restart |
| 404 | `module_not_found` | Unknown module, e.g. `module "notx" not found` | | 404 | `module_not_found` | Unknown module, e.g. `module "notx" not found` |
| 405 | `method_not_allowed` | Known route, wrong method, e.g. `DELETE /api/v1/print` with a valid token (without one, `/api/v1` answers `401` first). Sent with `Allow` | | 405 | `method_not_allowed` | Known route, wrong method, e.g. `DELETE /api/v1/print` with a valid token (without one, `/api/v1` answers `401` first). Sent with `Allow` |
| 408 | `request_timeout` | The request was not received in time | | 408 | `request_timeout` | The request was not received in time |
+5 -2
View File
@@ -19,8 +19,11 @@ run without a file.
## The daemon ## The daemon
`uberbringer` with no command runs the daemon. It shuts down gracefully on `uberbringer` with no command runs the daemon. It shuts down gracefully on
SIGINT/SIGTERM: a receipt that is already printing is finished, and jobs SIGINT/SIGTERM. With [`state.dir`](configuration.md#state), a receipt
still waiting are marked failed. already being written to the printer is finished, and every job that has
sent nothing yet stays queued and prints after the next start. Without
it, a receipt that is already printing is finished, and jobs still
waiting are marked failed.
## secret ## secret
+41 -2
View File
@@ -174,13 +174,44 @@ Quiet hours are off unless the subscription has a
|-----|---------|---------| |-----|---------|---------|
| `size` | `100` | Jobs that may wait to print; more get `503` `queue_full` | | `size` | `100` | Jobs that may wait to print; more get `503` `queue_full` |
| `history` | `1000` | Finished jobs whose status is kept; an older job's ID answers `404` `job_not_found` | | `history` | `1000` | Finished jobs whose status is kept; an older job's ID answers `404` `job_not_found` |
| `content_bytes` | `67108864` | The bytes of finished jobs' content kept, newest first, each job as its JSON: 64 MiB, at most 1 GiB (`1073741824`). Jobs not yet finished keep theirs whatever the total, and so do `uncertain` jobs while their status is kept. The content is kept in memory | | `content_bytes` | `67108864` | The bytes of finished jobs' content kept, newest first, each job as its JSON: 64 MiB, at most 1 GiB (`1073741824`). Jobs not yet finished keep theirs whatever the total, and so do `uncertain` jobs while their status is kept. The content is kept in the [job store](#state) with `state.dir`, and in memory without it |
### state ### state
| Key | Default | Meaning | | Key | Default | Meaning |
|-----|---------|---------| |-----|---------|---------|
| `dir` | none | The directory the [ntfy subscriptions](#ntfy-subscriptions) keep their state in, one `ntfy-<name>.json` file each, readable by the daemon's user only. Required with a subscription, and never only spaces. When it is set, the daemon creates it, readable by its user only, if it is missing, and does not start if it cannot write there. `install.sh` and the Docker image set it to `/var/lib/uberbringer` | | `dir` | none | The directory of the job store, `jobs.db`, and of the [ntfy subscriptions](#ntfy-subscriptions)' state, one `ntfy-<name>.json` file each, all readable by the daemon's user only. Empty keeps jobs in memory. Required with a subscription, and never only spaces. When it is set, the daemon creates it, readable by its user only, if it is missing, and does not start if it cannot write there. `install.sh` and the Docker image set it to `/var/lib/uberbringer` |
With `state.dir`, the daemon keeps every job in the job store, `jobs.db`, a
SQLite database, with its log `jobs.db-wal` beside it:
- Jobs still waiting when the daemon stops or crashes print after the next
start, in order, however old, and every kept status answers after a
restart. A job that was being sent to the printer when the daemon stopped
reads `uncertain` and is never sent again
([api.md](api.md#job-status)). Without `state.dir`, waiting jobs are
marked failed when the daemon stops, and forgotten after a crash.
- A job accepted from the HTTP routes is written to disk within about 30
seconds, or sooner with the next job sent to the printer, so a power cut
just after its `202` can lose it, but never prints it twice. A job from
an ntfy subscription is on disk before it is queued.
- One daemon uses a directory at a time: a second one on it does not
start. No other program, the `sqlite3` command included, can read the
database while the daemon runs.
- The store holds what the receipts print, each job as its JSON, never a
token. Its files are readable by the daemon's user only, and the content
of a job that is gone can linger in the file's free pages until they are
reused. `queue.content_bytes` bounds how much content is kept.
- A store that cannot be opened, such as a damaged one, stops the daemon
with an error naming the file. [install.md](install.md#a-job-store-that-will-not-open)
and [docker.md](docker.md#a-job-store-that-will-not-open) say how to set
it aside.
- `jobs.db` and `jobs.db-wal` belong together: never delete the log, or
copy the database without it.
- Going back to 0.2.0: it refuses every key added since as unknown, such
as `[state]`, `queue.content_bytes`, `printer.cut_feed` and the `ntfy`
tables, so remove them first, and it never reads `jobs.db`, so the jobs
waiting in it do not print.
### images ### images
@@ -222,6 +253,14 @@ Request bodies and the `Authorization` header are never sent to Sentry.
`module:<name>` or `ntfy:<name>`) and its `ref`, the ID of the request or `module:<name>` or `ntfy:<name>`) and its `ref`, the ID of the request or
ntfy message that sent it, or a digest's own reference, never with what ntfy message that sent it, or a digest's own reference, never with what
it prints. it prints.
- With `state.dir`, a start that finds jobs in the store logs
`print queue restored` at INFO, with how many `jobs` it holds, how many
are `waiting` and how many are `uncertain`. Each job that was being sent
when the daemon stopped is logged at WARN once, by its `job_id`,
`printer`, `source` and `ref`: it may have printed and is not sent again,
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
start.
- 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
+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 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 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 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 installs are deployed. It is one static binary, which keeps its jobs in a
receipt rates on one printer. SQLite file of its own, sized for receipt rates on one printer.
```text ```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 │ │ receipt.Render: whole job
│ │ to bytes, images via safehttp │ │ 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. 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 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. geometry as the TM-T88IV, so a single profile default covers all three.
- **The queue lives in memory, on purpose.** ESC/POS gives no - **Jobs survive a restart, and a restart never prints a receipt twice
acknowledgement of what has printed. A queue replayed after a crash could (owner, 2026-11-30).** With `state.dir` set, the queue keeps its jobs in
therefore print a receipt twice. A lost job, by contrast, shows as failed `jobs.db` there; without it, they stay in memory, and waiting jobs fail
or unknown, and the client can send it again. Waiting jobs are marked at shutdown. One worker prints them in submission order, and statuses are
failed at shutdown. After a crash their IDs answer `job_not_found`. One kept for the last `queue.history` finished jobs.
worker keeps jobs in submission order, and the history is capped by - **What can be known.** A TCP write returns once the kernel has the
`queue.history`. 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` - **Render, then send.** The handler validates the whole job, and a `400`
lists every problem. The worker then renders the complete receipt, images lists every problem. The worker then renders the complete receipt, images
included, to one byte stream that starts with a printer reset (ESC @). It 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. says to set the address it points to.
- The cursor moves past a message only once it is queued, held or - 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 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 daemon stops waits in the job store, which every subscription has,
memory, because ESC/POS cannot say what printed. 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 - State is one JSON file per subscription in `state.dir`, written
atomically (temporary file, fsync, rename), mode 0600 since held atomically (temporary file, fsync, rename), mode 0600 since held
messages carry titles. A change a restart must see, such as a message 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. before anything is built. They come in this order.
1. **Job store and print previews**: `docs/plans/job-store.md` (written; 1. **Job store and print previews**: `docs/plans/job-store.md` (written;
the owner accepted every proposed default, 2026-12-01). the owner accepted every proposed default, 2026-12-01). The store is
- Jobs survive a restart in SQLite, through `modernc.org/sqlite` and built (Decisions, "Jobs survive a restart"); what is left:
`database/sql`, not GORM: WAL mode, one connection, exclusive - `GET /api/v1/jobs` lists the history, job status shows `ref`, and
locking. `jobs.db` lives in `[state] dir`, beside the ntfy state `/healthz` counts the jobs found `uncertain` at the latest start.
files; empty keeps the queue in memory. modernc's exact - `DELETE /api/v1/jobs/{id}` cancels a waiting job, for full tokens. An
`modernc.org/libc` is the one exception to "latest stable", held by ntfy `message_delete` cancels the waiting receipts of its
a gate check. notification (`Queue.Cancel`); `message_clear` does not, and the
- A job has one delivery per printer, each with its own state. A subscriber filters priorities itself. A cancel is synced, as a
delivery's `sending` mark is synced before its first byte, and one failure is.
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.
- A PNG preview draws the paper one pixel per dot, box drawing from - 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 the cell geometry and other glyphs from a bitmap font. Stored jobs
preview by ID. preview by ID.
+48 -10
View File
@@ -6,7 +6,9 @@ plain HTTP on port 8080, and the proxy terminates HTTPS.
```sh ```sh
docker build -t uberbringer . docker build -t uberbringer .
docker run -d -p 127.0.0.1:8080:8080 -v "$PWD/config.toml:/etc/uberbringer/config.toml:ro" uberbringer docker run -d -p 127.0.0.1:8080:8080 --stop-timeout 40 \
-v "$PWD/config.toml:/etc/uberbringer/config.toml:ro" \
-v uberbringer-state:/var/lib/uberbringer uberbringer
``` ```
The examples publish the port on the host's loopback address only, for a The examples publish the port on the host's loopback address only, for a
@@ -42,7 +44,8 @@ UBERBRINGER_PRINTER_ADDRESS=192.168.1.245
``` ```
```sh ```sh
docker run -d -p 127.0.0.1:8080:8080 --env-file uberbringer.env uberbringer docker run -d -p 127.0.0.1:8080:8080 --stop-timeout 40 --env-file uberbringer.env \
-v uberbringer-state:/var/lib/uberbringer uberbringer
``` ```
## Health checks ## Health checks
@@ -51,19 +54,54 @@ For container health checks, use `GET /` to see whether the daemon is up.
`/healthz` answers `503` while the printer is unreachable, so it suits `/healthz` answers `503` while the printer is unreachable, so it suits
alerting better than restarting the container. alerting better than restarting the container.
## ntfy subscriptions ## The state directory
[ntfy subscriptions](ntfy.md) keep their state in `/var/lib/uberbringer`, The image sets [`state.dir`](configuration.md#state) to
which the image sets as `state.dir`. The daemon does not start if it `/var/lib/uberbringer`, where the daemon keeps its job store, `jobs.db`,
cannot write there. Mount a volume there: without one the state lives in so that waiting jobs print after a restart, and where the
the container, and a new container, after a pull or an upgrade, forgets [ntfy subscriptions](ntfy.md) keep their state. The daemon does not start
what was printed and what was held. if it cannot write there.
- Mount a named volume there, as the examples do. A new container, after a
pull or an upgrade, then takes over the jobs and the subscriptions'
state. Without a volume they live in the container and are lost with
it, and a container started with `--read-only` does not start at all.
The image declares no `VOLUME`, so a container never starts on a fresh,
empty one unnoticed.
- A bind mount works too, if the directory is owned by the image's user:
`sudo chown 10001:10001 state && sudo chmod 700 state`. It must be on a
local file system: the store's write-ahead log does not work over a
network file system, and a Docker Desktop bind mount passes through a
file share of its VM. Use a named volume there.
- Stop the container with a timeout above `printer.write_timeout` plus
10 seconds, `--stop-timeout 40` at the defaults, so a receipt being
written to the printer can finish. Docker's default, 10 seconds, can
kill that write, and the job then reads `uncertain`.
- Two containers must never share the directory: the second does not
start.
### A job store that will not open
If `jobs.db` is damaged, or was written by a newer version, the container
stops at start with an error naming the file (`docker logs`). It does not
start with an empty store, which would forget the jobs still waiting and
which receipts may have printed. To set the store aside, with the
container stopped, move `jobs.db` and `jobs.db-wal` out of the volume
together, then start it again:
```sh ```sh
docker run -d -p 127.0.0.1:8080:8080 -v "$PWD/config.toml:/etc/uberbringer/config.toml:ro" \ docker stop <container>
-v uberbringer-state:/var/lib/uberbringer uberbringer docker run --rm -v uberbringer-state:/state -v "$PWD:/out" alpine \
sh -c 'mkdir -p /out/broken-store && mv /state/jobs.db* /out/broken-store/'
docker start <container>
``` ```
The jobs in the old store are forgotten, so check the last receipts on
paper against what was sent. The moved files hold what those receipts
printed: delete them once you no longer need them.
## ntfy subscriptions
Subscriptions are set in `config.toml` only, so a container with one needs Subscriptions are set in `config.toml` only, so a container with one needs
the file. The image runs as user and group `10001`, so give a token file the file. The image runs as user and group `10001`, so give a token file
to that ID, mode `600`, and mount it read-only next to the config: to that ID, mode `600`, and mount it read-only next to the config:
+40 -4
View File
@@ -30,10 +30,23 @@ sudo UBERBRINGER_VERSION=v0.2.0 ./install.sh <domain> <acme-email> <printer-addr
- The first API token is in `/etc/uberbringer/initial-token`: copy it to - The first API token is in `/etc/uberbringer/initial-token`: copy it to
your client, then delete the file. [security.md](security.md#issuing-tokens) your client, then delete the file. [security.md](security.md#issuing-tokens)
shows how to issue more. shows how to issue more.
- The service may write only to `/var/lib/uberbringer`, where the - The service may write only to `/var/lib/uberbringer`, where it keeps its
[ntfy subscriptions](ntfy.md) keep their state. A config the script job store, `jobs.db`, so that waiting jobs print after a restart, and
creates sets [`state.dir`](configuration.md#state) to it; add that where the [ntfy subscriptions](ntfy.md) keep their state. A config the
setting to an older config before adding a subscription. script creates sets [`state.dir`](configuration.md#state) to it. Re-runs
keep the config, so an older config without that setting keeps its jobs
in memory until you add it:
```toml
[state]
dir = "/var/lib/uberbringer"
```
- 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
lower it with `systemctl edit`, keep it above `printer.write_timeout`
plus 10 seconds (40 at the defaults); a stop that kills the write leaves
the job `uncertain`.
- 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`.
@@ -43,3 +56,26 @@ Re-running the script upgrades the install and keeps the config. After
editing the config, run `systemctl restart uberbringer`. After changing editing the config, run `systemctl restart uberbringer`. After changing
`webserver.body_limit`, `bind_ip` or `port`, re-run the script instead: it `webserver.body_limit`, `bind_ip` or `port`, re-run the script instead: it
copies them into Caddy's config. copies them into Caddy's config.
## A job store that will not open
If `/var/lib/uberbringer/jobs.db` is damaged, or was written by a newer
version, the service stops at start with an error naming the file
(`journalctl -u uberbringer`). It does not start with an empty store,
which would forget the jobs still waiting and which receipts may have
printed. To set the store aside and start afresh:
```sh
sudo systemctl stop uberbringer
sudo mkdir -p -m 0700 /var/backups/uberbringer
sudo sh -c 'mv /var/lib/uberbringer/jobs.db* /var/backups/uberbringer/'
sudo systemctl reset-failed uberbringer
sudo systemctl start uberbringer
```
This moves `jobs.db` and its log, `jobs.db-wal`, together; never move or
delete one without the other. The jobs in the old store are forgotten, so
check the last receipts on paper against what was sent. The moved files
hold what those receipts printed: delete them once you no longer need
them. `reset-failed` matters only once systemd has stopped restarting the
service after three failed starts in a minute.
+4 -3
View File
@@ -98,9 +98,10 @@ a volume for the state and the token file next to the config, as
- **Jobs.** Each card and digest is an ordinary job with the source - **Jobs.** Each card and digest is an ordinary job with the source
`ntfy:<name>` and a reference: a card's is its message's ID, and a `ntfy:<name>` and a reference: a card's is its message's ID, and a
digest's is its own, `digest_` and a TypeID. A card or digest whose digest's is its own, `digest_` and a TypeID. A card or digest whose
source and reference the queue already holds is not queued again. Like source and reference the queue already holds is not queued again. Each
any job, one that is still waiting when the daemon shuts down is marked is in the job store, in `state.dir`, before it is queued: one still
failed, and is not printed after the restart. waiting when the daemon stops or crashes prints after the restart, and
a message the restart replays prints once.
## Securing the topics ## Securing the topics
+2 -1
View File
@@ -211,7 +211,8 @@ write_config() {
address = "$PRINTER_ADDRESS" address = "$PRINTER_ADDRESS"
[state] [state]
# The unit's StateDirectory; ntfy subscriptions keep their state here. # The unit's StateDirectory: the job store and the ntfy subscriptions'
# state live here.
dir = "/var/lib/uberbringer" dir = "/var/lib/uberbringer"
EOT EOT
) )
File diff suppressed because it is too large. Load diff
+243
View File
@@ -0,0 +1,243 @@
package uberbringer
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"os"
"path/filepath"
"strings"
"testing"
"time"
"go.jetify.com/typeid"
"uberbringer/internal/pkg/config"
"uberbringer/internal/pkg/jobstore"
"uberbringer/internal/pkg/printqueue"
)
// daemon is a run of the daemon in a test, with a token for its API.
type daemon struct {
base string
token string
cancel context.CancelFunc
served chan error
}
// startDaemon runs the daemon on cfg until stop is called, and waits until
// it answers.
func startDaemon(t *testing.T, cfg *config.Config) *daemon {
t.Helper()
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = ln.Close() })
listen := func(context.Context, string) (net.Listener, error) { return ln, nil }
token, err := signToken([]byte(cfg.API.Secret), tokenSpec{subject: "test"}, time.Now())
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithCancel(context.Background())
d := &daemon{base: "http://" + ln.Addr().String(), token: token, cancel: cancel, served: make(chan error, 1)}
t.Cleanup(cancel)
go func() { d.served <- run(ctx, cfg, BuildInfo{Version: "test"}, io.Discard, listen, skipSync) }()
waitFor(t, func() bool {
resp, err := http.Get(d.base + "/")
if err != nil {
return false
}
resp.Body.Close()
return resp.StatusCode == http.StatusOK
})
return d
}
// stop shuts the daemon down and waits for it.
func (d *daemon) stop(t *testing.T) {
t.Helper()
d.cancel()
select {
case err := <-d.served:
if err != nil {
t.Fatalf("the daemon returned %v after shutdown", err)
}
case <-time.After(15 * time.Second):
t.Fatal("the daemon did not shut down")
}
}
// print sends a receipt of one line of text and returns its job's ID.
func (d *daemon) print(t *testing.T, text string) string {
t.Helper()
body := fmt.Sprintf(`{"elements":[{"type":"text","text":%q}]}`, text)
req, _ := http.NewRequest(http.MethodPost, d.base+"/api/v1/print", strings.NewReader(body))
req.Header.Set("Authorization", "Bearer "+d.token)
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
var queued struct{ ID string }
if err := json.NewDecoder(resp.Body).Decode(&queued); err != nil || resp.StatusCode != http.StatusAccepted {
t.Fatalf("POST /api/v1/print = %d, %v", resp.StatusCode, err)
}
return queued.ID
}
// jobStatus is the part of a job's status the tests read.
type jobStatus struct {
Status, Error string
}
// status returns the status of job id, or job_not_found's code.
func (d *daemon) status(t *testing.T, id string) jobStatus {
t.Helper()
req, _ := http.NewRequest(http.MethodGet, d.base+"/api/v1/jobs/"+id, nil)
req.Header.Set("Authorization", "Bearer "+d.token)
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
var st struct {
jobStatus
Code string
}
if err := json.NewDecoder(resp.Body).Decode(&st); err != nil {
t.Fatal(err)
}
if st.Code != "" {
return jobStatus{Status: st.Code}
}
return st.jobStatus
}
// seedSending stores a job whose delivery is in sending, as the daemon
// leaves one that dies while it writes the job to the printer.
func seedSending(t *testing.T, dir, text string) string {
t.Helper()
ctx := context.Background()
store, err := jobstore.Open(ctx, dir)
if err != nil {
t.Fatal(err)
}
defer func() {
if err := store.Close(); err != nil {
t.Error(err)
}
}()
id, err := typeid.New[printqueue.JobID]()
if err != nil {
t.Fatal(err)
}
now := time.Now().UTC()
r := printqueue.Record{
Seq: 100, ID: id, Source: "print", Ref: "req_seeded", CreatedAt: now,
Deliveries: []printqueue.Delivery{{Seq: 100, Printer: printqueue.DefaultPrinter, State: printqueue.StoredQueued}},
}
job := fmt.Sprintf(`{"elements":[{"type":"text","text":%q}]}`, text)
if err := store.Add(ctx, r, []byte(job), false); err != nil {
t.Fatal(err)
}
d := r.Deliveries[0]
d.Attempts, d.StartedAt, d.SentAt = 1, now, now
if err := store.Sending(ctx, d); err != nil {
t.Fatal(err)
}
return id.String()
}
// 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) {
stateDir := t.TempDir()
file := filepath.Join(stateDir, jobstore.FileName)
if err := os.WriteFile(file, bytes.Repeat([]byte("not a database "), 500), 0o600); err != nil {
t.Fatal(err)
}
cfg := testConfig(9100)
cfg.State.Dir = stateDir
err := run(context.Background(), cfg, BuildInfo{Version: "test"}, io.Discard, noListen(t), skipSync)
if err == nil || !strings.Contains(err.Error(), file) {
t.Errorf("run = %v, want an error naming %s", err, file)
}
}
// freePort returns a port on 127.0.0.1 that nothing listens on, so that a
// connection to it is refused until a listener takes it.
func freePort(t *testing.T) int {
t.Helper()
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
port := ln.Addr().(*net.TCPAddr).Port
if err := ln.Close(); err != nil {
t.Fatal(err)
}
return port
}
// TestServeRestart runs the daemon twice on one state directory. Jobs still
// queued when the first run stops print after the restart, ahead of a job
// sent after it, and their statuses answer; a job that was being sent when
// the daemon died reads uncertain and never reaches the printer.
func TestServeRestart(t *testing.T) {
stateDir := t.TempDir()
// The first run's printer refuses connections, so its jobs stay queued.
cfg := testConfig(freePort(t))
cfg.State.Dir = stateDir
cfg.Printer.RetryDelay = time.Minute
first := startDaemon(t, cfg)
one := first.print(t, "first receipt")
two := first.print(t, "second receipt")
first.stop(t)
seeded := seedSending(t, stateDir, "never sent again")
// The second run's printer comes up only once a new job is queued, so
// the restored jobs are still waiting when it arrives.
port := freePort(t)
cfg = testConfig(port)
cfg.State.Dir = stateDir
cfg.Printer.RetryDelay = 100 * time.Millisecond
cfg.Printer.Retries = 10
second := startDaemon(t, cfg)
if st := second.status(t, seeded); st.Status != "uncertain" || !strings.Contains(st.Error, "may have printed") {
t.Errorf("the job seeded in sending: %+v, want it uncertain", st)
}
three := second.print(t, "third receipt")
for _, id := range []string{one, two, three} {
if st := second.status(t, id); st.Status == "done" {
t.Fatalf("job %s printed before the printer was up", id)
}
}
printer := startFakePrinterOn(t, fmt.Sprintf("127.0.0.1:%d", port))
waitFor(t, func() bool { return second.status(t, three).Status == "done" })
for _, id := range []string{one, two} {
if st := second.status(t, id); st.Status != "done" {
t.Errorf("job %s: %+v after the restart, want done", id, st)
}
}
received := printer.received()
at := func(text string) int { return bytes.Index(received, []byte(text)) }
if !(at("first receipt") >= 0 && at("first receipt") < at("second receipt") && at("second receipt") < at("third receipt")) {
t.Errorf("the printer received %q, want the restored jobs in order, then the new one", received)
}
if at("never sent again") >= 0 {
t.Error("the job that was being sent was sent again")
}
if st := second.status(t, seeded); st.Status != "uncertain" {
t.Errorf("the seeded job: %+v, want it still uncertain", st)
}
second.stop(t)
}
+24 -3
View File
@@ -18,6 +18,7 @@ import (
"uberbringer/internal/app/uberbringer/server" "uberbringer/internal/app/uberbringer/server"
"uberbringer/internal/pkg/config" "uberbringer/internal/pkg/config"
"uberbringer/internal/pkg/escpos" "uberbringer/internal/pkg/escpos"
"uberbringer/internal/pkg/jobstore"
"uberbringer/internal/pkg/printer" "uberbringer/internal/pkg/printer"
"uberbringer/internal/pkg/printqueue" "uberbringer/internal/pkg/printqueue"
"uberbringer/internal/pkg/receipt" "uberbringer/internal/pkg/receipt"
@@ -75,10 +76,15 @@ func run(ctx context.Context, cfg *config.Config, build BuildInfo, out io.Writer
if err := prepareStateDir(cfg.State.Dir); err != nil { if err := prepareStateDir(cfg.State.Dir); err != nil {
return err return err
} }
subscribers, err := newSubscribers(cfg, logger, syncState) // The store locks its file, so a second daemon on the same directory
// stops here, before it reads the subscriptions' state files.
store, err := openStore(ctx, cfg.State.Dir)
if err != nil { if err != nil {
return err return err
} }
// This runs once run returns, after the group below, so the queue has
// stopped before the store closes.
defer closeStore(store, logger)
fetcher := safehttp.New(safehttp.Options{ fetcher := safehttp.New(safehttp.Options{
Timeout: cfg.Images.Timeout, Timeout: cfg.Images.Timeout,
@@ -90,8 +96,6 @@ func run(ctx context.Context, cfg *config.Config, build BuildInfo, out io.Writer
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)
store := printqueue.NewMemoryStore()
defer closeStore(store, logger)
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,
@@ -104,6 +108,10 @@ func run(ctx context.Context, cfg *config.Config, build BuildInfo, out io.Writer
if err := queue.Restore(ctx); err != nil { if err := queue.Restore(ctx); err != nil {
return err return err
} }
subscribers, err := newSubscribers(cfg, logger, syncState)
if err != nil {
return err
}
srv := server.New(server.Config{ srv := server.New(server.Config{
Info: server.Info{ Info: server.Info{
Project: Project, Project: Project,
@@ -256,6 +264,19 @@ func runQueue(ctx context.Context, queue *printqueue.Queue, logger *slog.Logger)
return nil return nil
} }
// openStore opens the job store in the state directory dir, or keeps jobs
// in memory when there is none.
func openStore(ctx context.Context, dir string) (printqueue.Store, error) {
if dir == "" {
return printqueue.NewMemoryStore(), nil
}
store, err := jobstore.Open(ctx, dir)
if err != nil {
return nil, err
}
return store, nil
}
// closeStore releases the job store once the daemon has stopped. // closeStore releases the job store once the daemon has stopped.
func closeStore(store printqueue.Store, logger *slog.Logger) { func closeStore(store printqueue.Store, logger *slog.Logger) {
if err := store.Close(); err != nil { if err := store.Close(); err != nil {
+7 -1
View File
@@ -32,7 +32,13 @@ type fakePrinter struct {
func startFakePrinter(t *testing.T) *fakePrinter { func startFakePrinter(t *testing.T) *fakePrinter {
t.Helper() t.Helper()
ln, err := net.Listen("tcp", "127.0.0.1:0") return startFakePrinterOn(t, "127.0.0.1:0")
}
// startFakePrinterOn starts a fake printer listening on addr.
func startFakePrinterOn(t *testing.T, addr string) *fakePrinter {
t.Helper()
ln, err := net.Listen("tcp", addr)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
+4 -3
View File
@@ -327,9 +327,10 @@ type QueueConfig struct {
// StateConfig configures where the daemon keeps what must survive a // StateConfig configures where the daemon keeps what must survive a
// restart. // restart.
type StateConfig struct { type StateConfig struct {
// Dir is the directory each ntfy subscription keeps its state in: its // Dir is the directory of the job store, jobs.db, and of each ntfy
// cursor, the IDs it has seen and the messages it holds. It has no // subscription's state: its cursor, the IDs it has seen and the
// default, and is required when a subscription is configured. // messages it holds. It has no default; empty keeps jobs in memory, and
// it is required when a subscription is configured.
Dir string `mapstructure:"dir"` Dir string `mapstructure:"dir"`
} }
+11 -4
View File
@@ -20,6 +20,11 @@ ExecStart=/usr/local/bin/uberbringer --config /etc/uberbringer/config.toml
Restart=on-failure Restart=on-failure
RestartSec=5 RestartSec=5
LimitNOFILE=4096 LimitNOFILE=4096
# TimeoutStopSec= stays at systemd's default, 90 s. A stop lets a receipt
# already being written to the printer finish, which takes up to
# printer.write_timeout (30 s) and two commits; keep any lower timeout above
# write_timeout plus 10 s, or the stop kills the write and leaves its job
# uncertain.
# ── 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
@@ -29,12 +34,14 @@ AmbientCapabilities=
NoNewPrivileges=true NoNewPrivileges=true
# ── Sandboxing ──────────────────────────────────────────────────────────────── # ── Sandboxing ────────────────────────────────────────────────────────────────
# The daemon reads its config and the system CA bundle, writes only the state # The daemon reads its config and the system CA bundle, writes only its job
# of its ntfy subscriptions and opens no devices. The file system is read-only # store and the state of its ntfy subscriptions, and opens no devices. The
# to it, apart from /var/lib/uberbringer, which systemd creates for the # file system is read-only to it, apart from /var/lib/uberbringer, which
# service user (state.dir). # systemd creates for the service user (state.dir). The store holds what the
# receipts print, so every file the daemon creates there is its user's alone.
StateDirectory=uberbringer StateDirectory=uberbringer
StateDirectoryMode=0700 StateDirectoryMode=0700
UMask=0077
ProtectSystem=strict ProtectSystem=strict
ProtectHome=true ProtectHome=true
PrivateTmp=true PrivateTmp=true