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

+74 -6
View File
@@ -20,6 +20,7 @@ the daemon.
- [`notify`](#notify)
- [`ntfy`](#ntfy)
- [Notification cards](#notification-cards)
- [Digests](#digests)
## API
@@ -68,7 +69,7 @@ included, carry `Cache-Control: no-store`.
| POST | `/api/v1/preview/:module` | Show the lines that receipt prints, without printing it |
| GET | `/api/v1/modules` | List the modules |
| GET | `/api/v1/jobs/:id` | Job status |
| GET | `/healthz` | Printer and queue health (no auth) |
| GET | `/healthz` | Printer, queue and subscription health (no auth) |
| GET | `/openapi.json` | This API's OpenAPI 3.1 document (no auth) |
| GET | `/` | Version information (no auth) |
@@ -131,8 +132,9 @@ curl -H @"$HOME/.uberbringer-auth" https://printer.example.com/api/v1/jobs/job_0
`status` is `queued`, `printing`, `done` or `failed`. A failed job includes an
`error` field. `source` says where the job came from: `print` for
`/api/v1/print`, or `module:<name>` for a [module](#modules) route. The last
`queue.history` finished jobs are kept.
`/api/v1/print`, `module:<name>` for a [module](#modules) route, or
`ntfy:<name>` for an [ntfy subscription](../README.md#ntfy-subscriptions)
in the config. The last `queue.history` finished jobs are kept.
### Preview a receipt
@@ -153,12 +155,16 @@ curl -X POST https://printer.example.com/api/v1/preview \
│ !!! ACHTUNG !!! │
└─────────────────────┘
[qr: https://example.com]
- - - - - - - partial cut - - - - - - - -
```
- The preview is read back from the bytes the job renders to, so it shows
what the printer receives: wrapping, folded characters, `?` for missing
ones and the final cut.
ones, the blank lines [`printer.cut_feed`](../README.md#configuration)
feeds before a cut (3 by default) and the final cut.
- Centred and right-aligned text is indented as the printer places it,
counted in Font A columns. Text at a larger size shows each character
once.
@@ -172,11 +178,12 @@ With `Accept: application/json` the answer carries the styles too. For
{"type": "qr", "data": "https://example.com"}]`:
```json
{"columns": 42, "codepage": "cp437", "line_count": 3,
{"columns": 42, "codepage": "cp437", "line_count": 6,
"lines": [{"kind": "text", "text": "Total ............................. £12.50",
"runs": [{"from": 0, "to": 5, "bold": true}, {"from": 36, "to": 42, "bold": true}]},
{"kind": "text", "text": " Thanks ?"},
{"kind": "qr", "text": "[qr: https://example.com]", "data": "https://example.com"},
{"kind": "text", "text": ""}, {"kind": "text", "text": ""}, {"kind": "text", "text": ""},
{"kind": "cut", "text": " - - - - - - - partial cut - - - - - - - -", "data": "partial"}],
"warnings": ["elements[1]: 1 character not in cp437 printed as ?"]}
```
@@ -210,6 +217,28 @@ when the worker renders it, before anything is sent; its `error` reads
A printer that accepts connections but does not answer status requests is
reported as `"status": "unknown"` with HTTP `200`.
With [ntfy subscriptions](../README.md#ntfy-subscriptions) configured, an
`ntfy` array lists each one, in the order of the config. The status code
still depends on the printer alone, so a subscription that cannot connect
never turns `/healthz` to `503`:
```json
"ntfy": [{"name": "home", "state": "connected", "connected_since": "2026-11-29T20:58:01Z",
"last_message_at": "2026-11-29T21:04:05Z", "printed": 12, "digested": 2, "held": 0, "last_error": ""}]
```
| Field | Meaning |
|-------|---------|
| `state` | `connecting`, `connected`, `backoff` while it waits to reconnect after a failure, or `unauthorized` when the server refused its credentials; it then tries again every five minutes |
| `connected_since` | When the current connection opened; absent while there is none |
| `last_message_at` | When the last message arrived; absent until one has |
| `printed` | Messages printed on a card of their own since the daemon started |
| `digested` | Messages held for a [digest](#digests) since the daemon started |
| `held` | Messages waiting for the next digest |
| `last_error` | Why the last connection failed, such as `HTTP 401: the server refused the credentials` or `no data for 1m45s`; empty once one opens |
Credentials, topic names and message text never appear.
Details:
- **Brief problems are re-checked.** A printer that looks not ready is read
@@ -282,7 +311,8 @@ rendered.
A job is `{"elements": [...], "copies": 1}`. `copies` is 1–5, and each copy is
cut separately. A partial cut is added after the last element unless that
element is already a `cut`. Boxes, rules, key-value rows and lists are
element is already a `cut`. Before every cut, `printer.cut_feed` blank lines
feed (3 by default), so that the last line does not sit right at the cut. Boxes, rules, key-value rows and lists are
described under [Blocks](#blocks).
### `text`
@@ -652,6 +682,9 @@ curl -X POST https://printer.example.com/api/v1/print/notify \
[qr: https://grafana.lan/d/disk]
Open dashboard
- - - - - - - partial cut - - - - - - - -
```
@@ -704,6 +737,9 @@ attachment expires:
Open dashboard
[image 384 dots: sPs71M8A2Tq9.png]
- - - - - - - partial cut - - - - - - - -
```
@@ -728,6 +764,8 @@ attachment expires:
- A message that updates an earlier one, with the same `sequence_id`,
prints as it is, like any other: one message cannot tell whether it is
the first of its sequence, since a publisher may choose the sequence ID.
An [ntfy subscription](../README.md#ntfy-subscriptions), which remembers
what it printed, marks such a message `(updated)`.
- A message over the [limits](#notify) of `notify` is not refused; what is
over them is cut or left out. A title, topic, tag, label or file name is
cut with `...`, and the message after 4096 bytes. Tags after the 20th are
@@ -850,6 +888,36 @@ bold, the message, then the topic and time. That is a bug: it is logged at
ERROR as `module printed its fallback receipt` and reported to Sentry, and
`uberbringer preview --module` prints a warning.
A card an [ntfy subscription](../README.md#ntfy-subscriptions) prints for
a message that replaces one it printed before, of the same `sequence_id`,
has `(updated)` after its title, unless `ntfy.format.updates = "skip"`
leaves such messages out.
#### Digests
An ntfy subscription prints the messages it held back on one digest: those
over its rate limit as soon as the limit has room again, and those held in
quiet hours when the window ends. A row gives each message's time, its tag
markers and its title, or the first line of a message without one, or else
its topic, cut to 60 characters, in the order they arrived; the bottom
border holds the time from the first held message to the digest.
```text
┌─ ntfy digest · 6 held ─────────────────┐
│ 21:05 [!] Disk almost full │
│ 21:05 [!] Disk almost full (updated) │
│ 21:06 (!) Backup FAILED on nas01 │
│ 21:07 Watchtower │
│ 21:07 Jellyseerr │
│ 21:09 [x] grafana is DOWN │
└───────────────────────── 21:04-21:14 ──┘
```
A digest that holds a message from quiet hours is titled
`Overnight · N held`. It lists 50 messages and counts the rest on a last
row, `... and 13 more`. A digest that cannot be laid out prints as a plain
list of its rows, logged and reported like a card's fallback.
#### Markers
Up to two tags with a marker print it in front of the title, each marker
+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
+14 -293
View File
@@ -1,314 +1,35 @@
# Plan: CP437 blocks, modules and ntfy printing
Status: **phases 1-3 are done**. Phase 1: box, rule and kv, text folding and the preview. Phase 2: the list block, the module layer, the note module and its routes, and `[format] timezone` and `time_layout`. Phase 3: the notify and ntfy modules and their cards, scoped tokens, optional images and job sources. All three are built and checked on paper (docs/api.md § Blocks and § Modules, design.md). Phases 4-5 are not started. Every design decision for phase 4 is made; the open questions left are config values and the second printer. Each phase runs in its own session, briefed from its section.
## Decisions (owner, 2026-11-29)
- **ntfy server:** self-hosted at a public URL. The subscriber authenticates
with a token. Attachments come from a public host, so no private-network
exception in safehttp is needed.
- **Which priorities print:** configurable per subscription (minimum priority,
and whether priorities 1-2 print in the compact form). Default: all
priorities, 1-2 compact.
- **Text folding on /print:** yes. Characters the code page lacks fold to
ASCII look-alikes (smart quotes, dashes, ellipsis) and an emoji sequence
prints as one '?'.
- **Language:** English labels ('URGENT', 'HIGH', 'Tags:', '... N more
lines'). Footer time zone and format come from config, default local time
and "02 Jan 15:04".
## Decisions (owner, 2026-11-30)
- **Links:** every link prints as a QR code: the click URL and the view
actions, deduplicated, at most 3. `[ntfy.format] qr` defaults to "all".
- **Image attachments** print (`images = true`).
- **Edited messages** print again, marked "(updated)" (`updates = "print"`).
- **Paper budget:** 5 receipts per 10 minutes per subscription by default,
configurable; the rest fold into one digest receipt. Priority 5 always
prints.
- **Quiet hours:** wanted, as a morning digest, and part of phase 4. During
a configured window only priority 5 prints; everything else is held and
printed as one digest receipt when the window ends. Window, days and time
zone come from config (default 22:00-07:00 every day, local time); off
unless configured.
## Overview
FOUNDATION
The plan starts from Design 1 (components): layout blocks inside the existing element list, small Go modules that turn a plain payload into an ordinary receipt.Job, and ntfy as one of those modules. It is cut down to the vocabulary that notes and notifications actually need:
- box, rule and kv in phase 1
- list in phase 2
Ideas taken from the other designs:
- From Design 2 (templates): fit boxes, a hand-written markdown subset with no new dependency, a plain fallback receipt, a since=<time> cursor, token scopes, and '?' warnings in preview.
- From Design 3 (sources): a simple Notice input (the notify module), images marked optional, a cursor taken from ntfy server time, the time/tzdata import, and Submit Meta for traceability.
WHAT SHIPS WHEN (about 5 developer days left to the end of phase 4)
1. Boxes and preview: done.
2. Notes and modules: done. POST /api/v1/print/note {title, text, items} prints a boxed checklist.
3. Notifications: done. POST /api/v1/print/notify {title, message, priority, tags} is for scripts and phone shortcuts. POST /api/v1/print/ntfy takes the ntfy CLI's $NTFY_RAW unchanged, so ntfy printing needs only a client.yml entry and no jq.
4. Built-in ntfy subscriber, 5 days. You only change the config. It reconnects safely, removes duplicates, caps the backlog, folds floods into a digest receipt, and holds non-urgent messages during quiet hours for a morning digest.
5. Later, on demand: the second-printer pool, user templates, an ntfy-compatible publish endpoint, table/banner/spans, and webhooks.
BACKWARD COMPATIBILITY
- Every existing element, field and response keeps its meaning, and /print stays strictly decoded.
- TestRenderCompat (receipt/testdata/compat) and TestPaperReceipts pin the bytes of existing jobs; later phases keep them passing.
- Emoji are removed only on the module and ntfy paths; /print prints an emoji sequence as one '?'.
WHERE THE JUDGES DISAGREED, AND WHAT THIS PLAN CHOSE
- list: in (phase 2), because the note module needs checklists.
- spans, table, group, banner, nested boxes and goldmark: deferred.
- Geometry checks in the HTTP handler (Renderer.Check): rejected. Layout never fails on a valid job, preview shows the result and line count synchronously, and each module caps its own length.
- Scoped tokens: built in phase 3; design.md records the decision.
- Quiet hours: phase 4, as a morning digest (owner decision).
Status: **phases 1-4 are done**: the blocks and the preview; the list block, the module layer and the note module; the notify and ntfy modules, their cards and scoped tokens; and the ntfy subscriptions, with their digest, paper budget and quiet hours. All four are built and checked on paper, and docs/api.md, README.md and design.md describe them. Phase 5 is a list of items built one at a time, each when a real need appears, in its own session briefed from its item.
## Open questions
Before phase 4 (config, not design):
1. Topics and auth: which topics and quiet-hours window to configure. A
dedicated read-only ntfy user with an access token is assumed.
When the second printer arrives:
2. Which jobs and ntfy topics go to which printer, and should urgent messages
print on both?
1. Which jobs and ntfy subscriptions go to which printer, and should urgent messages print on both?
## Mockups (42 columns, CP437)
## Rules for phase 5
The notification cards are built: docs/api.md § Notification cards shows
the four priority forms as they printed. Still to come:
BACKWARD COMPATIBILITY
- Every existing element, field and response keeps its meaning, and /print stays strictly decoded.
- TestRenderCompat (receipt/testdata/compat) and TestPaperReceipts pin the bytes of existing jobs; later work keeps them passing.
- Emoji are removed only on the module and ntfy paths; /print prints an emoji sequence as one '?'.
```text
All lines are at most 42 columns; every
glyph is a CP437 byte >= 0x20 (checked
with Python cp437). Ruler, not printed:
1 2 3 4
123456789012345678901234567890123456789012
--- 12. Rate-limit digest (phase 4)
┌─ ntfy digest · 6 held ─────────────────┐
│ 21:05 [!] Disk almost full │
│ 21:05 [!] Disk almost full (updated) │
│ 21:06 (!) Backup FAILED on nas01 │
│ 21:07 Watchtower │
│ 21:07 Jellyseerr │
│ 21:09 [x] grafana is DOWN │
└───────────────────────── 21:04-21:14 ──┘
One row per held message, in arrival
order. Priority 5 never waits.
Glyphs never used: • (only cp1252 has
it), ► ◄ → ← and other 0x01-0x1F
glyphs (printer control codes), emoji.
Use · ∙ ■ » √ ° instead.
```
## API
All /api/v1 routes keep the existing Bearer JWT, rate limiter and error shape {"error","details"}. Successful print responses keep today's 202 body plus a Location header:
{"id":"job_01kbx4n6m3ex8tq0wq3r5vrzq1","status":"queued","source":"print","created_at":"2026-11-29T21:04:05Z"}
==== PHASE 4: configuration ====
Keys go through internal/pkg/config as today: strict keys in the file, an UBERBRINGER_<SECTION>_<KEY> variable for each setting. [format] and the card settings [ntfy.format] and [ntfy.markers] are built (README § Configuration).
[ntfy.format]
updates = "print" # print | skip: a message replacing one the subscriber printed
[ntfy]
state_dir = "/var/lib/uberbringer"
[[ntfy.subscriptions]]
name = "home"
server = "https://ntfy.sh"
topics = ["alerts", "backups"] # ^[-_A-Za-z0-9]{1,64}$, at most 150
token_file = "/etc/uberbringer/ntfy.token" # or user + password_file; exactly one
min_priority = 3 # sent to ntfy as ?priority=3,4,5
max_backlog = "1h" # 12h at most (the ntfy cache)
rate_limit = 5 # receipts per rate_window; the rest go into one digest
rate_window = "10m"
bypass_priority = 5
keepalive = "45s"
[ntfy.subscriptions.quiet] # optional; quiet hours are off without this table
start = "22:00"
end = "07:00" # may cross midnight
days = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"]
timezone = "Local"
min_priority = 5 # prints during the window; the rest are held
action = "digest" # digest | drop; digest prints the held messages when the window ends
GET /healthz (phase 4) adds a field. The HTTP status still depends only on the printer:
"ntfy":[{"name":"home","state":"connected","connected_since":"2026-11-29T20:58:01Z","last_message_at":"2026-11-29T21:04:05Z","printed":12,"digested":2,"last_error":""}]
- state is one of connecting, connected, backoff or unauthorized.
- Tokens are never returned.
## Architecture
LAYERS (each calls only downward)
- server (Fiber v3 handlers) -> modules (payload to receipt.Job) -> receipt (blocks, layout, render, preview) -> escpos (bytes, code pages, interpreter).
- internal/pkg/ntfy holds the ntfy wire types (built) and the subscriber (phase 4). modules imports it for the Message type. serve.go connects the subscriber to modules through a callback, so ntfy never imports modules.
- printqueue takes Submit(job, Meta) (built).
DEFERRED UNTIL A NEED APPEARS
- spans, table, group, banner, nested boxes and goldmark.
- Geometry checks in the HTTP handler (Renderer.Check) stay rejected: layout never fails on a valid job, preview shows the result and line count synchronously, and each module caps its own length.
INVARIANTS (all match the current code)
1. receipt.Job stays printer-neutral. Blocks are sized at render time from Options.Columns or Profile.Columns(font). The same job therefore prints correctly on a TM-T88IV, TM-T88VII or TM-m50II, and on several printers later.
2. Job.Validate stays structural and independent of geometry, so handlePrint keeps its Validate-then-Submit flow. New checks:
- nested problem paths, e.g. elements[0].children[3]
- checkFields: a field that does not apply to a new type is an error
- child rules
- children count toward MaxElements (500)
- one level of nesting only
3. Layout never fails on a valid job. Widths clamp, titles are cut with "...", and over-long words split the way wrap() already splits them. The only new render-time failure is the [format].max_lines backstop (default 2000).
4. Renderer.Render is still the only path to printer bytes, and still all-or-nothing.
2. Job.Validate stays structural and independent of geometry, so handlePrint keeps its Validate-then-Submit flow.
3. Layout never fails on a valid job. Widths clamp, titles are cut with "...", and over-long words split the way wrap() already splits them. The only render-time failure is the [format].max_lines backstop (default 2000).
4. Renderer.Render is the only path to printer bytes, and is all-or-nothing.
5. New code never emits raw ESC/POS. Payload text only ever lands in string fields of elements. The raw element stays available on /print only, to tokens issued with --raw.
6. /print stays strictly decoded (DisallowUnknownFields). A byte-compatibility test pins today's bytes.
DATA FLOW
- /print: strict decode -> Validate -> Submit -> worker -> Render.
- Render runs Validate, normalize, layout, loadImages, then builds the bytes, and sends them in one write.
- /preview: strict decode -> Validate -> Renderer.Preview -> escpos.Interpret -> text/plain or JSON.
- Preview uses a placeholder fetcher, so no network.
- /print/{module}: module.Build(body, Env) -> Validate (a failure here is a module bug, 422) -> Submit(job, Meta{Source: "module:<name>"}).
- Subscriber (phase 4): ntfy stream -> skip, dedupe, filter, rate limit -> modules.FromNtfy -> Card -> Validate -> Submit(job, Meta{Source: "ntfy:<sub>", Ref: <ntfy id>}).
KEY TYPES (the blocks, the preview, the module layer, the notification card and the ntfy wire types are built; docs/api.md and design.md describe them)
modules (built)
type Notice; type CardOptions (zero value is the default; Env.Card carries it)
func FromNtfy(m ntfy.Message) (Notice, error) // ErrSkip for non-message events and base64 bodies
func Card(n Notice, o CardOptions, env Env) (receipt.Job, error) // the job always prints; a *FallbackError comes with the plain receipt, for the caller to log and report
ntfy
type Message, Action, Attachment // built
type Subscriber // phase 4
func (s *Subscriber) Run(ctx context.Context, handle func(context.Context, Message) error) error
printqueue (built)
Submit(job receipt.Job, meta Meta) (Status, error); type Meta struct{ Source, Ref string }; Status.Source
The subscriber marks and skips updates itself (Dedupe and state below); Card prints the notice it is given.
SUBSCRIBER (phase 4, internal/pkg/ntfy)
Connection
- One request per subscription: GET {server}/{t1,t2}/json?since=<S>&priority=<min..5>.
- Auth is Bearer tk_... or Basic. The User-Agent is generic.
- Dial, TLS and response-header timeouts apply, with no overall timeout, because the response is a stream.
Cursor
- The cursor C is ntfy server time in Unix seconds, and is persisted.
- At start: since=C when C is no older than max_backlog; otherwise since = now - max_backlog. With no saved state, since is left out, so only new messages print.
- since=<id> is never used. An unknown or expired id makes ntfy replay the topic's whole history.
- C moves to a message's time only once its Submit has succeeded (or the message was deliberately skipped). It moves to an open or keepalive event's time only when no message is waiting to be retried.
Dedupe and state
- A ring of the last 512 ids is persisted. It drops ntfy 2.31+ same-second repeats and the overlap after a reconnect.
- Updates: the sequence IDs of printed messages are remembered with the ids. A message whose sequence was printed before sets Notice.Updated, so its card shows "(updated)", or with updates = "skip" it is left out. The module routes print every message plain (design.md).
- State is JSON in state_dir, written as temp file, then fsync, then rename. It is written at most once a second, and on shutdown.
Reconnects
- If no line arrives for 2 × keepalive + 15 s (105 s by default), the subscriber reconnects.
- Backoff is 5, 10, 20, 30, 60, then 120 s, with ±20% jitter. It resets after 2 minutes connected.
- A 429 follows Retry-After.
- 401 or 403 sets the state to "unauthorized" and retries every 5 minutes.
- GET /{topic}/auth is called at startup so bad credentials show up early.
Queue full
- On ErrQueueFull the subscriber stops reading the stream (TCP backpressure is fine) and retries the same message, waiting from 1 s up to 30 s.
Rate limit
- A token bucket allows rate_limit receipts per rate_window.
- Messages over the limit go into one digest receipt, printed when tokens return. The digest holds 50 rows; after that, messages are only counted.
- Messages at or above bypass_priority skip the bucket.
Quiet hours
- During a subscription's quiet window, messages below quiet.min_priority are held (action = digest) or dropped (action = drop). Held messages share the digest buffer and print as one "Overnight" digest when the window ends.
Images and logging
- Attachment images are fetched through safehttp like any image URL; the ntfy server is public, so no private-network exception is needed.
- Logs carry the source, ntfy id and job id, never the message text. No notification content goes to Sentry, matching sentryMiddleware's existing rule of attaching no bodies.
7. Layers call only downward: server -> modules -> receipt -> escpos. ntfy never imports modules; internal/app connects the subscriptions to modules.
## Phases
### Phase 4: Built-in ntfy subscriber (5 days)
**Goal.** No client code and no extra programs: add [[ntfy.subscriptions]] to the config and the phone's ntfy app becomes the only client. Restarts and outages must not lose a flood's worth of paper or reprint old messages, and nothing but urgent messages prints during quiet hours.
**Work.**
internal/pkg/ntfy
- subscriber.go:
- The JSON-stream client, reading lines through bufio with a 1 MiB cap.
- The since cursor, the stall watchdog, backoff with jitter and Retry-After, the /auth precheck, and the unauthorized state.
- Run(ctx, handle).
- state.go: the cursor plus the 512-id dedupe ring, written atomically (temp file, fsync, rename), at most once a second and on shutdown.
- ratelimit.go: the token bucket plus the digest buffer, with an injectable clock.
- quiet.go: quiet hours. During the window, messages below min_priority are held (action = digest) or dropped (action = drop); held messages print as one digest when the window ends, sharing the digest buffer and its 50-row cap. Boundaries are computed with time.Date in the configured zone, so windows cross midnight and handle DST. Held messages are persisted with the cursor state, so a restart during the night does not lose them.
- status.go: snapshots for /healthz.
internal/pkg/modules
- digest.go: the digest card (mockup 12), titled "ntfy digest · N held" for rate-limit overflow and "Overnight · N held" for quiet hours.
internal/app/uberbringer
- serve.go: one group.Go(sub.Run) per subscription.
- handle does FromNtfy, Card, Validate, then queue.Submit with Meta{Source:"ntfy:<name>", Ref:id}.
- On ErrQueueFull it retries and pauses the stream. If formatting fails, it prints the fallback receipt.
- Run returns nil on cancel and never fails the errgroup on temporary errors.
internal/pkg/config
- [ntfy] state_dir and [[ntfy.subscriptions]], with validation:
- unique names
- https unless allow_insecure is set
- the topic regex, at most 150 topics
- exactly one of token, token_file, or user + password_file
- max_backlog of 12h or less
- rate_limit greater than 0 (default 5 per 10m)
- quiet: start and end as HH:MM, known day names, a loadable time zone, min_priority 1-5, action digest or drop
- a warning when the token file can be read by group or others
internal/app/uberbringer/server
- /healthz gains the ntfy array without changing how the status code is decided.
Deployment
- install.sh: StateDirectory=uberbringer in the unit, because ProtectSystem=strict makes /var/lib read-only otherwise. Also write [ntfy] state_dir.
- Dockerfile and README: document a /var/lib/uberbringer volume.
- README: a Subscriber section with ntfy.sh security advice (a reserved or access-controlled topic, or a long random name, plus a dedicated read-only ntfy user).
**Tests.**
internal/pkg/ntfy (fake clock and fake sleeper)
Use an httptest server that streams NDJSON open, keepalive and message events. Cases:
- first start sends no since
- reconnect after EOF uses since=<cursor>
- a stored cursor older than max_backlog is clamped
- a stall triggers a reconnect after 2×keepalive+15s
- backoff follows its sequence and resets after a stable connection
- 429 honours Retry-After
- 401 sets the unauthorized state
- same-second duplicates and reconnect overlap are deduped, also after the state is reloaded from disk
- the cursor never advances past a message whose Submit failed (ErrQueueFull)
- the state file survives a restart, and a partial or corrupt file is treated as no state with a warning
- multi-topic URLs
- min_priority is sent as the priority filter
- the rate limit sends overflow to a digest, priority 5 bypasses it, and the digest caps at 50 rows
- quiet hours: a window crossing midnight, a DST change night, priority 5 printing during the window, held messages printed as one digest at the window's end, action = drop, and held messages surviving a restart
internal/pkg/config
- Table tests for every validation rule.
internal/app/uberbringer/server
- /healthz shows subscription status, and the status code is unchanged when ntfy is down.
Logs
- A test logger asserts no message text is logged.
**Done when.**
- A message published from the phone prints within a few seconds.
- Stopping uberbringer for 30 minutes while messages are published, then starting it, prints each missed message once (or one digest), with no reprints.
- A stored cursor older than max_backlog never replays older messages.
- A wrong token shows state 'unauthorized' in /healthz while printing keeps working.
- With quiet hours set a few minutes ahead, a priority 3 message published inside the window prints only in the digest at its end, while a priority 5 message prints at once.
- A 24-hour run shows no leaked goroutines.
- The full gate passes (CLAUDE.md lists it).
### Phase 5: Later, on demand (1-3 days each; build only when a real need appears)
**Goal.** Keep the core small. Each item below is independent and waits for real demand or an owner decision.
+65 -4
View File
@@ -294,6 +294,13 @@
"HealthResponse": {
"description": "HealthResponse is the body of GET /healthz.",
"properties": {
"ntfy": {
"description": "ntfy is the state of each ntfy subscription, in the order of the config; absent when none is configured.",
"items": {
"$ref": "#/components/schemas/NtfyHealth"
},
"type": "array"
},
"printer": {
"$ref": "#/components/schemas/PrinterHealth",
"description": "printer is the printer's state."
@@ -303,7 +310,7 @@
"description": "queue is the print queue's state."
},
"status": {
"description": "status is ok, degraded when the printer is not ready, or unavailable when it is unreachable or did not answer in time.",
"description": "status is ok, degraded when the printer is not ready, or unavailable when it is unreachable or did not answer in time. It depends on the printer alone.",
"enum": [
"ok",
"degraded",
@@ -407,7 +414,7 @@
"type": "string"
},
"source": {
"description": "source says where the job came from: print for POST /api/v1/print, or module:<name> for a module route, e.g. module:ntfy.",
"description": "source says where the job came from: print for POST /api/v1/print, module:<name> for a module route, e.g. module:ntfy, or ntfy:<subscription> for an ntfy subscription in the config.",
"type": "string"
},
"started_at": {
@@ -462,6 +469,60 @@
"description": "ModulePayload is a module's payload: a JSON object whose fields the module defines, such as a note's title, text and items.",
"type": "object"
},
"NtfyHealth": {
"description": "NtfyHealth is the state of an ntfy subscription. It holds no credentials and nothing a message says.",
"properties": {
"connected_since": {
"description": "connected_since is when the current connection opened; absent while there is none.",
"format": "date-time",
"type": "string"
},
"digested": {
"description": "digested is how many messages were held for a digest since the daemon started: over the rate limit, or in quiet hours.",
"type": "integer"
},
"held": {
"description": "held is how many messages wait for the next digest.",
"type": "integer"
},
"last_error": {
"description": "last_error says why the last connection failed; empty once one opens.",
"type": "string"
},
"last_message_at": {
"description": "last_message_at is when the last message arrived; absent until one has.",
"format": "date-time",
"type": "string"
},
"name": {
"description": "name is the subscription's name from the config.",
"type": "string"
},
"printed": {
"description": "printed is how many messages printed on a card of their own since the daemon started.",
"type": "integer"
},
"state": {
"description": "state is connecting, connected, backoff while it waits to reconnect after a failure, or unauthorized when the server refused its credentials; it then tries again every five minutes.",
"enum": [
"connecting",
"connected",
"backoff",
"unauthorized"
],
"type": "string"
}
},
"required": [
"name",
"state",
"printed",
"digested",
"held",
"last_error"
],
"type": "object"
},
"OpenAPIDocument": {
"description": "OpenAPIDocument is the body of GET /openapi.json: this API's OpenAPI 3.1 document, generated from the route table.",
"properties": {
@@ -1679,7 +1740,7 @@
},
"/healthz": {
"get": {
"description": "Reads the printer's real-time status. A printer that looks not ready is read again 750 ms later, and only a problem that is still there gives 503. A printer that does not answer status requests is reported as status unknown with 200.",
"description": "Reads the printer's real-time status. A printer that looks not ready is read again 750 ms later, and only a problem that is still there gives 503. A printer that does not answer status requests is reported as status unknown with 200. The ntfy subscriptions, when any are configured, are listed with their state; the status code depends on the printer alone.",
"operationId": "getHealth",
"responses": {
"200": {
@@ -1717,7 +1778,7 @@
}
},
"security": [],
"summary": "Printer and queue health",
"summary": "Printer, queue and subscription health",
"tags": [
"health"
]