The owner accepted every proposed default of docs/plans/remote-printers.md on 2026-11-30. Its open questions become numbered decisions, without the alternatives, and design.md's Planned next item 3 records them. The plan's acceptance edits are made: printers.md's seam, question 6, question 24 and stage 3 point to it, and job-store.md notes that a remote attempt whose outcome stays unknown turns uncertain during a run and that the acknowledgement runs at the agent for remote printers. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
68 KiB
Plan: remote printers, reached through an agent
Status: planned; nothing is built. The owner accepted every proposed default on 2026-11-30 (Decisions), and design.md's Planned next item 3 records them. This plan builds on docs/plans/job-store.md and docs/plans/printers.md and redesigns neither. It fills the seam that printers.md leaves for remote printers (printers question 6, and its Architecture section THE SEAM FOR REMOTE PRINTERS). Stage 1 needs nothing from those plans. Stage 2 needs printers stage 1a, for its key kind for a table of named tables. Stage 3 needs job-store stage 1c, for beforeWrite in printer.Client. Stage 4 needs printers stages 1a and 1b and job-store stage 1c. Its anycast part needs printers stage 3; whichever of the two lands second builds that part. Stage 6 waits for the owner's word and job-store phase 5. Each stage runs in its own session, briefed from its section, in the order listed. Every check on a real printer needs the owner's OK. Whichever stage finishes last deletes this plan, its findings with it, and design.md's Planned next item 3.
Decisions (owner, 2026-11-30)
- Printers on other networks are reached through an Überbringer agent next to them.
- The agent dials out to the main instance over HTTPS and WebSockets, using Fiber. No inbound port is opened at the remote site.
- Messages are MessagePack through
github.com/tinylib/msgp, at its latest stable release. The generator is pinned in go.mod'stoolblock and run asgo tool msgp. - NATS JetStream, embedded etcd and VPN tunnels are not used for this.
The owner accepted the details below on the same day. They are numbered, so the rest of the plan can refer to them. "Main" is the instance that takes jobs, queues and renders them; "the agent" is the process next to the remote printers.
For stage 1:
- Where rendering happens. main renders each delivery in full, with the remote printer's profile and options, as for a local printer. The agent receives the finished bytes and writes them unchanged. It never parses or renders a job, fetches no images and needs no profile for printing.
- Invariant 1 then holds where it holds today: main renders the whole receipt before anything leaves for the printer. The agent adds one check: it writes only once it holds every byte, matched by length and SHA-256.
- Images are fetched by main, through its SSRF guard and its
images.*exceptions. A URL that only the remote network can reach cannot print there. - Bytes cross the link instead of the JSON job: an image costs up to 64 bytes per dot row (256,000 bytes for one 4,000-dot image), against a few KB of JSON for a URL. A slow uplink at the remote site does not matter, since bytes flow from main to the agent.
- Trade-off: larger transfers, and no image only the remote site can fetch.
- The messages and their versioning.
- Each WebSocket binary message holds one envelope: a msgp map with the message's type, as a short string, and its body. Bodies are structs that msgp encodes as maps with short field names (
msg:"k"). Never tuples (//msgp:tuple), which cannot gain a field. - Generated decoders skip map keys they do not know (findings, MSGP). So a field may be added in any release, and a reader of an older release ignores it. Renaming or removing a field, or changing what one means, takes a new protocol version.
- The protocol version is the WebSocket subprotocol. The agent offers
uberbringer-agent.1inSec-WebSocket-Protocol, and main accepts the versions it speaks. A later breaking change offers.2beside.1for at least one release. An agent whose offer main does not speak is refused before the upgrade (decision 7). HelloandWelcomecarry each side's release version, for the logs. They also carry each side's capabilities as a list of names, so a feature can be added without a new version.- The message types are under Architecture, MESSAGES.
- Trade-off: field names cost a few bytes per message; job bytes dominate.
- Each WebSocket binary message holds one envelope: a msgp map with the message's type, as a short string, and its body. Bodies are structs that msgp encodes as maps with short field names (
- Sizes, chunks and limits.
- Main sends a delivery's bytes as
Datamessages of at most 64 KiB, each naming its attempt key, before it asks the agent to open the printer. The agent assembles them for that printer and acts only on the whole. Offset 0 starts a new buffer. - The agent holds at most one job per printer. Main has at most one attempt in flight per remote printer, through a slot of its own for each (Architecture, A REMOTE SEND, step 1).
agent.max_job_bytescaps one job: default 16 MiB, from 1 MiB to 256 MiB, announced inHello. Main checks a rendered delivery against it before it sends anything. One over the cap fails like a render error: nothing sent, no retry. An anycast delivery moves on to its next printer, as after any failure before a byte was sent.- Read limits per WebSocket message: 128 KiB at the agent and 64 KiB at main, since agent messages are small.
queryasks about at most 128 keys at a time, so its reply stays far under main's limit. msgp's//msgp:limit arrays:1024 maps:64bounds what a decoder allocates. A message over a limit, or one that fails to decode, closes the link as a protocol error. - Main's writer sends control messages (
Open,Go,Abort,Status,Query) before queuedData, so a large transfer holds back neither a status request nor a go-ahead. - No WebSocket compression (
permessage-deflate). - A 64-KiB frame within decision 9's 30-s write deadline needs about 17 kbit/s, so a slow uplink at main's side still carries image jobs.
- Trade-off: a receipt over 16 MiB (about 65 images of 4,000 rows) cannot print remotely. An agent on a small board holds up to 16 MiB per printer.
- Main sends a delivery's bytes as
For stage 2:
- One binary. the agent is the same binary, run as
uberbringer agent. One build, one release, one image and one set of licence notices, and the agent reusesprinter,escpos, the config loader and the logging.- Trade-off: the agent carries the whole server, about 20 MB once Expr is linked (printers question 10), on boards where it uses a fraction of it.
- The WebSocket libraries. main serves the link with
github.com/gofiber/contrib/v3/websocket(v1.3.1, the Fiber v3 middleware), and the agent dials with theDialerofgithub.com/fasthttp/websocket(v1.5.12), the library that middleware is built on. One implementation then serves both ends, and both are pure Go.- The middleware refuses a request without an
Originheader unlessAllowEmptyOriginis set. The agent sends none, so the setting is on. Main refuses a request that carries one instead (decision 7). - Trade-off: fasthttp/websocket has had no release since 2025-01-01. A fault there reaches both ends.
- The middleware refuses a request without an
- Authenticating and authorising agents. an agent's token is a bearer token like the others, signed with
api.secret(HS256), with a new scope claimagtnaming the agent.uberbringer token --agent <name>issues it, refusing--modulesand--rawbeside it.- A token with
agtopens the agent route only and is refused everywhere else with403token_scope. No other token opens the agent route.agtjoinsmodandrawamong the scope claims, so a malformed one (another type,null, another letter case) makes the token invalid (401). - Main lists its agents as
[agents.<name>]tables, named by the subscriptions' rule, from the file only. A table holdstokens_sinceand nothing else yet, and may be empty. A token whoseagtnames no configured agent answers401unauthorized, as an invalid token does. - Revoking one agent:
tokens_since(name assumed), a time. A token of that agent issued before it answers401. - Rotating: issue a new token and put it on the agent host. Then set
tokens_sinceto just before the new token'siat, and restart main. The agent reads its token file at each dial, so it needs no restart. Every other token is left alone, and changingapi.secretstill revokes everything. - Main authenticates to the agent through TLS (decision 12). An agent token grants the job bytes of its printers, so it is a secret of the same weight as
api.secret's tokens: a 0600 file, never argv or a log. - Trade-off: whoever holds
api.secretcan issue agent tokens, as with every token. A revoked agent is refused only after main's restart (or a reload, once printers stage 2b has one).
- A token with
- The agent route and its refusals.
GET /api/v1/agent, an entry in the route table withAuth, so it is rate limited like the others, with its case in TestRoutesConform. The OpenAPI document gives its101answer and the subprotocol, not the messages, which this plan's MESSAGES table and docs/agent.md describe.- A request that is not a WebSocket upgrade, or offers no subprotocol main speaks, answers
426with a new code,upgrade_required, whosedetailsname the subprotocols main speaks. - A request with an
Originheader answers403token_scope. Browsers send one, agents do not, and refusing it closes cross-site WebSocket requests even if a browser held a token. - The compress middleware skips this route, and the stage checks that the
101and the hijack pass the request logger, the recoverer and the Sentry hub unchanged. - Trade-off: one new code and a route outside JSON request and answer.
- A request that is not a WebSocket upgrade, or offers no subprotocol main speaks, answers
- One link per agent. an agent has at most one link. A new link for an agent that has one replaces it: the old link closes with close code 4001 and a WARN names the agent and both client addresses. A half-open old link thus never blocks a reconnect.
- The attempts in flight on the old link are resolved on the new one (decision 17).
- Trade-off: two agents run with one token take the link from each other in turn, which the WARN lines show. Their journals differ, so one never answers for an attempt the other took (decision 13).
- Keepalives and dead links. each side sends a WebSocket ping every 20 s and drops a link that has sent nothing for 60 s: no message, ping or pong. Every write has a 30-s deadline; one that misses it drops the link.
- The agent sends
Hellowithin 10 s of the upgrade, or main closes the link. Close codes come from RFC 6455's private range: 4001 replaced (decision 8), 4002 protocol error, 4003 refused, 4004 shutting down. - fasthttp clears the connection's deadlines when it hands over an upgraded connection, so
webserver.read_timeout(15 s) andidle_timeout(60 s) no longer apply to it; the link sets its own. - 20 s stays under nginx's default 60-s read timeout for a proxied WebSocket, for a main behind an operator's nginx, and under the idle limits common in home routers' NAT.
- Trade-off: about 6 small frames a minute per agent, both ways, while idle.
- The agent sends
/healthzand the agents./healthzgainsagents, one entry per configured agent, sorted by name:name,connectedandsince, the time of the last connect or disconnect. A remote printer's entry inprintersgainsagent. No address, version or token subject appears, since the route is public. The code still follows the default printer alone (printers question 9).- Trade-off: the public route shows agent names, as it shows printer names.
For stage 3:
- The agent's config, and printer names on both sides.
- The agent reads its own file,
/etc/uberbringer/agent.toml, which holds[agent],[agent.printers.<name>],[log]and[sentry]only. Any other section is an unknown key, so a main config given to the agent fails at start with a clear message. [agent]:url(main's base URL),name,token_file,ca_file(empty: the system roots),state_dir(empty: a journal in memory, decision 13) andmax_job_bytes(decision 3). Each scalar key also readsUBERBRINGER_AGENT_<KEY>.[agent.printers.<name>]:addressandport(9100) only, from the file only, as printers question 2 has for named tables. The agent writes only to printers its own file lists, so a compromised main cannot use it to reach other hosts on the remote network.- A printer has one name, main's. The agent's tables use the names that main's printer tables use.
Hellolists the names, never the addresses. A remote printer main configures that the agent does not list reads asunreachablewith a WARN; a name the agent lists that main does not use draws a WARN and is ignored. - Timeouts stay on main (decision 16), which owns each job's time budget and sends them with each request.
- Trade-off: a container agent mounts a config, since its printers come from the file. Renaming a printer means editing both files.
- The agent reads its own file,
- TLS from the agent.
urlmust behttps://, except to a loopback host, for development. The certificate is checked against the system roots, or againstca_filealone when it is set. There is no setting that skips verification. The dialler honoursHTTPS_PROXYfrom the environment. The token goes in theAuthorizationheader, never the URL.- Trade-off: a test set-up with a self-signed main needs
ca_file.
- Trade-off: a test set-up with a self-signed main needs
- The agent's journal. an append-only file,
<state_dir>/agent-journal, one record per write, each a msgp record with its length and a CRC-32.- Before the first byte of an attempt goes to the printer, the agent appends a
writingrecord for its attempt key and syncs it. After the write it appends the outcome, without a sync. - At start, a
writingrecord with no outcome becomesunknown: the agent stopped while it wrote. One WARN line gives itsjob_idandprinter. - So "no record" means "nothing written", in the journal that saw the attempt. That is what lets main resolve an attempt whose link was lost (decision 17).
- Each journal has an ID (a TypeID, prefix
journal), made with its file, and numbers its records.openedgives main the journal's ID and the number its next record will take. Aqueryreply ofnonecounts as "nothing written" only from that journal, while its oldest kept record is at or below that number. An emptied state directory, another host, or another agent with the same token therefore never answers for an attempt it did not see. - The newest 10,000 records are kept. Retention counts records, not days, since the agent's clock may be wrong; times in the journal serve its logs only. The file is rewritten (temporary file, sync, rename, then a sync of the directory) at start and whenever it passes 1 MiB, under the one lock that every append takes.
- A bad record at the end is a torn tail and is cut. A bad record followed by good ones is damage: the file is moved aside, an ERROR is logged, and a new journal with a new ID starts, so main trusts no
noneabout the old one. - With
state_dirempty, the journal lives in memory and gets a new ID at each start. - A failed
writingappend writes nothing, answersnothingand stops the agent. A failed outcome append answers the outcome the agent holds in memory, then stops the agent; at its restart the record readsunknown. systemd restarts it either way. - Trade-off: one synced write per receipt on the agent's disk, and our own recovery code.
- Before the first byte of an attempt goes to the printer, the agent appends a
- Reconnecting. the agent dials again after 1 s, doubling to 60 s, with ±20% jitter, and starts again at 1 s after a link that lived 60 s. A
401, a403or a426waits 5 minutes, logged at ERROR once per change of answer, as the ntfy subscriber treats refused credentials. A429waits for itsRetry-After.- The agent dials a new link only after it has closed the old one and every handler of the old link has finished, a write in hand included (Architecture, A REMOTE SEND, agent rule 5). That adds up to one write timeout to a reconnect.
- Trade-off: a remote site back from an outage waits up to a minute.
- The agent's wait for the go-ahead. once the agent has opened the printer's connection and said so, it waits at most 15 s for main's go-ahead. Then it closes the connection with nothing written, and a later go-ahead for that attempt is answered "nothing written".
- The wait covers main's synced
sendingcommit and one round trip. A slow commit on an SD card is measured by job-store stage 1a. - Trade-off: the printer's connection is held for that long; the printers close idle connections after 90 s (TM-T88VII, TM-m50II) or 300 s (UB-E02, UB-E03).
- The wait covers main's synced
For stage 4:
- A remote printer in main's config.
agent = "<name>"in a printer table,[printer]included, makes it remote. The name must have an[agents.<name>]table (decision 6).- A remote printer keeps the layout keys (
model,codepage,paper_width,columns,box_line_spacing,cut_feed), the timeouts (dial_timeout,write_timeout, sent to the agent with each attempt) and the retry keys (retries,retry_delay).addressandportare refused besideagent; they belong to the agent's file. - A remote printer's
dial_timeoutis at most 30 s and itswrite_timeoutat most 60 s. The agent caps what it receives at the same values, which agentproto holds, so the agent's stop timeout can be set without main's config (decision 21). [printer]may be remote, so a main on a hosted server can serve printers that are all behind agents.printer.addressis then required only whenagentis empty.UBERBRINGER_PRINTER_AGENTsets the key;[agents.*]comes from the file only.- The address rule of printers question 3 applies to local printers only; main cannot see where a remote one is. The agent refuses two of its own printers at one address and port.
- Trade-off: a printer's keys are split across two files.
- A remote printer keeps the layout keys (
- A remote send and its outcomes. the sequence under Architecture, A REMOTE SEND. An attempt ends in one of four outcomes:
done: written in full.nothing: no byte reached the printer. The agent says so (a refused dial, a printer not ready at the anycast check, a write that took nothing, a go-ahead it never acted on), or the go-ahead never left main's writer queue. It matches printqueue'sNothingWritten, so retries and failover treat it as today's dial failure.partial: some bytes went out before a write error. It is today's write error, and job-store question 23's retry rule applies.unknown: the go-ahead was written and no outcome came back. Main never sends that delivery again. It waits forresulton the link that carried the go-ahead. If that link drops, it asks the agent's journal on the next link, within the delivery's 2-minute bound (decision 13 says whennonecounts). With no answer, the delivery endsuncertain, and one WARN line names it.- An outcome is a string. A missing, empty or unknown one reads as
unknown, nevernothing, andnoneis a value of its own, sent only in reply toquery. - Main waits for
openedup to the dial timeout plus 10 s. At main's shutdown, an attempt before itssendingmark sendsAbortand stays queued; one past its mark gets itsGoand waits forresultup to the write timeout plus 10 s, then endsuncertain. - This adds one path that writes
uncertainduring a run; job-store writes it only at start. A lost lazy write of it still readsuncertainafter a restart, so it needs no sync. - Trade-off: a receipt that printed but whose answer was lost needs a person to check the paper.
- Deliveries while an agent is offline. a lane whose printer's agent is offline takes nothing; its deliveries wait queued, in order, and are taken once the agent is back, however long that is, as job-store question 6 has waiting jobs print however old.
- Its printers are marked down while the agent is offline, and so is a printer the agent does not list, for as long as it does not (printers question 24). Anycast passes over them and moves the anycast deliveries waiting on those lanes on.
- The wait never holds an anycast delivery. A lane whose agent is offline counts an anycast delivery it would take as failed before any byte, so it moves on, even when every printer of its list is marked down.
queue.sizestill bounds each lane, soSubmitanswersqueue_fullonce a lane is full. With the memory store, the waiting deliveries are lost at main's restart, as today.- An attempt in hand when the link drops is resolved as decision 17 says; it is not counted as a retry.
- Trade-off: after a long outage the backlog prints at once, stale receipts included.
- Status through the agent. on demand. Main sends
Statuswith its deadline. The agent readsDLE EOTwith itsprinter.Client, reads a not-ready answer again after 750 ms (printers question 23's settle function), and answers with the decoded status. Main's 3-s bound for/healthzholds; a missed deadline istimeout, never a fault.- An agent that is offline, or that does not list the printer, reads
unreachable(503for the default printer). Concurrent reads of one remote printer share one request. - The request carries the model, so a TM-T88VII's
GS r 1(printers stage 4a) is read at the agent as at main. - Trade-off: each
/healthzcall costs a round trip and a printer connection at the remote site, as it costs a connection locally. Status is read one round trip later than locally.
- An agent that is offline, or that does not list the printer, reads
- The agent's answer for a delivery already
uncertain. when an agent connects, main asks its journal about each of its printers' deliveries thatLoadturneduncertainat main's start. It asks in batches of at most 128 keys, and each key once per run of main. It logs one INFO line per answer (done,nothing,partial,unknownor no record). The status staysuncertain: a client may already have sent the receipt again.- Trade-off: the answer helps a person who checks the paper, and changes nothing else.
For stage 5:
- install.sh, and Caddy.
install.sh --agentinstalls the binary, writes/etc/uberbringer/agent.tomlfrom prompts (main's URL, the agent's name, its printers), reads the token on standard input into/etc/uberbringer/agent.token(0600, never argv), and installsuberbringer-agent.service. It sets up no Caddy and opens no port. Re-runs keep the config and the token.- The unit is the daemon's, sandboxed alike, with
StateDirectory=uberbringer-agent, so an agent and a main on one host keep separate state. Its stop timeout exceeds the 60-s cap onwrite_timeoutplus 10 s (decision 16); systemd's default of 90 s does. - Main's Caddy site gains
stream_close_delay 5minreverse_proxy. Without it, a reload of Caddy closes every WebSocket at once (findings, CADDY). Caddy needs nothing else to pass the upgrade. - Trade-off: one more unit and mode in install.sh.
- Docker. the same image runs the agent with the command
agent. The agent's config and token are mounted files, and a named volume holds the journal (UBERBRINGER_AGENT_STATE_DIR). The image changes nothing.- docs/docker.md tells operators whose own proxy sits in front of main to pass WebSocket upgrades. nginx needs
UpgradeandConnectionset, and closes a proxied WebSocket quiet for 60 s, which the pings of decision 9 prevent. - Trade-off: a container agent needs a mounted config.
- docs/docker.md tells operators whose own proxy sits in front of main to pass WebSocket upgrades. nginx needs
- Windows. no Windows release, as for the daemon.
uberbringer agentbuilds and runs on Windows for development, with the journal in memory unlessstate_diris set.- Trade-off: a shop whose only machine is a Windows PC needs a small Linux board.
For stage 6, later:
- Epson's acknowledgement at the agent (job-store question 21). built only with job-store phase 5, and for remote printers at the agent, which owns the connection. The agent appends
GS ( H 48 <id>after the bytes, waits for the matching reply and answersdonewithconfirmed. A capability inHellosays it can. Its IDs are counted per printer by the agent; they never cross the link.- Trade-off: as job-store question 21: the printer's connection stays open until the receipt is out, and a missed reply is still
unknown.
- Trade-off: as job-store question 21: the printer's connection stays open until the receipt is out, and a missed reply is still
Investigation findings
Research on 2026-11-30: module versions and source from proxy.golang.org and the module cache, Caddy's and nginx's documentation, RFC 6455, and a map of the repository. Nothing ran against a printer, no config.toml was read, and nothing was built.
VERSIONS (proxy.golang.org, @latest, 2026-11-30)
| Module | Latest | Released | Note |
|---|---|---|---|
| github.com/tinylib/msgp | v1.6.5 | 2026-09-30 | in go.mod already, indirect |
| github.com/gofiber/contrib/v3/websocket | v1.3.1 | 2026-11-25 | needs Fiber v3.7.0, the version in go.mod |
| github.com/fasthttp/websocket | v1.5.12 | 2025-01-01 | what the middleware is built on |
| github.com/coder/websocket | v1.8.15 | 2026-06-15 | no requirements |
| github.com/gorilla/websocket | v1.5.3 | 2024-06-14 | |
| github.com/lxzan/gws | v1.10.2 | 2026-09-11 | not studied further |
| github.com/gofiber/fiber/v3 | v3.7.0 | 2026-11-09 | the version in go.mod |
| github.com/valyala/fasthttp | v1.81.0 | 2026-11-27 | go.mod has v1.80.0, indirect |
MSGP
- Already a dependency: go.mod:44 lists
github.com/tinylib/msgp v1.6.5 // indirect, andgo list -deps ./cmd/uberbringershowsgithub.com/tinylib/msgp/msgpandgithub.com/philhofer/fwdlinked today, through Fiber's limiter middleware. The runtime adds nothing to the binary, and its notice is already in THIRD-PARTY-LICENSES.md. - The generator is the module's root package (
main.go), sogo get -tool github.com/tinylib/msgp@v1.6.5makes itgo tool msgp. Its go.mod needsgithub.com/philhofer/fwdandgolang.org/x/tools, which go.mod's tool modules already pull in at newer versions. - Directives (parse/directives.go):
tuple,vartuple,ignore,shim,replace,compactfloats,clearomitted,newtime,timezoneandlimit arrays:n maps:n marshal:bool(line 359), which caps the lengths a generated decoder accepts. - Generated decoders skip unknown map keys: gen/decode.go:316 emits
default: err = dc.Skip(). - The runtime uses
unsafeunless built with thepuregotag. It uses no cgo, soCGO_ENABLED=0builds hold.
FIBER V3 AND ITS WEBSOCKET MIDDLEWARE
github.com/gofiber/contrib/v3/websocketv1.3.1 wraps fasthttp/websocket's upgrader. ItsConfig(websocket.go:25-79) hasHandshakeTimeout,Subprotocols,Origins,AllowEmptyOrigin(default false: a request withoutOriginis refused unlessOriginsholds*), buffer sizes,EnableCompressionandRecoverHandler. The handler gets a*Connwith the route's params, query, headers and locals copied (lines 183-184, 328-345).- It sets fasthttp's
KeepHijackedConnson the server (lines 110-118), so fasthttp leaves an upgraded connection open after the handler returns, and the handler owns it. - fasthttp clears every deadline when it hands over an upgraded connection:
c.SetDeadline(zeroTime)beforehijackConnHandler(fasthttp v1.80.0, server.go:3086). Fiber's read, write and idle timeouts do not apply after the upgrade. - fasthttp's
Shutdownwaits for connections to go idle and does not close keep-alive ones (server.go:2190-2214); upgraded connections are the handler's to close. Main closes the links itself at shutdown. - Fiber has no WebSocket client. fasthttp/websocket's
Dialer(client.go) dials withnet/httptypes: request headers,Proxy,NetDialTLSContext.Conn.SetReadLimit(conn.go:1191) caps a whole message, all fragments, and returnsErrReadLimit;WriteControl(line 442) may run beside the one writer.
CADDY (https://caddyserver.com/docs/caddyfile/directives/reverse_proxy, § Streaming and § transport http)
reverse_proxyproxies WebSocket upgrades with no extra settings and then tunnels both ways. HTTP/2 extended CONNECT (RFC 8441) is not mentioned.- By default a config reload closes every WebSocket, sending a close message to both ends.
stream_close_delaykeeps them open for up to its duration after a reload (no default; the page suggests5m).stream_timeoutcloses streams after a set time (no default). - No idle or read timeout closes a quiet WebSocket by default:
transport http'sread_timeouthas none.keepalive(2 m) concerns pooled idle connections, not tunnels. request_body max_size(https://caddyserver.com/docs/caddyfile/directives/request_body) is described for request bodies only; nothing says it reaches an upgraded connection. install.sh sets it towebserver.body_limit(install.sh:384-387). If it did reach the link, it would count what the agent sends to main over the link's whole life, and cut the link after 4 MiB of pongs and replies. This plan assumes it does not; stage 2 checks it through Caddy.header_upapplies to every request sent upstream; the upgrade is one, soX-Real-IP(install.sh:393) reaches main and the rate limit and logs see the agent's address.
NGINX AND RFC 6455
- nginx (https://nginx.org/en/docs/http/websocket.html):
UpgradeandConnectionare hop-by-hop and must be set withproxy_set_header; before 1.29.7 alsoproxy_http_version 1.1. A proxied WebSocket closes if the upstream sends nothing for 60 s, unlessproxy_read_timeoutis raised or pings reset it. - RFC 6455 (https://www.rfc-editor.org/rfc/rfc6455): control frames carry at most 125 bytes and are never fragmented (§5.5), and may come between the fragments of a message (§5.4). A ping is answered with a pong; an unsolicited pong is a one-way heartbeat (§5.5.2, §5.5.3). The server picks one of the client's subprotocols or none (§4.2.2), and the client fails the connection if the server names one it did not offer (§4.1). Close codes 4000-4999 are for private use (§7.4.2).
THE REPOSITORY TODAY
printer.Client.Send(ctx, data)(internal/pkg/printer/printer.go:60) dials, sets a write deadline and writes, and discards the countWritereturns.Status(line 82) sendsDLE EOT 1-4over the same connection slot (connect, lines 118-141). job-store stage 1c addsbeforeWrite; printers stage 3 adds the count (SendError,NothingWritten) and the status check on an open connection.printqueue.Sender(internal/pkg/printqueue/queue.go:90) andserver.Printer(internal/app/uberbringer/server/server.go:36) are the interfaces a printer implements; printers.md's seam keeps them.- Tokens:
TokenClaims(server/auth.go:19-28) hasmodandraw;scopeClaims(line 31) lists them, so a malformed one makes the token invalid.requireBearerToken(line 86) accepts HS256 only.uberbringer tokensetssubandiat(internal/app/uberbringer/cli.go:242-243), and--ttlan expiry. - Routes: each is a
Routein the table (server/routes.go:26-49);Authroutes are rate limited per client and answerCache-Control: no-store. The compress middleware runs for every route (server/server.go:175), and the limiter after it (line 179). - Error codes (server/errors.go:26-46):
unauthorized(401) andtoken_scope(403) exist; nothing answers426today. - Webserver defaults: read and write timeouts 15 s, idle 60 s, body limit 4 MiB (internal/pkg/config/config.go:360-371).
- serve.go runs the queue, the server and the subscribers in one errgroup (internal/app/uberbringer/serve.go:136-141).
- The unit (packaging/uberbringer.service) has
StateDirectory=uberbringer(line 36) andRestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX(line 58), which an agent's outbound HTTPS and printer connections fit. - Release archives are built for linux amd64, armv6, armv7 and arm64 only (.goreleaser.yaml:25-33). The Dockerfile's image runs the binary as its entrypoint (Dockerfile:42), so
agentis a command for the same image. - The config has the sections
webserver,api,printer,format,ntfy,queue,images,sentryandlog(config.go:49-59);api.secretandprinter.addressare required at load.
WHERE THE REPORTS DISAGREE OR ARE UNSURE
- Whether Caddy's
request_body max_sizereaches an upgraded connection: not stated, and assumed not; stage 2 checks it. - Whether a printer behind a UB-E02 or UB-E03 takes the connection and holds the bytes while it is offline: printers question 23's paper check. It decides the anycast check at the agent too.
- The time of a synced append on an SD card, which bounds decision 15's wait at the agent and main's own mark: job-store stage 1a measures main's; the agent's journal is not measured.
- The round trip to a remote site and its effect on
/healthz's 3-s bound: not measured. - fasthttp/websocket's long gap since its last release: no advisory was found, and none was searched for beyond the module proxy. Stage 2 runs govulncheck.
- The binary's growth from the middleware and fasthttp/websocket: not measured. fasthttp is linked already; stage 2 records the size from the snapshot build.
SOURCES
- proxy.golang.org:
@latest,.modfiles and module sources for the modules in VERSIONS. - Module cache: tinylib/msgp v1.6.5 (
parse/directives.go,gen/decode.go,msgp/purego.go,README.md); gofiber/contrib/v3/websocket v1.3.1 (websocket.go,go.mod); fasthttp/websocket v1.5.12 (client.go,conn.go); valyala/fasthttp v1.80.0 (server.go). - Caddy: https://caddyserver.com/docs/caddyfile/directives/reverse_proxy, https://caddyserver.com/docs/caddyfile/directives/request_body.
- nginx: https://nginx.org/en/docs/http/websocket.html.
- RFC 6455: https://www.rfc-editor.org/rfc/rfc6455.
- Epson: as job-store.md's SOURCES for
GS ( Hand printers.md's for the printers' idle time-outs.
Overview
WHAT SHIPS WHEN
- Stage 1: the wire protocol,
internal/pkg/agentproto, generated withgo tool msgp. A library with its tests; nothing calls it yet. - Stage 2: main's end of the link:
[agents.<name>], agent tokens,GET /api/v1/agent, keepalives and/healthz'sagents. An agent can connect; nothing prints through it. - Stage 3:
uberbringer agent: its config, journal, reconnects, and the printer side of a send and of a status read, tested against stage 2's end in-process. - Stage 4: remote printers in main: the
agentkey, the remote sender behind the seam, outcomes and their resolution, lanes that wait while an agent is offline, and status through the agent. Receipts print through an agent. - Stage 5:
install.sh --agent, the agent's unit, Caddy'sstream_close_delay, and the Docker and agent docs. - Stage 6, later: Epson's acknowledgement at the agent, with job-store phase 5.
COMPATIBILITY
- A config without
[agents]andagentkeys runs and prints as today. The agent route exists and refuses every token, since no agent is configured. - Tokens: an older token has no
agtand keeps every route it had. An agent token is refused on every other route. - New: the route, the code
upgrade_required,/healthz'sagentsand a remote printer'sagent. Job status can readuncertainduring a run, for a remote delivery only (decision 17); its enum already has it from job-store stage 1c. - What prints does not change: a remote printer gets the bytes a local one with the same table would. TestRenderCompat and TestPaperReceipts keep passing.
- Main and agent of different releases work together while they share a protocol version (decision 2); each logs the other's version at connect.
- A downgrade: an older binary refuses
[agents]andagentas unknown keys, and has noagentcommand.
INVARIANTS
- Nothing reaches a remote printer unless main rendered the whole receipt for it and the agent holds every byte of it, checked by length and SHA-256.
- No byte of a job reaches a remote printer before main's
sendingmark for that attempt is committed (synced when the store is durable), and after it the agent'swritingrecord is synced. - The agent writes an attempt at most once. It writes only on a go-ahead for an attempt key it has no record of; a go-ahead for a key it has a record of is answered from the record.
- Main sends a remote delivery again only after an outcome of
nothingorpartial. Anunknownoutcome is never sent again; it endsuncertain. job-store's invariant 3 therefore gains no new path. - The agent writes only to printers its own config lists. Main never names an address.
- The link authenticates both ends: TLS authenticates main, and the agent's token the agent. Only an agent token opens the link, and it opens nothing else.
- Print bytes, tokens and
api.secretnever reach logs or Sentry, at either end. Remote printers' addresses never leave the agent. - Main and an agent never both drive one printer (printers.md's seam).
- Main has at most one attempt in flight per remote printer, through a slot it frees once the attempt's outcome is known or its link has ended. The agent holds at most one job's bytes per printer.
- job-store's and printers' invariants hold for each remote delivery.
Architecture
THE PICTURE
main lane "shop-front" ─▶ render in full ─▶ remote printer ─▶ link "shop" ◀══ Caddy ◀══ wss, dialled by the agent
agent link ─▶ bytes held for "shop-front" ─▶ printer.Client ─TCP 9100─▶ printer
THE CONFIG ON BOTH SIDES (decisions 6, 11 and 16)
Main's config:
[agents.shop] # may be empty
# tokens_since = 2026-12-01T10:00:00Z
[printers.shop-front] # a TM-m50II at the shop
agent = "shop"
model = "tm-m50ii"
The agent's agent.toml:
[agent]
url = "https://print.example.com"
name = "shop"
token_file = "/etc/uberbringer/agent.token"
state_dir = "/var/lib/uberbringer-agent"
[agent.printers.shop-front]
address = "192.0.2.50"
- Names and addresses here are examples.
- The token is issued on main:
uberbringer token --agent shop, then written to the agent host's token file through standard input. [agents.<name>]and[agent.printers.<name>]use printers stage 1a's key kind for a table of named tables, and the subscriptions' name rule.
THE LINK (stages 2 and 3)
- The agent dials
wss://<host>/api/v1/agentwith its token and offersuberbringer-agent.1. - Main checks the token (
agt,tokens_since), the subprotocol and the absence ofOrigin, then upgrades. - The agent sends
Hellowithin 10 s, or main closes the link. Itsnamemust match the token'sagt. - Main answers
Welcome, naming the printers it routes to this agent, or closes with a close code and reason (4002 protocol, 4003 refused). - A link with the same agent's name replaces the old one (decision 8). Pings run both ways (decision 9).
- Each end has one reader and one writer goroutine. Main's writer drains two queues: control first (
Welcome,Open,Go,Abort,Status,Query), thenData. A large transfer therefore holds back a status request or a go-ahead by oneDataframe at most. Pings go throughWriteControl, beside the writer. - Main's reader hands each reply to the waiter registered for its attempt key or request number, through a channel with room for one, and never blocks. A reply nobody waits for is logged at DEBUG and dropped, except a late
result, which resolves an attempt still in doubt. - The agent's reader never blocks either. It passes each message about a printer (
data,open,go,abort, andqueryfor that printer's keys) to that printer's goroutine, in the order they arrived. The queue holds one job'sDataand a few control messages; an overflow is a protocol error.statusgoes to a goroutine of its own, so a status read never waits behind the wait for a go-ahead. - At main's shutdown, the links close only after the queue has finished its lanes (Architecture, SHUTDOWN AND RESTARTS), with close code 4004.
MESSAGES (stage 1; decision 2)
| Type | From | Body |
|---|---|---|
hello |
agent | protocol, version, run (a TypeID, prefix agentrun), name, printers (names), journal (its ID), oldest (the number of the oldest record kept), max_job_bytes, capabilities |
welcome |
main | protocol, version, the printers main routes to this agent |
data |
main | attempt key, printer, offset, final, bytes (at most 64 KiB) |
open |
main | attempt key, printer, length, SHA-256, check (anycast), dial and write timeouts |
opened |
agent | attempt key, journal ID, the number the next record will take |
go |
main | attempt key |
abort |
main | attempt key |
result |
agent | attempt key, outcome (done, nothing, partial, unknown), bytes written, error class and text |
status |
main | request number, printer, model, deadline |
status_reply |
agent | request number, the decoded status, or an error class (timeout, unsupported, unreachable, not_listed) |
query |
main | attempt keys |
query_reply |
agent | journal ID, oldest; per key: an outcome, or none for no record |
- An attempt key is the job's ID, main's printer name and the attempt number:
job_…/shop-front/3. Main's store already holds all three, so it can ask after its own restart (decision 20). Each delivery's attempt numbers are unique, and attempt numbers go on across the printers of an anycast list (printers question 22). - The agent sends an error's class and a text without the printer's address; its own log keeps the whole error. No message carries an address.
Dataarrives in order on one stream. Offset 0 starts a new buffer for its printer, dropping an unfinished one. Any other offset that does not follow, or bytes pastmax_job_bytes, is a protocol error.- Outcomes are strings. A missing, empty or unknown outcome reads as
unknown;noneis explicit and appears only inquery_reply.
A REMOTE SEND, STEP BY STEP (stage 4; decisions 15 and 17)
Main's lane worker calls the remote printer's Send(ctx, data, beforeWrite) (or the checked send, for anycast). The remote printer:
- Takes its own slot, waiting on the caller's context. It frees the slot once the attempt's outcome is known or its link has ended, so an attempt given up on still holds the printer until the agent has answered.
- Fails at once with "agent offline" if the agent has no link or does not list the printer:
nothing, as a dial failure is. - Checks the length against the agent's
max_job_bytes(decision 3). - Sends the bytes as
Data, unless it sent the same bytes for this printer on this link already (the agent keeps the last job's bytes per printer until newDatareplaces them or the link closes). - Sends
Open. The agent checks length and hash, takes its printer's connection slot, dials, reads status ifcheckis set, and answersopenedwith its journal's ID and next record number, orresultnothingwith its class. Main waits at most the dial timeout plus 10 s. - Calls
beforeWrite: main's syncedsendingmark. If it fails, main sendsAbort, and the attempt isnothing. - Sends
Go. The agent appends itswritingrecord and syncs it, writes, appends the outcome and answersresult. Main waits forresulton this link and never sendsqueryon it. - Returns by the outcome:
donesucceeds;nothingreturns an error that matchesNothingWritten;partialreturns a write error;unknownreturns an error that ends the deliveryuncertain(decision 17).
If the caller's context ends while this attempt's Data or Go still waits in the writer's queue, main takes them out under the writer's lock. A Go the writer has already taken counts as written.
Where the link drops:
| Last step main completed | Outcome | Why |
|---|---|---|
1-6, or a Go still in the writer's queue |
nothing |
the agent never received the Go |
Go taken by the writer, link dropped before result |
resolved by query on the next link, within the delivery's bound |
the agent's journal says what happened |
the same, and the agent answers none |
nothing, only when the reply's journal ID is the one opened gave and its oldest is at or below the number opened gave |
that journal holds a record of every write it allowed |
the same, from another journal (an emptied state directory, another host, another agent with the same token), a journal that no longer covers the number, an unknown answer, or no link before the bound |
unknown |
the delivery ends uncertain |
The agent's rules:
- It writes only after a
Gofor a key whoseOpenit acted on in this link, and only within decision 15's wait. - It appends and syncs
writingbefore the first byte. Only a failedwritingappend answersnothing. A failed outcome append answers the outcome the agent holds (decision 13). - A
GoorOpenfor a key it has a record of is answered from the record and never written. - One goroutine per printer handles that printer's messages in the order they arrived, and holds its buffer, its open connection and its records. A
queryabout a key is answered by that key's printer's goroutine, after every message that came before it. - When a link ends, the agent marks it stale under each printer's lock. A handler of that link that has not appended its record refuses, writing nothing; a connection waiting for its go-ahead closes. A write already under way finishes and appends its outcome. The agent dials a new link only once all of these have finished, so a
queryon the new link finds every record settled, and an answer ofnoneis final.
Main's rules:
- A
Gostill in the writer's queue was never sent, and a dropped link then meansnothing. Once the writer has taken it, it counts as sent, and its outcome comes fromresultor the agent's journal. - An attempt in doubt keeps its waiter across links until it is resolved or its delivery's bound ends. It is asked about only on a later link.
- A delivery with an attempt in doubt is never sent again, never moved by anycast and never cancelled (its
sendingmark stands, as job-store phase 2b requires). - Retries after
nothingare new attempts with new keys; the agent may still hold their bytes (step 4).
THE AGENT'S JOURNAL (stage 3; decision 13)
- The journal's ID is made with its file; records are numbered from 1 in it.
- Records:
writing(number, key, printer, time) and the outcome (number, key, outcome, bytes written, time), each msgp with its length and a CRC-32. Times serve the agent's logs only. - One lock covers every append and every rewrite.
- At start: read the file. Cut a bad record at the end; move a file with a bad record before good ones aside and start a new journal (decision 13). Turn each
writingwithout an outcome intounknown, logged at WARN. Keep the newest 10,000 records; write them to a temporary file, sync, rename and sync the directory. - While running: the same rewrite whenever the file passes 1 MiB, the directory synced before the next append.
- In memory: a map from key to record, for
queryand for rule 3. - One synced append per receipt; the outcome is appended unsynced. A lost outcome reads as
unknownafter a crash, never asnone.
STATUS (stage 4; decision 19)
- Main's remote printer implements
server.Printer.Statusthroughstatusandstatus_reply, within the caller's deadline, and concurrent callers share one request. - The agent runs
printer.Client.Statusand printers stage 3's settle function, with the profile's status capabilities for the model the request names. /healthzshows a remote printer's entry like a local one's, plusagent, and theagentsarray (decision 10).
OFFLINE AGENTS (stage 4; decision 18)
- A lane whose printer is remote waits, before it takes a delivery, until its agent is connected and lists that printer. printqueue gains an optional interface on a
Senderfor that wait (Gate, name assumed); a local printer does not implement it, and its lane behaves as today. - The wait holds unicast and multicast deliveries only. An anycast delivery at a closed gate counts as failed before any byte and moves on (decision 18).
- On a link's loss, main marks the agent's printers down for as long as it is offline, and a printer the agent does not list for as long as it does not (printers question 24). That moves anycast deliveries on.
- Deliveries keep their order. A delivery's 2-minute bound starts when it is taken, so waiting for an agent does not use it up.
SHUTDOWN AND RESTARTS
- Main, durable store: waiting deliveries stay queued, as job-store says. An attempt that has not reached its
sendingmark sendsAbortand stays queued. One past its mark finishes, as job-store has for a write in hand: main sendsGoif it has not, and waits forresultup to the write timeout plus 10 s; with none, the delivery endsuncertain. Then the links close. - Main, memory store: as today; the attempt in hand finishes the same way.
- Main's restart:
Loadturns remote deliveries insendinguncertain; when each agent connects, main queries them and logs the answers (decision 20). The agent keeps an unansweredresultin its journal. - The agent, at SIGTERM: closes connections still waiting for a go-ahead, with nothing written; finishes a write in hand within its write timeout; sends its
result; closes the link with code 4004. - The agent's restart: records left
writingbecomeunknown. Main's attempts in doubt resolve throughqueryas the table above says.
LOCKS AND DEADLOCKS
- Main: the lane's worker blocks in
Sendon a channel the link's reader fills; the reader never waits on a lane, the queue or the store. The order inside main stays job-store's: the delivery lock, then the store. The agent's printer slot is not a lock in main, so no cycle crosses the link. - The agent: a status read waits on the printer's slot while a send holds it and fails with
timeoutat main's deadline, as a local read does today. The wait forGois bounded (decision 15), so a lost main never holds a printer. - Each end's writer has a bounded queue. A full queue waits on the caller's context, and a write that misses its 30-s deadline drops the link, so a stalled peer cannot block the other end for ever.
- The tests for stage 4 include a large transfer beside a status request (the status answers in time) and a peer that stops reading (the link drops within the deadline).
PACKAGES
internal/pkg/agentproto(new): the message types, their generated code, the envelope, the subprotocol names and the limits. Imports msgp only.internal/pkg/agentlink(new): main's end: the link manager, the links and the remote printer that implementsprintqueue.Senderandserver.Printer. Imports agentproto and escpos. It reads and writes through a small interface that both fasthttp/websocket'sConnand the middleware's*Connsatisfy, so tests can pair two ends in memory.internal/pkg/agent(new): the agent: its dialler, journal and printers. Imports agentproto, printer, escpos and fasthttp/websocket.- server: the route, its middleware and the scope check; it hands an upgraded connection to an interface in
Deps, so it does not import agentlink. - internal/app:
[agents], the constructor per printer that choosesprinter.Clientor the remote printer (printers.md's seam), and theagentcommand. - Imports: agentlink → agentproto, escpos; agent → agentproto, printer, escpos; internal/app → agentlink, agent. printqueue and printer import none of them.
LOGGING AND PRIVACY
- Main logs each connect and disconnect at INFO with the agent's name, client address, release version and
run; a replaced link at WARN (decision 8); a refused upgrade as any refusal, by its request line. - Every worker line of a remote attempt carries
printer,agentand the attempt number, never bytes. - The agent logs its link, each attempt's outcome by
job_id,printerand attempt number, and its printers' addresses at start, as main's start-up line does. - Sentry: each end reports its own unexpected errors once, tagged with the agent's name and printer, never content. A dropped link is not a fault and is not reported.
CONFIG, PACKAGING, DOCKER
- Main:
[agents.<name>](stage 2) and a printer'sagentkey (stage 4), each with its default, validation,configs/config.example.tomlentry and docs/configuration.md entry. - The agent:
configs/agent.example.tomland docs/agent.md (stage 3), a new page that the release archives carry, README's Documentation table lists and CLAUDE.md's "Read first" names. - install.sh
--agent,packaging/uberbringer-agent.service, Caddy'sstream_close_delayand docs/docker.md: stage 5.
Phases
Stage 1: The wire protocol
Goal. internal/pkg/agentproto defines the messages of the link and their encoding, generated by go tool msgp. A library with its tests; nothing calls it yet. Needs nothing from the other plans. Decisions 1-3.
Work.
- go.mod:
go get -tool github.com/tinylib/msgp@<latest stable>(v1.6.5 at the time of writing). The runtime becomes a direct requirement when this stage's code imports it. govulncheck after the change. - agentproto:
- messages.go: the types of the MESSAGES table,
msgtags with short names,//go:generate go tool msgp -tests=falseand//msgp:limit arrays:1024 maps:64. - messages_gen.go: generated, never edited.
- envelope.go:
Encode(msg)andDecode(b), the type names, the subprotocol names (uberbringer-agent.1), the chunk size, the read limits and the caps on dial and write timeouts (30 s and 60 s).Decoderefuses an unknown type with a protocol error.
- messages.go: the types of the MESSAGES table,
- The gate: CLAUDE.md's generated-files line and
.gitea/workflows/test.ymladdinternal/pkg/agentproto/messages_gen.goto thegit diff --exit-codecheck. CLAUDE.md's "Read first" says the file is generated and never edited by hand. - If gofmt or goimports flag the generated file, the
go:generateline pipes it through them, so the gate passes unchanged.
Docs
- docs/development.md: the package and the generator.
- No CHANGELOG entry: nothing a user sees.
Tests.
- Each message round-trips.
- A body with a field this version does not know decodes, and the field is skipped; a body missing a field decodes it as zero.
- An empty or unknown outcome decodes as
unknown. - An array or map over its limit is refused; so is an unknown type.
- FuzzDecode: no panic, and no allocation beyond the read limit.
Commits.
- Pin the msgp generator as a tool
- Add the agent link's message types
Done when. The full gate passes, go generate ./... leaves the tree unchanged, and govulncheck is clean.
Stage 2: Main's end of the link
Goal. Agents configured on main can connect with their tokens and stay connected. /healthz shows them. No printer is remote yet. Needs stage 1 and printers stage 1a. Decisions 4-10.
Work.
internal/pkg/config
Agents map[string]AgentConfig(agents) withTokensSince, through printers stage 1a's key kind; names by the subscriptions' rule; from the file only.
internal/app/uberbringer/server
- auth.go:
Agent string(agt) inTokenClaims, inscopeClaims; agent tokens refused on every route but the agent route (403token_scope);tokens_sinceand the configured names checked for agent tokens (401). - routes.go:
GET /api/v1/agentwithAuth, its101and refusals;upgrade_requiredin errors.go. - The handler: the middleware with
AllowEmptyOrigin, the subprotocols from agentproto, a refusal forOrigin; it hands the connection toDeps.Agents(an interface). - server.go: the compress middleware skips the route.
- handlers.go:
/healthz'sagents.
internal/pkg/agentlink
- The link manager: one link per agent, the newest winning (decision 8);
Hellowithin 10 s andWelcome; the reader and the two-queue writer; pings and the 60-s silence rule; close codes;Closefor shutdown.
internal/app/uberbringer
- cli.go:
token --agent <name>, refusing--modulesand--rawbeside it and a name not in[agents]; its subject defaults toagent:<name>. - serve.go: the manager in the errgroup; the links close after the queue has stopped.
Dependencies
github.com/gofiber/contrib/v3/websocketat its latest stable release, which bringsgithub.com/fasthttp/websocket, in the commit that first uses them.go generate ./...regenerates THIRD-PARTY-LICENSES.md andlicenses_embed.mdin that commit, and govulncheck runs.
Docs
- docs/api.md: the route,
upgrade_requiredin the codes table,token_scopefor agent tokens,/healthz'sagents. docs/swagger.json regenerated. - docs/security.md: agent tokens, rotation with
tokens_since, what an agent token grants. - docs/cli.md:
token --agent. - docs/configuration.md: § agents.
- configs/config.example.toml: a commented
[agents.<name>]. - design.md: "Tokens carry their scope" gains
agt. - docs/development.md and CLAUDE.md's Layout:
agentlink, and the import line agentlink → agentproto, escpos. - CHANGELOG: under Added, the agent route and agent tokens.
Tests.
- server: TestRoutesConform's case; an agent token on
/api/v1/printanswers403; a print token on the agent route answers403; a malformedagtanswers401; a token issued beforetokens_since, or naming an unconfigured agent, answers401; a plain GET answers426upgrade_required; anOriginheader answers403; the compress middleware leaves the upgrade alone; the schema test holdsagents' fields. - agentlink, on
testing/synctestwith an in-memory pair:Helloin time givesWelcome; none within 10 s closes the link; a name that differs from the token's closes it;- a second link for one agent replaces the first, with code 4001 and one WARN;
- a peer silent for 60 s is dropped; pings keep an idle link up for a simulated day without a leaked goroutine;
- a peer that stops reading drops the link within the 30-s write deadline;
- a message over the read limit, or one that fails to decode, closes the link.
- internal/app: a real upgrade over a socket, with fasthttp/websocket's
Dialerand a real token;token --agentrefusals.
Commits.
- Add agent tokens, scoped to the agent route
- Add the agent route and its link
- Show connected agents in /healthz
Commit 1 also adds [agents.<name>] and tokens_since, with their example and docs.
Done when.
- The full gate passes, the generated files included; govulncheck is clean. The snapshot build, which builds every target with
CGO_ENABLED=0, passes, and its size is recorded in the commit that adds the dependencies. - Through Caddy on a test host, without a printer: a test agent (stage 2's test dialler) connects over
wss, and a link quiet for 10 minutes stays up. A Caddy reload withstream_close_delaykeeps it; without it, it drops and reconnects. Unsolicited pongs totalling more thanwebserver.body_limitcross from the test agent to main and the link stays up; if it drops, the finding is corrected before stage 5.
Stage 3: The agent
Goal. uberbringer agent reads agent.toml, connects to main, and handles data, open, go, abort, status and query for its printers, keeping its journal. Tested against stage 2's end in-process; main sends it nothing outside tests until stage 4. Needs stage 2 and job-store stage 1c. If printers stage 3 has not shipped, this stage brings forward its SendError with NothingWritten and its move of the settle function into printer, each in a commit of its own. Decisions 11-15.
Work.
internal/pkg/config
LoadAgent:[agent],[agent.printers.<name>],[log]and[sentry]; defaults and checks (anhttpsURL or a loopback one; a token file that exists; at least one printer;max_job_bytesfrom 1 MiB to 256 MiB); variables for the scalar keys.
internal/pkg/agent
- run.go: the dial loop and backoff (decision 14),
Hello, the reader and writer, pings, close codes, shutdown. - printers.go: per printer a
printer.Client, the job buffer, the lock, and the send:Sendwith abeforeWritethat answersopened, waits forgo(decision 15), appends and syncswriting. The checked send whencheckis set. - journal.go: the journal and its recovery (decision 13).
- status.go:
statusthroughprinter.Client.Statusand the settle function.
internal/app/uberbringer
- cli.go and agent.go: the
agentcommand, its--config, logging and Sentry, and--check(name assumed), which loads and checksagent.tomland exits, so that install.sh can check a config before it restarts the unit.
Docs
- docs/agent.md (new): what the agent is, its token, its journal and what it logs. It is the reference for every key of
agent.tomland its variables, as docs/configuration.md is forconfig.toml, which links to it. .goreleaser.yaml's archives, README's Documentation table and CLAUDE.md's "Read first" name it. - docs/development.md and CLAUDE.md's Layout:
agent, and the import line agent → agentproto, printer, escpos. - configs/agent.example.toml (new).
- docs/cli.md:
agent. - CHANGELOG: under Added,
uberbringer agent.
Tests.
- config: the agent's file loads; a main config given to the agent is refused by its unknown sections;
http://to a host that is not loopback is refused. - agent, against stage 2's end in memory and a fake printer listener:
data,open,goprint the bytes once and answerdone;- a refused dial, a printer not ready at the check, a length or hash mismatch, and a
goafter the 15-s wait each answernothing, and the printer gets no byte; - a write cut short after some bytes answers
partialwith the count; - a second
gofor a key answers from the record and writes nothing; so does anopenfor a key with a record; - a
goread from a link marked stale writes nothing; the agent dials again only after a write in hand has finished; aqueryon the next link then answers from a settled record ornone; - the journal: a
writingrecord without an outcome becomesunknownat start; a torn tail is cut; a bad record before good ones starts a new journal with a new ID; only the newest 10,000 records stay; a failedwritingappend writes nothing and stops the agent; a failed outcome append answers the real outcome; an append from one printer during another's rewrite is kept; - a
querysent right after agofor the same key is answered after the write; dataat offset 0 replaces an unfinished buffer; a status read is answered while another printer's goroutine waits for a go-ahead;- a memory journal says so in
Hello; - backoff and the 5-minute wait after
401, on synctest; - SIGTERM closes waiting connections with nothing written and finishes a write in hand.
- TLS:
ca_filetrusts a test CA; an unknown certificate is refused.
Commits.
- Report how much of a job a send wrote
- Move the settled status read into the printer package
- Load the agent's config
- Add the agent's journal
- Connect the agent to main
- Print on an agent's printers
- Answer status requests at the agent
Commits 1 and 2 only if printers stage 3 has not shipped.
Done when. The full gate passes. No paper yet: main routes nothing to an agent until stage 4.
Stage 4: Remote printers
Goal. A printer table with agent prints through that agent. Sends follow A REMOTE SEND; lanes wait while their agent is offline; status comes through the agent. Needs stage 3, printers stages 1a and 1b, and job-store stage 1c. The anycast check needs printers stage 3. Decisions 16-20.
Work.
internal/pkg/config
agentinPrinterConfig,[printer]included;addressandportrefused beside it; the name must be in[agents];printer.addressrequired only withoutagent; a remote printer'sdial_timeoutat most 30 s andwrite_timeoutat most 60 s.
internal/pkg/agentlink
- remote.go: the remote printer:
SendwithbeforeWrite, the checked send, the outcomes and their errors (NothingWritten; one that ends the deliveryuncertain), the waiters in doubt across links,query;Statuswith one shared request; the offline wait.
internal/pkg/printqueue
- The optional wait before a lane takes a delivery (
Gate, name assumed). - A send error that says
uncertainfinishes the deliveryuncertain, with its WARN line.
internal/app/uberbringer
- serve.go: the constructor per printer chooses
printer.Clientor the remote printer; links lost and regained mark printers down and up; at each connect, the query of deliveriesLoadturneduncertain(decision 20). - server:
/healthz'sagenton remote printers.
Docs
- docs/configuration.md § printers:
agent, the keys a remote printer keeps and refuses. - docs/api.md:
uncertainduring a run for remote deliveries;/healthzfor remote printers. docs/swagger.json regenerated. - configs/config.example.toml: a commented remote printer.
- docs/agent.md: the send in plain words, what
uncertainmeans there, offline agents. - design.md: a decision "Remote printers are reached through an agent", with this plan's decisions; "Render, then send" for remote printers.
- CLAUDE.md: "Testing on the printer": how to print through an agent.
- CHANGELOG: under Added, remote printers.
Tests.
- agentlink, with a fake agent that stops at any step:
- a link lost before
Gogivesnothing, and the retry prints once; - a link lost after
Go: adoneanswer finishes the deliverydone;nothingretries;partialfollows today's retry rule;nonefrom the journalopenednamed, covering its number, retries;nonefrom another journal ID, from a journal whoseoldesthas passed the number, or no link before the bound, endsuncertainand never sends again; - main never sends
queryon the link that carried theGo; - a context that ends while
DataorGowaits in the writer's queue takes them out, and nothing is written; the next attempt waits for the slot until the agent has answered; - a query for 1,000 keys goes in batches that fit the read limit;
- a late
resultresolves an attempt in doubt; - a delivery in doubt is neither moved by anycast nor cancelled;
- over
max_job_bytes: failed, nothing sent; - status: a reply in time, a missed deadline (
timeout), an offline agent (unreachable), two callers sharing one request; a large transfer does not delay a status reply past its deadline.
- a link lost before
- printqueue: a lane whose gate is closed takes nothing and keeps order, and moves an anycast delivery on at once, also when every printer of its list is marked down; it takes again once open; a full lane answers
queue_full; shutdown with a delivery waiting at the gate keeps it queued (durable) or fails it (memory). - internal/app: two fake agents and a local fake printer; an anycast rule passes over an offline agent; main's restart with an
uncertainremote delivery logs the agent's answer and keeps the status.
Commits.
- Add the remote printer to agentlink
- Wait for an agent before a lane takes a delivery
- End a delivery uncertain when a send's outcome is unknown
- Print through an agent
- Read a remote printer's status through its agent
Commit 1 is library code with its tests; commit 4 adds the agent key and the wiring that makes it reachable.
Done when.
- The full gate passes.
- Paper, with the owner's OK, one short receipt at a time, waiting for his report after each. Main and an agent both run on the workstation; the agent's file lists the TM-T88IV at 192.168.1.245, and main's
[printer]hasagentset, so main never dials the printer itself:- The pinned note receipt,
internal/pkg/receipt/testdata/paper/note.json, through the agent. Look at the line breaks, the characters and the cut: as when main prints directly. - Stop the agent, send the same receipt, see it
queuedand/healthzshow the agent disconnected, then start the agent. The receipt prints once.
- The pinned note receipt,
- TestPaperReceipts already pins the note's bytes, and printing through an agent does not change them, so no new pin is needed.
Stage 5: Packaging
Goal. install.sh --agent sets up an agent; main's Caddy site keeps links through a reload; docs/docker.md covers the agent and proxies in front of main. Needs stage 4. Decisions 21-23.
Work.
- install.sh:
--agent: the binary,agent.tomlfrom prompts, the token from standard input into a 0600 file, the unit; re-runs keep the config and the token; no Caddy. Main's site gainsstream_close_delay 5m. - packaging/uberbringer-agent.service: the daemon's sandbox,
ExecStart=… agent --config /etc/uberbringer/agent.toml,StateDirectory=uberbringer-agent. - .goreleaser.yaml: the archives carry the agent's unit and example config.
- docs/install.md: § the agent; docs/docker.md: the agent container and proxies in front of main; docs/agent.md: links to both.
- CHANGELOG: under Added,
install.sh --agent; under Changed, the Caddy site keeps WebSockets open through a reload.
Tests.
- The snapshot build; the archive lists the new files.
- install.sh's agent mode run on a scratch host or container by the owner, if he wants; the script's shellcheck, if the repository runs it.
Commits.
- Keep agent links open through a Caddy reload
- Install an agent with install.sh --agent
Done when. The full gate and the snapshot build pass; docs/install.md's steps were followed once on a test host.
Stage 6: Epson's acknowledgement at the agent (later)
Built only on the owner's word, with job-store phase 5. The agent appends the process-ID request after the bytes, waits for the reply, and answers done with confirmed; Hello lists the capability. Decision 24.