From 10b6c57afb8786868247143a6ce25679dd9b8c7d Mon Sep 17 00:00:00 2001 From: William Gill Date: Mon, 30 Nov 2026 23:48:55 -0600 Subject: [PATCH] Record the owner's acceptance of the remote-printers plan The owner accepted every proposed default of docs/plans/remote-printers.md on 2026-11-30. Its open questions become numbered decisions, without the alternatives, and design.md's Planned next item 3 records them. The plan's acceptance edits are made: printers.md's seam, question 6, question 24 and stage 3 point to it, and job-store.md notes that a remote attempt whose outcome stays unknown turns uncertain during a run and that the acknowledgement runs at the agent for remote printers. Co-Authored-By: Claude Opus 5.5 --- docs/design.md | 29 +++-- docs/plans/job-store.md | 7 +- docs/plans/printers.md | 10 +- docs/plans/remote-printers.md | 199 ++++++++++++++-------------------- 4 files changed, 112 insertions(+), 133 deletions(-) diff --git a/docs/design.md b/docs/design.md index a2eab09..cfab8f7 100644 --- a/docs/design.md +++ b/docs/design.md @@ -463,13 +463,28 @@ not yet written is described here until it is. - Also covered: `/healthz` per printer, a printer per ntfy subscription through rules, per-model line spacing, and the TM-T88VII's paper near-end (`GS r 1`). -3. **Remote printers**: `docs/plans/remote-printers.md` (not yet written). - 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, and speaks MessagePack through - `github.com/tinylib/msgp`, whose generator is pinned in `go.mod` and - run as `go tool msgp`. NATS JetStream, embedded etcd and VPN tunnels - are not used for this. +3. **Remote printers**: `docs/plans/remote-printers.md` (written; the + owner accepted every proposed default, 2026-11-30). + - Printers on other networks are reached through an Überbringer agent + next to them: the same binary, run as `uberbringer agent`. It dials + out to the main instance over HTTPS and WebSockets, using Fiber's + WebSocket middleware, so no port opens at the remote site. + - Messages are MessagePack through `github.com/tinylib/msgp`, whose + generator is pinned in `go.mod` and run as `go tool msgp`. NATS + JetStream, embedded etcd and VPN tunnels are not used for this. + - Main renders each receipt in full. The agent writes the bytes + unchanged, and only to printers its own config lists. + - An agent signs in with a token scoped by an `agt` claim, and + `tokens_since` revokes one agent's older tokens. + - The agent syncs a journal record before the first byte of each + receipt. A send whose link is lost is resolved from that journal; + one whose outcome stays unknown ends `uncertain` and is never sent + again. + - While an agent is offline, its printers' jobs wait in order, and + anycast passes over them. Status is read through the agent on + demand. + - `install.sh --agent` sets up an agent, and the Docker image runs + one with the command `agent`. There is no Windows release. 4. **More blocks**: `docs/plans/blocks.md` (not yet written): table (with `╤╪╧` junctions), banner, group, inline spans and a custom rule character, each built when needed. diff --git a/docs/plans/job-store.md b/docs/plans/job-store.md index 43b9f26..7e41969 100644 --- a/docs/plans/job-store.md +++ b/docs/plans/job-store.md @@ -104,7 +104,7 @@ Before phase 2: 16. **A history listing.** Assumed: yes, `GET /api/v1/jobs`, newest first, for full tokens only. A listing shows every client's jobs, so tokens limited to modules do not get it. Trade-off: more API to keep; without it, a client must remember its own job IDs. Its details, also assumed: - `status`, `source`, `before` (a job ID; the page starts after it) and `limit` (1-100, default 50) in the query. A `before` that names a job no longer kept answers `invalid_query`, so paging never skips jobs silently. - Job status gains `ref`, so a client can find the job an ntfy message became. - - `/healthz`'s `queue` gains `uncertain`: the jobs found `uncertain` at the latest start, those with a delivery that `Load` turned from `sending`. A clean restart sets it back to 0, so it does not stay up for about 1,000 jobs. Alternatives: a time window, or a route that marks a job checked. + - `/healthz`'s `queue` gains `uncertain`: the jobs found `uncertain` at the latest start, those with a delivery that `Load` turned from `sending`. From remote-printers stage 4 it also counts the jobs a remote send has left `uncertain` since that start. A clean restart sets it back to 0, so it does not stay up for about 1,000 jobs. Alternatives: a time window, or a route that marks a job checked. Before phase 2b: @@ -333,7 +333,7 @@ A job has one or more deliveries, one per printer it goes to (DELIVERIES AND SEV | `sending`, attempt n | after the connection opens, before the first byte; the first sets `sent_at` | **yes** | `printing` | `uncertain`, never resent | | `done` | after the write returned in full | no | `done` | history | | `failed` | a render error, every attempt failed, or a stored job that no longer decodes | **yes** | `failed` | history | -| `uncertain` | at start, for each delivery found in `sending` | no | `uncertain` | history | +| `uncertain` | at start, for each delivery found in `sending`; during a run, for a remote attempt whose outcome stays unknown (docs/plans/remote-printers.md, decision 17) | no | `uncertain` | history | | `cancelled` (phase 2b) | on a cancel, only for a delivery that has not reached `sending` | **yes** | `cancelled` | history | - A dial failure writes nothing, because the mark is written only once a connection is open. Retries while the printer is offline cost no disk writes, and such a job stays safe to retry. @@ -359,7 +359,7 @@ Each delivery's state tells what reached its printer: - `done`: written in full to the printer's connection. It printed unless the printer itself failed, as today. - `queued`: never reached the printer. - `failed`: reached the printer only if `sent_at` is set, and then part of it may have printed. The error does not tell: it is the last attempt's, so a first attempt that wrote part of the receipt and a second that failed to dial end with a dial error. -- `uncertain`: may have printed. At start the daemon logs one WARN line per delivery that start turned `uncertain` (`Load` says which) with its `job_id`, `printer`, `source` and `ref`, never its content, and from phase 2 `/healthz` counts their jobs. A delivery found `uncertain` at an earlier start is not logged again. A person checks the paper; a reprint is always a new request. +- `uncertain`: may have printed. At start the daemon logs one WARN line per delivery that start turned `uncertain` (`Load` says which) with its `job_id`, `printer`, `source` and `ref`, never its content, and from phase 2 `/healthz` counts their jobs. A delivery found `uncertain` at an earlier start is not logged again. A remote attempt whose outcome stays unknown turns `uncertain` during the run, with a WARN line of its own (docs/plans/remote-printers.md, decision 17). A person checks the paper; a reprint is always a new request. - `cancelled` (phase 2b): never reached the printer. ACKNOWLEDGEMENT, WHERE THE PRINTER HAS IT (phase 5, question 21) @@ -367,6 +367,7 @@ ACKNOWLEDGEMENT, WHERE THE PRINTER HAS IT (phase 5, question 21) - The connection stays open while the daemon reads frames, classified by the first byte under the mask 0x93, and polls `DLE EOT` every few seconds. The polling also keeps the network board's idle time-out (300 s on the UB-E02 and UB-E03) away. It ends when the matching ID arrives, or after a time-out set by the job's printing time. - The send then has one of four outcomes: not sent (safe to retry), partly written, written but unconfirmed, or confirmed. Only a confirmation adds `confirmed_at` to the status. A time-out gives `uncertain`, never `failed`, and never a resend. - After a restart, a job in `sending` or awaiting its ID is still `uncertain`. Turning acknowledgement off leaves the store exactly as safe. +- For a printer behind an agent, it runs at the agent, which owns the connection (docs/plans/remote-printers.md, decision 24). - Holding the connection until the receipt prints would make `/healthz` time out (3 s) during long prints. While a job holds the connection, `/healthz` reports the status that connection last polled, with its age (assumed). THE STORE INTERFACE (printqueue) diff --git a/docs/plans/printers.md b/docs/plans/printers.md index ad8fe39..9b2e245 100644 --- a/docs/plans/printers.md +++ b/docs/plans/printers.md @@ -64,7 +64,7 @@ Before stage 1a: - Trade-off: renaming a printer fails what waits for it. - Alternatives: refuse to start until the printer is back, which stops every printer over one; or send them to the default printer, a room nobody chose. 6. **The seam for remote printers.** Assumed: no `kind` key and no address scheme now. Each printer is built by one constructor in internal/app, which returns what `printqueue.Sender` and `server.Printer` need; today that is a `*printer.Client`. The remote-printers plan adds its own key, which is purely additive, since unknown keys are refused today. Architecture, THE SEAM FOR REMOTE PRINTERS, writes down the contract a remote printer keeps, printqueue's send contract (stage 3) included. - - Trade-off: none known; the remote plan names the key. + - Trade-off: none known. docs/plans/remote-printers.md names the key, `agent` (its decision 16). - Alternative: reserve `kind = "tcp"` now, as the only value accepted. Before stage 1b: @@ -179,6 +179,7 @@ Before stage 3: 24. **A printer marked down.** An anycast delivery joins the lane of its first printer. When that printer is dead, the delivery waits behind every earlier delivery on that lane, and each of those retries before it fails. That is about 27 s each at the defaults when dials time out (four dials of 5 s, plus waits of 1, 2 and 4 s), or about 7 s when they are refused. Ten unicast jobs for a dead `office` would delay an `alerts` job by 4-5 minutes while `default` sits idle. Once the dead lane is full, `Submit` would refuse the anycast job. Anycast would fail in the very case it exists for. Assumed: - A printer is marked down after a failure before any byte of a job: a refused, unreachable or timed-out dial, or a printer still not ready at the anycast check. Any delivery's failure marks it, unicast included. A failure our own context caused never does. - The mark clears on the printer's next successful send, or after a hold of 30 s (a constant, not a key). It lives in memory and is lost at a restart. + - A printer behind an agent stays marked while its agent is offline or does not list it (docs/plans/remote-printers.md, decision 18). - At `Submit`, an anycast delivery joins the first printer of its list that is not marked down and whose lane has room; else the first with room. `queue_full` comes only when every lane of the list is full. - Marking a printer down moves the anycast deliveries waiting on its lane on at once. A worker that takes an anycast delivery for a printer marked down moves it on without dialling. - A mark only passes a printer over for a later one of the list that is not marked. When every printer left is marked, the first of them is tried as usual, so the attempt renews or clears its mark. @@ -609,13 +610,13 @@ PROFILES AND STATUS PER MODEL (stages 4a and 4b) - Status: `printer.Client.Status` keeps `DLE EOT 1-4`, one request at a time. On a profile whose near-end comes from `GS r 1`, it sends that last, only when online and ready, with its own deadline and decoder, and closes the connection after a missed answer (question 28). The anycast check never sends it. `Ready()` and `Normalized()` gain question 29's bits. THE SEAM FOR REMOTE PRINTERS (named, not built; question 6) -- Each printer is one value built by one constructor in internal/app from its table. It implements `printqueue.Sender` (`Send` with `beforeWrite`, and stage 3's checked send) and `server.Printer` (`Status`). Today it is a `*printer.Client`; the remote-printers plan adds one backed by an agent's link, chosen by a key that plan adds. +- Each printer is one value built by one constructor in internal/app from its table. It implements `printqueue.Sender` (`Send` with `beforeWrite`, and stage 3's checked send) and `server.Printer` (`Status`). Today it is a `*printer.Client`; docs/plans/remote-printers.md adds one backed by an agent's link, chosen by its `agent` key (its decision 16). - The contract a remote printer keeps is printqueue's send contract (stage 3): - `beforeWrite` runs only once a connection to the printer itself is open, wherever that is, so the `sending` mark and "nothing sent" stay true across the agent. - - A failed send that never called `beforeWrite` sent nothing. One that called it sent nothing only when its error matches printqueue's `NothingWritten` interface, which a remote sender reports only when the agent says nothing was written. A send whose link is lost part-way counts as "may have printed", never "nothing sent". + - A failed send that never called `beforeWrite` sent nothing. One that called it sent nothing only when its error matches printqueue's `NothingWritten` interface, which a remote sender reports only when the agent says nothing was written. A send whose link is lost part-way counts as "may have printed", never "nothing sent", unless the agent's journal shows nothing was written (docs/plans/remote-printers.md, decision 17). - Status follows the same rules: read a not-ready answer again; a timeout is never a fault. - The main instance and an agent never both drive one printer: its second connection blocks until the first closes. -- Nothing of this is built here: no key, no agent, no transport. +- Nothing of this is built here: no key, no agent, no transport. docs/plans/remote-printers.md builds them. LOGGING AND PRIVACY - Worker lines gain `printer`. Each printer's start-up line gives its name, address, model, code page and paper width, as today's `listening` line gives the address: logs are private, and that line is where an operator sees which address each name uses. @@ -1002,6 +1003,7 @@ internal/pkg/printqueue - Moves (question 26): under the status lock, and the delivery lock once job-store phase 2b exists; only while the queue is open and the delivery is not cancelled; never after a failure while the delivery's context has ended. - Round timers (question 25); shutdown and a cancel see a delivery on a timer as waiting. - `Sender` gains the checked send (name assumed). + - A remote printer's checked send is built by whichever of this stage and docs/plans/remote-printers.md's stage 4 lands second. - store.go: `Sending` adds its printer to `SentTo`; a restore drops printers no longer configured from a delivery's list (question 5). - `Status`: an anycast delivery's `printers` and `sent_to`. diff --git a/docs/plans/remote-printers.md b/docs/plans/remote-printers.md index 301de51..fc7ef47 100644 --- a/docs/plans/remote-printers.md +++ b/docs/plans/remote-printers.md @@ -1,14 +1,6 @@ # Plan: remote printers, reached through an agent -Status: **planning; nothing is built.** 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 (its 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. Each stage runs in its own session, briefed from its section. It starts once the owner has answered the questions listed for it, or accepted their assumed defaults: -- stage 1 needs questions 1-3, and 13, 17 and 19, whose answers the messages carry; -- stage 2 needs 4-10 and 12; -- stage 3 needs 11-15; -- stage 4 needs 16-20; -- stage 5 needs 21-23; -- stage 6, later and only on the owner's word, needs 24 and job-store phase 5. - -Each answer goes into design.md at once and leaves this list. The stages run in the order listed. Every check on a real printer 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 3. +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) @@ -21,163 +13,137 @@ Each answer goes into design.md at once and leaves this list. The stages run in and run as `go tool msgp`. - **NATS JetStream, embedded etcd and VPN tunnels are not used** for this. -## Open questions +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. -Each has the default the plan assumes unless the owner says otherwise. "Main" is the instance that takes jobs, queues and renders them; "the agent" is the process next to the remote printers. +For stage 1: -Before stage 1: - -1. **Where rendering happens.** Assumed: 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. +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. - - Alternative: the agent renders from the job JSON. It would need the renderer, the profiles, safehttp and `images.*` at the agent, two renderers that must match across versions, and invariant 1 would hold at the agent instead. -2. **The messages and their versioning.** Assumed: +2. **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.1` in `Sec-WebSocket-Protocol`, and main accepts the versions it speaks. A later breaking change offers `.2` beside `.1` for at least one release. An agent whose offer main does not speak is refused before the upgrade (question 7). + - The protocol version is the WebSocket subprotocol. The agent offers `uberbringer-agent.1` in `Sec-WebSocket-Protocol`, and main accepts the versions it speaks. A later breaking change offers `.2` beside `.1` for at least one release. An agent whose offer main does not speak is refused before the upgrade (decision 7). - `Hello` and `Welcome` carry 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. - - Alternatives: tuples, smaller and brittle; a version field in every envelope instead of the subprotocol; or protobuf, which goes against the owner's decision. -3. **Sizes, chunks and limits.** Assumed: +3. **Sizes, chunks and limits.** - Main sends a delivery's bytes as `Data` messages 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_bytes` caps one job: default 16 MiB, from 1 MiB to 256 MiB, announced in `Hello`. 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. `query` asks about at most 128 keys at a time, so its reply stays far under main's limit. msgp's `//msgp:limit arrays:1024 maps:64` bounds 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 queued `Data`, so a large transfer holds back neither a status request nor a go-ahead. - No WebSocket compression (`permessage-deflate`). - - A 64-KiB frame within question 9's 30-s write deadline needs about 17 kbit/s, so a slow uplink at main's side still carries image jobs. + - 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. - - Alternatives: one message per job, which holds back status replies and pings for the length of a large transfer; compression, which shrinks raster images a lot but adds CPU on a Pi and a decompressed-size limit to enforce. -Before stage 2: +For stage 2: -4. **One binary.** Assumed: 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 reuses `printer`, `escpos`, the config loader and the logging. +4. **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 reuses `printer`, `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. - - Alternative: `cmd/uberbringer-agent`, linking only `printer`, `escpos`, `agentproto` and a WebSocket client: smaller, with a second build, archive and image to keep. -5. **The WebSocket libraries.** Assumed: main serves the link with `github.com/gofiber/contrib/v3/websocket` (v1.3.1, the Fiber v3 middleware), and the agent dials with the `Dialer` of `github.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 `Origin` header unless `AllowEmptyOrigin` is set. The agent sends none, so the setting is on. Main refuses a request that carries one instead (question 7). +5. **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 the `Dialer` of `github.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 `Origin` header unless `AllowEmptyOrigin` is 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. - - Alternatives: `github.com/coder/websocket` (v1.8.15) at the agent, a context-aware API with no dependencies, at the cost of a second implementation; `github.com/gorilla/websocket` (v1.5.3, 2024-06-14), the original that fasthttp/websocket forks. -6. **Authenticating and authorising agents.** Assumed: an agent's token is a bearer token like the others, signed with `api.secret` (HS256), with a new scope claim `agt` naming the agent. `uberbringer token --agent ` issues it, refusing `--modules` and `--raw` beside it. +6. **Authenticating and authorising agents.** an agent's token is a bearer token like the others, signed with `api.secret` (HS256), with a new scope claim `agt` naming the agent. `uberbringer token --agent ` issues it, refusing `--modules` and `--raw` beside it. - A token with `agt` opens the agent route only and is refused everywhere else with `403` `token_scope`. No other token opens the agent route. `agt` joins `mod` and `raw` among the scope claims, so a malformed one (another type, `null`, another letter case) makes the token invalid (`401`). - Main lists its agents as `[agents.]` tables, named by the subscriptions' rule, from the file only. A table holds `tokens_since` and nothing else yet, and may be empty. A token whose `agt` names no configured agent answers `401` `unauthorized`, as an invalid token does. - Revoking one agent: `tokens_since` (name assumed), a time. A token of that agent issued before it answers `401`. - Rotating: issue a new token and put it on the agent host. Then set `tokens_since` to just before the new token's `iat`, and restart main. The agent reads its token file at each dial, so it needs no restart. Every other token is left alone, and changing `api.secret` still revokes everything. - - Main authenticates to the agent through TLS (question 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. + - 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.secret` can 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). - - Alternatives: a random key per agent, of which main keeps a SHA-256 in `[agents.]` and compares in constant time; revoking is removing the hash, and `api.secret` cannot mint one. Or client certificates checked by Caddy, which needs a private CA and moves authorisation out of the daemon. -7. **The agent route and its refusals.** Assumed: `GET /api/v1/agent`, an entry in the route table with `Auth`, so it is rate limited like the others, with its case in TestRoutesConform. The OpenAPI document gives its `101` answer and the subprotocol, not the messages, which this plan's MESSAGES table and docs/agent.md describe. +7. **The agent route and its refusals.** `GET /api/v1/agent`, an entry in the route table with `Auth`, so it is rate limited like the others, with its case in TestRoutesConform. The OpenAPI document gives its `101` answer 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 `426` with a new code, `upgrade_required`, whose `details` name the subprotocols main speaks. - A request with an `Origin` header answers `403` `token_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 `101` and 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. - - Alternative: a route outside the table, which TestRegisteredRoutesAreTheTable would refuse, and swagger.json would not show. -8. **One link per agent.** Assumed: 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 (question 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 (question 13). - - Alternative: refuse the newcomer while the old link lives, which blocks a reconnect for up to a minute after a half-open link. -9. **Keepalives and dead links.** Assumed: 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 `Hello` within 10 s of the upgrade, or main closes the link. Close codes come from RFC 6455's private range: 4001 replaced (question 8), 4002 protocol error, 4003 refused, 4004 shutting down. +8. **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). +9. **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 `Hello` within 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) and `idle_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. - - Alternatives: 30 s and 90 s, cheaper and slower to notice a dead link; or only the agent pings. -10. **`/healthz` and the agents.** Assumed: `/healthz` gains `agents`, one entry per configured agent, sorted by name: `name`, `connected` and `since`, the time of the last connect or disconnect. A remote printer's entry in `printers` gains `agent`. No address, version or token subject appears, since the route is public. The code still follows the default printer alone (printers question 9). +10. **`/healthz` and the agents.** `/healthz` gains `agents`, one entry per configured agent, sorted by name: `name`, `connected` and `since`, the time of the last connect or disconnect. A remote printer's entry in `printers` gains `agent`. 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. - - Alternative: agents only in an authenticated route. -Before stage 3: +For stage 3: -11. **The agent's config, and printer names on both sides.** Assumed: +11. **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.]`, `[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, question 13) and `max_job_bytes` (question 3). Each scalar key also reads `UBERBRINGER_AGENT_`. + - `[agent]`: `url` (main's base URL), `name`, `token_file`, `ca_file` (empty: the system roots), `state_dir` (empty: a journal in memory, decision 13) and `max_job_bytes` (decision 3). Each scalar key also reads `UBERBRINGER_AGENT_`. - `[agent.printers.]`: `address` and `port` (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. `Hello` lists the names, never the addresses. A remote printer main configures that the agent does not list reads as `unreachable` with a WARN; a name the agent lists that main does not use draws a WARN and is ignored. - - Timeouts stay on main (question 16), which owns each job's time budget and sends them with each request. + - 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. - - Alternatives: main sends each printer's address to the agent, so the agent's config holds only the link; it puts the remote network in the hands of whoever controls main. Or an agent name per printer on main (`agent_printer`), for agents whose names differ from main's. -12. **TLS from the agent.** Assumed: `url` must be `https://`, except to a loopback host, for development. The certificate is checked against the system roots, or against `ca_file` alone when it is set. There is no setting that skips verification. The dialler honours `HTTPS_PROXY` from the environment. The token goes in the `Authorization` header, never the URL. +12. **TLS from the agent.** `url` must be `https://`, except to a loopback host, for development. The certificate is checked against the system roots, or against `ca_file` alone when it is set. There is no setting that skips verification. The dialler honours `HTTPS_PROXY` from the environment. The token goes in the `Authorization` header, never the URL. - Trade-off: a test set-up with a self-signed main needs `ca_file`. - - Alternative: pin main's certificate by hash, which breaks at each renewal of a Caddy certificate. -13. **The agent's journal.** Assumed: an append-only file, `/agent-journal`, one record per write, each a msgp record with its length and a CRC-32. +13. **The agent's journal.** an append-only file, `/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 `writing` record for its attempt key and syncs it. After the write it appends the outcome, without a sync. - At start, a `writing` record with no outcome becomes `unknown`: the agent stopped while it wrote. One WARN line gives its `job_id` and `printer`. - - 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 (question 17). + - 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. `opened` gives main the journal's ID and the number its next record will take. A `query` reply of `none` counts 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 `none` about the old one. - With `state_dir` empty, the journal lives in memory and gets a new ID at each start. - A failed `writing` append writes nothing, answers `nothing` and stops the agent. A failed outcome append answers the outcome the agent holds in memory, then stops the agent; at its restart the record reads `unknown`. systemd restarts it either way. - Trade-off: one synced write per receipt on the agent's disk, and our own recovery code. - - Alternatives: SQLite, as job-store question 1 assumes for main: no recovery code of ours, and the agent then links it. Or no journal: every lost link after the go-ahead would leave a delivery `uncertain`, and nothing would stop a repeated go-ahead from printing twice after an agent restart. -14. **Reconnecting.** Assumed: 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`, a `403` or a `426` waits 5 minutes, logged at ERROR once per change of answer, as the ntfy subscriber treats refused credentials. A `429` waits for its `Retry-After`. +14. **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`, a `403` or a `426` waits 5 minutes, logged at ERROR once per change of answer, as the ntfy subscriber treats refused credentials. A `429` waits for its `Retry-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. - - Alternative: a fixed 5-s retry, which hits main's rate limit when many agents share an address. -15. **The agent's wait for the go-ahead.** Assumed: 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". +15. **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 `sending` commit 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). - - Alternative: no open connection until the go-ahead, which puts the dial after main's mark and breaks the seam's rule that `beforeWrite` runs only once a connection to the printer is open. -Before stage 4: +For stage 4: -16. **A remote printer in main's config.** Assumed: `agent = ""` in a printer table, `[printer]` included, makes it remote. The name must have an `[agents.]` table (question 6). +16. **A remote printer in main's config.** `agent = ""` in a printer table, `[printer]` included, makes it remote. The name must have an `[agents.]` 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`). `address` and `port` are refused beside `agent`; they belong to the agent's file. - - A remote printer's `dial_timeout` is at most 30 s and its `write_timeout` at 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 (question 21). + - A remote printer's `dial_timeout` is at most 30 s and its `write_timeout` at 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.address` is then required only when `agent` is empty. `UBERBRINGER_PRINTER_AGENT` sets 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. - - Alternative: a printer kind (`kind = "agent"`), which printers question 6 chose not to reserve. -17. **A remote send and its outcomes.** Assumed: the sequence under Architecture, A REMOTE SEND. An attempt ends in one of four outcomes: +17. **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's `NothingWritten`, 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 for `result` on 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 (question 13 says when `none` counts). With no answer, the delivery ends `uncertain`, and one WARN line names it. + - `unknown`: the go-ahead was written and no outcome came back. Main never sends that delivery again. It waits for `result` on 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 when `none` counts). With no answer, the delivery ends `uncertain`, and one WARN line names it. - An outcome is a string. A missing, empty or unknown one reads as `unknown`, never `nothing`, and `none` is a value of its own, sent only in reply to `query`. - Main waits for `opened` up to the dial timeout plus 10 s. At main's shutdown, an attempt before its `sending` mark sends `Abort` and stays queued; one past its mark gets its `Go` and waits for `result` up to the write timeout plus 10 s, then ends `uncertain`. - This adds one path that writes `uncertain` during a run; job-store writes it only at start. A lost lazy write of it still reads `uncertain` after 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. - - Alternative: treat `unknown` as a write error and retry, as today's rule does locally. Locally a write error leaves at most a partial receipt behind; here the first attempt may have printed whole, so a retry can print the whole receipt twice. -18. **Deliveries while an agent is offline.** Assumed: 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. +18. **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.size` still bounds each lane, so `Submit` answers `queue_full` once 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 question 17 says; it is not counted as a retry. + - 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. - - Alternatives: treat an offline agent as a dead printer, so each delivery fails after its retries (about 7 s at the defaults); or a new key that fails deliveries after they have waited a set time. -19. **Status through the agent.** Assumed: on demand. Main sends `Status` with its deadline. The agent reads `DLE EOT` with its `printer.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 `/healthz` holds; a missed deadline is `timeout`, never a fault. +19. **Status through the agent.** on demand. Main sends `Status` with its deadline. The agent reads `DLE EOT` with its `printer.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 `/healthz` holds; a missed deadline is `timeout`, never a fault. - An agent that is offline, or that does not list the printer, reads `unreachable` (`503` for 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 `/healthz` call 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. - - Alternative: the agent pushes status every 30 s and `/healthz` shows it with its age. Cheaper for the remote site, but it reports an old reading as current, and printers question 23's re-read needs a fresh one. -20. **The agent's answer for a delivery already `uncertain`.** Assumed: when an agent connects, main asks its journal about each of its printers' deliveries that `Load` turned `uncertain` at 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`, `unknown` or no record). The status stays `uncertain`: a client may already have sent the receipt again. +20. **The agent's answer for a delivery already `uncertain`.** when an agent connects, main asks its journal about each of its printers' deliveries that `Load` turned `uncertain` at 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`, `unknown` or no record). The status stays `uncertain`: a client may already have sent the receipt again. - Trade-off: the answer helps a person who checks the paper, and changes nothing else. - - Alternative: turn the delivery `done` or `failed` from the answer. That makes `uncertain` no longer final, against job-store question 12. -Before stage 5: +For stage 5: -21. **install.sh, and Caddy.** Assumed: +21. **install.sh, and Caddy.** - `install.sh --agent` installs the binary, writes `/etc/uberbringer/agent.toml` from 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 installs `uberbringer-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 on `write_timeout` plus 10 s (question 16); systemd's default of 90 s does. + - 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 on `write_timeout` plus 10 s (decision 16); systemd's default of 90 s does. - Main's Caddy site gains `stream_close_delay 5m` in `reverse_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. - - Alternative: no agent mode in install.sh; docs/agent.md gives the steps by hand. -22. **Docker.** Assumed: 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 `Upgrade` and `Connection` set, and closes a proxied WebSocket quiet for 60 s, which the pings of question 9 prevent. +22. **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 `Upgrade` and `Connection` set, 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. - - Alternative: a second image for the agent, which question 4 makes unnecessary. -23. **Windows.** Assumed: no Windows release, as for the daemon. `uberbringer agent` builds and runs on Windows for development, with the journal in memory unless `state_dir` is set. +23. **Windows.** no Windows release, as for the daemon. `uberbringer agent` builds and runs on Windows for development, with the journal in memory unless `state_dir` is set. - Trade-off: a shop whose only machine is a Windows PC needs a small Linux board. - - Alternative: a windows/amd64 archive of the agent, with a service wrapper (`golang.org/x/sys/windows/svc`, a new dependency) and an install guide. -Later (stage 6): +For stage 6, later: -24. **Epson's acknowledgement at the agent** (job-store question 21). Assumed: built only with job-store phase 5, and for remote printers at the agent, which owns the connection. The agent appends `GS ( H 48 ` after the bytes, waits for the matching reply and answers `done` with `confirmed`. A capability in `Hello` says it can. Its IDs are counted per printer by the agent; they never cross the link. +24. **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 ` after the bytes, waits for the matching reply and answers `done` with `confirmed`. A capability in `Hello` says 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`. - - Alternative: none at the agent. ## Investigation findings @@ -236,7 +202,7 @@ THE REPOSITORY TODAY WHERE THE REPORTS DISAGREE OR ARE UNSURE - Whether Caddy's `request_body max_size` reaches 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 question 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 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. @@ -262,9 +228,9 @@ WHAT SHIPS WHEN COMPATIBILITY - A config without `[agents]` and `agent` keys runs and prints as today. The agent route exists and refuses every token, since no agent is configured. - Tokens: an older token has no `agt` and keeps every route it had. An agent token is refused on every other route. -- New: the route, the code `upgrade_required`, `/healthz`'s `agents` and a remote printer's `agent`. Job status can read `uncertain` during a run, for a remote delivery only (question 17); its enum already has it from job-store stage 1c. +- New: the route, the code `upgrade_required`, `/healthz`'s `agents` and a remote printer's `agent`. Job status can read `uncertain` during 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 (question 2); each logs the other's version at connect. +- 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]` and `agent` as unknown keys, and has no `agent` command. INVARIANTS @@ -279,11 +245,6 @@ INVARIANTS 9. 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. 10. job-store's and printers' invariants hold for each remote delivery. -ON ACCEPTANCE -When the owner accepts this plan, these edits are made: -- design.md: Planned next item 3 says the plan is written and its questions await the owner. -- docs/plans/printers.md: THE SEAM FOR REMOTE PRINTERS and question 6 point here and name the key, `agent` (question 16). The seam's "a send whose link is lost part-way counts as 'may have printed', never 'nothing sent'" gains "unless the agent's journal shows nothing was written (remote-printers question 17)". Question 24's 30-s hold gains: a remote printer stays marked while its agent is offline or does not list it (question 18). Stage 3's Work notes that a remote printer's checked send is built by whichever of printers stage 3 and this plan's stage 4 lands second. -- docs/plans/job-store.md: JOB STATES' `uncertain` row and TELLING WHICH RECEIPTS PRINTED note that a remote attempt whose outcome stays unknown is written `uncertain` during a run (question 17), and logged then. ACKNOWLEDGEMENT, WHERE THE PRINTER HAS IT: for a remote printer it runs at the agent (question 24). Phase 2's `/healthz` count of `uncertain` jobs counts those written during the run too. ## Architecture @@ -294,7 +255,7 @@ main lane "shop-front" ─▶ render in full ─▶ remote printer ─▶ l agent link ─▶ bytes held for "shop-front" ─▶ printer.Client ─TCP 9100─▶ printer ``` -THE CONFIG ON BOTH SIDES (questions 6, 11 and 16) +THE CONFIG ON BOTH SIDES (decisions 6, 11 and 16) Main's config: @@ -329,13 +290,13 @@ THE LINK (stages 2 and 3) 2. Main checks the token (`agt`, `tokens_since`), the subprotocol and the absence of `Origin`, then upgrades. 3. The agent sends `Hello` within 10 s, or main closes the link. Its `name` must match the token's `agt`. 4. Main answers `Welcome`, naming the printers it routes to this agent, or closes with a close code and reason (4002 protocol, 4003 refused). -5. A link with the same agent's name replaces the old one (question 8). Pings run both ways (question 9). +5. A link with the same agent's name replaces the old one (decision 8). Pings run both ways (decision 9). 6. Each end has one reader and one writer goroutine. Main's writer drains two queues: control first (`Welcome`, `Open`, `Go`, `Abort`, `Status`, `Query`), then `Data`. A large transfer therefore holds back a status request or a go-ahead by one `Data` frame at most. Pings go through `WriteControl`, beside the writer. 7. 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. 8. The agent's reader never blocks either. It passes each message about a printer (`data`, `open`, `go`, `abort`, and `query` for that printer's keys) to that printer's goroutine, in the order they arrived. The queue holds one job's `Data` and a few control messages; an overflow is a protocol error. `status` goes to a goroutine of its own, so a status read never waits behind the wait for a go-ahead. 9. 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; question 2) +MESSAGES (stage 1; decision 2) | Type | From | Body | |---|---|---| @@ -352,22 +313,22 @@ MESSAGES (stage 1; question 2) | `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 (question 20). Each delivery's attempt numbers are unique, and attempt numbers go on across the printers of an anycast list (printers question 22). +- 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. - `Data` arrives 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 past `max_job_bytes`, is a protocol error. - Outcomes are strings. A missing, empty or unknown outcome reads as `unknown`; `none` is explicit and appears only in `query_reply`. -A REMOTE SEND, STEP BY STEP (stage 4; questions 15 and 17) +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: 1. 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. 2. Fails at once with "agent offline" if the agent has no link or does not list the printer: `nothing`, as a dial failure is. -3. Checks the length against the agent's `max_job_bytes` (question 3). +3. Checks the length against the agent's `max_job_bytes` (decision 3). 4. 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 new `Data` replaces them or the link closes). 5. Sends `Open`. The agent checks length and hash, takes its printer's connection slot, dials, reads status if `check` is set, and answers `opened` with its journal's ID and next record number, or `result` `nothing` with its class. Main waits at most the dial timeout plus 10 s. 6. Calls `beforeWrite`: main's synced `sending` mark. If it fails, main sends `Abort`, and the attempt is `nothing`. 7. Sends `Go`. The agent appends its `writing` record and syncs it, writes, appends the outcome and answers `result`. Main waits for `result` on this link and never sends `query` on it. -8. Returns by the outcome: `done` succeeds; `nothing` returns an error that matches `NothingWritten`; `partial` returns a write error; `unknown` returns an error that ends the delivery `uncertain` (question 17). +8. Returns by the outcome: `done` succeeds; `nothing` returns an error that matches `NothingWritten`; `partial` returns a write error; `unknown` returns an error that ends the delivery `uncertain` (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. @@ -381,8 +342,8 @@ Where the link drops: | 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: -1. It writes only after a `Go` for a key whose `Open` it acted on in this link, and only within question 15's wait. -2. It appends and syncs `writing` before the first byte. Only a failed `writing` append answers `nothing`. A failed outcome append answers the outcome the agent holds (question 13). +1. It writes only after a `Go` for a key whose `Open` it acted on in this link, and only within decision 15's wait. +2. It appends and syncs `writing` before the first byte. Only a failed `writing` append answers `nothing`. A failed outcome append answers the outcome the agent holds (decision 13). 3. A `Go` or `Open` for a key it has a record of is answered from the record and never written. 4. 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 `query` about a key is answered by that key's printer's goroutine, after every message that came before it. 5. 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 `query` on the new link finds every record settled, and an answer of `none` is final. @@ -393,36 +354,36 @@ Main's rules: 3. A delivery with an attempt in doubt is never sent again, never moved by anycast and never cancelled (its `sending` mark stands, as job-store phase 2b requires). 4. Retries after `nothing` are new attempts with new keys; the agent may still hold their bytes (step 4). -THE AGENT'S JOURNAL (stage 3; question 13) +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 (question 13). Turn each `writing` without an outcome into `unknown`, logged at WARN. Keep the newest 10,000 records; write them to a temporary file, sync, rename and sync the directory. +- 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 `writing` without an outcome into `unknown`, 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 `query` and for rule 3. - One synced append per receipt; the outcome is appended unsynced. A lost outcome reads as `unknown` after a crash, never as `none`. -STATUS (stage 4; question 19) +STATUS (stage 4; decision 19) - Main's remote printer implements `server.Printer.Status` through `status` and `status_reply`, within the caller's deadline, and concurrent callers share one request. - The agent runs `printer.Client.Status` and printers stage 3's settle function, with the profile's status capabilities for the model the request names. -- `/healthz` shows a remote printer's entry like a local one's, plus `agent`, and the `agents` array (question 10). +- `/healthz` shows a remote printer's entry like a local one's, plus `agent`, and the `agents` array (decision 10). -OFFLINE AGENTS (stage 4; question 18) +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 `Sender` for 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 (question 18). +- 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 `sending` mark sends `Abort` and stays queued. One past its mark finishes, as job-store has for a write in hand: main sends `Go` if it has not, and waits for `result` up to the write timeout plus 10 s; with none, the delivery ends `uncertain`. Then the links close. - Main, memory store: as today; the attempt in hand finishes the same way. -- Main's restart: `Load` turns remote deliveries in `sending` `uncertain`; when each agent connects, main queries them and logs the answers (question 20). The agent keeps an unanswered `result` in its journal. +- Main's restart: `Load` turns remote deliveries in `sending` `uncertain`; when each agent connects, main queries them and logs the answers (decision 20). The agent keeps an unanswered `result` in 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 `writing` become `unknown`. Main's attempts in doubt resolve through `query` as the table above says. LOCKS AND DEADLOCKS - Main: the lane's worker blocks in `Send` on 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 `timeout` at main's deadline, as a local read does today. The wait for `Go` is bounded (question 15), so a lost main never holds a printer. +- The agent: a status read waits on the printer's slot while a send holds it and fails with `timeout` at main's deadline, as a local read does today. The wait for `Go` is 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). @@ -435,7 +396,7 @@ PACKAGES - 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 (question 8); a refused upgrade as any refusal, by its request line. +- 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`, `agent` and the attempt number, never bytes. - The agent logs its link, each attempt's outcome by `job_id`, `printer` and 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. @@ -449,7 +410,7 @@ CONFIG, PACKAGING, DOCKER ### 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. Questions 1-3. +**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@` (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. @@ -479,7 +440,7 @@ Docs ### 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. Questions 4-10. +**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.** @@ -494,7 +455,7 @@ internal/app/uberbringer/server - handlers.go: `/healthz`'s `agents`. internal/pkg/agentlink -- The link manager: one link per agent, the newest winning (question 8); `Hello` within 10 s and `Welcome`; the reader and the two-queue writer; pings and the 60-s silence rule; close codes; `Close` for shutdown. +- The link manager: one link per agent, the newest winning (decision 8); `Hello` within 10 s and `Welcome`; the reader and the two-queue writer; pings and the 60-s silence rule; close codes; `Close` for shutdown. internal/app/uberbringer - cli.go: `token --agent `, refusing `--modules` and `--raw` beside it and a name not in `[agents]`; its subject defaults to `agent:`. @@ -536,7 +497,7 @@ Commit 1 also adds `[agents.]` and `tokens_since`, with their example and ### 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. Questions 11-15. +**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.** @@ -544,9 +505,9 @@ internal/pkg/config - `LoadAgent`: `[agent]`, `[agent.printers.]`, `[log]` and `[sentry]`; defaults and checks (an `https` URL or a loopback one; a token file that exists; at least one printer; `max_job_bytes` from 1 MiB to 256 MiB); variables for the scalar keys. internal/pkg/agent -- run.go: the dial loop and backoff (question 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: `Send` with a `beforeWrite` that answers `opened`, waits for `go` (question 15), appends and syncs `writing`. The checked send when `check` is set. -- journal.go: the journal and its recovery (question 13). +- 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: `Send` with a `beforeWrite` that answers `opened`, waits for `go` (decision 15), appends and syncs `writing`. The checked send when `check` is set. +- journal.go: the journal and its recovery (decision 13). - status.go: `status` through `printer.Client.Status` and the settle function. internal/app/uberbringer @@ -590,7 +551,7 @@ Commits 1 and 2 only if printers stage 3 has not shipped. ### 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. Questions 16-20. +**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.** @@ -605,7 +566,7 @@ internal/pkg/printqueue - A send error that says `uncertain` finishes the delivery `uncertain`, with its WARN line. internal/app/uberbringer -- serve.go: the constructor per printer chooses `printer.Client` or the remote printer; links lost and regained mark printers down and up; at each connect, the query of deliveries `Load` turned `uncertain` (question 20). +- serve.go: the constructor per printer chooses `printer.Client` or the remote printer; links lost and regained mark printers down and up; at each connect, the query of deliveries `Load` turned `uncertain` (decision 20). - server: `/healthz`'s `agent` on remote printers. Docs @@ -613,7 +574,7 @@ Docs - docs/api.md: `uncertain` during a run for remote deliveries; `/healthz` for remote printers. docs/swagger.json regenerated. - configs/config.example.toml: a commented remote printer. - docs/agent.md: the send in plain words, what `uncertain` means there, offline agents. -- design.md: a decision "Remote printers are reached through an agent", with this plan's answers; "Render, then send" for remote printers. +- 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. @@ -649,7 +610,7 @@ Commit 1 is library code with its tests; commit 4 adds the `agent` key and the w ### 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. Questions 21-23. +**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.toml` from 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 gains `stream_close_delay 5m`. @@ -670,4 +631,4 @@ Commit 1 is library code with its tests; commit 4 adds the `agent` key and the w ### 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. Question 24. +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.