Files
uberbringer/docs/design.md
T
57_WolveandClaude Opus 5.5 2497157b36 Record that every install is fresh until v1
The owner decided on 2026-12-01: "No active installs, don't concern
self with upgrade paths, we assume until v1 that every install is
new/fresh/breaking". The releases plan records it as decision 19 and
applies it:

- Until v1 any release may break callers, configs, installs and
  stores, and the CHANGELOG says so once at its top. Entries list what
  each version has, with no upgrade or migration steps and no Breaking
  heading.
- The release checklist tests fresh installs only: install.sh in Debian
  and Ubuntu containers, and the Docker image. The upgrade test, the
  0.1 config check and the open question about 0.1 hosts go.
- No data is migrated. jobstore's schema steps give way to one schema
  and its version, and a binary refuses a jobs.db of any other version,
  naming the file and saying to move it aside or remove it. v0.2.0
  gains that commit and one that rewrites the docs for fresh installs.

The job-store and printers plans now raise the schema version and
refuse an earlier store where they planned schema steps, and drop their
downgrade notes. Phase 2b's cancelled status goes under Changed.
design.md's Why no longer says 0.1 installs are deployed, its 0.1
compatibility bullet becomes the decision, and install.sh migrates
nothing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 23:06:27 -06:00

61 KiB

Überbringer: design

Status: version 0.2.0, checked on paper on the TM-T88IV. Next is the work under Planned next, each feature in its own plan in docs/plans/. This page records why the daemon is shaped as it is. README.md and the other docs in docs/ 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, through POST /api/v1/print behind a TLS reverse proxy. No 0.1 install is in use, and until v1 every install is a fresh one (owner, 2026-12-01). It is one static binary, which keeps its jobs in a SQLite file of its own, sized for receipt rates on one printer.

client ─HTTPS─▶ Caddy ─▶ server ── validate ──▶ printqueue (1 worker) ◀──▶ jobstore
                           │                         │                (SQLite, state.dir)
                           │                         │ 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.

  • Jobs survive a restart, and a restart never prints a receipt twice (owner, 2026-11-30). With state.dir set, the queue keeps its jobs in jobs.db there; without it, they stay in memory, and waiting jobs fail at shutdown. One worker prints them in submission order, and statuses are kept for the last queue.history finished jobs.

    • What can be known. A TCP write returns once the kernel has the bytes, not once they print, so no store can record a receipt as printed. Each attempt therefore commits its sending mark, synced, after the printer's connection opens and before the first byte; if that commit fails, the connection closes with nothing written. A dial failure writes nothing, so a job retried while the printer is offline stays safe to retry. At start, every delivery found in sending ends uncertain, a status of its own, with an error saying it may have printed, and one WARN line by its job_id, printer, source and ref. It is never sent again; a person checks the paper, and a reprint is a new request. A crash between the mark and the write leaves an uncertain receipt that never printed, the safe direction. queued never reached the printer, and a failed job reached it only if sent_at is set.
    • Done means the printer confirmed it (owner, 2026-12-01). A write that returned says only that the operating system holds the bytes. On the TM-T88IV with its cover open, Windows took a whole 128 KB receipt into its send buffer at once; the daemon stopped, and once the cover closed only the receipt's first third printed, uncut, and the printer waited for the rest of the image, so the next receipt would have printed as noise until it was switched off and on. So the client asks with GS r 1, which the printer answers only once it has run every byte before it, and, on the TM-T88IV, only while it can print (printer.confirm):
      • Before the sending mark it sends DLE EOT 1, GS a 0 and GS r 1 in one write. The printer answers DLE EOT on receipt, ahead of anything it receives after it, so that answer is a fence: everything before it left the printer before the request reached it, and is dropped, however long a lost segment holds the request back. That takes care of answers owed to requests the printer ran earlier, on an earlier connection or for an earlier run of the daemon, and of the last bytes of an automatic status block whose header went to an earlier connection. A late answer to an earlier connection's DLE EOT looks like the fence's and can stand in for it; the last check below catches what follows from that. It then waits, up to printer.write_timeout, for an answer to GS r 1 after the fence. Without it, as with the cover open, paper out or a printer stuck inside a cut-short image, nothing is sent, and the job retries as after a failed dial and fails with no sent_at. Requests still queued in the printer ahead of this one are answered first, and the answers carry nothing that tells them apart, so the wait reads every answer until 100 ms have passed since the last and drops them all. Only answers keep the wait open, and one that the deadline or the connection's end cuts short counts as not ready. A printer may run GS r 1 while offline, as the TM-m50II's settings may allow, so it then asks DLE EOT 1 again, for up to 2 s beyond printer.write_timeout, and sends the job only if the printer answers that it is online. Last, it reads on for 100 ms. Once the answers have settled none is owed, so an answer to GS r 1 during the online check or after it means that one taken for the ready answer was not, as when a late DLE EOT answer stood in for the fence and an owed answer followed it; then nothing is sent, and the job is tried again. Each job waits about 200 ms for these checks.
      • After the job it sends GS a 0 and GS r 1 again, and the job is done only on that answer. Without it within printer.write_timeout, the job is uncertain, with a WARN line, and never sent again. A receipt that takes longer to print than that reads uncertain though it printed, and the job's 2-minute bound caps the timeout.
      • Automatic status blocks: the UB-E02 and UB-E03 boards turn them on at power-on, and a job's ESC @ turns them off, but not on a TM-T88VII with DIP switch 2-1 on. A block's last three bytes have the GS r answer's fixed bits, and the board can send them on the next connection. So the client sends GS a 0 before each GS r 1; the printer runs it in order, so no block follows the answer on that connection. Bytes of blocks before the fence are dropped with the rest; blocks after it are passed over by their header's fixed bits, a block split across reads included, and after the confirmation the client reads on for up to 100 ms for the rest of a block it ended inside. Status sends no GS a 0, which the printer does not run while offline; before it closes, it reads what has come, to the end of any block.
      • Not DLE EOT for the confirmation: it is answered at once, and an image's bytes can hold it, which the printer answers too; such answers are told from the GS r answer by their fixed bits (bits 4 and 7 clear). The TM-T88IV answers 0x00; Epson's pages also give a form with bit 4 set, which a model must not use unless it runs with printer.confirm = false, unchecked on the TM-T88VII and TM-m50II. printer.confirm also needs a printer that answers DLE EOT on receipt.
      • Two cases are accepted as they are, by design (the next decision). In each a job can read done before it has printed, and the daemon does not try to catch it; only an acknowledgement that names the job, GS ( H fn 48 (phase 5), could tell it apart:
        • A raw job holding a command the printer answers with a byte whose bits 4 and 7 are clear, such as GS r, GS I, ESC v or ESC u 0, with printing after it, is confirmed by that answer before it has printed. Answers it leaves owed, far enough apart, can do the same to the next job. Only a token issued with --raw can send one.
        • An answer taken for the ready answer that is not it: the answer to a request still queued in the printer when the fence arrived, or, when a late DLE EOT answer stood in for the fence while this connection's request was held back, one the printer owed from before. The printer runs queued requests back to back, so the real ready answer follows within the settle, which drops both, or within 100 ms of the online answer, which sends nothing, unless printing comes between them, which only a raw job puts there, or the printer pauses longer while it reports online. The TM-m50II feeds and cuts when its cover closes; if it reports online before it has run the queued requests and pauses between them, the late ready answer confirms the job before it has printed.
      • The client relies on the printer answering DLE EOT on receipt, ahead of the GS r 1 sent just after it, running GS a 0 in order, and never answering DLE EOT between the bytes of a status block, and on how the board routes bytes across connections. The TM-T88IV answers DLE EOT; the rest is unverified, and stage 4a's raw-byte probe (docs/plans/printers.md) checks it.
      • A job holds the printer's connection until it has printed, so /healthz answers 503 timeout during a receipt that takes more than 3 seconds.
    • The daemon never reprints (owner, 2026-12-01). It does not reprint a job by itself, not when a cover closes and not at start. An uncertain job, and a job that reads done in one of the two cases above, are left as they are on purpose: the daemon cannot tell a receipt that printed from one that is missing, so a reprint of its own would risk a duplicate. A reprint when the cover closes would not even reach the second case, whose job reads done; the printer resumes its own buffer when the cover closes (paper check 3), so it would print the receipt twice; and after a cut-short image the printer can still be inside the image command. A person who finds a receipt missing reprints it through the API instead. POST /api/v1/jobs/{id}/reprint reprints one stored job by its ID, as often as asked. In place of the ID, which can never be one of them, last reprints the last completed job, one that read done, never one still waiting or printing; failed retries the last failed print; and uncertain reprints every uncertain job. A job one of these categories reprints is marked, so no category takes it again, and each answer names the new job, so a person can print it again by its ID. A reprint takes a job from any source: a print or module route, an ntfy card or digest, and later a webhook. The routes take every input in the JSON body, never in a query parameter, and the ID or category in the path is the route itself. No message a source receives, an ntfy message included, makes the daemon print a job again. Phase 2 of docs/plans/job-store.md builds the routes (its decisions 24-39).
    • 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 file of any other schema version, naming it: nothing is migrated until v1.
    • 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 with an ID. Epson also documents GS ( H fn 48, answered with an ID of the host's choosing once a job has printed, which would tell one job's answer from another's even across connections. Whether the TM-T88IV's network board passes it to port 9100 is unverified, so it waits for a paper test (docs/plans/job-store.md, phase 5). The state machine is safe without it.
  • Render, then send. The handler validates the whole job, and a 400 lists every problem. The worker then renders the complete receipt, images included, to one byte stream that starts with a printer reset (ESC @). It 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 a receipt, or part of one, 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 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.
  • Existing jobs keep their meaning and their bytes. Every element, field and response keeps its meaning, and /print stays strictly decoded. TestRenderCompat (receipt/testdata/compat) and TestPaperReceipts, in internal/pkg/receipt/compat_test.go, pin the bytes of existing jobs, and later work keeps them passing. Renderer.Render is the only path to printer bytes. A job is printer-neutral, so the same job prints alike on each printer it is rendered for.

  • 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). The module routes name each by its path in the request body (payload.done[0]). 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.
    • Labels are in English, and the footer's time zone and date format come from the config (owner, 2026-11-29).
    • 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.
    • A module route's body holds the payload under payload, with copies and the reserved printer (only default until a second printer is configured) beside it: {"payload": {...}, "copies": 2, "printer": "default"}. No name a module gives its payload's fields can collide with them. The body is decoded strictly, so any other field 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 the payload 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 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 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> or ntfy:<subscription>) and a reference, the request ID on the HTTP routes and the message's ID, or the digest's own reference, 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 fasthttp reuses for the next request. A subscription's references are unique at it: a card's is its message's ID, and a digest's is a TypeID with the prefix digest, minted when the digest is made. A job whose source and reference the queue holds, among the last 512 of that source kept apart from the statuses, is not queued again, and the queue answers with the earlier job. A message the subscription would hold for a digest never reaches Submit, so the subscription asks the queue first, and one whose card it holds counts as printed. So a message or a digest offered again after a restart prints once while its job is stored. A request ID is never checked, since a client may set it.

  • 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.

  • Inputs go in the JSON body (owner, 2026-12-01). An API input goes in the request's JSON body, never in a query parameter. The path holds only a resource's ID, or a fixed word that names the route, as last, failed and uncertain do in /jobs/.../reprint. A GET takes no inputs beyond its path, so a read that takes inputs is a POST, as the planned job list, POST /api/v1/jobs/list, is. Every route answers a query string with 400 invalid_query, after the token and its scope under /api/v1, so a caller that still sends one learns so instead of having it ignored. The module routes' body holds the module's payload, copies and printer.

  • 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.

  • Nothing stays compatible with 0.1 or between releases before v1 (owner, 2026-12-01). His words: "No active installs, don't concern self with upgrade paths, we assume until v1 that every install is new/fresh/breaking". Any release may break callers, configs, installs and stores; the CHANGELOG lists what each version has, with no upgrade or migration steps. 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.
  • Stack choices (owner, 2026-12-01):

    • modernc.org/libc is the one module held below its latest release. It stays at the exact version modernc.org/sqlite requires, since the driver is C transpiled to Go against that libc and works with it alone, and moves only with the driver. A routine go get -u would move it and break the driver without a compile error, so the gate runs tools/libcpin, which fails when the two differ.
  • 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. It migrates nothing, from 0.1 or from an earlier release; a re-run keeps the config. 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.
    • Third-party notices are generated from what go list -deps says the binary links on each release platform, not from go.mod, so modules that only tools and tests use stay out. The binary embeds them and prints them with uberbringer licenses, so a host that kept only the binary still has them. They are not served over HTTP.
  • 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 ID ntfy does not know, expired or not yet stored on the node asked, makes ntfy replay the topic's whole history, unless that node delivered it in the last two minutes. 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 waits in the job store, which every subscription has, since it needs state.dir, and prints after the restart; if the restart replays it, the queue's duplicate check answers with its job.
    • State is one JSON file per subscription in state.dir, written atomically (temporary file, fsync, rename), mode 0600 since held messages carry titles. A change a restart must see, such as a message printed, held or left out, is written within a second, and so is the state at shutdown. A cursor that only keepalives moved is written at most every 10 minutes (owner, 2026-11-30): keepalives come every 45 seconds, and writing each one would mean about 1,900 synced writes a day per subscription, which wears an SD card. A saved cursor that is behind costs only a longer replay after a crash, and the saved IDs drop the messages it sends again. 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. Once made, a digest gets its reference and is saved with it, apart from the messages held, and is submitted only once that save has succeeded; messages held after that wait for the next digest. A restart before the queue's answer is saved submits the same digest again under the same reference, ahead of the later messages, so the queue's duplicate check finds it while its job is stored.

  • 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 next (owner, 2026-11-30)

Each feature below has its own plan in docs/plans/<feature>.md, written before anything is built. They come in this order.

Tagged releases follow docs/plans/releases.md, which maps these plans onto vX.Y.Z tags. The owner decided on 2026-12-01 that a tag comes soon, that every tag is stable with usable features, and that anything not finished stays hidden from users. The same day he accepted the plan's details as proposed (its decisions 1-18), and decided that until v1 every install is a fresh one (its decision 19):

  • v0.2.0 is the first tag: main as it stands, with [Unreleased] folded into [0.2.0], listing what it has. v0.2.1 follows as a patch, with ntfy stage 1 and a /healthz that reports a printer which stops answering. After that, each feature group is a minor of its own, in the order below, and a patch carries fixes alone.
  • Each tag goes out first as vX.Y.Z-rc.N, and the owner tags the same commit once the plan's checklist passes. The checklist covers the gate, CI on main and the release snapshot, and one smoke receipt on paper with the owner's OK. It also runs fresh-install tests in podman containers of Debian and Ubuntu on leil-test-1, under its lease, with a fake printer.
  • v0.2.0 documents that the TM-T88IV reads unknown with 200 while its cover is open, and that a printer stuck after a cut-short receipt needs switching off and on. v0.2.1 fixes the first; the second waits. Its CHANGELOG says that a printer that does not answer status prints nothing unless printer.confirm = false. The ARM builds ship once the store's tests pass under QEMU.
  • A stage lands on main usable, or as library code that nothing calls. A stage whose wiring would show a half-made feature lands with the stage that completes it: printers 1a with 1b, and remote-printers 2 and 3 with 4. Between a minor and its patch, only fixes land.
  • The module routes' reserved printer and queue.content_bytes stay. The Docker image is not published. Each release attaches its install.sh.
  • Until v1, any release may break anything, and the CHANGELOG says so once, at its top. Its entries carry no upgrade or migration steps and no Breaking heading. No data is migrated: a binary refuses a jobs.db of another schema version, naming the file to move aside. The docs describe fresh installs only.
  1. Job store and print previews: docs/plans/job-store.md (written; the owner accepted every proposed default, 2026-12-01). The store is built (Decisions, "Jobs survive a restart"); what is left:
    • POST /api/v1/jobs/list lists the history, its filters and paging in the JSON body. Job status shows ref, and /healthz counts the jobs that became uncertain since the latest start, at it or during the run.
    • DELETE /api/v1/jobs/{id} cancels a waiting job, for full tokens. An ntfy message_delete cancels the waiting receipts of its notification (Queue.Cancel); message_clear does not, and the subscriber filters priorities itself. A cancel is synced, as a failure is.
    • A PNG preview draws the paper one pixel per dot, box drawing from the cell geometry and other glyphs from a bitmap font. Stored jobs preview by ID.
    • POST /api/v1/jobs/{id}/reprint reprints a stored job by its ID, and by category /jobs/last/reprint the last completed job, /jobs/failed/reprint the last failed one and /jobs/uncertain/reprint every uncertain one, each marked so that no category takes it again: the user-side path for uncertain jobs and any receipt that went missing, since the daemon never reprints by itself and no message asks it to (owner, 2026-12-01; the plan's decision 24). The owner accepted its details as proposed on 2026-12-01 (the plan's decisions 25-39):
      • last takes the newest unmarked done job, failed the newest unmarked failed one, and uncertain every unmarked uncertain one, oldest first, with no age limit. Each category is per printer, named by the body's printer, the default printer without one.
      • A job is marked when its reprint is queued, by the new job's reprint_of, kept in the store. The answer is 202 with the new job's status, or a list of them for uncertain.
      • Nothing in a category answers 404 job_not_found, an unfinished job 409 job_not_finished, and pruned content 410 job_content_expired.
      • Full tokens only, and a job with a raw element also needs a --raw token. A reprint is never refused as a repeat, prints unmarked, does not clear the printer first, and has no CLI command.
    • Epson's acknowledgement, ntfy state in the store and an age limit wait for phase 5.
  2. Several printers: docs/plans/printers.md (written; the owner accepted every proposed default, 2026-12-01).
    • [printer] stays, as the printer default, and [printers.<name>] tables add the others, from the file only. Each takes every key of [printer]; no two local printers share an address and port.
    • One queue with a lane per printer: its own worker, renderer and connection, and queue.size per lane. History, references and the store stay shared.
    • A printer in the body of /print, /preview and the module routes is a direct unicast; an empty one is the same as none. Every job status gains deliveries. /healthz lists every printer, and its code follows the default printer alone.
    • Routing is done by rules written in Expr (github.com/expr-lang/expr), modelled on Kanrisha's policy engine: [[routing.rules]] and [routing.groups], compiled once against a typed environment of routing facts, never print content, with a unique order, first match wins. A rule that fails to compile stops the start; one that fails at run time counts as no match. The compile options and iteration guard are templates' rules.Options.
    • A rule sends a job unicast (one printer), multicast (each printer of a set), broadcast (every printer) or anycast (one printer of an ordered list). A job no rule matches goes to the default printer, so a single-printer config keeps working.
    • A multicast or broadcast job is one job with several deliveries, one per printer, each tracked on its own, accepted while any of its printers has room. The route is decided once, when the job is accepted, and stored with it.
    • SIGHUP reloads the rules. uberbringer route and the JSON preview's route show what the rules decide.
    • Anycast is a priority list with failover: the first printer, on failure the second, then the third. It checks status before it sends, passes over a printer marked down for 30 s, and fails over after bytes went out only once that printer's retries are spent.
    • The profile keeps the exact model, so a TM-T88VII reports its paper near-end through GS r 1. Per-model defaults come only when a paper check needs one.
  3. Remote printers: docs/plans/remote-printers.md (written; the owner accepted every proposed default, 2026-11-30).
    • Printers on other networks are reached through an Überbringer agent next to them: the same binary, run as uberbringer agent. It dials out to the main instance over HTTPS and WebSockets, using Fiber's WebSocket middleware, so no port opens at the remote site.
    • Messages are MessagePack through github.com/tinylib/msgp, whose generator is pinned in go.mod and run as go tool msgp. NATS JetStream, embedded etcd and VPN tunnels are not used for this.
    • Main renders each receipt in full. The agent writes the bytes unchanged, and only to printers its own config lists.
    • An agent signs in with a token scoped by an agt claim, and tokens_since revokes one agent's older tokens.
    • The agent syncs a journal record before the first byte of each receipt. A send whose link is lost is resolved from that journal; one whose outcome stays unknown ends uncertain and is never sent again.
    • While an agent is offline, its printers' jobs wait in order, and anycast passes over them. Status is read through the agent on demand.
    • install.sh --agent sets up an agent, and the Docker image runs one with the command agent. There is no Windows release.
  4. More blocks: docs/plans/blocks.md (written; the owner accepted every proposed default, 2026-12-01). A table (with ╤╪╧ junctions), a banner, a group, inline spans and a custom rule character, each built when it is needed, one at a time.
    • A rule takes char, one character repeated across the line. Where the code page lacks it, it falls back to its one-character fold, then to the rule's style. A divider inside a box refuses it.
    • A table has cols (head, align, width, grow), rows and bold foot rows. Its frame is double-h (╒╤╕ ╞╪╡ ╘╧╛) by default, or any box style, or none. Columns size by content, and spare room goes to the grow columns or else the first. Cells wrap; padding gives way first, and a table whose columns cannot each keep their longest word, up to 8 characters, prints as key-value rows. It takes 1-8 columns, 1-100 rows and 0-10 foot rows, and may go inside a box.
    • The renderer stops as soon as a job passes format.max_lines, so the error gives a lower bound on its lines.
    • A banner is large text across the line: band (white on black, the default), plain or ruled, at a size from 4 down to 2 that fits the paper's dots. The printer centres it, and it never goes inside a box.
    • A text element takes spans, runs with their own bold, underline, invert and size, wrapped by width in dots; text of one size wraps as today. Inside a box spans change no size, and "wrap": false is refused with them.
    • A group holds any element but a group, raw or cut, under an optional heading rule, and lends its font and size to children that set none. Keep-together adds nothing on a receipt. Its children are named by path, and the raw-scope check walks every child list.
    • A glyph a code page lacks falls back as the box styles do, without a warning; only cp437 has ╤╪╧. No module changes. Each block's example receipt prints with the owner's OK and is pinned once he passes it.
  5. Templates and rules for webhooks and ntfy subscriptions: docs/plans/templates.md (written; the owner accepted every proposed default, 2026-12-01). Templates and rule actions use Expr, as in Kanrisha, sharing the routing engine. Webhooks come after templates, since a webhook needs a template to become a receipt.
    • A template is one Expr expression in [[templates]], checked at load on the sample payload it carries. It returns a notification card's fields or a list of elements, and every template is also a module, with its own print and preview routes.
    • Expr reads no clock, variable or file, and a run is bounded in nodes, memory and iterations. Its output takes the strict job decoder: raw and hex are refused, images are optional, and each job is laid out before it is queued. Expr's messages quote the payload and are never logged.
    • [[ntfy.rules]] print a message through a template or as today's card, drop it, or hold it for a digest of its own after digest_wait. They run after the updates check; quiet hours and the paper budget still apply, unless a rule sets bypass. A template that fails prints the card instead. A rule's digest does not hold later messages, which narrows the paper budget decision from stage 3 on.
    • Webhooks arrive at POST /hooks/{name}, outside /api/v1. Each hook has a secret and a preset for its sender's signature (github, gitea, forgejo, gitlab, standard or header), checked on the raw body first. A repeated delivery gets its first answer, and a template that fails prints a fallback receipt.
    • Templates do not need the group block.
  6. ntfy: docs/plans/ntfy.md (written; the owner accepted every proposed default, 2026-12-01).
    • The subscriber prefers ntfy's WebSocket endpoint (/<topics>/ws), falls back to the JSON stream, and the transport is chosen per subscription in the config: transport is auto (the default), websocket or json. The owner keeps WebSockets first, although behind Caddy the JSON stream does as well or better.
    • auto falls back when the WebSocket itself is refused, such as by a proxy that drops the upgrade, not on ordinary failures, and tries it again on the first reconnect an hour later. /healthz shows each subscription's transport.
    • A WebSocket answers ntfy's pings, which reset the stall timer and never move the cursor, and learns the server's clock from open alone. The client is fasthttp/websocket's, as for the remote agents, with the token in the Authorization header, never in ?auth=.
    • On a connection that asked for a replay, no message moves the cursor until the first keepalive, so a message that arrives during a replay cannot skip its rest. A WebSocket has no keepalives, so its cursor stays put for the connection, and the floor follows max_backlog while connected, which bounds the next replay and the saved IDs.
    • It handles ntfy's replay limits: X-Messages-Truncated: 1 on a replay cut at 10 MB, and 429 with error code 42905 when the daily bandwidth budget is spent. ntfy 2.38.3 sends both on polls only, so the stream keeps its replay; a cut replay is logged, 42905 is named in last_error, and an error ntfy writes into a stream ends the connection and prints nothing.
    • The cursor stays a server time, never since=<message ID>, as checked in ntfy's source.
    • docs/ntfy.md advises, for ntfy behind Caddy, behind-proxy: true in ntfy, and a stream_close_delay so that Caddy's reloads do not drop streams at once; and no response_buffers.
    • There is no ntfy-compatible publish endpoint (owner, 2026-12-01).

Deferred

  • Printer alerts sent out to ntfy (paper out, cover open). They have not been requested. Incoming ntfy messages already print (Decisions, ntfy subscriptions).
  • Nested boxes, and goldmark for full CommonMark. Cards need the hand-written markdown subset only.
  • Geometry checks in the HTTP handler (Renderer.Check) stay rejected. Layout never fails on a valid job, the preview shows the result and its line count at once, and each module caps its own lengths.