Breaking: a job with a raw element prints only with a token issued with uberbringer token --raw. Every other token, every existing one included, gets 403 token_scope for it, with the raw elements in details, and keeps every other route. The notify module prints a notification card from a title, message, priority and tags, with topic, click, up to three actions, image, markdown and time as options; it decodes strictly and refuses a payload over its length caps. The ntfy module takes one ntfy message as ntfy sends it, such as the ntfy client's $NTFY_RAW, ignores fields it does not know, cuts text over the caps, and answers 204 for other events and binary bodies. Both print every message plain: one message cannot tell the first of a sequence from a replacement, since a publisher may choose the sequence ID. internal/pkg/ntfy holds ntfy's message types. Both print the same card. The priority picks the form: a dark URGENT rule and a double box, a double box headed HIGH, a single box with the title in its border, or a rule with no box. Tags print as markers in front of the title, the rest on a Tags row; links print as QR codes with their labels; attached PNG, JPEG, GIF and WebP images print after the card. A line-level markdown subset is laid out without a dependency, keeping marks inside code spans and URLs, and emoji are removed after a few typed ones become markers. A card that cannot be laid out prints as a plain receipt, and the server logs the fault once at ERROR and reports it to Sentry once. [ntfy.format] and [ntfy.markers] shape the cards; the markers table is a setting with the user's own keys, also settable as UBERBRINGER_NTFY_MARKERS=name=value,... uberbringer token --modules issues a token limited to those modules' print and preview routes, job status and the module list; each route in the table says which tokens it takes, and a scope claim that could read as absent makes the token invalid. image elements take optional, which also shrinks a too-wide image to the paper; a QR code that could be too wide for the paper prints with smaller modules; box takes title_bold. Submit takes a Meta whose source shows in job status and, with a copy of the request ID, in every worker log line of the job. The four ntfy cards passed on the TM-T88IV, posted as the client recipe posts them, and their bytes are pinned in TestPaperReceipts. docs/api.md describes the modules, the card and the client recipe, with tokens read from a header file; docs/swagger.json is regenerated. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
328 lines
20 KiB
Markdown
328 lines
20 KiB
Markdown
# Überbringer: design
|
|
|
|
Status: version 0.2.0, checked on paper on the TM-T88IV. Next is the
|
|
formatters work in `docs/plans/formatters.md`. This page records why the
|
|
daemon is shaped as it is. README.md and docs/api.md describe how to use it.
|
|
|
|
## Why
|
|
|
|
Scripts and services on the owner's network send short JSON jobs, and one
|
|
Epson receipt printer prints them. The daemon replaces the 0.1 one on the
|
|
same endpoint, `POST /api/v1/print` behind a TLS reverse proxy, and 0.1
|
|
installs are deployed. It is one static binary with no database, sized for
|
|
receipt rates on one printer.
|
|
|
|
```text
|
|
client ─HTTPS─▶ Caddy ─▶ server ── validate ──▶ printqueue (memory, 1 worker)
|
|
│ │ receipt.Render: whole job
|
|
│ │ to bytes, images via safehttp
|
|
│ ▼
|
|
└─ /healthz ──────▶ printer.Client ─TCP 9100─▶ printer
|
|
(one connection at a time)
|
|
```
|
|
|
|
## Decisions
|
|
|
|
- **One printer per instance.** The config names one printer, and its client
|
|
holds one connection to it at a time, shared by sends and status reads. A
|
|
second printer means a second instance with its own config and port.
|
|
The planned TM-T88VII and TM-m50II (owner, 2026-11-29) have the same
|
|
geometry as the TM-T88IV, so a single profile default covers all three.
|
|
- **The queue lives in memory, on purpose.** ESC/POS gives no
|
|
acknowledgement of what has printed. A queue replayed after a crash could
|
|
therefore print a receipt twice. A lost job, by contrast, shows as failed
|
|
or unknown, and the client can send it again. Waiting jobs are marked
|
|
failed at shutdown. After a crash their IDs answer `job_not_found`. One
|
|
worker keeps jobs in submission order, and the history is capped by
|
|
`queue.history`.
|
|
- **Render, then send.** The handler validates the whole job, and a `400`
|
|
lists every problem. The worker then renders the complete receipt, images
|
|
included, to one byte stream that starts with a printer reset (ESC @). It
|
|
sends that stream over one connection. A failure before the send, such as a
|
|
broken image, costs no paper and leaves no half-printed receipt. A retry
|
|
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.
|
|
- **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
|
|
data can never become a printer command. Only the `raw` element sends bytes
|
|
as given.
|
|
- Before wrapping, text is composed to NFC, and characters the code page
|
|
lacks fold to ASCII look-alikes (curly quotes, dashes, the ellipsis and
|
|
a few symbols). An emoji sequence prints as one `?` (owner, 2026-11-29).
|
|
A fold applies only where the code page lacks the character, so cp1252
|
|
keeps its curly quotes. After this step one rune is one column and one
|
|
byte, which is what wrap counts.
|
|
- **Blocks are laid out when the job renders.** `box`, `rule` and `kv` take
|
|
their width from the profile (or `printer.columns`) and their own size and
|
|
font, never from fixed numbers, so a job stays printer-neutral. Layout
|
|
never fails on a valid job: widths clamp, titles and labels are cut with
|
|
`...`, and a box narrower than its padding gives up the padding. The only
|
|
render-time failure added is `format.max_lines`. Validation stays
|
|
structural, because geometry depends on the printer.
|
|
- Glyphs the code page lacks fall back per glyph set: `double-h` and
|
|
`double-v` to `double`, then `single`, then `ascii`. A divider junction
|
|
the page lacks switches to the other line weight first, and a capped
|
|
title on double lines uses `╣ ╠`, which cp850 has, instead of `╡ ╞`.
|
|
- Block fields are rejected on the older element types, which otherwise
|
|
stay lenient, so a block field sent to the wrong type still fails as an
|
|
unknown field did before blocks existed.
|
|
- Boxes print at the printer's default line spacing. The small gaps that
|
|
leaves in vertical borders were judged acceptable on the TM-T88IV
|
|
(owner, 2026-11-30), so `printer.box_line_spacing` stays 0 by default.
|
|
The bytes of that calibration receipt, `examples/blocks.json`, are
|
|
pinned in a receipt test.
|
|
- A `list` follows the same rules. `done` is a set of indexes into
|
|
`items`, so an index out of range or given twice is a validation
|
|
problem, and so is an empty item. A done item's `√` prints as `x` where
|
|
the code page lacks it.
|
|
- **Modules build ordinary jobs.** A module (`internal/pkg/modules`) turns a
|
|
plain payload into a `receipt.Job` made of the existing elements and
|
|
blocks, which then takes the same path as a `/print` job: validation, the
|
|
queue and the renderer. Payload text only lands in string fields of
|
|
elements, so a module cannot send printer commands.
|
|
- Payloads are decoded strictly and report every problem at once. Field
|
|
names match exactly, not case-insensitively as `encoding/json` would.
|
|
Decoding problems are reported before the module's own checks, because a
|
|
field of the wrong type would otherwise also be reported as missing.
|
|
- A module checks its payload for everything the blocks would refuse, and
|
|
words the problems in the payload's terms (`done[0]: index 5 is out of
|
|
range`). A built job that still fails validation is a bug in the module:
|
|
the client gets `422` `module_failed` with the problems, and it is
|
|
logged and reported to Sentry once, without the problems, which can
|
|
quote the payload.
|
|
- A module never reads the clock. It gets the time, zone and layout in an
|
|
`Env`, from `format.timezone` and `format.time_layout`, so its output is
|
|
reproducible in tests. The binary embeds the zone database, because
|
|
Windows and slim containers have none.
|
|
- Module routes take `copies` and the reserved `printer` (only `default`
|
|
until a second printer is configured) in the query. Any other parameter
|
|
is refused, for the same reason unknown config keys are: a typo must
|
|
not be ignored.
|
|
- The registry lists modules sorted by name.
|
|
- The module routes are entries in the route table like any other. The
|
|
OpenAPI document describes their body as a JSON object whose fields the
|
|
module defines, not as a strict schema: one route serves every module,
|
|
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.
|
|
- `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
|
|
hand-made body does not silently print nothing.
|
|
- The routes print every message plain, never marked `(updated)` and
|
|
never skipped as an update (owner, 2026-11-30). A publisher may choose
|
|
a message's sequence ID, so the first message of a sequence can carry
|
|
one that differs from its ID, and one message cannot tell a first from
|
|
a replacement. Only the subscriber, which remembers what it printed,
|
|
can mark replacements.
|
|
- The priority picks the form; `[ntfy.format] style` can force the box or
|
|
the boxless form. The default form prints its title bold in the top
|
|
border, so `box` has `title_bold`; it is a field of its own because
|
|
making every box title bold would change receipts already checked on
|
|
paper.
|
|
- Emoji are removed on this path rather than printed as `?`, after a few
|
|
typed ones become markers. `receipt.StripEmoji` keeps the symbols among
|
|
the emoji ranges that some code page prints or folds (`■ → ✓`), since
|
|
a module does not know the configured code page. A title or tag that
|
|
is only emoji counts as missing.
|
|
- The markdown subset is line by line and hand-written, with no
|
|
dependency: a card needs bold lines, lists, dividers and links, not
|
|
full CommonMark. Emphasis inside a word follows CommonMark, so `2*3*4`
|
|
loses its stars; `_` inside a word stays, and so does every mark inside
|
|
a code span or a bare URL, such as `__init__.py`. As in GitHub's
|
|
autolinks, marks and punctuation at a URL's end are not part of it, so
|
|
`**https://x.lan**` is bold around a whole URL.
|
|
- A module lays out a job before it knows the printer, so its lengths are
|
|
capped in characters, not lines: title 250, topic 64, 20 tags of 64,
|
|
labels 64, file names 128, links 2000 bytes and the message 4096 bytes,
|
|
ntfy's own default. `notify` refuses a payload over a cap. From an ntfy
|
|
message a card cuts the text over a cap and leaves out the tags after
|
|
the 20th and the links over 2000 bytes, and names an attachment with
|
|
such a URL on a `File` row. A card then prints well inside the default
|
|
`format.max_lines` of 2000, even on 58 mm paper; with a much lower
|
|
limit a long card can still fail when it renders, which stays the
|
|
backstop, as for `/print`. `ntfy.format.max_lines` counts the
|
|
message's lines as written and is at most 400, so that a card stays
|
|
under the 500-element limit.
|
|
- Links print as QR codes, size 5, and the renderer narrows a code's
|
|
modules until it fits the paper; a link over 500 bytes prints as text.
|
|
Only view actions and the click URL become links; `http`, `broadcast`
|
|
and `copy` actions can carry secrets in their headers, bodies and
|
|
values and never print.
|
|
- Only PNG, JPEG, GIF and WebP attachments print as images, the formats
|
|
the renderer decodes; any other `image/*` type is named on a `File` row
|
|
rather than printed as `[image unavailable]`. Attached images are
|
|
`optional` images 384 dots wide, which the renderer shrinks to a
|
|
narrower paper: an optional image never fails for its width. `optional`
|
|
is an image-only field; the other older types refuse it as they refuse
|
|
the block fields.
|
|
- A card always prints: a layout that panics or builds an invalid job
|
|
gives a plain receipt of title, message, topic and time. `Card` returns
|
|
the fault with it, and the server logs it once at ERROR, with the
|
|
panic's stack, and reports it to Sentry once, as for any unexpected
|
|
error, without quoting the notification.
|
|
- The card options travel in the module `Env`, and their zero value is
|
|
the default, so a module built without config still prints sensibly.
|
|
- **Tokens carry their scope (owner, 2026-11-30).** Integration tokens must
|
|
not send printer commands, and the owner chose to fence raw ESC/POS off
|
|
for every token rather than only for new ones.
|
|
- A `mod` claim limits a token to the module routes it names, plus job
|
|
status and the module list. Each route in the table says whether such
|
|
tokens may use it, and the check runs before the handler.
|
|
- Printing a job with a `raw` element needs a `raw: true` claim
|
|
(`uberbringer token --raw`). Tokens without it, every older token
|
|
included, keep every other route, so only clients that send raw hex
|
|
need a new token. Previewing raw elements stays open, since a preview
|
|
sends nothing to the printer.
|
|
- A scope claim that could read as absent makes the token invalid
|
|
(`401`): one of the wrong type, `mod` given as `null`, and `mod` or
|
|
`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
|
|
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
|
|
fasthttp reuses for the next request.
|
|
- **The preview reads the bytes back.** `escpos.Interpret` parses the stream
|
|
the renderer produced, so the preview and the tests show what the printer
|
|
receives rather than what the layout meant. It simulates the printer's own
|
|
wrapping and alignment, which needs the profile. `raw` bytes stay opaque,
|
|
since arbitrary bytes cannot be parsed reliably, and images are blank
|
|
placeholders, so a preview never fetches anything.
|
|
- **Profiles set the layout, and the default is the narrower one.** Columns
|
|
are the profile's dots per line divided by the glyph width; nothing
|
|
hard-codes 42 or 512. The first paper test ran the 576-dot `tm-t20`
|
|
profile on the TM-T88IV, which has 512 dots, and the printer broke words at
|
|
its own edge (`seve` / `ral`). A profile wider than the printer breaks
|
|
words, while a narrower one only shortens lines. So `tm-t88` (512 dots, 42
|
|
columns) is the default.
|
|
- A QR code is fitted to the paper the same way. The printer encodes it
|
|
and picks the mode, so its width is worked out from the bytes each QR
|
|
version holds, byte mode being the least dense: a code that could be
|
|
wider than the paper prints with smaller modules instead of running off
|
|
the edge, and one of digits or capitals may shrink before it strictly
|
|
has to. Data that only a denser mode holds counts as the largest
|
|
version.
|
|
- **Status is read in a way that tolerates a busy printer.** `/healthz` sends
|
|
DLE EOT 1 to 4 over the same connection slot that sends use.
|
|
- The DLE EOT 2 bits (cover open, paper-end stop) are cleared while DLE
|
|
EOT 1 says online. Epson printers go offline for both causes, and a
|
|
TM-T88IV reported a stale cover-open bit while cutting.
|
|
- A not-ready reading is re-read 750 ms later.
|
|
- A read cut short by our own deadline is `timeout` with `503`. It never
|
|
counts as "status unsupported", because an unknown state must not look
|
|
healthy.
|
|
- A printer that never answers status gets `200` `unknown`.
|
|
- The TM-T88VII does not report paper near-end through DLE EOT 4.
|
|
- **Health is for monitors.** `/healthz` answers `200` when the printer is
|
|
ready, or when it cannot report status. It answers `503` when a job could
|
|
not print now: the printer is unreachable, not ready or timed out. A `503`
|
|
from it is a refusal: it is logged at WARN by the request line and never
|
|
sent to Sentry.
|
|
- **Images are fetched by the worker, through an SSRF guard.** A slow or
|
|
broken image URL holds no HTTP request and shows up as a `failed` job.
|
|
`safehttp` checks the resolved address at connect time, so DNS rebinding
|
|
and redirects cannot reach loopback, private, link-local or cloud metadata
|
|
addresses. Exceptions are configured explicitly (`images.*`). Time, size,
|
|
pixel and height limits bound each image.
|
|
- **Errors are flat JSON with a stable code.** The shape is
|
|
`{"error", "code", "details"}`. `code` is the contract with clients, and
|
|
`error` is for people. A refusal is answered and never logged as a failure.
|
|
An unexpected error or panic is logged once and reported to Sentry once,
|
|
without the body or the `Authorization` header.
|
|
- **The OpenAPI document is generated (owner, 2026-11-30).** One route
|
|
table drives both the server's routes and `docs/swagger.json`, so the
|
|
document cannot describe a route the server lacks. Schemas come from the
|
|
Go types by reflection, descriptions from the first paragraph of their doc
|
|
comments, and enums and limits from `jsonschema` tags. Tests hold the tags
|
|
to validation and to the values the handlers send; the enums list the
|
|
canonical spellings, while validation also takes other letter case and a
|
|
few aliases. Request schemas are strict, as the decoder is; response
|
|
schemas allow fields added later. Nothing in the document is written by
|
|
hand. The server gets the document in its config, so the generator does
|
|
not build the package that embeds its own output.
|
|
- **What stays compatible with 0.1.** The endpoint, the HS256 tokens and the
|
|
config keys stay as they were, though a job with raw elements now needs a
|
|
token issued with `--raw`. The 0.1 body and its plain-text answer do
|
|
not. A 0.1 body gets a `400` that points to the element format in
|
|
`docs/api.md`, instead of being translated. Tokens are read only from the header, because tokens in
|
|
query strings end up in proxy logs.
|
|
- **Stack choices (owner, 2026-11-29):**
|
|
- Fiber v3 instead of Echo.
|
|
- TypeID (UUIDv7) job and request IDs instead of snowflakes. They sort by
|
|
time and need no node configuration.
|
|
- An Alpine Docker image.
|
|
- **Stack choices (owner, 2026-11-30):**
|
|
- Viper instead of BurntSushi/toml for the config, as it goes with Cobra.
|
|
Every key can also come from an `UBERBRINGER_<SECTION>_<KEY>` environment
|
|
variable, which wins over the file, so a container can run without one.
|
|
Unknown keys in the file stay errors; unknown variables are ignored,
|
|
because the environment holds much besides Überbringer's settings.
|
|
A table whose keys are the user's own, such as `ntfy.markers`, is one
|
|
setting: its variable holds `name=value` entries separated by commas,
|
|
and in the file a name with a dot or a nested table is an unknown key.
|
|
- `go.mod`'s go line is the latest Go release, with no separate toolchain
|
|
line.
|
|
- **Packaging.** The daemon serves no TLS itself and binds 127.0.0.1 by
|
|
default; a reverse proxy in front terminates HTTPS and sets `X-Real-IP`.
|
|
- The release tarballs are built for linux amd64, armv6, armv7 and arm64.
|
|
`install.sh` sets up Caddy as that proxy (TLS with automatic
|
|
certificates, `X-Real-IP`) and the sandboxed unit from `packaging/`.
|
|
Caddy replaced nginx and acme.sh because it issues and renews
|
|
certificates itself, so the installer needs no webroot, cron job or
|
|
certificate paths.
|
|
- `install.sh` sets up a fresh host, and re-runs upgrade what it set up.
|
|
It does not migrate hosts set up by the 0.1 script (owner, 2026-11-30).
|
|
It reads the settings Caddy needs through `uberbringer config get`, so
|
|
the daemon's own loader checks the config before the service restarts
|
|
and no TOML is parsed in shell.
|
|
- The Docker image is a microservice with no proxy inside: it runs behind
|
|
the operator's own reverse proxy, whose address goes in
|
|
`webserver.trusted_proxies`.
|
|
|
|
## 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
|
|
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.
|
|
|
|
## Deferred
|
|
|
|
- **Paper near-end on the TM-T88VII**, which `GS r 1` reports. Add it when
|
|
that printer arrives.
|
|
- **Several printers from one instance**, through routing or a pool. Until
|
|
then, run one instance per printer.
|
|
- **A persistent job store and print previews** (requested by the owner on
|
|
2026-11-30; to be planned in full in `docs/plans/` before any of it is
|
|
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
|
|
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
|
|
a text preview (`POST /api/v1/preview`); this goes further, rendering
|
|
text, boxes, barcodes, QR codes and images to a picture.
|
|
- Previews of submitted jobs, read back from the store by job ID.
|
|
- **Printer alerts sent out to ntfy** (paper out, cover open). They have not
|
|
been requested. Printing incoming ntfy messages is part of the formatters
|
|
plan.
|