Add ntfy subscriptions with digests, quiet hours and a cut feed
Security / Vulnerability check (push) Successful in 40s
Test / Lint and test (push) Failing after 6m43s

[[ntfy.subscriptions]] tables make the daemon subscribe to ntfy topics
itself and print each message as a notification card, so the phone's
ntfy app is the only client. Each subscription is one ntfy.Subscriber in
the daemon's errgroup: one event loop owns its state, and one goroutine
per connection reads the JSON stream. internal/app hands its messages to
modules.FromNtfy, Card, Validate and Submit with the source ntfy:<name>
and the message's ID as ref, so ntfy never imports modules.

The cursor is ntfy server time, never an ID. ntfy sends open before the
replay, so only keepalives and messages dealt with move it, and a
reconnect asks for two minutes before it, since a message is dated
before its attachment is stored. The IDs of the messages a replay could
send again are kept, at least the last 512 and 20,000 at most, so a
flood in the overlap never reprints; when the cap forgets IDs a replay
could send, the floor rises past them. A saved floor bounds replays: a
first start sets it to the open event's time, and max_backlog (default
1h, at most 12h), measured by the server's clock as each connection
tells it (its open event, else its Date, then the monotonic clock), never the
host's, so replays are requested unclamped and filtered as they arrive,
raises it when it clamps, so what it left out stays out. The
state, with the held messages and the receipt times, is written
atomically at most once a second and at shutdown. Redirects are never
followed, so credentials never go to another address or over plain http.
A stalled stream reconnects after twice the keepalive plus 15 s,
failures back off 5 to 120 s with jitter, a 429 waits for Retry-After,
and refused credentials, checked at startup through /auth, show as
unauthorized and retry every 5 minutes. A full print queue pauses
reading and retries the message from 1 s to 30 s, and the cursor moves
past it only once it is queued.

The paper budget is a strict window: at most rate_limit receipts (5) in
any rate_window (10m), digests included; the rest are held and print on
one digest card once there is room, and outside quiet hours
bypass_priority (5) and above print at once. Quiet hours hold everything
below their min_priority for one Overnight digest when the window ends,
or drop it; windows cross midnight and keep their times of day when
clocks change, also where the change skips midnight or a window's end.
A message whose sequence printed before, on a card or a digest row, is marked
(updated), or skipped with ntfy.format.updates = "skip"; the first of a
sequence its publisher named prints plain.

/healthz lists the subscriptions without changing how its status code is
decided, and no credential, topic or message text reaches it, the logs
or a config error. Subscriptions come from the file only, with strict
keys and per-entry defaults; credentials are optional, at most one kind.
ntfy.state_dir is required with a subscription: the unit gains
StateDirectory=uberbringer, install.sh writes the path into a new
config, and the Docker image sets it for a volume and runs as the fixed
user 10001. README explains how to lock a self-hosted ntfy server down
so that only your publishers can print.

Breaking: printer.cut_feed (default 3) feeds blank lines before every
cut, so the last line no longer sits right at the cut. They count toward
format.max_lines once per copy, so a job within 3 lines a copy of the
limit now fails. The renderer's option is 0 unless set, so the pinned
receipts keep their bytes.

testing/synctest drives the subscriber on a virtual clock, including a
24-hour soak with floods, repeats, refusals, a full queue, quiet hours
and a restart that fails on any leaked goroutine; it replaces a 24-hour
run on hardware. Tests over real sockets cover net/http's goroutines and
redirects to plain http and to another port.

Checked on the TM-T88IV against a live ntfy server: a phone message, quiet
hours with priorities 3 and 5 and the Overnight digest, a stale cursor, a
30-minute outage with an update, a wrong token, and the three-line cut
feed. The digest and the cut-feed card are pinned in TestPaperReceipts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
57_WolveandClaude Opus 5.5 committed 2026-11-30 17:50:23 -06:00
1 parent 1335ed0687
commit fb76284129
52 files changed
+6464 -390

No files matched your search

+138 -18
View File
@@ -43,6 +43,13 @@ client ─HTTPS─▶ Caddy ─▶ server ── validate ──▶ printqueue (
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
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`,
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.
They are `ESC d` lines rather than `GS V`'s extra motion units, because
a line is the same on every model while the motion unit is not. The
renderer's option is 0 unless set, so receipts whose bytes tests pin
keep their bytes; the daemon's default is 3.
- **Text in, code page out.** Clients send UTF-8, which is transcoded to
`printer.codepage`. The default is CP437, for the box drawing and shading
the owner prints (owner, 2026-11-29). Control characters are stripped, so
@@ -107,7 +114,7 @@ client ─HTTPS─▶ Caddy ─▶ server ── validate ──▶ printqueue (
and each module checks its own payload.
- **Notifications print as one card.** The `notify` and `ntfy` modules turn
their payloads into a `Notice` and lay it out with the same `Card`, which
phase 4's subscriber will use too.
the ntfy subscriptions use too.
- `ntfy` decodes leniently, so that messages from newer ntfy versions
still print, while `notify`, which scripts write by hand, is strict like
`note`. A message without an `event` counts as a message, so that a
@@ -182,8 +189,9 @@ client ─HTTPS─▶ Caddy ─▶ server ── validate ──▶ printqueue (
`raw` written in another letter case, which `encoding/json` would
match. A malformed scope can therefore never widen access.
- **Jobs remember their source.** `Submit` takes a `Meta`: the source
(`print`, `module:<name>`, later `ntfy:<subscription>`) and a reference,
the request ID on the HTTP routes. Job status shows the source and every
(`print`, `module:<name>` or `ntfy:<subscription>`) and a reference, the
request ID on the HTTP routes and the message's ID, or `digest`, for a
subscription. Job status shows the source and every
worker log line of the job carries both, so a printed receipt can be
traced to its request without logging what it says. The server copies
both strings, since a request ID the client sent lives in a buffer that
@@ -285,22 +293,133 @@ client ─HTTPS─▶ Caddy ─▶ server ── validate ──▶ printqueue (
the operator's own reverse proxy, whose address goes in
`webserver.trusted_proxies`.
- **ntfy subscriptions run in the daemon.** ntfy is an input: its
notifications are printed (owner, 2026-11-29). The owner's server is
self-hosted at a public URL and attachments come from a public host, so
image fetches need no private-network exception. Each
`[[ntfy.subscriptions]]` table is one `ntfy.Subscriber`, run as one
goroutine of the daemon's errgroup that never fails it: connection and
print failures are retried, and `Run` returns nil when the daemon stops.
The subscriber hands messages and digests to a handler in
`internal/app`, which builds them with `modules` and submits them, so
`ntfy` never imports `modules`.
- One connection per subscription reads `GET /<topics>/json` as a
stream: dial, TLS and header timeouts, no overall one. A loop owns all
state and one goroutine per connection reads lines, so the loop can
stop reading (TCP backpressure) while the print queue is full, and
every timer (reconnect, stall, retry, digest, save) is one deadline
in it.
- The cursor is ntfy server time, never `since=<id>`: an unknown or
expired ID makes ntfy replay the topic's whole history. ntfy sends
`open` before the replay, so only a keepalive or a dealt-with message
moves the cursor, except on a first start without `since`, where
nothing is replayed and `open`'s time is safe. ntfy dates a message
before it stores its attachment, so one can arrive after others dated
later; a reconnect therefore asks for two minutes before the cursor.
The IDs of the messages a replay could send again, those dated at or
after where a replay can start, are kept, so the repeats of a flood
drop, as do ntfy 2.31+'s same-second repeats; the last 512 are kept
anyway, and 20,000 in all at most. When that cap forgets IDs a replay
could still send, the floor rises past them.
- A saved floor bounds every replay from below. A first start sets it to
`open`'s time, so a reconnect soon after never reaches before the
start. `max_backlog`, at most ntfy's 12-hour cache, clamps a replay
by the server's clock, never the host's, so a host clock that is off,
or is stepped, can neither widen a replay nor lose messages. A
connection asks for its replay unclamped; its `open` event, which ntfy
sends first, before any replay, tells ntfy's own clock, the one it
dates messages by. The answer's `Date` stands in only when the open
event has no time, since a proxy in front of ntfy may write it from a
clock of its own. The time since the clock was read is measured on
the monotonic clock. The replay's messages
older than the backlog are then left out as they arrive. Each
connection learns the clock afresh, so nothing learned earlier, before
a step of the host's clock, carries over; keepalives do not count,
since they can wait in the connection while a full queue pauses
reading. The clamp raises the floor at once, so a later start with a
longer backlog never prints what it left out, even if no keepalive
came before the daemon stopped. An unclamped request after a long
outage costs only a larger replay, bounded by the server's cache.
- Redirects are never followed. Go would resend the credentials to the
same host over plain `http`, and a redirect to another host or port,
such as the printer's raw port, would carry the request there and
print what came back; a `3xx` is a failed connection whose error
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.
- State is one JSON file per subscription in `ntfy.state_dir`, written
atomically (temporary file, fsync, rename) at most once a second and
at shutdown, mode 0600 since held messages carry titles. A damaged
file means a fresh start with a warning. `state_dir` has no default,
since the daemon also runs on Windows; `install.sh` writes the unit's
`StateDirectory`, `/var/lib/uberbringer`, and the image sets the same
path.
- Credentials are optional, at most one kind, so that a long random
topic on a public server works without an account. Refused
credentials show at startup through `/<topics>/auth`, then as
`unauthorized` in `/healthz`, retried every five minutes. Failures
back off 5 s to 120 s with ±20% jitter, a `429` waits for its
`Retry-After`, and a stream silent for twice the keepalive plus 15 s
is reconnected.
- `/healthz` lists the subscriptions but its status code still depends
on the printer alone. `last_error` is built from the failure without
the request URL, which names the topics, and a topic on a public
server can be a secret.
- Which priorities print is set per subscription with `min_priority`
(default all), which the server filters by. How priorities 1 and 2
print, compact by default, is `ntfy.format.style`, shared by every
source of cards.
- Subscriptions come from the file only: a list of tables has no
environment variable, and each entry starts from its own defaults,
which Viper cannot give the entries of a list.
- **The paper budget is a strict window (owner, 2026-11-30).** At most
`rate_limit` receipts print in any `rate_window` (5 in 10 minutes by
default), digests included, so a flood never prints more than that,
even in its first minutes. Messages over it are held and print on one
digest once the window has room, and outside quiet hours, while a
digest is waiting, later messages join it, so they print in order.
Outside quiet hours, `bypass_priority` (5) and above print at once;
during them, `quiet.min_priority` decides first. The receipt times are
saved, so a restart cannot reset the budget. A digest lists 50
messages and counts the rest; only those with a row count as printed
for updates.
- **Quiet hours print a morning digest (owner, 2026-11-30).** During a
subscription's daily window only `quiet.min_priority` (5) and above
print; the rest are held in the same digest buffer and print as one
`Overnight` digest when the window ends, or are dropped with
`action = "drop"`. A window's bounds are the instants the zone's clocks
show its times of day, so a window crossing midnight or a change of
clocks keeps them. A bound the clocks skip is the first instant after
the gap, and one they show twice is the one Go's `time.Date` gives;
days are taken at noon, which every zone has. The zone defaults to
`format.timezone`, the zone the cards print in. Held messages are saved
with the state.
- **A subscription marks updates by what it printed (owner, 2026-11-30).**
A message is an update when its sequence (`sequence_id`, or its ID)
printed before, on a card or a digest row, among the last 512 sequences
remembered. So the first message of a sequence its publisher named
prints plain, and the routes, which remember nothing, never mark
updates. `ntfy.format.updates = "skip"` leaves updates out instead.
- **The subscriber is tested on a virtual clock (owner, 2026-11-30).**
`testing/synctest` runs it against an in-memory ntfy server:
reconnects, stalls, backoff, `Retry-After`, quiet nights across clock
changes and a 24-hour soak with floods, repeats, refusals, a full queue
and a restart, in seconds. `synctest.Test` fails if a goroutine
outlives the test, so the soak replaces a 24-hour leak run on
hardware; a short test over real sockets covers `net/http`'s own
goroutines. Both run in every `go test`.
## Planned: formatters
Modules, ntfy among them, that turn plain input into receipts built from the
blocks. The plan is `docs/plans/formatters.md`. Its first three phases are
blocks. The plan is `docs/plans/formatters.md`. Its first four phases are
built: the blocks and the preview; the `list` block, the module layer and
the `note` module; then the `notify` and `ntfy` modules and scoped tokens.
Next is the built-in ntfy subscriber. Decided so far (owner, 2026-11-29):
- ntfy is an input: its notifications are printed. The server is
self-hosted at a public URL, the subscriber authenticates with a token, and
attachments come from a public host, so image fetches need no
private-network exception.
- Which priorities print is configurable per subscription. By default every
priority prints, and priorities 1 and 2 print in a compact form.
- Labels are in English. The footer's time zone and date format come from
the config.
the `note` module; the `notify` and `ntfy` modules and scoped tokens; and
the ntfy subscriptions. What is left, phase 5, is built only when a need
appears. Labels are in English, and the footer's time zone and date format
come from the config (owner, 2026-11-29).
## Deferred
@@ -313,9 +432,10 @@ Next is the built-in ntfy subscriber. Decided so far (owner, 2026-11-29):
built):
- Jobs stored with GORM on SQLite, so queued jobs, statuses and history
survive a restart. Release builds use `CGO_ENABLED=0`, so the SQLite
driver must be pure Go (for example `github.com/glebarez/sqlite`), and the
systemd unit needs a `StateDirectory` because its file system is
read-only. The plan must also say how to tell which receipts printed
driver must be pure Go (for example `github.com/glebarez/sqlite`), and
the database belongs in the unit's `StateDirectory`,
`/var/lib/uberbringer`, the only directory it may write. The plan must
also say how to tell which receipts printed
before a crash, so a restart never prints a receipt twice.
- A print preview as an image: a digital test print of a job that shows
what the paper would look like, without printing. Formatters phase 1 adds