Files
uberbringer/docs/plans/printers.md
T
57_WolveandClaude Opus 5.5 10b6c57afb
Security / Vulnerability check (push) Successful in 46s
Test / Lint and test (push) Successful in 2m6s
Record the owner's acceptance of the remote-printers plan
The owner accepted every proposed default of
docs/plans/remote-printers.md on 2026-11-30. Its open questions become
numbered decisions, without the alternatives, and design.md's Planned
next item 3 records them.

The plan's acceptance edits are made: printers.md's seam, question 6,
question 24 and stage 3 point to it, and job-store.md notes that a
remote attempt whose outcome stays unknown turns uncertain during a run
and that the acknowledgement runs at the agent for remote printers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 23:48:55 -06:00

1151 lines
120 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Plan: several printers, routed by Expr rules
Status: **planning; nothing is built.** This plan builds on docs/plans/job-store.md and does not redesign its store. Stages 1a to 3 need that plan's stage 1c: jobs with deliveries, the waiting list, `beforeWrite` and the memory store. None needs its durable store (job-store stage 1d). Where that has shipped, question 5's restore rule applies to it, and stage 2a adds a schema step (question 18). Each stage runs in its own session, briefed from its section, once the owner has answered the questions listed for it or accepted their assumed defaults:
- stage 1a needs questions 1-6, and stage 1b needs 7-9;
- stage 2a needs 10-19, stage 2b needs 20, and stage 2c needs 21;
- stage 3 needs 22-26, and question 23's paper check;
- stage 4a needs 27-29, and stage 4b needs 30 and 31. Question 31 is also needed before the first receipt on a new printer.
Each answer goes into design.md at once and leaves this list. The stages run in the order listed, except that stages 2b and 2c each need only 2a. Stage 4a needs only the TM-T88VII on hand, which can be the default printer until stage 1a ships. Stage 4b runs once for each new model as it arrives; it needs 4a only when a value differs between models of one family. Every check on a real printer, of its paper or of its status, needs the owner's OK. When the owner accepts the plan, the edits under Overview, ON ACCEPTANCE, are made. Whichever stage finishes last deletes this plan, its findings with it, and design.md's Planned next item 2.
## Decisions (owner, 2026-11-30)
- **Printers are defined in the TOML config as named tables, with named
groups of printers.**
- **Routing is decided by rules written in Expr**
(`github.com/expr-lang/expr`), modelled on the policy engine of the
owner's other project, Kanrisha (`internal/policy`, engine.go and
policy.go, and its docs/policies.md). That engine compiles each rule once
against a typed environment (`expr.Env(EnvPrototype())`,
`expr.AsBool()`), orders rules by priority, has an enabled flag, swaps
the rule set atomically on reload, skips and logs a rule that fails to
compile, and has a dry-run.
- **A rule's action sends a job in one of four delivery modes:** unicast
(one printer); multicast (each printer in a named set, "one to some");
broadcast (every printer); and anycast (one printer from an ordered
list).
- **Anycast is a priority list with failover:** try the first printer, on
failure the second, then the third. A failure before any byte was sent
fails over at once. After bytes were sent, the assumed default is the
existing retry rule on that printer, then failover. job-store.md
question 23 names the double-print risk this carries; this plan settles
it as an open question (question 22).
- **A multicast or broadcast job is one job with several deliveries,** one
per printer, each tracked on its own. job-store.md already plans that
model (its DELIVERIES AND SEVERAL PRINTERS section, question 12 on a
job's status from its deliveries, and question 23). This plan builds on
it and does not redesign the store.
- **An explicit `?printer=` on a request is a direct unicast.**
- **A job that matches no rule goes to the default printer,** so today's
single-printer config keeps working.
## Open questions
Each has the default the plan assumes unless the owner says otherwise.
Before stage 1a:
1. **Today's `[printer]` table.** Assumed: it stays, and it is the printer named `default`. `[printers.<name>]` tables add the others. The name `default` is reserved, so `[printers.default]` is refused with a message that points to `[printer]`.
- Nothing needs migrating. install.sh writes `[printer] address` and keeps an existing config on a re-run. `UBERBRINGER_PRINTER_*` keep their meaning in Docker. `?printer=default` keeps working on the module routes. job-store.md's planned delivery rows name `default`. The CHANGELOG lists it under Added.
- Trade-off: two table shapes, and the default printer cannot be renamed.
- Alternatives: move it into `[printers.default]`, as formatters phase 5 sketched. That is **Breaking** for every deployed config: `[printer]` becomes an unknown key, the daemon stops at start after an upgrade, and install.sh parses no TOML to migrate it. Or accept both and refuse a config with both: a shim, and unclear which variables win. Or `[printer]` as defaults the others inherit: inheriting an address makes no sense, and inheritance hides which values a printer uses.
2. **Printer names, and no variables for named printers.** Assumed: a name follows the subscriptions' rule, `^[a-z0-9][a-z0-9_-]{0,31}$`. It is checked on the raw TOML key, because Viper lowercases map keys: `[printers.Office]` would otherwise load silently as `office`. `[printers.*]` comes from the file only, as `[[ntfy.subscriptions]]` does. The default printer keeps its `UBERBRINGER_PRINTER_*` variables. No key reads a `UBERBRINGER_PRINTERS_*` variable, so at start one WARN line names any that is set, never its value; from stage 2a it names `UBERBRINGER_ROUTING_*` variables too. They are ours, and a Docker user could otherwise set one and never learn it does nothing.
- Trade-off: a container with several printers needs a mounted config, as one with subscriptions does, and a named printer's address cannot come from a variable.
- Alternatives: bind `UBERBRINGER_PRINTERS_<NAME>_<KEY>` after the file is read, for the printers it names (the probe shows this works; a name with `-` gives a variable no POSIX shell can set). Or declare printers by scanning the environment, which rules out `-` in names and needs a test that no printer key ends another after an `_`. The module names' rule, `^[a-z][a-z0-9-]{0,31}$`, is the other candidate pattern.
3. **Which keys belong to each printer.** Assumed: every key of today's `[printer]`: `address`, `port`, `model`, `codepage`, `paper_width`, `columns`, `box_line_spacing`, `cut_feed`, `dial_timeout`, `write_timeout`, `retries` and `retry_delay`. A `[printers.<name>]` table starts from the same defaults as `[printer]`, not from `[printer]`'s values, and only `address` is required. `format.*`, `images.*`, `queue.*` and `ntfy.*` stay global.
- `model` and `codepage` are checked when the config loads, by one helper in internal/app that the start, `config get` and `preview` share. Today they are checked only at start, so `config get` passes a bad model and install.sh restarts the daemon into the error.
- Two printers may not share an address and port, `[printer]` included; hosts are compared without regard to case. Each table gets its own client and connection slot, and a printer prints from one connection at a time. A second connection's data waits until the first closes, its writes stall until `write_timeout`, and its status reads time out (`503` if one of them is the default printer). Two names that resolve to one address cannot be caught.
- Trade-off: `format.max_lines` is global, so a multicast job that wraps into more lines on a narrower printer can fail there and print on the others. One image fetcher serves every printer.
- Alternatives: per-printer `format.*`, which nothing asks for; for a repeated address, one client shared by both lanes.
4. **One queue with a lane per printer.** Assumed: one `printqueue.Queue`. Each printer is a lane with its own waiting list, worker, renderer, sender, retries and retry delay. The submit lock, the status map, the history, the references of ntfy jobs and the store stay shared, so a job with several deliveries is one `Store.Add` commit, as job-store.md plans. `queue.size` bounds each lane, so a dead printer's backlog cannot refuse jobs for the others (question 19 for multicast and broadcast). Order is first in, first out per printer.
- Trade-off: no global order; a broadcast prints at different times on each printer. A host with three printers can hold three times `queue.size` jobs. With a durable store, unfinished content can reach N × `queue.size` × 4 MiB: about 1.2 GiB for three printers at the defaults, where job-store question 9 counts about 400 MiB for one. A unicast rule or a `?printer=` to a dead printer still refuses jobs once its lane is full, and an ntfy subscription whose jobs go there stops reading, as it does today when the one printer is dead.
- Alternatives: formatters phase 5's Pool of independent queues. It suits unicast only: a multicast job would have a status in each queue, capacity could not be checked across them at once, history would be evicted per queue, and anycast could not move a job between channels. For capacity, one global `queue.size`.
5. **A printer removed from the config while deliveries wait for it** (job-store.md, DELIVERIES AND SEVERAL PRINTERS). It matters once the store is durable. Assumed: at restore, a queued delivery whose printer is no longer configured fails, in a synced commit, with an error naming the printer, and one WARN line by `job_id` and `printer`. Finished deliveries, `uncertain` ones included, stay as history. An anycast delivery drops the missing printers from its list and fails only when none is left (stage 3).
- Trade-off: renaming a printer fails what waits for it.
- Alternatives: refuse to start until the printer is back, which stops every printer over one; or send them to the default printer, a room nobody chose.
6. **The seam for remote printers.** Assumed: no `kind` key and no address scheme now. Each printer is built by one constructor in internal/app, which returns what `printqueue.Sender` and `server.Printer` need; today that is a `*printer.Client`. The remote-printers plan adds its own key, which is purely additive, since unknown keys are refused today. Architecture, THE SEAM FOR REMOTE PRINTERS, writes down the contract a remote printer keeps, printqueue's send contract (stage 3) included.
- Trade-off: none known. docs/plans/remote-printers.md names the key, `agent` (its decision 16).
- Alternative: reserve `kind = "tcp"` now, as the only value accepted.
Before stage 1b:
7. **`?printer=` on `/print` and `/preview`.** Assumed: `POST /api/v1/print` and `POST /api/v1/preview` read `printer`, as the module routes already do. An empty value means the default printer, as on the module routes today. A name matches only as configured, so `Office` is not `office`. A name that is not a configured printer, a group's name included, answers `400` `unknown_printer`. A parameter given twice, or any other parameter, answers `400` `invalid_query`. A preview renders for the named printer, or for the default printer without one.
- Refusing other parameters is **Breaking**: a client that sends `/print?x=1` gets `400`. It matches the module routes, where a typo must not be ignored; here a mistyped `printr=office` would print in the wrong room.
- Any token that may print may name any printer. A token claim that limits printers can come later.
- Trade-off: the break above. A preview without `printer` lays the job out for the default printer, even when the rules would send it elsewhere; from stage 2c the JSON preview's `route` says where it would go.
- Alternatives: ignore other parameters, as today; or render a preview for the first printer of the route the rules give.
8. **A job's status with several deliveries.** Assumed: from stage 1b, every status gains `deliveries`, whatever the number of printers configured, so a client's parsing does not depend on the config. Each entry gives a delivery's `printer`, `status`, `attempts`, `started_at`, `sent_at`, `finished_at` and `error`. The job's `status` follows job-store question 12. Beside the array, the job's own fields read:
- `attempts`: the sum;
- `started_at` and `sent_at`: the earliest;
- `finished_at`: the latest, once every delivery has finished;
- `error`: that of the first failed or `uncertain` delivery, prefixed with its printer's name when the job has more than one.
- Trade-off: one more field on every status.
- Alternative: the array only on a job with several deliveries, as job-store.md's COMPATIBILITY assumes, and the job's own fields then left empty.
9. **`/healthz` per printer.** Assumed: `status` and the HTTP code follow the default printer alone, as today, and `printer` stays the default printer's health. A new `printers` array lists every printer, the default first, then by name. Each entry has `name`, `default`, `model` as configured, the fields `printer` has, and its own `pending`. `queue.pending` is the total. No address appears, since the route is public. There is no `?printer=` on `/healthz`.
- The default printer is read once, and that one settled read fills both `printer` and the first entry. Two reads would queue on its one slot. With a second read 750 ms later for each, they could pass the 3-s bound, turning a `200` into a `503` `timeout`.
- The others are read in parallel, each within the same bound, so a slow one cannot make the others time out.
- A dial that times out reads as `timeout`, as today: Go's dial time-out error matches `context.DeadlineExceeded`. So a host that does not answer can show `timeout` rather than `unreachable`, since the 5-s dial outlasts the 3-s bound.
- Trade-off: a monitor alerts on another printer only by reading the body. A health read takes that printer's connection slot for up to 3 s and delays only its own lane. The public route now shows printer names, often room names, and models.
- Alternative: `/healthz?printer=<name>`, whose code follows that printer, with an error for an unknown name. It goes beyond what was asked.
Before stage 2a:
10. **Expr's version, and the size it adds.** Assumed: `github.com/expr-lang/expr` at its latest stable release, v1.18.1 (2026-11-22) at the time of writing. v1.18.0 and v1.18.1 fixed five advisories rated High that affect v1.17.8, Kanrisha's pin. Assumed too: the binary may grow by about 5.3-5.8 MB (+36-37%) on every target, armv6 included.
- About half is Expr itself. The rest is other packages' methods that the linker can no longer drop, because Expr calls `reflect.Value.MethodByName` with a name that is not a constant. GORM has the same effect (job-store question 1). It applies once per binary, so with Expr linked, GORM's extra cost over plain SQL falls to about its own code.
- The size was measured with v1.17.8 from the module cache. Stage 2a records the size with the version it pins, from the snapshot build.
- Trade-off: a larger tarball and image, and more to load on a Pi.
- Alternative: a match table in TOML with no expressions, which goes against the owner's decision.
11. **The config's shape.** Assumed: a `[routing]` section. `[routing.groups]` maps a group's name to its printers. Each `[[routing.rules]]` has `name`, `order`, `when`, `mode`, `to` and `enabled`. A rule's name follows the printer names' rule and is unique, so logs and `route` name one rule. `to` takes a name or a list, as list keys do. `when` is best written as a TOML literal string, so Expr's double quotes need no escaping. Both come from the file only: a list of tables has no variable, and a table of lists does not fit the `name=value` form, as the probe showed.
- Not `[[routes]]` and a top-level `[groups]`: "route" already means an HTTP route in server/routes.go, CLAUDE.md and api.md. A `[routing]` section also gives later keys a home.
- Trade-off: one more level in the file.
- Alternatives: `[[routes]]` and `[groups]`, which load the same way; or a key per mode (`printer`, `printers`, `group`) in place of `to`.
12. **Rule order.** Assumed: `order` is a required integer, unique across all rules, disabled ones included, lower first, as Kanrisha's priority; the first match wins. A disabled rule's `order` is unique too, so enabling it cannot break a start. It is not called `priority`, which a rule's `when` already uses for the ntfy priority. A unique `order` avoids Kanrisha's `sort.Slice`, which is not stable, so there rules of equal priority run in no fixed order.
- Trade-off: inserting a rule can mean renumbering; gaps of 10 help.
- Alternatives: an optional `order`, sorted stably, ties broken by position in the file. Or the order in which the rules are written, with no number, which departs from the owner's decision that rules are ordered by priority.
13. **Groups, and what `to` takes.** Assumed: groups hold printers, never other groups, so no cycle can form. Groups and printers share one namespace, since `to` can name either; a group named like a printer, or `default`, is an error. A group is not empty, repeats no member and names configured printers. `to` by mode:
- unicast: exactly one printer;
- multicast: one or more printers or groups, expanded, a repeated printer kept once;
- broadcast: nothing; it means every configured printer;
- anycast (stage 3): one or more printers or groups, in order, a group expanded in its member order, the first copy of a repeated printer kept.
- Trade-off: lists repeat where nested groups would not. Nesting needs a cycle check whose error names the cycle.
14. **A rule that fails to compile.** Assumed: a config error. The start fails, and so does `config get`, listing every problem with the rule's name, Expr's position and its message, for example `routing.rules[1] ("alerts").when: unknown name sorce (1:1)`. The source line Expr adds under its message is left out, since it could quote a topic. Expr's message itself can still quote a name or a constant pattern from the rule. Disabled rules are compiled too, so enabling one cannot break a start. On a reload (question 20), the new set is refused whole and the old one kept.
- This departs from the owner's decision as worded, which takes Kanrisha's "skips and logs a rule that fails to compile"; accepting this default amends it. Kanrisha's rules are database rows that must not stop the archiver. Here they sit in a file whose unknown keys already stop the start, and a skipped rule would send its jobs to the default printer without a word: paper in the wrong room.
- Trade-off: one broken rule stops the daemon at start.
- Alternative: Kanrisha's skip and log, as the decision words it.
15. **A rule that fails at run time.** Assumed: as in Kanrisha, the rule counts as not matched and the next rule is tried. One WARN line gives the `job_id`, the rule's name, and the line and column from Expr's `*file.Error`. It never calls `Error()`, whose text carries the rule's source and quotes values from the env: the probe's `int(topic)` gave `invalid operation: int(alerts-door)`, and a topic can be a secret. An error of any other type logs the rule's name only. It is reported to Sentry once per rule per run, without the message. A panic while the env is built is recovered: logged at ERROR, reported once, and the job goes to the default printer, since on the ntfy path a panic would end the daemon.
- Trade-off: the log does not say what went wrong; `uberbringer route` shows the whole message on the terminal.
- Alternatives: refuse the job, which is louder but loses jobs. Or list the rules that failed, by name, in the job's `route`, so that a job sent to `default` because a rule broke shows without the logs; that needs one more stored column, or a field a restart loses.
16. **What a rule sees.** Assumed: the variables under Architecture, THE ENVIRONMENT: routing facts only. No print content, no token or secret, no `ref`, no client address and no printer state. Stage 2a gives the job's source, shape and clock; stage 2c adds a notification's topic, priority and tags and the token's subject. In particular:
- `client` is the token's subject. It is free text chosen when the token is minted, and two tokens can share it.
- `priority` is 0 for a job that is not a notification. With 3, ntfy's default, `priority >= 3` would match plain jobs.
- A digest's `priority` is its highest row's, and its `topics` and `tags` the union of its rows'.
- `topic`, `topics` and `tags` also print on a card, and a topic can be a secret. They are in the env because routing notifications by them is the main use. The facts are used at `Submit` only: they are never kept in the job's status, logged, stored or sent to Sentry, and neither is the env or an Expr run-time message (question 15).
- Printer readiness stays out. Reading it at `Submit` would wait for each printer's connection slot, and flap with the passing states Epson printers report while cutting. It would come at the wrong moment, since the job prints later, and give another answer in a dry-run or after a restart. Only anycast acts on it, when it sends (questions 23 and 24).
- Trade-off: no rule can say "multicast when the kitchen is out of paper".
- Alternative: content in the env too, for routing by what a job says. Expr's messages and a dry-run would then quote it, and a 4 MiB body in a string builtin can exceed Expr's memory budget, so the same rule would fail only on big jobs.
17. **Compile options and the clock.** Assumed: `expr.Env(routing.Env{})`, `expr.AsBool()`, `expr.DisableBuiltin("now")`, `expr.DisableBuiltin("$env")` and the default node limit. `expr.Timezone` takes `format.timezone` once validation has loaded the zone, since it panics on an unknown name. The clock is injected: `now` is the job's acceptance time in `format.timezone`, so a dry-run with `--at` and the tests reproduce any decision. No guard against literal ranges, since rules are trusted config.
- Trade-off: Expr has no step limit. Nested predicates over large literal ranges, such as `any(1..999, any(1..999, # < 0))`, took about 30 ms, and one more level would take seconds here and minutes on a Pi, on every job. Only the owner writes rules.
- Alternative: a `Patch` visitor that refuses `..` ranges.
18. **Storing the decision.** Assumed: a route is decided once, at `Submit`, and stored; a restore never runs the rules again. The job keeps its `route`: `by` (`rule`; `query` for an explicit `?printer=`; or `default`), the rule's name and the mode, and job status shows it. An anycast delivery keeps its ordered list and the printers that got a `sending` mark (stage 3).
- This replaces job-store.md's assumption that a restored anycast delivery's list is "given again" by the rules and the config. Its `jobs` row keeps no priority, tags or client, and the rules may have changed since.
- With SQLite, `jobs` gains `route_by`, `route_rule` and `route_mode`, and `deliveries` gains `candidates` and `sent_to`, names joined by commas, which a name cannot hold. If job-store stage 1d has not shipped when stage 2a starts, these columns join its first schema; otherwise stage 2a adds one schema step to `user_version` 2.
- Trade-off: five columns; a job keeps the route it was given after the rules change.
- Alternative: store the facts as JSON and evaluate again at restore. That costs as many bytes, gives another answer after a config change, and puts topics on disk.
19. **Multicast and broadcast.** Assumed:
- Capacity is checked on every target lane under the submit lock. The job is accepted when at least one target lane has room. A delivery whose lane is full is inserted already `failed`, with the error "printer's queue is full", in a synced commit as any failure is. It is logged at WARN by `job_id` and `printer`, and not sent to Sentry, since a full queue is a refusal, not a fault. `Submit` answers `queue_full` only when every target lane is full.
- With all-or-nothing capacity instead, a dead printer's full lane would refuse every broadcast, and every multicast that includes it, though every other printer is fine. A dead lane fills fast, since it drains one delivery per 7-27 s. On the ntfy path `queue_full` makes the subscriber stop reading, so one dead printer would stall a whole subscription, the `urgent-on-desks` example included.
- Each delivery renders on its own lane with its printer's options, so an image is fetched once per delivery. Rendered bytes are never stored (job-store question 8).
- An ntfy subscription's paper budget counts jobs, not deliveries, so a multicast rule prints a budgeted receipt on each printer of its set.
- `copies` applies to each delivery.
- Trade-offs: a job can be `failed` on one printer while it prints on the others; its `status` says so once they finish (job-store question 12), and `deliveries` at once. The same image URL is fetched N times and may answer differently. Lanes render in parallel, so a broadcast with large images holds N renders in memory at once, which matters on a Pi Zero. The budget does not count the second roll.
- Alternatives: all or nothing, which keeps a job whole but lets one dead printer refuse the others' jobs; render once per distinct set of options and share the bytes; one render at a time across the lanes; count deliveries in the budget.
Before stage 2b:
20. **Reloading the rules.** Assumed: SIGHUP reads the config again. The whole file must load and pass, its rules compiled; then `[routing]` takes effect at once, swapped as one set.
- The new routing is checked against the printers that are running, not the new file's. Every rule's `to` and every group member must name a printer that has a lane, or the whole reload is refused. `broadcast` means the running printers. The rules compile with the running `format.timezone`, so that `date()` and `now` agree.
- Any other change is logged at WARN, by section name only and never a value, as taking effect at the next restart, and is not applied.
- A file that fails, or a refused reload, keeps the old set and is logged at ERROR. Like a bad config at start, it is not sent to Sentry.
- Deliveries already queued keep their routes.
- The unit gains `ExecReload`, so `systemctl reload uberbringer` works; a container takes `docker kill --signal HUP`; Windows, for development only, has no reload. Viper's `WatchConfig` is not used: it fires on an editor's partial saves.
- With these checks, `Submit`'s guard for a printer with no lane cannot fire; it stays for a bug (Architecture, ROUTING RULES).
- Trade-off: more code and tests than a restart. A new printer, and a rule for it, need a restart. Until job-store stage 1d, a restart fails the waiting jobs, which a reload does not.
- Alternative: no reload, which goes against the owner's decision ("swaps the rule set atomically on reload").
Before stage 2c:
21. **The dry-run.** Assumed: a command, `uberbringer route`, reads the config and a job file or a module payload. It takes the facts as flags (`--source`, `--subscription`, `--client`, `--topic`, `--priority`, `--tag`, `--digest`, `--printer`, `--at`). It prints the env, each rule's result, error or "disabled" in order, and the decision. It sends nothing, reads no status and fetches nothing. The JSON preview also gains `route`, the decision the rules make for that request now, so a client can check its routing without printing. No route takes an expression from a request: Expr's advisories matter only for expressions nobody trusts.
- Trade-off: the JSON preview shows rule and printer names to any token that may preview, tokens limited to modules included.
- Alternative: `POST /api/v1/route` for full tokens, which needs its own entry in the route table, test case, docs and schema.
Before stage 3:
22. **Failover after bytes went out** (job-store question 23). Assumed, the owner's default: the existing retry rule on that printer (`retries`, with the doubling `retry_delay`), then failover to the next printer of the list.
- The delivery's `sent_to` lists every printer that got a `sending` mark, so a person knows which paper to check.
- A write error after which `Write` had taken nothing counts as nothing sent and fails over at once. That needs `Send` to report what it wrote, which it discards today. The printer stays in `sent_to` all the same: over-reporting is the safe direction, and dropping it would cost one more store write.
- `attempts` counts every attempt on every printer, and each mark's attempt number goes on from the last.
- The risk: the next printer prints the whole receipt. A first printer that took all of it before the error, or buffered it and prints it once its fault clears, prints it too.
- Some sends that will not print show no error at all. `Write` returns once the kernel holds the bytes, so a printer that goes offline after taking them, or one that another host holds, takes the receipt without a word, and no failover happens (Investigation findings, WHAT "THE PRINTER FAILED" CAN MEAN).
- Alternatives: (a) no failover after a `sending` mark: the delivery retries on that printer, then fails, and a person checks the paper; (b) failover at once after a mark, without retries: faster, with the same risk; (c) once job-store phase 5's confirmed send exists, a partial write makes the delivery `uncertain` and never resent.
23. **A status check before an anycast send.** Assumed: after the dial and before the `sending` mark, on the same connection and inside the printer's slot, anycast reads `DLE EOT`. It reads a not-ready answer again 750 ms later, as `/healthz` does.
- The read runs over the connection already open, so it never waits on its own slot.
- It reads `DLE EOT` only. Stage 4a's `GS r 1` is not real-time, adds up to 500 ms, and could close the connection the job is about to be written on (question 28). Near-end never decides a failover.
- A printer still not ready (offline, cover open, paper out, an error) counts as nothing sent. It is marked down (question 24), and the delivery fails over at once.
- A timeout or no answer sends anyway: a timeout is never a printer fault, and a printer busy with an earlier job may answer late.
- Unicast and multicast do not check, as today. The check and `/healthz` share one settle function, moved from the server to `printer`, which takes the read to use.
- Without the check, a printer out of paper most likely still takes the connection and the bytes, so the main anycast case would fall into question 22's path. That is an inference, and a paper check tests it before stage 3 starts. With the owner's OK, one short receipt goes unicast to the TM-T88IV with its paper out (or its cover open). Does the printer take the connection and the bytes, and print the receipt once the paper is loaded?
- Trade-off: one status round trip per attempt, and up to 0.75 s more in the slot. An auto-recoverable error, such as a print head that is too hot, clears by itself, so waiting for it may beat failing over.
- Alternatives: no check; or a check on every send, unicast included, which changes today's behaviour of buffering a job for a printer that is briefly offline.
24. **A printer marked down.** An anycast delivery joins the lane of its first printer. When that printer is dead, the delivery waits behind every earlier delivery on that lane, and each of those retries before it fails. That is about 27 s each at the defaults when dials time out (four dials of 5 s, plus waits of 1, 2 and 4 s), or about 7 s when they are refused. Ten unicast jobs for a dead `office` would delay an `alerts` job by 4-5 minutes while `default` sits idle. Once the dead lane is full, `Submit` would refuse the anycast job. Anycast would fail in the very case it exists for. Assumed:
- A printer is marked down after a failure before any byte of a job: a refused, unreachable or timed-out dial, or a printer still not ready at the anycast check. Any delivery's failure marks it, unicast included. A failure our own context caused never does.
- The mark clears on the printer's next successful send, or after a hold of 30 s (a constant, not a key). It lives in memory and is lost at a restart.
- A printer behind an agent stays marked while its agent is offline or does not list it (docs/plans/remote-printers.md, decision 18).
- At `Submit`, an anycast delivery joins the first printer of its list that is not marked down and whose lane has room; else the first with room. `queue_full` comes only when every lane of the list is full.
- Marking a printer down moves the anycast deliveries waiting on its lane on at once. A worker that takes an anycast delivery for a printer marked down moves it on without dialling.
- A mark only passes a printer over for a later one of the list that is not marked. When every printer left is marked, the first of them is tried as usual, so the attempt renews or clears its mark.
- Rules never see the mark (invariant 4).
- Trade-off: a printer that recovers within the hold gets no anycast jobs for up to 30 s, and a passing not-ready sends a job to the next printer.
- Alternatives: check capacity on any lane of the list but keep the place, which does not end the wait; put the delivery at the front of the first lane, which still waits for the dial in hand and its retries; no mark.
25. **A list that fails before any byte.** Assumed: rounds. When the last printer fails before sending, the list starts again from the top after the first printer's `retry_delay`, doubling, for up to the first printer's `retries` more rounds.
- Between rounds the delivery waits on a timer, on no lane. When the delay ends, the timer puts it on the lane of its first printer not marked down (question 24). No worker sleeps, so no lane is blocked by a delivery bound elsewhere. The timer follows the rules for a move (question 26), and at shutdown or a cancel a delivery on a timer counts as waiting.
- Once the rounds are spent, one last attempt sends to the first printer without the status check, as unicast does. No other printer got bytes, so it cannot print twice. A list whose printers are all briefly not ready, such as a cover opened to change the paper, then still prints, as unicast would have. Only then does the delivery fail.
- A delivery that sent bytes anywhere starts no new round. Each lane's take keeps its own 2-minute bound.
- Trade-off: a failed anycast delivery can take about a minute with three printers at the defaults.
- Alternatives: one pass, then failed; or the last attempt with the check too, which loses a job that unicast would have printed.
26. **Moving a delivery.** Assumed:
- A moved delivery joins the next printer's waiting list in sequence order, ahead of later jobs, and is never refused for capacity. The first printer's slot is released before the next printer's worker takes its own, so failover never holds two slots.
- A move takes the status lock, and job-store phase 2b's delivery lock once that exists. It happens only while the queue is open and the delivery is not cancelled. A failure while the delivery's context has ended (a shutdown, a cancel or its 2-minute bound) never moves it. With a durable store, dialling runs on a context that ends with the daemon, and a cancel ends the delivery's context, so their errors would otherwise look like a dead printer. Shutdown and the cancel follow their own rules, and the bound fails the delivery, as today.
- It renders again only when the next printer's options key differs; with an equal key it keeps its bytes. Each lane computes its key at start from its profile and every `receipt.Options` field, since the options may come to hold fields that cannot be compared.
- A render error moves on only to a printer whose key differs, since it would fail the same way on the others. With none left, the delivery fails.
- A moved delivery counts as taken from its first take until it finishes, so a job never reads `printing`, then `queued`, then `printing` (job-store question 12).
- After a `sending` mark, a moved delivery stays `sending` in the store while it waits on the next lane. A crash then turns it `uncertain` at the restart, and it is never sent, even when its write took nothing. That is the safe direction, as job-store has for a crash between the mark and the write.
- At a clean shutdown, a delivery waiting on a lane after a mark fails with `sent_at` and `sent_to`, with either store. That is job-store's rule for a delivery between retries after reaching `sending`.
- Job-store phase 2b's cancel leaves a delivery with any mark alone, even while it waits on the next printer. One without a mark can be cancelled wherever it waits.
- A restored queued anycast delivery starts again from the top of its stored list (question 18).
- Trade-off: a moved delivery goes ahead of the next printer's later jobs. A receipt whose write took nothing just before a crash is lost as `uncertain`.
- Alternatives: the end of the next printer's list. Or a lazy commit back to `queued` after a write that took nothing, when no attempt sent bytes, so a restart sends it; that needs one more store method and write.
Before stage 4a:
27. **Keeping the exact model.** Assumed: `escpos.Profile` gains `Model`, the name as configured (`tm-t88iv` to `tm-t88vii`, `tm-m50ii`, `tm-t20ii`; a family name stays itself). It also gains the model's status capabilities: where paper near-end comes from (`DLE EOT 4`, `GS r 1` or nowhere), and whether `DLE EOT 3` bit 2 exists.
- Only `tm-t88vii` takes near-end from `GS r 1`. Every other name keeps today's `DLE EOT 4`. The families `tm-t88` and `tm-m50` behave as the TM-T88IV and the TM-m50II; `tm-m50` (the TM-m50) and the `tm-t20` and generic profiles stay unverified.
- `Name` stays the layout family (`tm-t88`), so previews and pinned bytes do not change.
- The default, `tm-t88`, keeps the TM-T88IV's status behaviour, so a TM-T88VII must be configured as `tm-t88vii` to report its near-end.
- Trade-off: a TM-T88VII configured as `tm-t88` reports no near-end, as today.
- Alternative: `tm-t88vii` as a profile with a name of its own, which changes the name that previews and the models table in docs/configuration.md show.
28. **The TM-T88VII's near-end through `GS r 1`.** Assumed: `Status` sends it last, only when `DLE EOT` says online and ready, under a deadline of its own (500 ms, assumed). The anycast check (question 23) never sends it.
- Its reply has a decoder of its own, since its fixed bits differ from `DLE EOT`'s and `Status.Apply` would refuse it. The decoder accepts the byte the TM-T88VII actually sends, since Epson's page contradicts itself.
- No answer means near-end is unknown: `paper` reads as `DLE EOT 4` gave it, never `timeout`, never `503`.
- The connection closes after a missed answer, since a late one could be read as the answer to the next request. Closing does not stop a late reply: the board, not TCP, routes the printer's output, so the reply can reach the next connection. There it fails the `DLE EOT` mask, since its bits 0 and 1 are both clear or both set, and reads once as unsupported (`unknown`, `200`).
- Trade-off: `GS r 1` is not real-time. It is answered once the lines before it have printed, so during a long print it is usually missed. A late reply costs one `unknown` reading.
- Alternatives: automatic status (`GS a`), whose third byte may carry near-end on that model (unverified, and it arrives unasked); or the TM-T88VII's TM-T88V emulation, if it brings the bits back to `DLE EOT 4` (unknown).
29. **More status bits, and frames nobody asked for.** Assumed: `Ready()` also counts `DLE EOT 2` bit 6 (an error occurred) and `DLE EOT 3` bit 2 (a recoverable error; the TM-T88IV lacks it), read again like the rest. `Normalized()` clears `DLE EOT 2` bit 6 while `DLE EOT 1` says online, as it clears that byte's other bits, so a stale bit while cutting does not read as not ready. On the TM-T88VII the autocutter-error bit also means a paper jam; api.md says so. Automatic-status frames are left alone until stage 4a's first step shows whether they reach a port 9100 client. The UB-E02 and UB-E03 boards turn them on at power-on, and a TM-T88VII with DIP switch 2-1 on keeps them on. If they do reach the client, job-store phase 5's frame reader comes forward.
- Trade-off: `/healthz` can answer `503` on a recoverable error where it answered `200`.
- Alternative: decode what is decoded today.
Before stage 4b:
30. **Per-model defaults in the profile.** Assumed:
- The default line spacing (`ESC 2`) is 30 dots, 1/6 inch, on all three printers, so it changes no byte. job-store phase 3a's drawing is its first reader and defines `Profile.LineSpacing` there. This plan adds nothing for it.
- `box_line_spacing` keeps one default, 0, as calibrated on the TM-T88IV, until stage 4b's paper check finds a model whose borders need another value. Only then does `Profile` gain `BoxLineSpacing`. The key's default then becomes -1, meaning "the model's", validated from -1 to 255, since an explicit 0, and `UBERBRINGER_PRINTER_BOX_LINE_SPACING=0`, must still mean `ESC 2`. The load helper resolves -1 from the profile, so `config get` prints the value in use.
- `cut_feed` stays one default for every model. `GS V 66` feeds to the printer's own cutter, and a line is the same on every model, so the cut lands alike. Only the distance from the head to the cutter (about 15 mm on the TM-T88IV to VII, about 9.5 mm on the TM-m50II) differs, and with it the next receipt's top margin, which matters for the drawn preview alone.
- Trade-off: -1 is a value a user can write; the docs say what it means.
- Alternatives: a pointer (`*int`) for a key left out, which the decode hooks and `Value()` must handle; or no per-model default, with a calibrated value written into that printer's table by hand.
31. **Printer settings that change layout.** Needed before the first receipt on a new printer. Assumed: factory settings: 42/30 column mode, 80 mm paper, no automatic paper reduction and the default top margin. The owner reads each printer's status sheet when it arrives.
- Trade-off: in 48/36 column mode the width is 480 dots and Font A is 10 dots wide, so `tm-t88` and `tm-m50` would break words at the printer's edge. Paper reduction of the bottom margin would remove `cut_feed`'s blank lines.
- Alternative: profile variants for 48-column mode. 58 mm paper already works through `paper_width = 360`.
## Investigation findings
Four research tracks ran on 2026-11-30: Expr and Kanrisha's engine, the config loader, a map of the repository, and Epson's documents for the three printers. Runs were light: probes on a copy of the code exported with `git archive`, offline against the module cache, with Go 1.27.3. Nothing contacted the printer, no `config.toml` was read, and the repository was not changed.
EXPR
- Versions, from proxy.golang.org: v1.18.1 (2026-11-22) is the latest; v1.18.0 (2026-11-21) limits nesting to 10,000 levels, counts string building against the memory budget and makes `DisableAllBuiltins` cover the predicates too; Kanrisha pins v1.17.8 (2026-02-14).
- Seven advisories, all rated High. Five affect v1.17.8 and are fixed in v1.18.0 or v1.18.1: type checking that grows exponentially with nested overloaded builtins, which cannot be cancelled; deep `(` nesting that overflows the stack fatally at compile time; and three ways around the memory budget (`repeat()`, string concatenation, builtins called through `OpCall*`). They matter only for expressions nobody trusts, so no route takes one. Kanrisha's pin is outside this repository and noted for the owner.
- MIT licence. Its go.mod has no requirements, so it is pure Go with no dependencies. The daemon built with it linked, `CGO_ENABLED=0`, for every release target. Expr's own CI builds 386 and tests amd64 only.
- Size, built with the goreleaser flags and v1.17.8:
| Target | Without Expr | With Expr | Added |
|---|---|---|---|
| linux/amd64 | 15,380,640 | 21,106,848 | +5,726,208 (+37.2%) |
| linux/arm GOARM=6 | 15,007,904 | 20,381,856 | +5,373,952 (+35.8%) |
| linux/arm GOARM=7 | 15,007,904 | 20,381,856 | +5,373,952 (+35.8%) |
| linux/arm64 | 14,221,472 | 19,529,888 | +5,308,416 (+37.3%) |
| windows/amd64 | 15,879,168 | 21,724,672 | +5,845,504 (+36.8%) |
Expr itself is about 2.5 MB. The rest comes from `reflect.Value.MethodByName` called with a name that is not a constant (`vm/runtime/runtime.go`, `builtin/lib.go`), which keeps other packages' unused methods in the binary: Fiber's text symbols went from 564 to 1,247. No build tag avoids it.
- Speed (v1.17.8, workstation): a compiled rule runs in 89-418 ns with 2-6 allocations; a method call on a `time.Time` field is the slowest. Compiling one rule takes about 15 µs. A compiled program never changes and is safe for many goroutines; `expr.Run` makes a new VM per call, and reusing one was not faster.
- Checked at compile time with a struct env and `AsBool()`: unknown names, `priority == "5"`, `tags == "x"`, a result that is not a bool, and a bad constant regex all fail, with a caret at the position.
- Safety:
- No side effects, and it always terminates: there are no loops or recursion. Panics in the VM come back as errors.
- No step limit. The memory budget counts allocations, not steps: `all(1..999999, # > 0)` took 35 ms, `any(1..999, any(1..999, # < 0))` 31 ms.
- Runtime errors quote values: `int(topic) > 3` gave `invalid operation: int(alerts-door)`, `tags[5]` gave `index out of range: 5 (array length is 2)`. Errors also carry the rule's source with a caret.
- `$env` reaches every exported field of the env.
- `now()` reads the wall clock. An env field named `now` hides it; `DisableBuiltin("now")` removes it.
- `Timezone(name)` panics on an unknown zone. Without it, `date()` parses in UTC.
- Expr runs its own bytecode with no JIT, so it does not conflict with `MemoryDenyWriteExecute=true` in the unit.
- `"x" in tags` on an empty list is false, with no error. Strings compare in byte order, so a zero-padded `clock >= "22:00"` works.
KANRISHA'S ENGINE
- `Rule` has an ID, name, expression, action and params, filesystem scopes, an integer `Priority` (lower first) and `Enabled`. `CompiledRule` pairs it with its program.
- Compile: `expr.Compile(expression, expr.Env(EnvPrototype()), expr.AsBool())`, with no node limit and no builtin turned off, so `now()` stays beside the injected `now`. The API compiles a rule before storing it, so a bad one is refused when it is created.
- `LoadRules` skips disabled rules, compiles the rest, logs and skips a rule that fails, sorts by priority with `sort.Slice`, which is not stable, and swaps the set under a write lock. `AddRule`, `UpdateRule` and `RemoveRule` re-sort.
- Evaluation copies the rule slice under a read lock, builds the context once, and runs each rule; a runtime error is logged and the next rule is tried; the first match wins.
- The env is a map, with a hand-kept prototype, a third list for its form builder and a fourth in its docs, which already differ.
- Reload: an API route and a NATS broadcast make every node read the rules again. Dry-run: compiles a rule that need not be loaded and evaluates it against chosen files, with no side effects.
- Its tests include a concurrency test of 100 goroutines under `-race`.
- What this plan keeps: compile once against a typed env with `AsBool`; first match wins; `enabled`; a set swapped whole; a runtime error means no match; an injected clock; a dry-run that changes nothing; the concurrency test. What it changes: a struct env with `expr` tags in place of a map and its prototype (question 17); a unique `order` in place of an unstable sort (question 12); `now()` turned off (question 17); a rule that fails to compile is a config error (question 14); an `atomic.Pointer` to an immutable set in place of a lock and incremental changes; a generic engine that templates can share, as design.md's Planned next item 5 asks.
THE CONFIG LOADER
- Today's loader refuses `[printers.office]` as an unknown key: a map field is one setting, and the walker refuses an entry of it that is itself a table. With a new key kind, whose entries are checked against `printers.*.<key>`, and the per-entry default hook the subscriptions use, `[printers.kitchen]` with only `address` got every default.
- The existing walker already refuses an unknown key in an entry, two names differing in case, a quoted dotted name and an entry that is not a table.
- Viper lowercases map keys: `[printers.Office]` loaded silently as `office`, and a group named `Desks` as `desks`. Values keep their case, so a group member `"Office"` stays `"Office"`.
- A list of tables loads `enabled` as false when it is left out, unless a default hook sets it true, as the subscriptions' does.
- `[groups]` as a table of lists gets a variable, `UBERBRINGER_GROUPS`, whose `name=value` form cannot hold a list: `desks=default,office` fails with a misleading example in its error.
- `UBERBRINGER_PRINTERS_OFFICE_ADDRESS`, bound after the file is read, overrides the file for a printer it names. One for a printer the file does not name is ignored without a word.
- `Value()`, behind `config get`, walks struct fields only and cannot reach `printers.office.address`.
- There is no reload: the daemon handles SIGINT and SIGTERM only, the unit has no `ExecReload`, and nothing calls Viper's `WatchConfig`.
THE REPOSITORY TODAY
- serve.go builds one renderer, one `printer.Client`, one queue with one worker, and one `Printer` for `/healthz`. Its `listening` line gives the printer's address. `printqueue.Sender` and `server.Printer` are already the interfaces a printer needs.
- `escpos.LookupProfile` folds `tm-t88iv` to `tm-t88vii` into `tm-t88`, and `tm-m50ii` into `tm-m50`, and TestLookupProfile pins it. Nothing after the lookup can tell a TM-T88VII from a TM-T88IV.
- `printqueue.Meta` holds the source and the reference only, and its doc comment says it is kept with the job's status and logged with it. The ntfy priority, topic and tags are in hand in ntfy.go but never reach `Submit`. `Module.Build` returns only a `receipt.Job`, so the facts of `/print/notify` and `/print/ntfy` stay inside the module. It is called at server/handlers_modules.go:90 and internal/app/uberbringer/preview.go:137 (`preview --module`); its fakes are `fakeModule` (server/handlers_modules_test.go) and `stubModule` (modules/registry_test.go). auth.go keeps only the token's scope, not its subject.
- An ntfy subscription offers a message again after any `Submit` error, `queue_full` included, and stops reading meanwhile (design.md, TCP backpressure).
- `/print` and `/preview` read no query. Only the module routes parse one, and accept `printer=default` alone (`unknown_printer` otherwise); an empty `printer` means the default.
- The worker retries every `Send` error alike, and `Send` discards the count `Write` returns, so a dial failure and a write cut short look the same.
- `Client.Status` takes the connection slot through `connect`, and `settledPrinterStatus` in server/handlers.go calls it twice. Run inside a send that holds the slot, it would wait on that slot until the job's bound ends.
- `/healthz` reads one printer, reading a not-ready answer again after 750 ms, within 3 s. A dial that times out returns Go's time-out error, which `errors.Is` matches to `context.DeadlineExceeded`, so `/healthz` maps it to `timeout`.
- The server's test helpers have 50 callers that pass one printer: `newTestServer` 40 and `newLoggedServer` 10.
THE THREE PRINTERS (Epson's Technical Reference Guides and command reference)
| | TM-T88IV | TM-T88VII | TM-m50II |
|---|---|---|---|
| Density | 180 × 180 dpi | 180 × 180 dpi | 180 × 180 dpi |
| 80 mm paper | 512 dots (72.2 mm) | 512 dots | 512 dots, in 42/30 column mode |
| Font A / Font B | 12 × 24, 42 columns / 9 × 17, 56 | the same | the same |
| Default line spacing | 30 dots (1/6 inch) | the same | the same |
| `GS P` motion units (x, y) | 180, 360 | 180, 360 | 180, 360 |
| Head to autocutter | about 15 mm | about 15 mm | about 9.5 mm |
| 58 mm paper | not supported | a printer setting: 360 dots | a printer setting: 360 dots |
| 48/36 column mode | none | a printer setting: 480 dots, Font A 10 wide | the same |
| Code pages (`ESC t`) | 0-5, 16-19 | 0-5, 11-21, 26, 30-53 | 0-5, 11-21, 26, 30-53 |
| Near-end in `DLE EOT 4` | yes | **no** (bits 2 and 3 not supported) | yes |
| Network | UB-E02 or UB-E03 board, port 9100 | built in, port 9100 | built in, port 9100 |
| Connections accepted / printing | 3 / 1 | 6 / 1 | 6 / 1 |
| Idle time-out | 300 s | 90 s | 90 s |
- CLAUDE.md's geometry holds: the TM-m50II is 512 dots, not 576. One profile's layout covers all three, and the default line spacing is the same on all three, so a per-model line spacing changes no byte for them.
- Every command the renderer sends is in each model's command list, and so are the code pages it uses (0, 2, 16 and 19). Each job starts with `ESC @` then `ESC t`, so a printer's own default page never matters.
- The TM-m50II's command list includes `GS ( H` fn 48, which job-store.md lists as unconfirmed for it. It is still unverified over port 9100.
- Only the first accepted connection prints; the others connect, and their data waits until it closes.
- The UB-E02 and UB-E03 turn automatic status on at power-on; a job's `ESC @` turns it off. A TM-T88VII with DIP switch 2-1 on keeps it on after `ESC @`. A frame's first byte fails the `DLE EOT` mask, so `Status` would read it as "unsupported".
- A byte string inside a command's parameters that matches a real-time command is executed as one: image or `raw` bytes that hold `10 04 n` make the printer send a status byte during a send.
- Settings that change layout, on the TM-T88VII and TM-m50II: 58 mm paper, 48/36 column mode, automatic paper reduction (top and bottom margins, blank lines, barcode and character height), and the top margin.
- SNMP on the boards and the newer printers reports status without the print connection. Not researched further.
REAL-TIME STATUS (`DLE EOT`) PER MODEL
| n | Bits | TM-T88IV | TM-T88VII | TM-m50II |
|---|---|---|---|---|
| 1 | 3 offline; 5 waiting for recovery; 6 feed button | bits 5 and 6 not supported | all | all |
| 2 | 2 cover open; 3 feeding by button; 5 paper-end stop; 6 error occurred | all | all | all |
| 3 | 2 recoverable error; 3 autocutter error; 5 unrecoverable; 6 auto-recoverable | bit 2 not supported | bit 3 also means a paper jam | all |
| 4 | 2 and 3 near-end; 5 and 6 paper end | paper-end bits keep their value while the cover is open | bits 2 and 3 not supported | paper-end bits keep their value while the cover is open |
- `escpos.Status` decodes neither `DLE EOT 2` bit 6 nor `DLE EOT 3` bit 2, so `Ready()` misses a recoverable error on the newer models.
- `GS r 1` reports near-end on all three, but it is not real-time: it is answered after the printing before it has finished, and at paper end the TM-T88IV to VII go offline and do not run it. Its fixed bits differ from `DLE EOT`'s (bit 4 is 0, where `DLE EOT` has 1), so `Status.Apply` would refuse it; Epson's page also says to accept `0xx1xx10`, contradicting its own table.
WHAT "THE PRINTER FAILED" CAN MEAN
"Sent" means bytes the kernel took from `Write`. Whether they printed is unknowable without an acknowledgement (job-store phase 5). A text receipt of a few KB is usually taken whole at once, so a write error mostly shows on large image jobs or blocked or reset connections (an inference).
| Signal | Bytes of the job sent | Printer at fault |
|---|---|---|
| The wait for this daemon's own connection slot ends | none | no: busy here |
| DNS failure; connection refused (port closed, or the board's connection table full); dial time-out; host unreachable | none | usually |
| Setting the write deadline fails | none | no |
| A status check before the first byte (proposed), read again: offline, cover open, paper out, an error | none | yes |
| The same check shows near-end only | none | no: it still prints |
| The same check times out, or gets no or a malformed answer | none | unknown; a timeout is never a fault |
| `Write` fails having taken nothing | none | depends |
| `Write` times out, or the connection resets, after part of the job | part | unknown, or yes |
| The dial succeeds while another host holds the printer; a small job's `Write` returns | all, held | unknown: it may print when the other host lets go |
| `Write` returns, then the printer goes offline (cover, paper end); the data prints when the cause clears | all | yes, but failing over prints it twice |
| A render error | none | no: a fault of the job, unless that printer's options cause it |
WHERE THE REPORTS DISAGREE OR ARE UNSURE
- Rule order: the Expr track assumed the order in the file with no number; the config track a required, unique `order`. Question 12.
- Config names: the Expr track sketched `[[rules]]` and `[groups]` with a key per mode; the config track `[routing]` with `to`. Question 11.
- Reload: the Expr track assumed SIGHUP; the config track none in this plan. Question 20.
- A rule's runtime error in the log: with its message (Expr track), or never (config track), since the message quotes env values. Question 15.
- The name pattern: the module names' form (Expr track) or the subscriptions' (config track). Question 2.
- Whether an offline printer behind a UB-E02 or UB-E03 still accepts the connection and holds the bytes: an inference, unverified. Question 23's paper check, before stage 3.
- `GS r 1`'s fixed bits: Epson's page contradicts itself. Stage 4a's first step reads what the TM-T88VII sends.
- Whether automatic-status frames reach a port 9100 client: unverified (job-store.md says the same). Stage 4a's first step.
- Whether the TM-T88VII's TM-T88V emulation brings near-end back to `DLE EOT 4`: unknown.
- Head-to-cutter distances are "approximately" in Epson's guides; the drawn preview marks them unverified until checked on paper.
- The TM-m50II's receive buffer was not checked.
- Every measurement used Expr v1.17.8; v1.18.1 was read on GitHub, not built. Stage 2a records the size with the version it pins.
SOURCES
- Expr: proxy.golang.org (`@v/list`, `@latest`, `v1.18.1.info`, `v1.18.1.mod`); https://github.com/expr-lang/expr/releases and /security/advisories; at v1.18.1, `expr.go`, `conf/config.go`, `vm/vm.go`, `vm/runtime/runtime.go`, `builtin/builtin.go`, `builtin/lib.go` and `.github/workflows/`; https://expr-lang.org/docs/language-definition.
- Kanrisha: `internal/policy` (engine.go, policy.go, context.go, rules.go, builder.go, engine_test.go), `internal/api/v1/policies.go`, `internal/daemon/policy_sync.go`, docs/policies.md.
- Viper: https://github.com/spf13/viper (FAQ on case-sensitive keys). POSIX variable names: https://pubs.opengroup.org/onlinepubs/9799919799/basedefs/V1_chap08.html.
- Epson:
- TM-T88IV TRG Rev. C: https://files.support.epson.com/pdf/pos/bulk/tm-t88iv_eng_trg_revc_02.pdf
- TM-T88VII TRG M00138506 Rev. G, a third-party copy: https://www.123inkt.be/pdf/TM-T88VII_manual.pdf
- TM-m50II TRG M00153106 Rev. G: https://files.support.epson.com/pdf/pos/bulk/tm-m50ii_trg_en_rev_g.pdf
- UB-E02 TRG Rev. A: https://files.support.epson.com/pdf/pos/bulk/ube02_trg_reva.pdf; UB-E03 TRG, p. 50: https://www.manualslib.com/manual/1807854/Epson-Ub-E03.html?page=50
- The ESC/POS command reference, read in a browser, since it refuses automated fetches: `dle_eot.html`, `gs_lr.html` (`GS r`), `esc_2.html`, `esc_3.html`, `gs_cp.html` (`GS P`), `gs_cv.html` (`GS V`), `esc_lt.html` (`ESC t`), `gs_la.html` (`GS a`), `realtime_commands.html`, and the model pages `tmt88iv.html`, `tmt88vii.html` and `tmm50ii.html`, under https://download4.epson.biz/sec_pubs/pos/reference_en/escpos/.
## Overview
WHAT SHIPS WHEN
1. Stage 1a: named printers beside the default, a lane each, `preview --printer`, and `config get` checking every printer. Every job still prints on the default printer. Stage 1b: `?printer=` on every print and preview route, `/healthz` per printer, and deliveries in job status.
2. Stage 2a: Expr rules in unicast, multicast and broadcast, on a job's source, module, subscription, shape and clock; groups; the stored decision. Stage 2b: SIGHUP reloads the rules. Stage 2c: a notification's topic, priority and tags and the token's subject in rules; `uberbringer route` and the route in the JSON preview.
3. Stage 3: anycast, with failover down an ordered list.
4. Stages 4a and 4b, as each printer arrives: the exact model in the profile, the TM-T88VII's near-end, and each model checked on paper.
5. Next, in docs/plans/remote-printers.md: printers behind an agent, through the seam this plan leaves and does not build.
COMPATIBILITY
- A config with `[printer]` alone loads and prints as today: one lane, no rules, every job on `default`. install.sh, the Dockerfile and `UBERBRINGER_PRINTER_*` do not change. Two changes reach every config:
- **Breaking:** `/print` and `/preview` refuse query parameters other than `printer` (question 7).
- Job status gains `deliveries` (question 8), and from stage 2a `route` (question 18). Its other fields keep their meaning.
- `?printer=default` keeps working on the module routes, and an empty `printer` still means the default printer.
- `/healthz` keeps `status`, `printer` and its code; it gains `printers`. `queue.pending` becomes the total across printers.
- `queue.size` bounds each printer's queue, so a host with several printers can hold more jobs (question 4).
- What prints does not change. TestRenderCompat and TestPaperReceipts keep passing; stage 4b changes bytes only for a model whose paper check sets a value.
- A downgrade: an older binary refuses `[printers.*]` and `[routing]` as unknown keys. With a durable store:
- Between job-store stage 1d and this plan's stage 2a, an older binary opens the store, and its single worker would take every waiting delivery, whatever its printer. The queue must drain first.
- From stage 2a's schema step to `user_version` 2, an older binary refuses to open the store, so a downgrade also moves the store aside, by the steps in docs/install.md and docs/docker.md.
- docs/install.md and the CHANGELOG say so.
INVARIANTS
1. Nothing reaches a printer unless the whole receipt rendered for it, with its own profile and options. A failover to a printer with other options renders in full before it sends.
2. Layout comes from each printer's profile. A job stays printer-neutral (formatters invariant 1), so any delivery can go to any printer. The exception is a `raw` element, whose bytes are written for one model; a rule on `types` keeps them there.
3. A job no rule matches prints on the default printer, and a config without `[printers]` or `[routing]` prints as today.
4. A rule sees routing facts only, never print content, a token, a secret, a `ref` or a printer's state, its down mark included. Neither the env, the facts nor an Expr run-time message reaches logs, Sentry, the store or job status. A compile error leaves out the rule's source line.
5. A route is decided once, at `Submit`, from the job's facts, its acceptance time and the rule set, and stored. A restore never decides again.
6. Each printer has its own connection slot and one connection at a time, and no two printers share an address. Failover never holds two slots.
7. An anycast delivery fails over at once only when none of its job's bytes went out: before its `sending` mark, or when `Write` took nothing. A failure its own context caused (a shutdown, a cancel or its bound) never fails over.
8. `/healthz`'s status code follows the default printer alone.
9. printqueue, server and config never import Expr, so tools/genopenapi never compiles it. printqueue and printer never import each other.
10. job-store.md's invariants hold for each delivery.
ON ACCEPTANCE
When the owner accepts this plan, these edits are made:
- design.md: Planned next item 2 says the plan is written and its questions await the owner.
- docs/plans/formatters.md: its open question goes, answered by the example under Architecture, ROUTING RULES. Its phase 5 items for a second printer and for per-model line spacing go, and so do the phase 5 Tests for the printer pool (the migration test from `[printer]` to `printers.default`, unknown keys in `[printers.x]`, two queues in parallel). Each points here.
- docs/plans/job-store.md:
- COMPATIBILITY's "Job status keeps its shape until there are several printers", and the DELIVERIES AND SEVERAL PRINTERS bullet that gives the `deliveries` array and leaves the job's own fields to this plan: point to question 8, under which every status gains `deliveries` from stage 1b.
- DELIVERIES AND SEVERAL PRINTERS: the bullet on a row that stores nothing of its route, and the anycast bullet's restored list, point to question 18; the anycast bullet's failover after a mark, to question 22; "one store, with one queue and worker per printer", to question 4; a printer removed from the config, to question 5.
- Invariant 3's "which the printers plan settles (question 23)": point to question 22. Invariant 2 reads "No byte of the job goes to the printer before its delivery's `sending` mark", since an anycast check sends `DLE EOT` before the mark.
- Question 23: point to question 22 here.
- Question 1's size comparison with GORM: with Expr linked, GORM's extra cost over plain SQL falls to about its own code (question 10).
- Question 9: point to question 4's bound with several lanes.
- Phase 2b, in case it ships after stage 3: a delivery with any `sending` mark is not cancellable, even while it waits on the next printer of an anycast list; a move takes the delivery lock (question 26).
- PRINT ACKNOWLEDGEMENT: the TM-m50II's command list includes `GS ( H` fn 48, still unverified over port 9100. The side finding's power-on part is confirmed in Epson's guides; whether the frames reach a port 9100 client is still unverified.
- Phases 3c and 4: a PNG preview uses the profile the text preview uses, the named printer's or the default's; a preview by ID uses its first delivery's printer. Phase 5's printer keys, such as `printer.confirm`, apply to each printer's table.
## Architecture
PRINTERS IN THE CONFIG (stage 1a)
```toml
# The printer "default". Jobs that match no rule print here.
[printer]
address = "192.0.2.10"
model = "tm-t88"
[printers.kitchen] # a TM-T88VII
address = "192.0.2.11"
model = "tm-t88vii"
[printers.office] # a TM-m50II
address = "192.0.2.12"
model = "tm-m50ii"
```
- Names and addresses here are examples. Each table starts from the printer defaults; only `address` is required (question 3). No two printers share an address and port.
- The loader gains a key kind for a table of named tables. `registerDefaults` registers its entry keys as `printers.*.<key>`. The walker checks that each entry is a table, checks the name on the raw key, finds case clashes and checks the keys. Each entry decodes onto `DefaultPrinter()` through the per-entry default hook. No variable is bound (question 2).
- Printer order, wherever one is needed (broadcast, `/healthz`, the start-up log): the default first, then by name. The decoder does not keep a TOML table's order.
LANES (stage 1a)
```text
┌─ lane "default": waiting list ─▶ worker ─▶ render ─▶ client ─TCP 9100─▶ TM-T88IV
request ─▶ Submit ─▶ route ─┼─ lane "kitchen": … ─▶ TM-T88VII
(one Store.Add per job) └─ lane "office": … ─▶ TM-m50II
```
- One `Queue` (question 4). Shared: the submit lock (the job's and its deliveries' sequence numbers, the capacity check, `Store.Add`, the appends to waiting lists), the status lock and map, the history, the references of ntfy jobs, the store and `OnFailure`. Per lane: the name, the renderer with that printer's `receipt.Options`, the sender (its `printer.Client`, with its own slot), retries and retry delay, a waiting slice in sequence order with its wake channel, and one worker.
- Lock order per lane is job-store's: the printer's slot, then the delivery lock, then the store; the status lock is innermost and never held across a store call.
- `Submit` routes first, outside the locks (stage 2a). Then, under the submit lock, it checks capacity on the target lanes (question 19), commits `Store.Add` with every delivery, and appends each delivery to its lane.
- `Run` starts one worker per lane; shutdown covers every lane, by `Durable()`.
- A store failure stops every lane. The first store error from any lane ends the others, and `Run` returns it, as an errgroup does (job-store question 11). An idle lane must not keep `Run` alive, and no lane may send after the store broke.
- Every worker log line carries `printer`. `OnFailure` gets the printer, and Sentry tags it; never content.
DELIVERIES AND JOB STATUS (stages 1b-3)
```json
{"id": "job_…", "status": "printing", "source": "ntfy:alerts", "created_at": "…",
"route": {"by": "rule", "rule": "urgent-on-desks", "mode": "multicast"},
"deliveries": [
{"printer": "default", "status": "done", "attempts": 1, "sent_at": "…", "finished_at": "…"},
{"printer": "office", "status": "queued"}]}
```
- `deliveries` from stage 1b (question 8). `route` from stage 2a (question 18), whose `by` is `rule`, `query` or `default`. An anycast delivery's `printers`, its ordered list, and `sent_to` from stage 3 (questions 22 and 26).
- The job's `status` derives from its deliveries by job-store question 12; with one delivery it is that delivery's.
- Enums go into `jsonschema` tags, held by printqueue's and the server's schema tests.
`?printer=` AND THE PREVIEW (stages 1b and 2c)
- `?printer=` is a direct unicast: the rules do not run, and `route.by` is `query`. It names a printer, never a group. An empty value means the default printer.
- Routes: the module routes, as today, and `POST /api/v1/print` and `POST /api/v1/preview` (question 7). `unknown_printer` and `invalid_query` keep their codes; their api.md rows cover the new routes.
- A preview renders for the named printer, or the default printer. The JSON answer gains `printer` (stage 1b) and `route` (stage 2c): the decision without queueing (question 21).
HEALTH (stage 1b)
```json
{"status": "ok",
"printer": {"reachable": true, "status": "ready", "online": true, "cover_open": false, "paper": "ok"},
"printers": [
{"name": "default", "default": true, "model": "tm-t88", "reachable": true, "status": "ready", "online": true, "cover_open": false, "paper": "ok", "pending": 0},
{"name": "kitchen", "default": false, "model": "tm-t88vii", "reachable": true, "status": "ready", "online": true, "cover_open": false, "paper": "ok", "pending": 1},
{"name": "office", "default": false, "model": "tm-m50ii", "reachable": false, "status": "unreachable", "pending": 2}],
"queue": {"pending": 3}}
```
- The code and `status` follow the default printer, as today (question 9). The entries reuse `printer`'s fields, so the existing enum test covers them. `model` is the model as configured. The ntfy array is unchanged.
- The default printer is read once, and that read fills `printer` and the first entry. The others are read each on its own goroutine, through the same settle path, within the one 3-s bound.
ROUTING RULES (stages 2a-2c)
- Packages:
- `internal/pkg/rules` (new): a generic engine, importing only Expr. `Rule[A]` (`Name`, `Order`, `When`, `Enabled`, `Action`). `Compile[E, A]` compiles every rule against `E`'s zero value with question 17's options and joins every error, each naming its rule and position. `Set.Match(env)` returns the first enabled rule in `order` whose `when` is true, with the runtime errors of the rules before it. `Set.Explain(env)` gives every rule's result, error or "disabled", for the dry-run. `Engine` holds the current set behind an `atomic.Pointer`, with `Swap`, `Match` and `Explain`. Templates share it later (design.md, Planned next item 5).
- `internal/pkg/routing` (new): `Env` and how it is built; the action (`Mode`, `To`) and its resolution against the printers and groups; the `printqueue.Router` it implements.
- printqueue defines `Route` and `Router`; it, the server and config never import Expr. Imports: routing → rules, printqueue, receipt; rules → Expr; internal/app → routing.
- config checks structure only: names, `order`, modes, `to`. The load helper in internal/app compiles the rules, so `config get` fails on a bad rule before install.sh restarts the daemon.
- At `Submit`: an explicit printer gives unicast, `by = "query"`. Otherwise the first match gives its action, with `to` expanded (question 13). No match gives unicast to the default printer, `by = "default"`. A runtime error passes to the next rule (question 15).
- `Submit` still refuses a printer with no lane (`ErrUnknownPrinter`, name assumed): a guard for a bug, once stage 2b checks reloads (question 20). The server answers `500` and reports it, as any unexpected error. ntfy.go logs it at ERROR, reports it and does not offer the message again, as it does with a receipt that fails validation, so a subscription cannot stall on it.
- Facts reach the router in `printqueue.Meta`. `Meta.Printer` comes in stage 1a. Stage 2a reads the module and the subscription from `Source`. Stage 2c adds `Meta.Facts`: client, topics, priority, tags and digest. The server fills them from the token's subject (auth.go keeps it beside the scope; never the token) and the module's built facts, since `Module.Build` returns the job with its topic, priority and tags. ntfy.go fills them from the message or the digest's rows. `Facts` are used at `Submit` only (question 16). The job's size comes from encoding it once, which `Store.Add` also takes.
- A reload swaps the set and the groups as one value, checked against the running printers (question 20, stage 2b).
An example, which also answers formatters.md's open question (which jobs and subscriptions go to which printer, and whether urgent messages print on both):
```toml
[routing.groups]
desks = ["default", "office"]
# Urgent notifications print on both desks.
[[routing.rules]]
name = "urgent-on-desks"
order = 10
when = 'source startsWith "ntfy:" && priority == 5'
mode = "multicast"
to = "desks"
# The alerts subscription prints in the office, or on the default printer while the office is down.
[[routing.rules]]
name = "alerts"
order = 20
when = 'subscription == "alerts"'
mode = "anycast"
to = ["office", "default"]
# Notes print in the kitchen.
[[routing.rules]]
name = "notes"
order = 30
when = 'module == "note"'
mode = "unicast"
to = "kitchen"
# Raw ESC/POS is written for one model.
[[routing.rules]]
name = "raw-on-the-t88iv"
order = 40
when = '"raw" in types'
mode = "unicast"
to = "default"
# A drill prints on every printer; off until needed.
[[routing.rules]]
name = "drill"
order = 50
when = 'subscription == "drill"'
mode = "broadcast"
enabled = false
```
- First match wins: an urgent message from `alerts` matches `urgent-on-desks` and prints on both desks, not through the anycast list.
- The example grows with the stages. Stage 2a's docs, example config and tests use `notes`, `raw-on-the-t88iv` and `drill`. Stage 2c adds `urgent-on-desks` and its group, since `priority` comes with it. Stage 3 adds `alerts`, since stage 2a refuses `anycast`.
- A subscription gets its printer through a rule on `subscription` or `source`; subscriptions gain no `printer` key.
- A multicast or broadcast rule not limited by `source` or `types` sends `raw` jobs to every model; the docs warn of it.
THE ENVIRONMENT (stages 2a and 2c; question 16)
`routing.Env`, a struct whose `expr` tags name the variables, built once per job at `Submit`. One type gives the compile-time prototype and the run-time values. A variable a stage has not added is an unknown name, so a rule on it fails to compile.
| Variable | Type | Stage | Value |
|---|---|---|---|
| `source` | string | 2a | `print`, `module:<name>` or `ntfy:<subscription>`, as job status shows it |
| `module` | string | 2a | the module's name on a module route; else empty |
| `subscription` | string | 2a | the subscription's name for its jobs; else empty |
| `copies` | int | 2a | the copies the job prints, 1-5 |
| `elements` | int | 2a | the job's elements, box children included, as validation counts them |
| `types` | list | 2a | the distinct element types, children included, sorted |
| `bytes` | int | 2a | the size of the job as stored, in JSON |
| `now` | time | 2a | when the job was accepted, in `format.timezone` |
| `hour`, `minute` | int | 2a | from `now` |
| `clock` | string | 2a | `"HH:MM"`, zero-padded, so `clock >= "22:00"` compares as text |
| `weekday` | string | 2a | `mon` to `sun`, the names `quiet.days` uses |
| `client` | string | 2c | the subject of the request's token; empty for a subscription's job |
| `topic` | string | 2c | the notification's topic: from a `notify` or `ntfy` payload, an ntfy message, or a digest whose rows share one; else empty |
| `topics` | list | 2c | a digest's row topics, or `[topic]`; empty without one |
| `priority` | int | 2c | 1-5 for a notification (3 when it gives none); a digest's highest row's; 0 for other jobs |
| `tags` | list | 2c | a notification's tags; the tags of a digest's rows; else empty |
| `digest` | bool | 2c | true for a digest |
Rules the probe compiled and ran against this env: `source == "ntfy:alerts"`; `source startsWith "ntfy:" && priority >= 4`; `"urgent" in tags || priority == 5`; `weekday in ["sat", "sun"] || clock >= "22:00" || clock < "07:00"`; `"image" in types && bytes > 100000`; `now.Hour() >= 22`; `any(tags, # startsWith "kitchen")`; `topic matches "^alerts-"`; `module == "note" && copies > 1`.
ANYCAST AND FAILOVER (stage 3)
1. At `Submit`, the delivery keeps its ordered list. It joins the lane of the first printer of the list that is not marked down and has room, else the first with room; `queue_full` comes only when every lane of the list is full (question 24). Its stored `printer` is the one to try first.
2. That lane's worker renders with its printer's options, or keeps bytes rendered for an equal options key (question 26).
3. The checked send takes the printer's slot and dials. It reads `DLE EOT` on that connection, reading a not-ready answer again (question 23). Then it calls `beforeWrite`, which commits the `sending` mark and adds the printer to `sent_to`, and writes.
4. Nothing of the job sent (the error came before `beforeWrite`, or matches `NothingWritten`): the slot is released, and the delivery moves at once to its next printer. A refused, unreachable or timed-out dial, or a printer still not ready, also marks the printer down (question 24). No store write, as job-store's JOB STATES has for a dial failure.
5. Bytes sent: the retry rule on that printer, then the move (question 22).
6. A move takes the status lock, and job-store phase 2b's delivery lock once that exists, and happens only while the queue is open and the delivery is not cancelled. A failure while the delivery's context has ended (a shutdown, a cancel or its 2-minute bound) never moves it: shutdown and the cancel follow their rules, and the bound fails the delivery, as today (question 26).
7. After the last printer, with nothing sent anywhere: a new round (question 25). The delivery waits on a timer, on no lane, and the timer puts it back on its first printer's lane; no worker sleeps. Once the rounds are spent, one last attempt sends to the first printer without the status check. With bytes sent anywhere, the delivery fails, `sent_at` and `sent_to` set.
8. While a printer is marked down, an anycast delivery passes over it to a later printer of its list that is not marked (question 24).
9. A restored queued anycast delivery starts from the top of its stored list, without printers no longer configured (questions 5 and 18).
10. A shutdown or a cancel finds the delivery in one place: one lane or one timer.
WHAT IS STORED
- Stage 1a: nothing new. A delivery's `printer` is its lane's name, as job-store's schema already allows.
- Stage 2a (question 18): the route on the job (`route_by`, `route_rule`, `route_mode`), and on the delivery `candidates` and `sent_to`, written from stage 3. `printqueue.Record` and `Delivery` gain the same fields; the memory store keeps them. A delivery whose lane is full is inserted `failed`, and the insert then syncs (question 19).
- Stage 2c: nothing. Facts are never stored (question 16).
- `Store.Sending(delivery, printer, attempt, at)` already names the printer; from stage 3 it also adds it to `sent_to`, so a failover keeps the record that the first printer got bytes, which job-store.md's TELLING WHICH RECEIPTS PRINTED relies on.
PROFILES AND STATUS PER MODEL (stages 4a and 4b)
- `escpos.Profile` keeps `Name`, the layout family, and gains `Model` and the status capabilities (question 27). Layout fields stay shared by the three printers. `LineSpacing` comes with job-store phase 3a; `BoxLineSpacing` comes only if a paper check needs it (question 30).
- Status: `printer.Client.Status` keeps `DLE EOT 1-4`, one request at a time. On a profile whose near-end comes from `GS r 1`, it sends that last, only when online and ready, with its own deadline and decoder, and closes the connection after a missed answer (question 28). The anycast check never sends it. `Ready()` and `Normalized()` gain question 29's bits.
THE SEAM FOR REMOTE PRINTERS (named, not built; question 6)
- Each printer is one value built by one constructor in internal/app from its table. It implements `printqueue.Sender` (`Send` with `beforeWrite`, and stage 3's checked send) and `server.Printer` (`Status`). Today it is a `*printer.Client`; docs/plans/remote-printers.md adds one backed by an agent's link, chosen by its `agent` key (its decision 16).
- The contract a remote printer keeps is printqueue's send contract (stage 3):
- `beforeWrite` runs only once a connection to the printer itself is open, wherever that is, so the `sending` mark and "nothing sent" stay true across the agent.
- A failed send that never called `beforeWrite` sent nothing. One that called it sent nothing only when its error matches printqueue's `NothingWritten` interface, which a remote sender reports only when the agent says nothing was written. A send whose link is lost part-way counts as "may have printed", never "nothing sent", unless the agent's journal shows nothing was written (docs/plans/remote-printers.md, decision 17).
- Status follows the same rules: read a not-ready answer again; a timeout is never a fault.
- The main instance and an agent never both drive one printer: its second connection blocks until the first closes.
- Nothing of this is built here: no key, no agent, no transport. docs/plans/remote-printers.md builds them.
LOGGING AND PRIVACY
- Worker lines gain `printer`. Each printer's start-up line gives its name, address, model, code page and paper width, as today's `listening` line gives the address: logs are private, and that line is where an operator sees which address each name uses.
- A rule's runtime error logs its name, the `job_id` and the error's line and column, never the message (question 15). A compile error gives the rule's name, the position and Expr's message, never the rule's source line (question 14).
- The env and the facts are never logged, stored, kept in job status or sent to Sentry. `uberbringer route` prints the env on the terminal only.
- A reload's WARN names the sections that need a restart, never a value (question 20).
- A WARN at start names `UBERBRINGER_PRINTERS_*` and `UBERBRINGER_ROUTING_*` variables, never their values (question 2).
- `/healthz` shows printer names and models, never addresses.
- Sentry gets the printer's name as a tag, never content, a topic or an Expr message.
CONFIG, PACKAGING, DOCKER
- New keys: `[printers.<name>]` (stage 1a), `[routing.groups]` and `[[routing.rules]]` (stage 2a), each with its default, validation, `configs/config.example.toml` entry and docs/configuration.md entry. All are read from the file only.
- Printers and routing are documented in docs/configuration.md, § printers and § routing, not on a page of their own, so the release archives, README's Documentation table and CLAUDE.md's "Read first" need no new entry.
- install.sh and the Dockerfile do not change. A container with named printers or rules mounts a config, as one with subscriptions does.
- The stop timeout must exceed the largest `write_timeout` of any printer plus 10 s, since each lane finishes the write in hand (job-store question 15). docs/install.md says so for the unit, and docs/docker.md for `--stop-timeout` (stage 1a).
- The unit gains `ExecReload` in stage 2b.
## Phases
### Stage 1a: Named printers, a lane each
**Goal.** `[printers.<name>]` tables add printers beside `[printer]`, the printer `default`. Each printer has its own client, renderer and lane, and `preview --printer` lays a job out for any of them. No route reaches a named printer yet: every job still prints on the default printer, and a config with `[printer]` alone prints as today. Needs job-store stage 1c. Questions 1-6.
**Work.**
internal/pkg/config
- config.go:
- `Printers map[string]PrinterConfig` (`printers`), and `DefaultPrinter()`.
- The key kind for a table of named tables, its walker checks and its per-entry defaults (Architecture, PRINTERS IN THE CONFIG). No variable.
- `validatePrinter(path, p)`, made from today's printer checks, reporting `printers.<name>.<key>`. `[printers.default]` is refused, pointing to `[printer]`. A host and port repeated across `[printer]` and `[printers.*]` is refused, hosts compared without regard to case (question 3).
- The names of any `UBERBRINGER_PRINTERS_*` variables, for internal/app's WARN (question 2).
- The comment on the environment prefix: named printers have no variable.
- value.go: `Value()` reaches `printers.<name>.<key>`.
internal/pkg/printqueue
- queue.go:
- `New` takes the lanes, the default first: each (`Lane`, name assumed) with `Name`, `Renderer`, `Sender`, `Retries` and `RetryDelay`, which leave `Options`.
- One waiting list and worker per lane; `Run` starts them all; shutdown covers every lane. The first store error from any lane stops every lane, and `Run` returns it.
- `Meta.Printer`, the printer the job goes to; empty means the default. `Submit` refuses a name with no lane (`ErrUnknownPrinter`, name assumed), a guard for a bug: the server and the router check first.
- Capacity per lane; `Pending` per printer and in total.
- A delivery's `Printer` is its lane's name. Restore puts each queued delivery on its lane; one whose printer is gone fails (question 5).
- `OnFailure` gains the printer; every worker log line carries `printer`.
internal/app/uberbringer
- load.go (new; name assumed): `config.Load`, then each printer's renderer options, so a bad model or code page fails the start, `config get` and `preview` alike. `token` keeps `config.Load` alone: it needs only `api.secret`, and a token can then be issued while the config is being fixed.
- serve.go:
- a renderer, a `printer.Client` and a lane per printer;
- one start-up line per printer: name, address, model, code page and paper width;
- one WARN naming any `UBERBRINGER_PRINTERS_*` variable, never its value;
- the server still gets the default printer alone.
- `rendererOptions` takes one printer's config.
- `reportJobFailure` tags the printer.
- preview.go: `--printer`.
- cli.go: `config get` through the load helper.
Docs
- docs/configuration.md:
- a § printers: `[printers.<name>]`, the printer `default`, the names, the keys and their defaults, no shared address, file only;
- § Loading: a named printer requires its `address`, beside `api.secret` and `printer.address`;
- § Environment variables: the exception names the printers beside the ntfy subscriptions, and the WARN for `UBERBRINGER_PRINTERS_*`;
- § queue: `size` counts per printer;
- § printer: `retries` fails the job on that printer.
- configs/config.example.toml: a commented `[printers.<name>]` after `[printer]`; the `size` comment says per printer; the header's "sets any key" names the exceptions.
- docs/cli.md: `preview --printer`, `config get printers.<name>.<key>`, and `config get` failing on a bad model or code page.
- docs/docker.md: variables set the default printer only, so a container with named printers mounts a config; `--stop-timeout` above the largest `write_timeout` of any printer plus 10 s.
- docs/install.md: the unit's stop timeout, systemd's 90 s, must exceed the largest `write_timeout` of any printer plus 10 s. Whichever of this stage and job-store stage 1d lands second words it for several printers.
- design.md:
- "Why": "one Epson receipt printer" and "sized for receipt rates on one printer";
- the diagram: a lane per printer;
- "One printer per instance" gives way to several printers with a lane each;
- "The queue lives in memory": order is per printer, one worker per lane;
- the stack choices: named printers have no variable.
- CLAUDE.md: the opening paragraph ("one Epson receipt printer") and the rule "The printer takes one TCP connection at a time" speak of each printer.
- CHANGELOG: under Added, named printers; under Changed, `queue.size` counts per printer, and `config get` checks the model and code page.
**Tests.**
internal/pkg/config (a new printers_test.go)
- A `[printers.kitchen]` with only `address` gets every default; `retries = 0` stays 0.
- Refused, each error naming the key:
- an unknown key in an entry;
- two names differing only in case, and `[printers.Office]`;
- a quoted dotted name; an entry that is not a table;
- `[printers.default]`; a name outside the rule; a missing address;
- an address and port another printer uses, `[printer]` included, in another letter case too.
- No variable sets a named printer; `UBERBRINGER_PRINTER_ADDRESS` still sets the default; a `UBERBRINGER_PRINTERS_*` variable is named for the WARN.
- TestLoadInstallScriptConfigGetsDefaults and TestExampleConfigLoads pass unchanged.
- `Value()` reads `printers.kitchen.address`.
internal/pkg/printqueue
- Two lanes print in parallel: a Sender blocked on one lane does not hold the other.
- Order is kept per lane.
- A full lane refuses its jobs while the other takes them; `Pending` per printer and in total.
- Shutdown covers every lane, by `Durable()`.
- A store error on one lane stops every lane, and `Run` returns it while another lane is idle.
- Restore puts deliveries on their lanes; a queued delivery for a printer no longer configured fails with its WARN line (the memory store's durable test option).
- TestMetaInStatusAndLogs: every line carries `printer`, and none carries content.
- The existing tests, rebuilt on lanes: order, retries, render failure, queue full, shutdown, history.
internal/app/uberbringer
- TestServeEndToEnd passes unchanged, as the single-printer compatibility test.
- A run with two fake printer listeners: every job reaches only the default's, and the log has one start-up line per printer.
- `preview --printer`; `config get` fails on a bad model.
**Done when.**
- The full gate passes.
- Paper, with the owner's OK: with a second printer configured at an address that refuses the connection, such as a closed port on the workstation, one short receipt through the default printer, the TM-T88IV. Look at the line breaks, the characters and the cut: as before. Wait for his report.
### Stage 1b: `?printer=`, `/healthz` per printer, and deliveries in job status
**Goal.** `?printer=` sends a job to one printer on every print and preview route. `/healthz` lists every printer, and its code still follows the default printer. Job status gains `deliveries`. Needs stage 1a. Questions 7-9.
**Work.**
internal/pkg/printqueue
- queue.go: `Status.Deliveries` and the job's own fields (question 8), with their `jsonschema` tags.
- schema_test.go: a delivery's `status` enum held to the `State` constants.
internal/app/uberbringer/server
- server.go: `Deps` takes the printers, the default first, each with its name, configured model, `Printer` and `Previewer`; the nil checks follow. `Jobs.Pending` per printer.
- handlers.go: `handlePrint` reads the query (question 7). `handleHealth`, `healthResponse` and `queueHealth` (question 9): the default printer read once, filling `printer` and the first entry; the others read in parallel.
- handlers_modules.go: `moduleQuery` checks `printer` against the configured names; the `defaultPrinter` constant and its "the only printer is" message go.
- handlers_preview.go: `?printer=` on both preview routes; the JSON answer's `printer`.
- routes.go: query parameters for `/api/v1/print` and `/api/v1/preview`; `unknown_printer` and `invalid_query` in their error lists; the descriptions of the module routes' `printer` and of `/healthz` ("depends on the printer alone").
- errors.go: no new code; the messages of `unknown_printer` and `invalid_query` fit the new routes.
internal/app/uberbringer
- serve.go: the server gets every printer.
Docs
- docs/api.md:
- `?printer=` on print and preview, and the module routes' `printer`;
- the `unknown_printer` and `invalid_query` rows, the latter no longer "On a module route" only;
- Health, with `printers`; `queue.pending` as the total across printers, which changes its meaning for monitors that alert on it; the status code following the default printer;
- Job status, with `deliveries` and the job's own fields.
- docs/swagger.json regenerated.
- docs/configuration.md § printers: a job reaches a named printer with `?printer=`.
- docs/security.md: any token that may print may name any printer.
- docs/docker.md § Health checks: `/healthz` answers `503` while the default printer is unreachable; the others show in its body.
- design.md: the diagram's `/healthz`; "Module routes take `copies` and the reserved `printer`"; "Health is for monitors" and the ntfy paragraph's "depends on the printer alone" name the default printer.
- CHANGELOG: under Added, `?printer=` on print and preview, `printers` in `/healthz` and `deliveries` in job status; under **Breaking**, `/print` and `/preview` refuse other query parameters; under Changed, `queue.pending` is the total across printers.
**Tests.**
internal/pkg/printqueue
- Status: `deliveries` and the job's own fields, as a table test over one, two and three deliveries.
internal/app/uberbringer/server. The test helpers keep their `Printer` argument as the default printer and take more through an option, to limit the churn across their 50 callers (`newTestServer` 40, `newLoggedServer` 10).
- `?printer=` on `/print`, `/preview`, `/preview/{module}` and `/print/{module}`:
- a configured name reaches its lane, and an empty value the default's;
- another name, `Office` for `office` included, gives `unknown_printer`;
- a parameter given twice, or another parameter, gives `invalid_query`.
- The JSON preview names its printer and renders with that printer's options.
- `/healthz` with three printers:
- the code follows the default printer only;
- the default printer is read once, and `printer` equals the first entry;
- another printer on a refused port gives `200` with its entry `unreachable`;
- one that answers late does not push the others past 3 s;
- the body holds no address.
- TestHealthEnumsMatchHandler covers the entries. TestRoutesConform and TestRegisteredRoutesAreTheTable pass with no new route.
internal/app/uberbringer
- A two-printer run against two fake printer listeners: `?printer=<name>` reaches only that listener; a job without it reaches only the default's.
**Done when.**
- The full gate passes.
- With the owner's OK, a status read only: with a second printer configured at an address that refuses the connection, `/healthz` answers `200`, with that entry `unreachable`. An address with no host behind it may read `timeout` instead (question 9).
- Paper, with the owner's OK, once a second printer is on hand and its status sheet read (question 31): one short receipt with `?printer=<name>`. It prints there only, with line breaks at 42 columns. Wait for his report. With one printer only, this check waits, and the stage is done on the fakes.
### Stage 2a: Expr rules on a job's source, shape and clock
**Goal.** Expr rules route every job without `?printer=`, in unicast, multicast and broadcast. They see the job's source, module, subscription, shape and clock. The rule set is compiled once, ordered, and held as one value the engine can swap. The decision is stored with the job and shown in its status. Needs stage 1b. Questions 10-19.
**Work.**
go.mod
- `github.com/expr-lang/expr` at its latest stable release. Run govulncheck. `go generate` regenerates THIRD-PARTY-LICENSES.md and internal/app/uberbringer/licenses_embed.md.
internal/pkg/rules (new)
- rules.go: the generic engine (Architecture, ROUTING RULES).
internal/pkg/routing (new)
- env.go: `Env` with stage 2a's variables and their `expr` tags (Architecture, THE ENVIRONMENT), built from the job, `Meta.Source`, the job's size, the acceptance time and the zone.
- action.go: `Mode` and `To`; `to` resolved against the printers and groups (question 13).
- router.go: the `printqueue.Router`.
- A rule's runtime error gives one WARN line with the rule's name, the `job_id`, and the line and column from Expr's `*file.Error`, never `Error()`. Any other error type gives the rule's name only.
- One Sentry event per rule per run, through a reporter internal/app passes in (question 15).
- A panic while the env is built is recovered: logged at ERROR, reported once, and the job goes to the default printer.
internal/pkg/printqueue
- queue.go:
- `Route` (`By`, `Rule`, `Mode`, `Printers`) and the `Router` interface; `Options.Router`, nil keeping stage 1b's behaviour.
- `Submit` routes first, outside the locks, then makes one delivery per printer of the route. Capacity by question 19: a delivery whose lane is full is inserted `failed`, "printer's queue is full", and logged at WARN by `job_id` and `printer`; `queue_full` only when every target lane is full. The job's JSON is encoded once, for `bytes` and for `Store.Add`.
- `Status.Route`, with enum tags for `by` and `mode`.
- store.go: `Record.Route`, and `Delivery.Candidates` and `Delivery.SentTo` for stage 3; the memory store keeps them. `Add` takes a delivery inserted `failed`, and then syncs.
- schema_test.go: the `by` and `mode` enums.
internal/pkg/jobstore, if job-store stage 1d has shipped
- A schema step to `user_version` 2 with the route and delivery columns (question 18). Otherwise job-store stage 1d's schema takes them.
internal/pkg/config
- config.go:
- `Routing` with `Groups` and `Rules`.
- A key kind for `routing.groups`, a table of lists read from the file only, its names checked on the raw key.
- `[[routing.rules]]` as a list of tables, each entry starting from `DefaultRule()` (`enabled` true).
- Validation: rule names by the printer names' rule, unique; a unique `order` across all rules, disabled ones included; a `when` that is not empty; `mode` one of `unicast`, `multicast` and `broadcast` (`anycast` comes in stage 3); `to` by mode against the printers and groups. No Expr.
- The names of any `UBERBRINGER_ROUTING_*` variables, for the WARN at start.
internal/app/uberbringer
- load.go: the load helper compiles the rules with `format.timezone`'s zone, so a bad rule fails the start, `config get` and `preview`, naming the rule without its source line.
- serve.go: the engine and the Router into the queue; the WARN names `UBERBRINGER_ROUTING_*` variables too.
- ntfy.go: an `ErrUnknownPrinter` from `Submit` is a bug, handled as an invalid receipt is: logged at ERROR, reported, and not offered again.
Docs
- docs/configuration.md:
- a § routing: groups, rules, the modes, stage 2a's variable table, the rules `notes`, `raw-on-the-t88iv` and `drill` from the example, literal strings for `when`, and what a compile error and a runtime error do;
- a warning that a multicast or broadcast rule not limited by `source` or `types` sends `raw` jobs to every model;
- § Environment variables: the exception names `[routing]`, and the WARN for `UBERBRINGER_ROUTING_*`.
- configs/config.example.toml: a commented `[routing]` example.
- docs/ntfy.md: a subscription gets its printer through a rule on `subscription` or `source`; the paper budget counts jobs, not deliveries (question 19).
- docs/development.md § Package layout: `internal/pkg/rules` and `internal/pkg/routing`.
- docs/api.md: job status `route`; `queue_full` only when every printer of the route is full; a delivery `failed` with "printer's queue is full".
- docs/swagger.json regenerated.
- design.md: "Jobs remember their source", which now names the route; the stack choices, with Expr's version, the size it adds, and no variable for `[routing]`.
- CLAUDE.md: the layout and the imports (routing → rules, printqueue, receipt; rules → Expr; internal/app → routing).
- docs/plans/job-store.md, while it is open: DELIVERIES AND SEVERAL PRINTERS and stage 1d's RECORDS name the route columns (question 18).
- CHANGELOG: under Added, routing rules and groups, and `route` in job status; under Changed, a multicast job is refused only when every printer's queue is full.
**Tests.**
internal/pkg/rules
- Compile: a valid rule; a syntax error; an unknown name, `priority` included until stage 2c; a result that is not a bool; a type mismatch (`copies == "5"`); `now()` and `$env` refused; a bad constant regex. Each error names its rule and position and holds no source line, and every error of a set is reported.
- Order: the first match wins; `order` decides, not the position in the file; a disabled rule is compiled and never matches.
- A runtime error: the next rule is tried, and the error comes back with its rule.
- `Match` and `Explain` from 100 goroutines under `-race` while sets are swapped.
internal/pkg/routing
- The env from each source: `/print`, a module route, an ntfy card, a digest.
- The clock in a zone with clock changes (Europe/London); `weekday` uses `quiet.days`' names; `clock` is zero-padded.
- Decisions: an explicit printer (`query`; the rules not run); a match; no match (`default`); multicast expanded with repeats dropped; broadcast to every printer, the default first.
- A rule failing at run time logs one WARN line with its name, the job's ID and the position and no message, and reports to Sentry once however many jobs it fails.
- A panic while the env is built routes to the default printer, logged and reported once.
- A test holds the variable table in docs/configuration.md to `Env`'s `expr` tags.
internal/pkg/config
- `enabled` defaults to true.
- Refused: a repeated rule name; a repeated `order`, a disabled rule's included; an unknown mode; `anycast` until stage 3; `to` against each mode; a name in `to` that is neither a printer nor a group; a group named like a printer, or `default`; an empty group; a group member that is not a printer; a group name outside the rule, checked on the raw key.
- No variable sets `routing`; a `UBERBRINGER_ROUTING_*` variable is named for the WARN.
internal/pkg/printqueue
- A multicast job gets one delivery per printer in one `Add`, and its status follows job-store question 12.
- A multicast job with one target lane full is accepted: that delivery is `failed`, "printer's queue is full", in a synced commit, and the others are queued. With every target lane full, `queue_full`.
- The route is stored and restored with the job, and a restore never calls the Router.
internal/pkg/jobstore, if it exists
- The new columns survive a close and a reopen; a database at `user_version` 1 steps to 2.
internal/app/uberbringer
- A bad rule fails the start and `config get`, naming the rule.
- A two-printer run with a multicast rule: both listeners get the job.
- A subscription whose multicast rule includes a dead printer with a full lane keeps reading: its next message prints on the live printer.
- ntfy: an `ErrUnknownPrinter` is logged and reported, and the message is not offered again.
internal/app/uberbringer/server
- A group's name in `?printer=` gives `unknown_printer`.
- schema_test: the `route` enums.
**Done when.**
- The full gate passes; govulncheck is clean; the snapshot builds every target, and design.md records the size Expr adds.
- Paper, with the owner's OK, once a second printer is on hand, one short receipt at a time, waiting for his report after each: a multicast rule prints one receipt on both printers, each with its own cut; then a unicast rule sends a note to the second printer only. With one printer only, this check waits, and the stage is done on the fakes.
### Stage 2b: Reloading the rules
**Goal.** SIGHUP swaps in the config's `[routing]` without a restart (question 20). Needs stage 2a.
**Work.**
internal/app/uberbringer
- serve.go: a goroutine in the errgroup waits for SIGHUP and calls `reload`:
- the load helper, compiling the rules with the running `format.timezone`; a file that fails is logged at ERROR and changes nothing;
- every rule's `to` and every group member must name a printer that has a lane, or the whole reload is refused at ERROR and the old set kept; `broadcast` resolves to the printers that have lanes;
- each other section that changed is logged at WARN by its name only, as needing a restart;
- then the rule set and the groups are swapped as one value, and one INFO line gives the number of rules.
internal/pkg/config
- A comparison of two configs that leaves `[routing]` out and names the sections that differ (name assumed).
packaging/uberbringer.service
- `ExecReload=/bin/kill -HUP $MAINPID`.
Docs
- docs/configuration.md § routing: reloading, what takes effect, and that a new printer needs a restart; none on Windows.
- docs/install.md: `systemctl reload uberbringer` after a change to `[routing]`.
- docs/docker.md: `docker kill --signal HUP`.
- design.md: the reload, under Packaging.
- CHANGELOG: under Added.
**Tests.**
- `reload` called directly, so the tests run on Windows too:
- a new rule set routes the next job; queued deliveries keep their routes;
- a file with a bad rule keeps the old set and logs ERROR;
- a changed printer is logged as needing a restart and not applied;
- a reload that adds `[printers.new]` with a rule `to = "new"` is refused, and so is a group naming a printer with no lane;
- a changed `format.timezone` is not applied, and the rules compile with the running zone;
- the WARN names the changed sections, such as `api` and `ntfy`, and holds no secret, credential or topic.
- The signal wiring: one test, skipped on Windows, sends SIGHUP to the test process.
**Done when.**
- The full gate passes; the snapshot builds, since the unit changed.
- On a host, with the owner's OK: `systemctl reload uberbringer` with a changed rule logs the swap; once stage 2c has shipped, the JSON preview's `route` shows the new decision. Nothing prints.
### Stage 2c: Notification facts in rules, and the dry-runs
**Goal.** Rules also see a notification's topic, priority and tags, a digest's, and the token's subject. `uberbringer route` and the JSON preview show what the rules decide. Needs stage 2a. Questions 16 and 21.
**Work.**
internal/pkg/printqueue
- queue.go:
- `Meta.Facts` (name assumed): client, topics, priority, tags and digest. Used at `Submit` only: the Router reads them and the queue drops them, so they are never kept in the status, logged, stored or sent to Sentry. `Meta`'s doc comment says so, since it says today that `Meta` is kept with the status and logged.
- `Route(job, meta)` (name assumed): the decision without queueing, for the dry-runs.
internal/pkg/routing
- env.go: the variables stage 2c adds (Architecture, THE ENVIRONMENT).
internal/pkg/modules
- registry.go: `Build` returns the job with its facts (a result type, name assumed). note.go returns none; notify.go and ntfy.go return their `Notice`'s topic, priority and tags. Their tests follow, and so do the fakes `stubModule` (modules/registry_test.go) and `fakeModule` (server/handlers_modules_test.go).
internal/app/uberbringer
- ntfy.go: cards and digests carry their facts.
- preview.go: `preview --module` follows `Build`'s result.
- route.go (new): `uberbringer route` (question 21).
internal/app/uberbringer/server
- auth.go: the token's subject joins the scope in Locals; never the token.
- handlers.go: `client` for `/print`. handlers_modules.go: `Meta.Facts` from the token and from `Build`'s result.
- handlers_preview.go: the JSON answer's `route`; `Jobs` gains `Route`, and `fakeJobs` with it.
Docs
- docs/configuration.md § routing: the variables stage 2c adds, and the example's `urgent-on-desks` rule and its group, which answers formatters' open question.
- docs/cli.md: `uberbringer route`.
- docs/security.md: the token's subject becomes the rule variable `client`; the env and Expr's run-time messages are never logged; the JSON preview's `route` shows rule and printer names to tokens limited to modules.
- docs/api.md: the JSON preview's `route`.
- docs/swagger.json regenerated.
- CHANGELOG: under Added, the notification facts and `client` in rules, `uberbringer route`, and `route` in the JSON preview.
**Tests.**
internal/pkg/routing
- The env with its facts from each source: an ntfy card, a digest (union of topics and tags, highest priority), a `notify` payload, a token's subject.
- No content in the env: a job and an ntfy message filled with a sentinel string; neither the env (`%#v`) nor any `Explain` output holds it.
- A sentinel topic and tag, sent through a job a rule fails on at run time, a job that prints, and a reload: no log line (the runtime WARN included), Sentry event, status JSON, stored record or reload WARN holds either.
internal/app/uberbringer
- A subscription's card and digest reach the Router with their facts.
- TestNtfyPrinter compares `Meta`'s fields, not the whole struct, now that `Facts` holds lists.
- `uberbringer route`: a golden output for the example config without `alerts`, with `--at`.
internal/app/uberbringer/server
- `client` is the token's subject; the JSON preview's `route`.
**Done when.**
- The full gate passes.
- `uberbringer route` explains the example config's decisions for an urgent ntfy message, a note and a raw job. Nothing prints.
### Stage 3: Anycast with ordered failover
**Goal.** `mode = "anycast"` sends a job to the first printer of an ordered list that takes it. A failure before any byte of the job fails over at once; after bytes, question 22 decides. Needs stage 2c, and job-store stage 1c's `beforeWrite`. If job-store phase 2b has shipped, a move takes its delivery lock. Questions 22-26, and question 23's paper check before the stage starts.
**Work.**
internal/pkg/printer
- printer.go:
- `readStatus(ctx, conn)`: the `DLE EOT` reads on an open connection. `Status` calls it after `connect`; the checked send calls it on its own connection, so it never waits on its own slot. `GS r 1`, once stage 4a adds it, belongs to `Status` alone.
- `Settle(ctx, read, delay)` (name assumed): the read again of a not-ready answer, moved from server/handlers.go's `settledPrinterStatus`. `/healthz` passes `Client.Status` and its `HealthRecheckDelay`; the checked send passes a read over its own connection, and the 750-ms delay internal/app gives each lane.
- The checked send: after the dial and before `beforeWrite`, the settled read of question 23.
- `Send` returns an error type (`SendError`, name assumed) holding the count `Write` took, with a method `NothingWritten() bool`.
internal/pkg/printqueue
- queue.go:
- The send contract, in printqueue's own terms, so that neither package imports the other. A failed send that never called `beforeWrite` sent nothing. One that called it sent nothing only when its error matches, through `errors.As`, an interface printqueue declares with `NothingWritten() bool`.
- Anycast deliveries (Architecture, ANYCAST AND FAILOVER). Only anycast branches on how far a send got; unicast and multicast keep today's rule of retrying every error.
- The down marks (question 24), in memory under the status lock.
- Moves (question 26): under the status lock, and the delivery lock once job-store phase 2b exists; only while the queue is open and the delivery is not cancelled; never after a failure while the delivery's context has ended.
- Round timers (question 25); shutdown and a cancel see a delivery on a timer as waiting.
- `Sender` gains the checked send (name assumed).
- A remote printer's checked send is built by whichever of this stage and docs/plans/remote-printers.md's stage 4 lands second.
- store.go: `Sending` adds its printer to `SentTo`; a restore drops printers no longer configured from a delivery's list (question 5).
- `Status`: an anycast delivery's `printers` and `sent_to`.
internal/pkg/routing, internal/pkg/config
- `anycast` accepted; `to` kept in order, groups expanded in member order (question 13).
internal/pkg/jobstore, if it exists
- Writes `candidates` at insert and `sent_to` with each `sending` mark.
internal/app/uberbringer/server
- handlers.go: `/healthz` uses `printer.Settle`.
internal/app/uberbringer
- serve.go: each lane gets the settle delay.
Docs
- docs/configuration.md § routing: anycast, failover, the down mark, rounds and the double-print risk, in plain words; the example's `alerts` rule.
- docs/api.md: job status, `printers` and `sent_to`, and what `sent_to` with two printers means for the paper.
- docs/swagger.json regenerated.
- design.md: "Render, then send": a failover renders for the next printer before it sends, and a write error's retries.
- CHANGELOG: under Added.
**Tests.**
internal/pkg/printer, against a fake listener
- How far a send got: a refused dial and a dial time-out never call `beforeWrite`; a write error with nothing written matches `NothingWritten`; a write cut short after some bytes does not.
- The checked send:
- a printer still not ready after the second read gets no job byte and no `beforeWrite` call;
- a passing not-ready answer followed by ready sends, and the send finishes without waiting on its own slot;
- a status time-out or no answer sends;
- if stage 4a has shipped, a TM-T88VII profile's check never sends `1D 72 01`.
internal/pkg/printqueue, with a fake sender per printer that fails at a chosen point
- A failure before any byte fails over at once: no `Sending` commit, no retry on the first printer, and the next printer prints.
- After a `sending` mark, the first printer's retries run, then failover; `sent_to` lists both, and the status shows it.
- A write error with nothing written fails over at once, though its mark was committed; `sent_to` keeps the first printer.
- `attempts` counts across printers.
- The down mark:
- a dead first printer with a backlog of unicast jobs delays an anycast job by at most one dial time-out;
- the anycast job is accepted while that lane is full;
- the mark clears on a success and after the hold;
- with every printer of the list marked, the first is tried.
- Rounds by question 25:
- no worker sleeps while a delivery waits for its round, so the last printer's lane goes on with its own jobs;
- once the rounds are spent, the last attempt goes to the first printer without the check;
- a delivery that sent bytes starts no new round.
- A render error moves on only to a printer whose options key differs.
- A moved delivery joins the next lane in sequence order and is taken although that lane is full. The first printer's slot is free before the second's is taken. The job's status stays `printing` through the move.
- Shutdown:
- during a move or a round's wait, a delivery with no mark stays queued with a durable store and fails with the memory store, as any waiting delivery;
- a delivery with a mark waiting on the next lane fails with `sent_at` and `sent_to`, with either store;
- a dial failure the shutdown caused does not move the delivery.
- A cancel, if job-store phase 2b has shipped:
- a delivery without a mark is never sent after the cancel, and is found in one place, a lane or a timer;
- a delivery with a mark that waits on the next printer is not cancelled;
- a dial failure the cancel caused does not move the delivery.
- Restore: a queued anycast delivery starts from the top of its stored list; one whose printers are all gone fails.
internal/app/uberbringer
- A two-printer run: an anycast rule with the first listener closed prints on the second; with the first answering status "cover open", the second prints and the first receives no job byte.
- `uberbringer route`'s golden gains the example's `alerts` rule.
**Done when.**
- The full gate passes.
- Paper, with the owner's OK, once a second printer is on hand, one short receipt at a time, waiting for his report after each:
1. An anycast rule with the first printer switched off. The receipt prints on the second only.
2. The same with the first printer's cover open. The receipt prints on the second, and closing the cover prints nothing on the first.
- With one printer only, these checks wait, and the stage is done on the fakes.
### Stage 4a: The exact model, and status per model
**Goal.** The profile keeps the exact model. The TM-T88VII reports paper near-end through `GS r 1`, and status counts the bits question 29 adds. Needs only the TM-T88VII on hand, which can be the default printer of a test config until stage 1a ships. Questions 27-29.
**Work.**
First, before any code, with the owner's OK. These are status reads only, nothing printed, and they settle the details of questions 28 and 29:
1. On the TM-T88VII: the `GS r 1` reply byte with a full roll, and with a roll past the near-end mark if he has one, read by a probe run from outside the repository.
2. On the TM-T88IV just after power-on, and on the TM-T88VII with DIP switch 2-1 as it is set: does `/healthz` read `unknown`, a sign that automatic-status frames reach the connection?
3. The TM-T88VII's status sheet, read by the owner: column mode, paper width, paper reduction, top margin, the port 9100 time-out and DIP switch 2-1 (question 31).
internal/pkg/escpos
- profile.go: `Model` and the status capabilities (question 27); `LookupProfile` keeps the exact name.
- status.go: the `GS r 1` request and its decoder (question 28); question 29's bits in `Status`, `Normalized()` and `Ready()`; the comment on the TM-T88VII.
internal/pkg/printer
- printer.go: `Status` sends `GS r 1` last when the profile says so, only when online and ready, under its own deadline, and closes the connection after a missed answer. If stage 3 has shipped, `readStatus`, which the checked send uses, stays `DLE EOT` only.
internal/app/uberbringer
- serve.go: each client gets its profile's status capabilities.
internal/app/uberbringer/server
- handlers.go: `paper` from either source.
Docs
- docs/api.md: Health: "Paper low on the TM-T88VII" rewritten; the autocutter error that also means a paper jam; the new not-ready causes. docs/swagger.json regenerated if a field's doc comment changes.
- docs/configuration.md: the models table names the exact models, and says a TM-T88VII needs `tm-t88vii` to report near-end.
- design.md: "Status is read in a way that tolerates a busy printer": the TM-T88VII line.
- CHANGELOG: under Added, near-end on the TM-T88VII; under Changed, recoverable errors count as not ready.
**Tests.**
- escpos:
- TestLookupProfile pins the exact names and the shared layout;
- the `GS r 1` decoder on near-end, paper end, both bit-4 forms and a malformed byte;
- a `GS r 1` reply read as a `DLE EOT` answer is refused;
- the new bits in `Ready()`, and `DLE EOT 2` bit 6 cleared while online.
- printer, against a fake listener: `GS r 1` is sent last and only when online; no answer gives near-end unknown, not a timeout, and closes the connection; a `tm-t88` profile never sends it.
- server: `/healthz` shows `near_end` from `GS r 1`; a missed answer leaves `200`.
- TestRenderCompat and TestPaperReceipts pass: no printed byte changes.
**Done when.**
- The full gate passes.
- With the owner's OK, a status read only: `/healthz` on the TM-T88VII shows `paper` from `GS r 1`.
### Stage 4b: Each new model checked on paper
**Goal.** One paper check per new model confirms its line breaks, box borders and cut. A model whose box borders need another `box_line_spacing` gets its own default in the profile (question 30). It runs once for each new model as it arrives, and needs only that printer on hand, configured as the default printer of a test config or, from stage 1a, as a named one. It needs stage 4a only when a value differs between models of one family. Questions 30 and 31.
**Work.**
First, the owner reads the new printer's status sheet (question 31), if stage 4a has not.
Only if the paper check finds a model that needs a value other than 0:
- internal/pkg/escpos, profile.go: `BoxLineSpacing`, the model's default, with its source.
- internal/pkg/config: `box_line_spacing`'s default becomes -1, "the model's", validated from -1 to 255.
- internal/app/uberbringer, load.go: -1 resolved from the profile, so `config get` prints the value in use. The renderer gets the resolved value; 0 keeps `ESC 2`.
internal/pkg/receipt
- A receipt test pins the bytes of each receipt the owner passes on the new model.
Docs
- docs/configuration.md: the `box_line_spacing` row and the models table. If the default changes, configs/config.example.toml too.
- design.md: "Boxes print at the printer's default line spacing" per model, with the owner's verdict and its date.
- CLAUDE.md: "Testing on the printer" names the new printer, its model and its address, as the owner gives them.
- CHANGELOG: under Changed, if a default changes.
**Tests.**
- If a per-model default is built: a profile's `BoxLineSpacing` reaches the renderer when the printer's table leaves the key out; an explicit value, 0 included, wins; `UBERBRINGER_PRINTER_BOX_LINE_SPACING=0` gives 0; `config get` prints the resolved value.
- TestRenderCompat and TestPaperReceipts pass.
- The pinned receipts of the new model.
**Done when.**
- Paper, with the owner's OK, on the new printer, one receipt at a time, waiting for his report after each: `examples/blocks.json`, the calibration receipt. Look at the line breaks at 42 and 56 columns, the box borders at the default spacing, the characters, and the cut with its blank lines; the TM-m50II's cutter sits closer to the head, about 9.5 mm against 15 mm. If the borders show gaps the owner does not accept, one more receipt for each value tried.
- design.md records the verdict, and the passed bytes are pinned.
- The full gate passes.