The owner accepted every proposed default of docs/plans/templates.md on 2026-12-01. Its open questions become numbered decisions, without the alternatives, and design.md's Planned next item 5 records them. The plan's acceptance edits are made: formatters.md's phase 5 points to the plan for user templates and webhook sources; printers.md's rules package also exports the shared compile options, its environment gains template and the source hook:<name>, and its rule-visibility and reload questions name the templates plan; blocks.md says templates do not need the group; job-store.md's duplicate check takes webhook deliveries. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
121 KiB
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:
- Today's
[printer]table. Assumed: it stays, and it is the printer nameddefault.[printers.<name>]tables add the others. The namedefaultis reserved, so[printers.default]is refused with a message that points to[printer].- Nothing needs migrating. install.sh writes
[printer] addressand keeps an existing config on a re-run.UBERBRINGER_PRINTER_*keep their meaning in Docker.?printer=defaultkeeps working on the module routes. job-store.md's planned delivery rows namedefault. 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.
- Nothing needs migrating. install.sh writes
- 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 asoffice.[printers.*]comes from the file only, as[[ntfy.subscriptions]]does. The default printer keeps itsUBERBRINGER_PRINTER_*variables. No key reads aUBERBRINGER_PRINTERS_*variable, so at start one WARN line names any that is set, never its value; from stage 2a it namesUBERBRINGER_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.
- 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,retriesandretry_delay. A[printers.<name>]table starts from the same defaults as[printer], not from[printer]'s values, and onlyaddressis required.format.*,images.*,queue.*andntfy.*stay global.modelandcodepageare checked when the config loads, by one helper in internal/app that the start,config getandpreviewshare. Today they are checked only at start, soconfig getpasses 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 untilwrite_timeout, and its status reads time out (503if one of them is the default printer). Two names that resolve to one address cannot be caught. - Trade-off:
format.max_linesis 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.
- 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 oneStore.Addcommit, as job-store.md plans.queue.sizebounds 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.sizejobs. 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.
- Trade-off: no global order; a broadcast prints at different times on each printer. A host with three printers can hold three times
- 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_idandprinter. Finished deliveries,uncertainones 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.
- The seam for remote printers. Assumed: no
kindkey and no address scheme now. Each printer is built by one constructor in internal/app, which returns whatprintqueue.Senderandserver.Printerneed; 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.
- Trade-off: none known. docs/plans/remote-printers.md names the key,
Before stage 1b:
?printer=on/printand/preview. Assumed:POST /api/v1/printandPOST /api/v1/previewreadprinter, 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, soOfficeis notoffice. A name that is not a configured printer, a group's name included, answers400unknown_printer. A parameter given twice, or any other parameter, answers400invalid_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=1gets400. It matches the module routes, where a typo must not be ignored; here a mistypedprintr=officewould 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
printerlays the job out for the default printer, even when the rules would send it elsewhere; from stage 2c the JSON preview'sroutesays where it would go. - Alternatives: ignore other parameters, as today; or render a preview for the first printer of the route the rules give.
- Refusing other parameters is Breaking: a client that sends
- 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'sprinter,status,attempts,started_at,sent_at,finished_atanderror. The job'sstatusfollows job-store question 12. Beside the array, the job's own fields read:attempts: the sum;started_atandsent_at: the earliest;finished_at: the latest, once every delivery has finished;error: that of the first failed oruncertaindelivery, 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.
/healthzper printer. Assumed:statusand the HTTP code follow the default printer alone, as today, andprinterstays the default printer's health. A newprintersarray lists every printer, the default first, then by name. Each entry hasname,default,modelas configured, the fieldsprinterhas, and its ownpending.queue.pendingis 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
printerand 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 a200into a503timeout. - 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 matchescontext.DeadlineExceeded. So a host that does not answer can showtimeoutrather thanunreachable, 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.
- The default printer is read once, and that one settled read fills both
Before stage 2a:
- Expr's version, and the size it adds. Assumed:
github.com/expr-lang/exprat 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.MethodByNamewith 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.
- About half is Expr itself. The rest is other packages' methods that the linker can no longer drop, because Expr calls
- The config's shape. Assumed: a
[routing]section.[routing.groups]maps a group's name to its printers. Each[[routing.rules]]hasname,order,when,mode,toandenabled. A rule's name follows the printer names' rule and is unique, so logs androutename one rule.totakes a name or a list, as list keys do.whenis 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 thename=valueform, 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 ofto.
- Not
- Rule order. Assumed:
orderis a required integer, unique across all rules, disabled ones included, lower first, as Kanrisha's priority; the first match wins. A disabled rule'sorderis unique too, so enabling it cannot break a start. It is not calledpriority, which a rule'swhenalready uses for the ntfy priority. A uniqueorderavoids Kanrisha'ssort.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.
- Groups, and what
totakes. Assumed: groups hold printers, never other groups, so no cycle can form. Groups and printers share one namespace, sincetocan name either; a group named like a printer, ordefault, is an error. A group is not empty, repeats no member and names configured printers.toby 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.
- 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 examplerouting.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.
- 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 callsError(), whose text carries the rule's source and quotes values from the env: the probe'sint(topic)gaveinvalid 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 routeshows 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 todefaultbecause a rule broke shows without the logs; that needs one more stored column, or a field a restart loses.
- Trade-off: the log does not say what went wrong;
- 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:clientis the token's subject. It is free text chosen when the token is minted, and two tokens can share it.priorityis 0 for a job that is not a notification. With 3, ntfy's default,priority >= 3would match plain jobs.- A digest's
priorityis its highest row's, and itstopicsandtagsthe union of its rows'. topic,topicsandtagsalso 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 atSubmitonly: 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
Submitwould 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). - The rules of docs/plans/templates.md, for ntfy messages and webhooks, see print contents (its decision 14). A routing rule still sees routing facts only.
- 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.
- Compile options and the clock. Assumed:
expr.Env(routing.Env{}),expr.AsBool(),expr.DisableBuiltin("now"),expr.DisableBuiltin("$env")and the default node limit.expr.Timezonetakesformat.timezoneonce validation has loaded the zone, since it panics on an unknown name. The clock is injected:nowis the job's acceptance time informat.timezone, so a dry-run with--atand 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
Patchvisitor that refuses..ranges.
- Trade-off: Expr has no step limit. Nested predicates over large literal ranges, such as
- Storing the decision. Assumed: a route is decided once, at
Submit, and stored; a restore never runs the rules again. The job keeps itsroute:by(rule;queryfor an explicit?printer=; ordefault), the rule's name and the mode, and job status shows it. An anycast delivery keeps its ordered list and the printers that got asendingmark (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
jobsrow keeps no priority, tags or client, and the rules may have changed since. - With SQLite,
jobsgainsroute_by,route_ruleandroute_mode, anddeliveriesgainscandidatesandsent_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 touser_version2. - 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.
- This replaces job-store.md's assumption that a restored anycast delivery's list is "given again" by the rules and the config. Its
- 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 byjob_idandprinter, and not sent to Sentry, since a full queue is a refusal, not a fault.Submitanswersqueue_fullonly 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_fullmakes the subscriber stop reading, so one dead printer would stall a whole subscription, theurgent-on-desksexample 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.
copiesapplies to each delivery.- Trade-offs: a job can be
failedon one printer while it prints on the others; itsstatussays so once they finish (job-store question 12), anddeliveriesat 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.
- 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
Before stage 2b:
- 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
toand every group member must name a printer that has a lane, or the whole reload is refused.broadcastmeans the running printers. The rules compile with the runningformat.timezone, so thatdate()andnowagree. - 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, sosystemctl reload uberbringerworks; a container takesdocker kill --signal HUP; Windows, for development only, has no reload. Viper'sWatchConfigis 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). - The reload also swaps docs/plans/templates.md's templates, ntfy rules and webhooks, in one snapshot with
[routing](its decision 17). - 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").
- The new routing is checked against the printers that are running, not the new file's. Every rule's
Before stage 2c:
- 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 gainsroute, 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/routefor full tokens, which needs its own entry in the route table, test case, docs and schema.
Before stage 3:
- Failover after bytes went out (job-store question 23). Assumed, the owner's default: the existing retry rule on that printer (
retries, with the doublingretry_delay), then failover to the next printer of the list.- The delivery's
sent_tolists every printer that got asendingmark, so a person knows which paper to check. - A write error after which
Writehad taken nothing counts as nothing sent and fails over at once. That needsSendto report what it wrote, which it discards today. The printer stays insent_toall the same: over-reporting is the safe direction, and dropping it would cost one more store write. attemptscounts 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.
Writereturns 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
sendingmark: 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 deliveryuncertainand never resent.
- The delivery's
- A status check before an anycast send. Assumed: after the dial and before the
sendingmark, on the same connection and inside the printer's slot, anycast readsDLE EOT. It reads a not-ready answer again 750 ms later, as/healthzdoes.- The read runs over the connection already open, so it never waits on its own slot.
- It reads
DLE EOTonly. Stage 4a'sGS r 1is 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
/healthzshare one settle function, moved from the server toprinter, 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.
- 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
officewould delay analertsjob by 4-5 minutes whiledefaultsits idle. Once the dead lane is full,Submitwould 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_fullcomes 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.
- 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'sretriesmore 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.
- 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.Optionsfield, 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, thenqueued, thenprinting(job-store question 12). - After a
sendingmark, a moved delivery stayssendingin the store while it waits on the next lane. A crash then turns ituncertainat 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_atandsent_to, with either store. That is job-store's rule for a delivery between retries after reachingsending. - 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
queuedafter 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:
- Keeping the exact model. Assumed:
escpos.ProfilegainsModel, the name as configured (tm-t88ivtotm-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 1or nowhere), and whetherDLE EOT 3bit 2 exists.- Only
tm-t88viitakes near-end fromGS r 1. Every other name keeps today'sDLE EOT 4. The familiestm-t88andtm-m50behave as the TM-T88IV and the TM-m50II;tm-m50(the TM-m50) and thetm-t20and generic profiles stay unverified. Namestays 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 astm-t88viito report its near-end. - Trade-off: a TM-T88VII configured as
tm-t88reports no near-end, as today. - Alternative:
tm-t88viias a profile with a name of its own, which changes the name that previews and the models table in docs/configuration.md show.
- Only
- The TM-T88VII's near-end through
GS r 1. Assumed:Statussends it last, only whenDLE EOTsays 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 andStatus.Applywould 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:
paperreads asDLE EOT 4gave it, nevertimeout, never503. - 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 EOTmask, since its bits 0 and 1 are both clear or both set, and reads once as unsupported (unknown,200). - Trade-off:
GS r 1is 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 oneunknownreading. - 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 toDLE EOT 4(unknown).
- Its reply has a decoder of its own, since its fixed bits differ from
- More status bits, and frames nobody asked for. Assumed:
Ready()also countsDLE EOT 2bit 6 (an error occurred) andDLE EOT 3bit 2 (a recoverable error; the TM-T88IV lacks it), read again like the rest.Normalized()clearsDLE EOT 2bit 6 whileDLE EOT 1says 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:
/healthzcan answer503on a recoverable error where it answered200. - Alternative: decode what is decoded today.
- Trade-off:
Before stage 4b:
- 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 definesProfile.LineSpacingthere. This plan adds nothing for it. box_line_spacingkeeps 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 doesProfilegainBoxLineSpacing. The key's default then becomes -1, meaning "the model's", validated from -1 to 255, since an explicit 0, andUBERBRINGER_PRINTER_BOX_LINE_SPACING=0, must still meanESC 2. The load helper resolves -1 from the profile, soconfig getprints the value in use.cut_feedstays one default for every model.GS V 66feeds 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 andValue()must handle; or no per-model default, with a calibrated value written into that printer's table by hand.
- The default line spacing (
- 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-t88andtm-m50would break words at the printer's edge. Paper reduction of the bottom margin would removecut_feed's blank lines. - Alternative: profile variants for 48-column mode. 58 mm paper already works through
paper_width = 360.
- Trade-off: in 48/36 column mode the width is 480 dots and Font A is 10 dots wide, so
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
DisableAllBuiltinscover 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 throughOpCall*). 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.Timefield is the slowest. Compiling one rule takes about 15 µs. A compiled program never changes and is safe for many goroutines;expr.Runmakes 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) > 3gaveinvalid operation: int(alerts-door),tags[5]gaveindex out of range: 5 (array length is 2). Errors also carry the rule's source with a caret. $envreaches every exported field of the env.now()reads the wall clock. An env field namednowhides 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=truein the unit.
"x" in tagson an empty list is false, with no error. Strings compare in byte order, so a zero-paddedclock >= "22:00"works.
KANRISHA'S ENGINE
Rulehas an ID, name, expression, action and params, filesystem scopes, an integerPriority(lower first) andEnabled.CompiledRulepairs it with its program.- Compile:
expr.Compile(expression, expr.Env(EnvPrototype()), expr.AsBool()), with no node limit and no builtin turned off, sonow()stays beside the injectednow. The API compiles a rule before storing it, so a bad one is refused when it is created. LoadRulesskips disabled rules, compiles the rest, logs and skips a rule that fails, sorts by priority withsort.Slice, which is not stable, and swaps the set under a write lock.AddRule,UpdateRuleandRemoveRulere-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 withexprtags in place of a map and its prototype (question 17); a uniqueorderin place of an unstable sort (question 12);now()turned off (question 17); a rule that fails to compile is a config error (question 14); anatomic.Pointerto 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 againstprinters.*.<key>, and the per-entry default hook the subscriptions use,[printers.kitchen]with onlyaddressgot 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 asoffice, and a group namedDesksasdesks. Values keep their case, so a group member"Office"stays"Office". - A list of tables loads
enabledas 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, whosename=valueform cannot hold a list:desks=default,officefails 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(), behindconfig get, walks struct fields only and cannot reachprinters.office.address.- There is no reload: the daemon handles SIGINT and SIGTERM only, the unit has no
ExecReload, and nothing calls Viper'sWatchConfig.
THE REPOSITORY TODAY
- serve.go builds one renderer, one
printer.Client, one queue with one worker, and onePrinterfor/healthz. Itslisteningline gives the printer's address.printqueue.Senderandserver.Printerare already the interfaces a printer needs. escpos.LookupProfilefoldstm-t88ivtotm-t88viiintotm-t88, andtm-m50iiintotm-m50, and TestLookupProfile pins it. Nothing after the lookup can tell a TM-T88VII from a TM-T88IV.printqueue.Metaholds 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 reachSubmit.Module.Buildreturns only areceipt.Job, so the facts of/print/notifyand/print/ntfystay inside the module. It is called at server/handlers_modules.go:90 and internal/app/uberbringer/preview.go:137 (preview --module); its fakes arefakeModule(server/handlers_modules_test.go) andstubModule(modules/registry_test.go). auth.go keeps only the token's scope, not its subject.- An ntfy subscription offers a message again after any
Submiterror,queue_fullincluded, and stops reading meanwhile (design.md, TCP backpressure). /printand/previewread no query. Only the module routes parse one, and acceptprinter=defaultalone (unknown_printerotherwise); an emptyprintermeans the default.- The worker retries every
Senderror alike, andSenddiscards the countWritereturns, so a dial failure and a write cut short look the same. Client.Statustakes the connection slot throughconnect, andsettledPrinterStatusin 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./healthzreads 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, whicherrors.Ismatches tocontext.DeadlineExceeded, so/healthzmaps it totimeout.- The server's test helpers have 50 callers that pass one printer:
newTestServer40 andnewLoggedServer10.
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 @thenESC t, so a printer's own default page never matters. - The TM-m50II's command list includes
GS ( Hfn 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 afterESC @. A frame's first byte fails theDLE EOTmask, soStatuswould read it as "unsupported". - A byte string inside a command's parameters that matches a real-time command is executed as one: image or
rawbytes that hold10 04 nmake 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.Statusdecodes neitherDLE EOT 2bit 6 norDLE EOT 3bit 2, soReady()misses a recoverable error on the newer models.GS r 1reports 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 fromDLE EOT's (bit 4 is 0, whereDLE EOThas 1), soStatus.Applywould refuse it; Epson's page also says to accept0xx1xx10, 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]withto. 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.goand.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 pagestmt88iv.html,tmt88vii.htmlandtmm50ii.html, under https://download4.epson.biz/sec_pubs/pos/reference_en/escpos/.
Overview
WHAT SHIPS WHEN
- Stage 1a: named printers beside the default, a lane each,
preview --printer, andconfig getchecking every printer. Every job still prints on the default printer. Stage 1b:?printer=on every print and preview route,/healthzper printer, and deliveries in job status. - 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 routeand the route in the JSON preview. - Stage 3: anycast, with failover down an ordered list.
- 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.
- 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 ondefault. install.sh, the Dockerfile andUBERBRINGER_PRINTER_*do not change. Two changes reach every config:- Breaking:
/printand/previewrefuse query parameters other thanprinter(question 7). - Job status gains
deliveries(question 8), and from stage 2aroute(question 18). Its other fields keep their meaning.
- Breaking:
?printer=defaultkeeps working on the module routes, and an emptyprinterstill means the default printer./healthzkeepsstatus,printerand its code; it gainsprinters.queue.pendingbecomes the total across printers.queue.sizebounds 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_version2, 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
- 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.
- 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
rawelement, whose bytes are written for one model; a rule ontypeskeeps them there. - A job no rule matches prints on the default printer, and a config without
[printers]or[routing]prints as today. - A rule sees routing facts only, never print content, a token, a secret, a
refor 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. - 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. - 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.
- An anycast delivery fails over at once only when none of its job's bytes went out: before its
sendingmark, or whenWritetook nothing. A failure its own context caused (a shutdown, a cancel or its bound) never fails over. /healthz's status code follows the default printer alone.- printqueue, server and config never import Expr, so tools/genopenapi never compiles it. printqueue and printer never import each other.
- 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]toprinters.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
deliveriesarray and leaves the job's own fields to this plan: point to question 8, under which every status gainsdeliveriesfrom 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
sendingmark", since an anycast check sendsDLE EOTbefore 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
sendingmark 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 ( Hfn 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.
- COMPATIBILITY's "Job status keeps its shape until there are several printers", and the DELIVERIES AND SEVERAL PRINTERS bullet that gives the
Architecture
PRINTERS IN THE CONFIG (stage 1a)
# 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
addressis required (question 3). No two printers share an address and port. - The loader gains a key kind for a table of named tables.
registerDefaultsregisters its entry keys asprinters.*.<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 ontoDefaultPrinter()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)
┌─ 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 andOnFailure. Per lane: the name, the renderer with that printer'sreceipt.Options, the sender (itsprinter.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.
Submitroutes first, outside the locks (stage 2a). Then, under the submit lock, it checks capacity on the target lanes (question 19), commitsStore.Addwith every delivery, and appends each delivery to its lane.Runstarts one worker per lane; shutdown covers every lane, byDurable().- A store failure stops every lane. The first store error from any lane ends the others, and
Runreturns it, as an errgroup does (job-store question 11). An idle lane must not keepRunalive, and no lane may send after the store broke. - Every worker log line carries
printer.OnFailuregets the printer, and Sentry tags it; never content.
DELIVERIES AND JOB STATUS (stages 1b-3)
{"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"}]}
deliveriesfrom stage 1b (question 8).routefrom stage 2a (question 18), whosebyisrule,queryordefault. An anycast delivery'sprinters, its ordered list, andsent_tofrom stage 3 (questions 22 and 26).- The job's
statusderives from its deliveries by job-store question 12; with one delivery it is that delivery's. - Enums go into
jsonschematags, 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, androute.byisquery. It names a printer, never a group. An empty value means the default printer.- Routes: the module routes, as today, and
POST /api/v1/printandPOST /api/v1/preview(question 7).unknown_printerandinvalid_querykeep 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) androute(stage 2c): the decision without queueing (question 21).
HEALTH (stage 1b)
{"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
statusfollow the default printer, as today (question 9). The entries reuseprinter's fields, so the existing enum test covers them.modelis the model as configured. The ntfy array is unchanged. - The default printer is read once, and that read fills
printerand 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 againstE'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 inorderwhosewhenis 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.Engineholds the current set behind anatomic.Pointer, withSwap,MatchandExplain. It also exportsOptions, the compile options and the iteration guard that docs/plans/templates.md shares; whichever of this stage and that plan's stages comes first builds what it needs of the package (its decision 1).internal/pkg/routing(new):Envand how it is built; the action (Mode,To) and its resolution against the printers and groups; theprintqueue.Routerit implements.- printqueue defines
RouteandRouter; 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, soconfig getfails 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, withtoexpanded (question 13). No match gives unicast to the default printer,by = "default". A runtime error passes to the next rule (question 15). Submitstill refuses a printer with no lane (ErrUnknownPrinter, name assumed): a guard for a bug, once stage 2b checks reloads (question 20). The server answers500and 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.Printercomes in stage 1a. Stage 2a reads the module and the subscription fromSource. Stage 2c addsMeta.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, sinceModule.Buildreturns the job with its topic, priority and tags. ntfy.go fills them from the message or the digest's rows.Factsare used atSubmitonly (question 16). The job's size comes from encoding it once, whichStore.Addalso 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):
[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
alertsmatchesurgent-on-desksand 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-t88ivanddrill. Stage 2c addsurgent-on-desksand its group, sinceprioritycomes with it. Stage 3 addsalerts, since stage 2a refusesanycast. - A subscription gets its printer through a rule on
subscriptionorsource; subscriptions gain noprinterkey. - A multicast or broadcast rule not limited by
sourceortypessendsrawjobs 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>, ntfy:<subscription> or, from docs/plans/templates.md stage 4, hook:<name>, 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 |
template |
string | 2c | the template the job was built through, by its module route, an ntfy rule or a webhook, once docs/plans/templates.md stage 1 has shipped (its decision 13); else empty |
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)
- 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_fullcomes only when every lane of the list is full (question 24). Its storedprinteris the one to try first. - That lane's worker renders with its printer's options, or keeps bytes rendered for an equal options key (question 26).
- The checked send takes the printer's slot and dials. It reads
DLE EOTon that connection, reading a not-ready answer again (question 23). Then it callsbeforeWrite, which commits thesendingmark and adds the printer tosent_to, and writes. - Nothing of the job sent (the error came before
beforeWrite, or matchesNothingWritten): 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. - Bytes sent: the retry rule on that printer, then the move (question 22).
- 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).
- 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_atandsent_toset. - 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).
- A restored queued anycast delivery starts from the top of its stored list, without printers no longer configured (questions 5 and 18).
- 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
printeris 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 deliverycandidatesandsent_to, written from stage 3.printqueue.RecordandDeliverygain the same fields; the memory store keeps them. A delivery whose lane is full is insertedfailed, 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 tosent_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.ProfilekeepsName, the layout family, and gainsModeland the status capabilities (question 27). Layout fields stay shared by the three printers.LineSpacingcomes with job-store phase 3a;BoxLineSpacingcomes only if a paper check needs it (question 30).- Status:
printer.Client.StatuskeepsDLE EOT 1-4, one request at a time. On a profile whose near-end comes fromGS 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()andNormalized()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(SendwithbeforeWrite, and stage 3's checked send) andserver.Printer(Status). Today it is a*printer.Client; docs/plans/remote-printers.md adds one backed by an agent's link, chosen by itsagentkey (its decision 16). - The contract a remote printer keeps is printqueue's send contract (stage 3):
beforeWriteruns only once a connection to the printer itself is open, wherever that is, so thesendingmark and "nothing sent" stay true across the agent.- A failed send that never called
beforeWritesent nothing. One that called it sent nothing only when its error matches printqueue'sNothingWritteninterface, 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'slisteningline 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_idand 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 routeprints 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_*andUBERBRINGER_ROUTING_*variables, never their values (question 2). /healthzshows 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.tomlentry 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_timeoutof 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
ExecReloadin 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), andDefaultPrinter().- 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, reportingprinters.<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()reachesprinters.<name>.<key>.
internal/pkg/printqueue
- queue.go:
Newtakes the lanes, the default first: each (Lane, name assumed) withName,Renderer,Sender,RetriesandRetryDelay, which leaveOptions.- One waiting list and worker per lane;
Runstarts them all; shutdown covers every lane. The first store error from any lane stops every lane, andRunreturns it. Meta.Printer, the printer the job goes to; empty means the default.Submitrefuses a name with no lane (ErrUnknownPrinter, name assumed), a guard for a bug: the server and the router check first.- Capacity per lane;
Pendingper printer and in total. - A delivery's
Printeris its lane's name. Restore puts each queued delivery on its lane; one whose printer is gone fails (question 5). OnFailuregains the printer; every worker log line carriesprinter.
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 getandpreviewalike.tokenkeepsconfig.Loadalone: it needs onlyapi.secret, and a token can then be issued while the config is being fixed. - serve.go:
- a renderer, a
printer.Clientand 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.
- a renderer, a
rendererOptionstakes one printer's config.reportJobFailuretags the printer.- preview.go:
--printer. - cli.go:
config getthrough the load helper.
Docs
- docs/configuration.md:
- a § printers:
[printers.<name>], the printerdefault, the names, the keys and their defaults, no shared address, file only; - § Loading: a named printer requires its
address, besideapi.secretandprinter.address; - § Environment variables: the exception names the printers beside the ntfy subscriptions, and the WARN for
UBERBRINGER_PRINTERS_*; - § queue:
sizecounts per printer; - § printer:
retriesfails the job on that printer.
- a § printers:
- configs/config.example.toml: a commented
[printers.<name>]after[printer]; thesizecomment says per printer; the header's "sets any key" names the exceptions. - docs/cli.md:
preview --printer,config get printers.<name>.<key>, andconfig getfailing 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-timeoutabove the largestwrite_timeoutof any printer plus 10 s. - docs/install.md: the unit's stop timeout, systemd's 90 s, must exceed the largest
write_timeoutof 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.sizecounts per printer, andconfig getchecks the model and code page.
Tests.
internal/pkg/config (a new printers_test.go)
- A
[printers.kitchen]with onlyaddressgets every default;retries = 0stays 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_ADDRESSstill sets the default; aUBERBRINGER_PRINTERS_*variable is named for the WARN. - TestLoadInstallScriptConfigGetsDefaults and TestExampleConfigLoads pass unchanged.
Value()readsprinters.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;
Pendingper printer and in total. - Shutdown covers every lane, by
Durable(). - A store error on one lane stops every lane, and
Runreturns 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 getfails 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.Deliveriesand the job's own fields (question 8), with theirjsonschematags. - schema_test.go: a delivery's
statusenum held to theStateconstants.
internal/app/uberbringer/server
- server.go:
Depstakes the printers, the default first, each with its name, configured model,PrinterandPreviewer; the nil checks follow.Jobs.Pendingper printer. - handlers.go:
handlePrintreads the query (question 7).handleHealth,healthResponseandqueueHealth(question 9): the default printer read once, fillingprinterand the first entry; the others read in parallel. - handlers_modules.go:
moduleQuerychecksprinteragainst the configured names; thedefaultPrinterconstant and its "the only printer is" message go. - handlers_preview.go:
?printer=on both preview routes; the JSON answer'sprinter. - routes.go: query parameters for
/api/v1/printand/api/v1/preview;unknown_printerandinvalid_queryin their error lists; the descriptions of the module routes'printerand of/healthz("depends on the printer alone"). - errors.go: no new code; the messages of
unknown_printerandinvalid_queryfit 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_printerandinvalid_queryrows, the latter no longer "On a module route" only; - Health, with
printers;queue.pendingas the total across printers, which changes its meaning for monitors that alert on it; the status code following the default printer; - Job status, with
deliveriesand 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:
/healthzanswers503while the default printer is unreachable; the others show in its body. - design.md: the diagram's
/healthz; "Module routes takecopiesand the reservedprinter"; "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,printersin/healthzanddeliveriesin job status; under Breaking,/printand/previewrefuse other query parameters; under Changed,queue.pendingis the total across printers.
Tests.
internal/pkg/printqueue
- Status:
deliveriesand 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,
Officeforofficeincluded, givesunknown_printer; - a parameter given twice, or another parameter, gives
invalid_query.
- The JSON preview names its printer and renders with that printer's options.
/healthzwith three printers:- the code follows the default printer only;
- the default printer is read once, and
printerequals the first entry; - another printer on a refused port gives
200with its entryunreachable; - 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,
/healthzanswers200, with that entryunreachable. An address with no host behind it may readtimeoutinstead (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/exprat its latest stable release. Run govulncheck.go generateregenerates 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:
Envwith stage 2a's variables and theirexprtags (Architecture, THE ENVIRONMENT), built from the job,Meta.Source, the job's size, the acceptance time and the zone. - action.go:
ModeandTo;toresolved 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, neverError(). 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.
- A rule's runtime error gives one WARN line with the rule's name, the
internal/pkg/printqueue
- queue.go:
Route(By,Rule,Mode,Printers) and theRouterinterface;Options.Router, nil keeping stage 1b's behaviour.Submitroutes first, outside the locks, then makes one delivery per printer of the route. Capacity by question 19: a delivery whose lane is full is insertedfailed, "printer's queue is full", and logged at WARN byjob_idandprinter;queue_fullonly when every target lane is full. The job's JSON is encoded once, forbytesand forStore.Add.Status.Route, with enum tags forbyandmode.
- store.go:
Record.Route, andDelivery.CandidatesandDelivery.SentTofor stage 3; the memory store keeps them.Addtakes a delivery insertedfailed, and then syncs. - schema_test.go: the
byandmodeenums.
internal/pkg/jobstore, if job-store stage 1d has shipped
- A schema step to
user_version2 with the route and delivery columns (question 18). Otherwise job-store stage 1d's schema takes them.
internal/pkg/config
- config.go:
RoutingwithGroupsandRules.- 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 fromDefaultRule()(enabledtrue).- Validation: rule names by the printer names' rule, unique; a unique
orderacross all rules, disabled ones included; awhenthat is not empty;modeone ofunicast,multicastandbroadcast(anycastcomes in stage 3);toby 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 getandpreview, 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
ErrUnknownPrinterfromSubmitis 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-t88ivanddrillfrom the example, literal strings forwhen, and what a compile error and a runtime error do; - a warning that a multicast or broadcast rule not limited by
sourceortypessendsrawjobs to every model; - § Environment variables: the exception names
[routing], and the WARN forUBERBRINGER_ROUTING_*.
- a § routing: groups, rules, the modes, stage 2a's variable table, the rules
- configs/config.example.toml: a commented
[routing]example. - docs/ntfy.md: a subscription gets its printer through a rule on
subscriptionorsource; the paper budget counts jobs, not deliveries (question 19). - docs/development.md § Package layout:
internal/pkg/rulesandinternal/pkg/routing. - docs/api.md: job status
route;queue_fullonly when every printer of the route is full; a deliveryfailedwith "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
routein 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,
priorityincluded until stage 2c; a result that is not a bool; a type mismatch (copies == "5");now()and$envrefused; 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;
orderdecides, 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.
MatchandExplainfrom 100 goroutines under-racewhile 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);
weekdayusesquiet.days' names;clockis 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'sexprtags.
internal/pkg/config
enableddefaults to true.- Refused: a repeated rule name; a repeated
order, a disabled rule's included; an unknown mode;anycastuntil stage 3;toagainst each mode; a name intothat is neither a printer nor a group; a group named like a printer, ordefault; 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; aUBERBRINGER_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_version1 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
ErrUnknownPrinteris logged and reported, and the message is not offered again.
internal/app/uberbringer/server
- A group's name in
?printer=givesunknown_printer. - schema_test: the
routeenums.
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
toand every group member must name a printer that has a lane, or the whole reload is refused at ERROR and the old set kept;broadcastresolves 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.
- the load helper, compiling the rules with the running
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 uberbringerafter a change to[routing]. - docs/docker.md:
docker kill --signal HUP. - design.md: the reload, under Packaging.
- CHANGELOG: under Added.
Tests.
reloadcalled 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 ruleto = "new"is refused, and so is a group naming a printer with no lane; - a changed
format.timezoneis not applied, and the rules compile with the running zone; - the WARN names the changed sections, such as
apiandntfy, 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 uberbringerwith a changed rule logs the swap; once stage 2c has shipped, the JSON preview'srouteshows 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 atSubmitonly: 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 thatMetais 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:
Buildreturns the job with its facts (a result type, name assumed). note.go returns none; notify.go and ntfy.go return theirNotice's topic, priority and tags. Their tests follow, and so do the fakesstubModule(modules/registry_test.go) andfakeModule(server/handlers_modules_test.go).
internal/app/uberbringer
- ntfy.go: cards and digests carry their facts.
- preview.go:
preview --modulefollowsBuild'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:
clientfor/print. handlers_modules.go:Meta.Factsfrom the token and fromBuild's result. - handlers_preview.go: the JSON answer's
route;JobsgainsRoute, andfakeJobswith it.
Docs
- docs/configuration.md § routing: the variables stage 2c adds, and the example's
urgent-on-desksrule 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'srouteshows 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
clientin rules,uberbringer route, androutein 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
notifypayload, 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 anyExplainoutput 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 thatFactsholds lists. uberbringer route: a golden output for the example config withoutalerts, with--at.
internal/app/uberbringer/server
clientis the token's subject; the JSON preview'sroute.
Done when.
- The full gate passes.
uberbringer routeexplains 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): theDLE EOTreads on an open connection.Statuscalls it afterconnect; 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 toStatusalone.Settle(ctx, read, delay)(name assumed): the read again of a not-ready answer, moved from server/handlers.go'ssettledPrinterStatus./healthzpassesClient.Statusand itsHealthRecheckDelay; 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. Sendreturns an error type (SendError, name assumed) holding the countWritetook, with a methodNothingWritten() 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
beforeWritesent nothing. One that called it sent nothing only when its error matches, througherrors.As, an interface printqueue declares withNothingWritten() 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.
Sendergains 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.
- The send contract, in printqueue's own terms, so that neither package imports the other. A failed send that never called
- store.go:
Sendingadds its printer toSentTo; a restore drops printers no longer configured from a delivery's list (question 5). Status: an anycast delivery'sprintersandsent_to.
internal/pkg/routing, internal/pkg/config
anycastaccepted;tokept in order, groups expanded in member order (question 13).
internal/pkg/jobstore, if it exists
- Writes
candidatesat insert andsent_towith eachsendingmark.
internal/app/uberbringer/server
- handlers.go:
/healthzusesprinter.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
alertsrule. - docs/api.md: job status,
printersandsent_to, and whatsent_towith 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 matchesNothingWritten; 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
beforeWritecall; - 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.
- a printer still not ready after the second read gets no job byte and no
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
Sendingcommit, no retry on the first printer, and the next printer prints. - After a
sendingmark, the first printer's retries run, then failover;sent_tolists both, and the status shows it. - A write error with nothing written fails over at once, though its mark was committed;
sent_tokeeps the first printer. attemptscounts 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
printingthrough 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_atandsent_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'salertsrule.
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:
- An anycast rule with the first printer switched off. The receipt prints on the second only.
- 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:
- On the TM-T88VII: the
GS r 1reply 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. - On the TM-T88IV just after power-on, and on the TM-T88VII with DIP switch 2-1 as it is set: does
/healthzreadunknown, a sign that automatic-status frames reach the connection? - 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:
Modeland the status capabilities (question 27);LookupProfilekeeps the exact name. - status.go: the
GS r 1request and its decoder (question 28); question 29's bits inStatus,Normalized()andReady(); the comment on the TM-T88VII.
internal/pkg/printer
- printer.go:
StatussendsGS r 1last 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, staysDLE EOTonly.
internal/app/uberbringer
- serve.go: each client gets its profile's status capabilities.
internal/app/uberbringer/server
- handlers.go:
paperfrom 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-t88viito 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 1decoder on near-end, paper end, both bit-4 forms and a malformed byte; - a
GS r 1reply read as aDLE EOTanswer is refused; - the new bits in
Ready(), andDLE EOT 2bit 6 cleared while online.
- printer, against a fake listener:
GS r 1is sent last and only when online; no answer gives near-end unknown, not a timeout, and closes the connection; atm-t88profile never sends it. - server:
/healthzshowsnear_endfromGS r 1; a missed answer leaves200. - TestRenderCompat and TestPaperReceipts pass: no printed byte changes.
Done when.
- The full gate passes.
- With the owner's OK, a status read only:
/healthzon the TM-T88VII showspaperfromGS 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 getprints the value in use. The renderer gets the resolved value; 0 keepsESC 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_spacingrow 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
BoxLineSpacingreaches the renderer when the printer's table leaves the key out; an explicit value, 0 included, wins;UBERBRINGER_PRINTER_BOX_LINE_SPACING=0gives 0;config getprints 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.