From 68bce4db59bb1a47747dec6859ced1ff5488997f Mon Sep 17 00:00:00 2001 From: William Gill Date: Tue, 1 Dec 2026 11:07:58 -0600 Subject: [PATCH] Record the owner's acceptance of the printers plan The owner accepted every proposed default of docs/plans/printers.md on 2026-12-01. Its open questions become numbered decisions, without the alternatives, and design.md's Planned next item 2 records them. Decisions 6, 10 and 17 keep the wording that the remote-printers and templates plans had already settled. Decision 14 amends the owner's earlier wording: a rule that fails to compile stops the start rather than being skipped. The plan's acceptance edits are made, and its list of them goes. formatters.md loses its open question, which the routing example answers, and points to this plan for a second printer and per-model line spacing, without the printer pool's tests. job-store.md points to these decisions for the deliveries array, the stored route, failover after a sending mark, the lanes and their content bound, and a printer removed from the config. Its invariant 2 speaks of the job's bytes, since an anycast check sends DLE EOT before the mark. Its findings confirm the TM-m50II's command list and the power-on part of the automatic-status side finding. Phase 2b, phases 3c and 4 and phase 5 say how they meet several printers. The other plans cite printers decisions in place of questions, and templates decision 1 now follows printers decisions 12, 14, 15 and 17 rather than leaning on assumed defaults. Co-Authored-By: Claude Opus 5.5 --- docs/design.md | 46 +++-- docs/plans/formatters.md | 20 +- docs/plans/job-store.md | 31 +-- docs/plans/printers.md | 348 +++++++++++++++------------------- docs/plans/remote-printers.md | 20 +- docs/plans/templates.md | 22 +-- 6 files changed, 224 insertions(+), 263 deletions(-) diff --git a/docs/design.md b/docs/design.md index 9921c10..4dccd9f 100644 --- a/docs/design.md +++ b/docs/design.md @@ -480,26 +480,42 @@ not yet written is described here until it is. preview by ID. - Epson's acknowledgement, ntfy state in the store and an age limit wait for phase 5. -2. **Several printers**: `docs/plans/printers.md` (written; its open - questions await the owner). - - Printers are named TOML tables, with named groups. +2. **Several printers**: `docs/plans/printers.md` (written; the owner + accepted every proposed default, 2026-12-01). + - `[printer]` stays, as the printer `default`, and `[printers.]` + tables add the others, from the file only. Each takes every key of + `[printer]`; no two local printers share an address and port. + - One queue with a lane per printer: its own worker, renderer and + connection, and `queue.size` per lane. History, references and the + store stay shared. + - `?printer=` on `/print`, `/preview` and the module routes is a direct + unicast; any other query parameter is refused (**Breaking**). Every + job status gains `deliveries`. `/healthz` lists every printer, and + its code follows the default printer alone. - Routing is done by rules written in Expr (`github.com/expr-lang/expr`), modelled on Kanrisha's policy engine: - compiled once against a typed environment, ordered, reloaded - atomically, with a dry-run. + `[[routing.rules]]` and `[routing.groups]`, compiled once against a + typed environment of routing facts, never print content, with a + unique `order`, first match wins. A rule that fails to compile stops + the start; one that fails at run time counts as no match. The + compile options and iteration guard are templates' `rules.Options`. - A rule sends a job unicast (one printer), multicast (each printer of a set), broadcast (every printer) or anycast (one printer of an - ordered list). - - Anycast is a priority list with failover: the first printer, on - failure the second, then the third. + ordered list). A job no rule matches goes to the default printer, so + a single-printer config keeps working. - A multicast or broadcast job is one job with several deliveries, one - per printer, each tracked on its own. - - `?printer=` on a request is a direct unicast. A job no rule matches - goes to the default printer, so a single-printer config keeps - working. - - 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`). + per printer, each tracked on its own, accepted while any of its + printers has room. The route is decided once, when the job is + accepted, and stored with it. + - SIGHUP reloads the rules. `uberbringer route` and the JSON preview's + `route` show what the rules decide. + - Anycast is a priority list with failover: the first printer, on + failure the second, then the third. It checks status before it + sends, passes over a printer marked down for 30 s, and fails over + after bytes went out only once that printer's retries are spent. + - The profile keeps the exact model, so a TM-T88VII reports its paper + near-end through `GS r 1`. Per-model defaults come only when a paper + check needs one. 3. **Remote printers**: `docs/plans/remote-printers.md` (written; the owner accepted every proposed default, 2026-11-30). - Printers on other networks are reached through an Überbringer agent diff --git a/docs/plans/formatters.md b/docs/plans/formatters.md index c4811be..954b298 100644 --- a/docs/plans/formatters.md +++ b/docs/plans/formatters.md @@ -2,12 +2,6 @@ Status: **phases 1-4 are done**: the blocks and the preview; the list block, the module layer and the note module; the notify and ntfy modules, their cards and scoped tokens; and the ntfy subscriptions, with their digest, paper budget and quiet hours. All four are built and checked on paper, and docs/api.md, README.md and design.md describe them. Phase 5 is a list of items built one at a time, each when a real need appears, in its own session briefed from its item. -## Open questions - -When the second printer arrives: - -1. Which jobs and ntfy subscriptions go to which printer, and should urgent messages print on both? - ## Rules for phase 5 BACKWARD COMPATIBILITY @@ -36,24 +30,16 @@ INVARIANTS (all match the current code) **Work.** -- Second printer, for the TM-T88VII and TM-m50II: - - a printqueue Pool with one Queue and worker per printer - - [printers.] config, each table decoded through Viper onto the printer defaults, with the old [printer] table becoming "default" and strict unknown-key checks kept - - ?printer= on print, preview and modules; printer = "name" per subscription; optional priority routes - - /healthz per printer, with the status still following the default printer - - Jobs stay printer-neutral, so nothing in the block or module code changes. +- Several printers: planned in docs/plans/printers.md. - User templates: planned in docs/plans/templates.md. - More blocks: planned in docs/plans/blocks.md. - Queue.Cancel so message_delete can cancel a still-queued job. - Webhook sources: planned in docs/plans/templates.md. -- Default line spacing per model in escpos.Profile, once calibrated on each model. +- Default line spacing per model: planned in docs/plans/printers.md (decision 30). **Tests.** -Each item ships with its own goldens and table tests in the phase 1-4 style. For the printer pool, also: -- a config migration test from [printer] to printers.default -- unknown keys inside [printers.x] still rejected -- two queues printing in parallel +Each item ships with its own goldens and table tests in the phase 1-4 style. **Done when.** diff --git a/docs/plans/job-store.md b/docs/plans/job-store.md index 951be13..9f5c442 100644 --- a/docs/plans/job-store.md +++ b/docs/plans/job-store.md @@ -63,7 +63,7 @@ For stage 1c: - Print contents now rest on disk: 0600 files in the 0700 state directory, `secure_delete=FAST`, and deleted content can linger in free pages and the WAL until they are overwritten. 9. **Retention.** Statuses as today, the last `queue.history` (1000) finished jobs. The content of finished jobs within a byte budget, a new key `queue.content_bytes`, default 64 MiB and at most 1 GiB, newest kept. The content of unfinished jobs is always kept, and so is that of `uncertain` jobs until their status goes, since a reprint needs it. - A count alone cannot bound it: `webserver.body_limit` (4 MiB) × 1000 jobs is about 4 GB, too much for an SD card. - - Trade-off: unfinished content alone can reach `queue.size` 100 × 4 MiB, about 400 MiB, and with `auto_vacuum=NONE` the file never shrinks below its high-water mark. + - Trade-off: unfinished content alone can reach `queue.size` 100 × 4 MiB, about 400 MiB, and with `auto_vacuum=NONE` the file never shrinks below its high-water mark. With several printers the bound is per lane: about 1.2 GiB for three (docs/plans/printers.md decision 4). - An age limit, for privacy, would be another key (phase 5). 10. **ntfy replays after a crash.** A subscription saves its state within a second of queueing a message. Today a job lost in a crash is replaced by the replay. Once queued jobs resume, a crash in that second would print the message twice. So: - A `Submit` whose source and reference the queue already holds, from an ntfy subscription, returns the earlier job and queues nothing. Only ntfy jobs take part: on the HTTP routes the reference is a request ID, which a client may set, so a check on it could answer a new request with an old job. @@ -126,7 +126,7 @@ For phase 5, later: 21. **Epson's process-ID acknowledgement** (`GS ( H` fn 48) on models that have it: not in phases 1-4; phase 5, if the owner says yes after a paper test. docs/plans/remote-printers.md decision 24 builds it at the agent with this phase 5 (its stage 6). The state machine is safe without it. Trade-off: it would turn most `uncertain` jobs into confirmed prints, but it holds the printer connection until the receipt is done, so `/healthz` needs another way to read status mid-job, and whether its answer gets through the printer's network board is unverified. 22. **ntfy state stays out of the store.** The JSON files stay. They write within a second of a change, and a keepalive-only cursor at most every 10 minutes, and the subscriber is built and tested on them. On a WebSocket each save also writes every seen ID within `max_backlog`, up to some 700 KB on a busy topic with a 12-hour backlog (docs/plans/ntfy.md decision 12). Trade-off: one file and one sync policy, against coupling ntfy to the store, which could write only the IDs that changed. -23. **A write error after part of a receipt went out.** Today such a send is retried, and design.md accepts that part of a receipt can then print twice, because retries let a job survive a printer that is briefly offline. That stays. docs/plans/remote-printers.md decision 17 builds on it: a remote `partial` outcome is today's write error. Once `Send` reports how many bytes `Write` took (docs/plans/printers.md stage 3's `SendError`, or phase 5's confirmed send), the owner may choose that such a job becomes `uncertain` and is never resent. Trade-off: fewer doubled fragments, against more jobs a person must check. With several printers, docs/plans/printers.md question 22 decides when such a delivery fails over to the next printer of an anycast list (Architecture, DELIVERIES AND SEVERAL PRINTERS). Its default, failover after the retries on the first printer, is a second double-print path: the next printer gets the whole receipt, so a receipt the first printer took in full before the write error prints in full on both. +23. **A write error after part of a receipt went out.** Today such a send is retried, and design.md accepts that part of a receipt can then print twice, because retries let a job survive a printer that is briefly offline. That stays. docs/plans/remote-printers.md decision 17 builds on it: a remote `partial` outcome is today's write error. Once `Send` reports how many bytes `Write` took (docs/plans/printers.md stage 3's `SendError`, or phase 5's confirmed send), the owner may choose that such a job becomes `uncertain` and is never resent. Trade-off: fewer doubled fragments, against more jobs a person must check. With several printers, docs/plans/printers.md decision 22 fails such a delivery over to the next printer of an anycast list after the retries on the first printer (Architecture, DELIVERIES AND SEVERAL PRINTERS). That is a second double-print path: the next printer gets the whole receipt, so a receipt the first printer took in full before the write error prints in full on both. ## Investigation findings @@ -248,7 +248,7 @@ Only by not syncing. Badger's saving with `SyncWrites=false` comes from leaving PRINT ACKNOWLEDGEMENT ON EPSON PRINTERS - design.md says ESC/POS gives no acknowledgement of what printed. Epson documents one: `GS ( H` fn 48, the process ID response. The host sends `1D 28 48 06 00 30 30 d1 d2 d3 d4` after the data. For print data, the printer answers `37 22 d1 d2 d3 d4 00` "when the printing is completed" (ESC/POS reference Ver. 10.01, p. 428-429). -- The TM-T88IV Technical Reference Guide (Rev. C) lists the command, and so does the TM-T88V's (Rev. E). Epson's model pages list it for the TM-T88IV to TM-T88VII, seen only in search extracts, since the pages refuse direct fetches. TM-m50II support is unconfirmed. +- The TM-T88IV Technical Reference Guide (Rev. C) lists the command, and so does the TM-T88V's (Rev. E). Epson's model pages list it for the TM-T88IV to TM-T88VII, seen only in search extracts, since the pages refuse direct fetches. The TM-m50II's command list includes it too (docs/plans/printers.md, Investigation findings), still unverified over port 9100. - Limits: - If the host misses responses, the printer sends only the latest ID. - Pending IDs are dropped when the buffers are cleared (`DLE DC4` fn 8, `DLE ENQ 2`) or the power goes off. @@ -257,7 +257,7 @@ PRINT ACKNOWLEDGEMENT ON EPSON PRINTERS - Unverified: whether the response reaches the host over port 9100 through the printer's Ethernet board (UB-E02 or UB-E03), and what happens to a response sent after the host closed the connection. Only a paper test can tell. - No other mechanism on raw port 9100 reports a job's progress. `DLE EOT`, automatic status (`GS a`) and `GS ( H` fn 49 report the printer's state. `GS r 1` answers once the preceding lines have fed, without an ID. ePOS-Print on newer models reports a print result over HTTP, a different transport. - Even a perfect acknowledgement leaves a window between the printer finishing and the daemon recording it, so the store must be safe without one. -- A side finding (an inference, unverified): the UB-E02 and UB-E03 boards turn automatic status on at power-on, and the `ESC @` that starts each job turns it off. Until the first job after a power-on, the printer may send unrequested 4-byte status frames, which `printer.Client.Status`, reading one byte per request, could take as "status unsupported". +- A side finding: the UB-E02 and UB-E03 boards turn automatic status on at power-on, and the `ESC @` that starts each job turns it off, as Epson's guides confirm (docs/plans/printers.md, Investigation findings). Until the first job after a power-on, the printer may send unrequested 4-byte status frames, which `printer.Client.Status`, reading one byte per request, could take as "status unsupported". Whether the frames reach a port 9100 client is unverified. WHERE THE REPORTS DISAGREE OR ARE UNSURE - WAL bytes per job: about 15 KB (spike: small table, no pruning), 20-40 KiB (the key-value track's estimate) and 57.7 KiB (SQLite track: full history with pruning). The setups differ; stage 1a measures the schema under RECORDS. @@ -301,15 +301,15 @@ WHAT SHIPS WHEN COMPATIBILITY - Without `state.dir` the queue stays in memory and behaves as today, waiting jobs failing at shutdown included. - Existing statuses keep their meaning; `uncertain`, `cancelled` (phase 2b) and the `sent_at` field are new. -- Job status keeps its shape until there are several printers; only then does it gain the `deliveries` array (Architecture, DELIVERIES AND SEVERAL PRINTERS). +- Job status gains the `deliveries` array with docs/plans/printers.md stage 1b, for every job, whatever the number of printers (its decision 8). - What prints does not change. TestRenderCompat and TestPaperReceipts keep passing. - The Docker image keeps a job store in `/var/lib/uberbringer`, so a container that cannot write there stops at start (decision 14, **Breaking**). - A downgrade: an older binary refuses `[state] dir` and `queue.content_bytes` as unknown keys and ignores `jobs.db`. The CHANGELOG and docs/configuration.md say so. INVARIANTS 1. Nothing reaches the printer unless the whole receipt rendered. -2. No byte goes to the printer before its delivery's `sending` mark is committed to the store, and synced when the store is durable. -3. A delivery that a client could have read as failed, `uncertain` or cancelled is never sent again without a new request. Nor, after a restart, is one that may have reached the printer. Within one run, before a delivery finishes, two paths resend one that may have reached the printer: the retries after a write error, as today, and an anycast failover after a `sending` mark, which the printers plan settles (decision 23). +2. No byte of the job goes to the printer before its delivery's `sending` mark is committed to the store, and synced when the store is durable. +3. A delivery that a client could have read as failed, `uncertain` or cancelled is never sent again without a new request. Nor, after a restart, is one that may have reached the printer. Within one run, before a delivery finishes, two paths resend one that may have reached the printer: the retries after a write error, as today, and an anycast failover after a `sending` mark, which docs/plans/printers.md decision 22 settles. 4. A status a client reads is never ahead of the store: memory changes only after the store's commit returns. 5. Print contents never reach logs or Sentry, and the store's errors never quote them. 6. printqueue never imports a database, so server and tools/genopenapi never compile one. @@ -532,7 +532,7 @@ DELIVERIES AND SEVERAL PRINTERS - broadcast: to every printer; - anycast: to one printer of an ordered list, as a priority list with failover: the first, on failure the second, then the third. - A job has one or more deliveries, one per printer it goes to, each tracked on its own. A multicast or broadcast job is one job with several deliveries; a unicast or anycast job has one. The state machine under JOB STATES applies to each delivery. The `Store` interface carries deliveries from stage 1c, and the database keeps them in a table of their own from stage 1d (RECORDS), so several deliveries per job need new rows, not new tables. Until the printers plan lands, every job has exactly one delivery, for the printer `default`. -- The printers plan settles whether it needs new columns, and so a schema step. A delivery's row stores one `printer` and nothing of its route: no mode, group or anycast list, so a restored anycast delivery's list must be derived again from the rules and the config. And a failover after a `sending` mark would overwrite `printer`, so the row would no longer show that the first printer got bytes, which TELLING WHICH RECEIPTS PRINTED relies on; keeping that needs a column or a row per printer tried. +- docs/plans/printers.md decision 18 stores the route: `route_by`, `route_rule` and `route_mode` on `jobs`, and `candidates` and `sent_to` on `deliveries`, in stage 1d's first schema or in a step to `user_version` 2. So a restored anycast delivery keeps its list, and a failover after a `sending` mark keeps the record that the first printer got bytes, which TELLING WHICH RECEIPTS PRINTED relies on. - A job's API `status` derives from its deliveries (decision 12). A delivery counts as taken from when the worker picks it up until it finishes: while it renders, waits for the printer's slot, dials, waits between retries or sends (decision 12): - Cancelled deliveries (phase 2b) are passed over unless every delivery is cancelled; then the job is `cancelled`. The rest of the rule reads the other deliveries. - `queued` while every one waits, none taken and none finished; @@ -540,11 +540,11 @@ DELIVERIES AND SEVERAL PRINTERS - once every one has finished: `uncertain` if any is, since it means a receipt may have printed; otherwise `failed` if any is; otherwise `done`. So `failed` and `uncertain` stay final, as today: a failed or `uncertain` delivery beside one that still waits or prints leaves the job `printing`, and one cancelled delivery beside done ones reads `done`. With one delivery, the job's status is the delivery's. -- Once there are several printers, the status gains a `deliveries` array, one entry per delivery with its `printer`, `status`, `sent_at` and `error`. Until then the status looks as this plan describes, its fields those of the one delivery. What the job's own `sent_at`, `attempts` and `error` hold beside the array is for the printers plan. -- Anycast: a delivery's printer is chosen when it is dispatched, and its row records the printer used. Before any byte was sent, a failure fails over to the next printer at once: the delivery moves to it and no `sending` mark is written, just as a dial failure writes nothing today. After a `sending` mark, the default is the existing retry rule on that printer, then failover to the next; the printers plan settles this. That failover can print a whole receipt on two printers (decision 23). A queued delivery restored after a restart starts again from the top of its list (assumed), which the rules and the config give again at restore, since the row stores no list. -- One store per instance. Each delivery names its printer, so the printers plan can use one store, with one queue and worker per printer, each loading its own unfinished deliveries. +- From docs/plans/printers.md stage 1b, every status gains a `deliveries` array, one entry per delivery with its `printer`, `status`, `attempts`, `started_at`, `sent_at`, `finished_at` and `error`, and the job's own fields sum or pick from them (its decision 8). Until then the status looks as this plan describes, its fields those of the one delivery. +- Anycast: a delivery's printer is chosen when it is dispatched, and its row records the printer used. Before any byte was sent, a failure fails over to the next printer at once: the delivery moves to it and no `sending` mark is written, just as a dial failure writes nothing today. After a `sending` mark, the existing retry rule on that printer runs, then failover to the next (docs/plans/printers.md decision 22). That failover can print a whole receipt on two printers (decision 23). A queued delivery restored after a restart starts again from the top of its stored list (printers decision 18). +- One store per instance. Each delivery names its printer, so one store serves every printer: one queue with a lane and a worker per printer, each loading its own unfinished deliveries (docs/plans/printers.md decision 4). - Job IDs stay global, so `GET /api/v1/jobs/{id}` needs no printer. -- The stored job is printer-neutral (formatters invariant 1) and rendered bytes are not stored, so a queued delivery can move to another printer. A printer removed from the config while deliveries wait for it needs a rule; the printers plan settles it. +- The stored job is printer-neutral (formatters invariant 1) and rendered bytes are not stored, so a queued delivery can move to another printer. A queued delivery whose printer was removed from the config fails at restore (docs/plans/printers.md decision 5). - Acknowledgement IDs are counted per printer. - `cancelled` comes with phase 2b, as a delivery's state; the `deliveries.state` column takes it without a schema change. - Two instances must not share a state directory. Exclusive locking makes the second fail at start; today they would also share the `ntfy-.json` files. Until one instance drives several printers, each instance gets its own directory. @@ -825,6 +825,7 @@ internal/pkg/printqueue - The cancel leaves alone a delivery that has reached `sending` or finished. It commits the others `cancelled` in one synced commit (Architecture, JOB STATES), which drops what the cancel pushes out of retention as `Finish` does; then memory changes, they leave the waiting list, and their contexts end, so rendering, waiting for the printer's slot and dialling stop. - The worker of a cancelled delivery stops with no retry, no `Finish`, no "job failed" line and no `OnFailure`, since the cancel's commit is its final state: `errCancelled` from `Send` is never retried, and an error after its context ended ("rendering: context canceled", "giving up after n attempts") finds the delivery `cancelled` under the lock. - A store error stops the queue (decision 11). + - If docs/plans/printers.md stage 3 has shipped, a delivery with any `sending` mark is not cancellable, even while it waits on the next printer of an anycast list, and a move takes the delivery lock (its decision 26). - A cancelled job counts as finished for retention. An ntfy job keeps its reference (decision 10), so a replay after a restart does not queue it again. - store.go: `StoredState` gains `cancelled`, and `Store` gains `Cancel(ctx, deliveries []uint64, at time.Time, dropJobs, dropDeliveries, dropContent []uint64) error`, one synced commit. The memory store implements it. @@ -945,7 +946,7 @@ internal/pkg/paper **Work.** internal/pkg/receipt -- `Renderer.PreviewImage`: `base64` images from their data, `url` images fetched through safehttp under one 30-s deadline for the whole preview, a crossed box for each image that failed or is still loading. +- `Renderer.PreviewImage`: `base64` images from their data, `url` images fetched through safehttp under one 30-s deadline for the whole preview, a crossed box for each image that failed or is still loading. It draws with the profile the text preview uses: the named printer's, or the default printer's. internal/app/uberbringer/server - `Previewer` gains `PreviewImage`. handlers_preview.go answers `image/png` when asked; text stays the default. The cap's error answers `422` `preview_too_long` (errors.go). Check that the compress middleware leaves PNG alone. @@ -983,7 +984,7 @@ internal/pkg/printqueue - `Content(id)`: the stored job, `ErrNotFound` or `ErrContentGone`. internal/app/uberbringer/server -- The route `GET /api/v1/jobs/{id}/preview` in the table, for full tokens. It decodes the stored job strictly and answers through the same negotiation as the POST preview. `Jobs` gains `Content`, and `fakeJobs` with it. +- The route `GET /api/v1/jobs/{id}/preview` in the table, for full tokens. It renders with the profile of its first delivery's printer. It decodes the stored job strictly and answers through the same negotiation as the POST preview. `Jobs` gains `Content`, and `fakeJobs` with it. - errors.go: `410` `job_content_expired`. Docs @@ -1016,7 +1017,7 @@ Docs - escpos: `ProcessIDRequest(id)` and a frame reader for real-time status, automatic status, process IDs, clear responses and unknown blocks. - printer: a confirmed send with its four outcomes, using the count `Write` returns. `Status` reads through the frame reader and skips frames it did not ask for. - `/healthz` while a job holds the connection. - - Config: `printer.confirm` (`auto`, `process_id` or `off`) and `printer.confirm_timeout`. Status gains `confirmed_at`. The store keeps the ID counter. + - Config: `printer.confirm` (`auto`, `process_id` or `off`) and `printer.confirm_timeout`, in each printer's table (docs/plans/printers.md decision 3). Status gains `confirmed_at`. The store keeps the ID counter. - The partial-write choice (decision 23), once the confirmed send reports the bytes written. - ntfy state in the store (decision 22). - An `Idempotency-Key` header on `POST /api/v1/print`. diff --git a/docs/plans/printers.md b/docs/plans/printers.md index ead5c79..a969a0a 100644 --- a/docs/plans/printers.md +++ b/docs/plans/printers.md @@ -1,12 +1,12 @@ # Plan: several printers, routed by Expr rules -Status: **planning; nothing is built.** This plan builds on docs/plans/job-store.md and does not redesign its store. Stages 1a to 3 need that plan's stage 1c: jobs with deliveries, the waiting list, `beforeWrite` and the memory store. None needs its durable store (job-store stage 1d). Where that has shipped, question 5's restore rule applies to it, and stage 2a adds a schema step (question 18). Each stage runs in its own session, briefed from its section, once the owner has answered the questions listed for it or accepted their assumed defaults: -- stage 1a needs questions 1-5, and stage 1b needs 7-9; -- stage 2a needs 11-16, 18 and 19, stage 2b needs 20, and stage 2c needs 21; -- stage 3 needs 22-26, and question 23's paper check; -- stage 4a needs 27-29, and stage 4b needs 30 and 31. Question 31 is also needed before the first receipt on a new printer. +Status: **planned; nothing is built.** The owner accepted every proposed default on 2026-12-01 (Decisions), and design.md's Planned next item 2 records them. This plan builds on docs/plans/job-store.md and does not redesign its store. Stages 1a to 3 need that plan's stage 1c: jobs with deliveries, the waiting list, `beforeWrite` and the memory store. None needs its durable store (job-store stage 1d). Where that has shipped, decision 5's restore rule applies to it, and stage 2a adds a schema step (decision 18). Each stage runs in its own session, briefed from its section: +- stage 1a follows decisions 1-6, and stage 1b decisions 7-9; +- stage 2a follows decisions 10-19, stage 2b decision 20, and stage 2c decision 21; +- stage 3 follows decisions 22-26, after decision 23's paper check; +- stage 4a follows decisions 27-29, and stage 4b decisions 30 and 31. The status sheet of decision 31 is also read before the first receipt on a new printer. -Questions 6, 10 and 17 are settled by plans the owner has accepted since, and say so where they stand, so that the numbers other plans cite still hold. Each answer goes into design.md at once and leaves this list. The stages run in the order listed, except that stages 2b and 2c each need only 2a. Stage 4a needs only the TM-T88VII on hand, which can be the default printer until stage 1a ships. Stage 4b runs once for each new model as it arrives; it needs 4a only when a value differs between models of one family. Every check on a real printer, of its paper or of its status, needs the owner's OK. When the owner accepts the plan, the edits under Overview, ON ACCEPTANCE, are made. Whichever stage finishes last deletes this plan, its findings with it, and design.md's Planned next item 2. +The stages run in the order listed, except that stages 2b and 2c each need only 2a. Stage 4a needs only the TM-T88VII on hand, which can be the default printer until stage 1a ships. Stage 4b runs once for each new model as it arrives; it needs 4a only when a value differs between models of one family. Every check on a real printer, of its paper or of its status, needs the owner's OK. Whichever stage finishes last deletes this plan, its findings with it, and design.md's Planned next item 2. ## Decisions (owner, 2026-11-30) @@ -19,17 +19,17 @@ Questions 6, 10 and 17 are settled by plans the owner has accepted since, and sa against a typed environment (`expr.Env(EnvPrototype())`, `expr.AsBool()`), orders rules by priority, has an enabled flag, swaps the rule set atomically on reload, skips and logs a rule that fails to - compile, and has a dry-run. + compile (decision 14 makes that a config error here), and has a + dry-run. - **A rule's action sends a job in one of four delivery modes:** unicast (one printer); multicast (each printer in a named set, "one to some"); broadcast (every printer); and anycast (one printer from an ordered list). - **Anycast is a priority list with failover:** try the first printer, on failure the second, then the third. A failure before any byte was sent - fails over at once. After bytes were sent, the assumed default is the - existing retry rule on that printer, then failover. job-store.md - decision 23 names the double-print risk this carries; this plan settles - it as an open question (question 22). + fails over at once. After bytes were sent, the existing retry rule on + that printer runs, then failover. job-store.md decision 23 names the + double-print risk this carries; decision 22 settles it. - **A multicast or broadcast job is one job with several deliveries,** one per printer, each tracked on its own. job-store.md already plans that model (its DELIVERIES AND SEVERAL PRINTERS section, decision 12 on a @@ -39,115 +39,98 @@ Questions 6, 10 and 17 are settled by plans the owner has accepted since, and sa - **A job that matches no rule goes to the default printer,** so today's single-printer config keeps working. -## Open questions +The owner accepted the details below on 2026-12-01. They are numbered, so the rest of the plan can refer to them. Decision 6 follows docs/plans/remote-printers.md decision 16, and decisions 10 and 17 follow docs/plans/templates.md decisions 1 and 6. -Each has the default the plan assumes unless the owner says otherwise. +For stage 1a: -Before stage 1a: - -1. **Today's `[printer]` table.** Assumed: it stays, and it is the printer named `default`. `[printers.]` tables add the others. The name `default` is reserved, so `[printers.default]` is refused with a message that points to `[printer]`. +1. **Today's `[printer]` table stays,** and it is the printer named `default`. `[printers.]` tables add the others. The name `default` is reserved, so `[printers.default]` is refused with a message that points to `[printer]`. - Nothing needs migrating. install.sh writes `[printer] address` and keeps an existing config on a re-run. `UBERBRINGER_PRINTER_*` keep their meaning in Docker. `?printer=default` keeps working on the module routes. job-store.md's planned delivery rows name `default`. The CHANGELOG lists it under Added. - - docs/plans/remote-printers.md decision 16 builds on this default: `[printer]` may be remote, through `agent` and `UBERBRINGER_PRINTER_AGENT`. + - docs/plans/remote-printers.md decision 16 builds on this: `[printer]` may be remote, through `agent` and `UBERBRINGER_PRINTER_AGENT`. - Trade-off: two table shapes, and the default printer cannot be renamed. - - Alternatives: move it into `[printers.default]`, as formatters phase 5 sketched. That is **Breaking** for every deployed config: `[printer]` becomes an unknown key, the daemon stops at start after an upgrade, and install.sh parses no TOML to migrate it. Or accept both and refuse a config with both: a shim, and unclear which variables win. Or `[printer]` as defaults the others inherit: inheriting an address makes no sense, and inheritance hides which values a printer uses. -2. **Printer names, and no variables for named printers.** Assumed: a name follows the subscriptions' rule, `^[a-z0-9][a-z0-9_-]{0,31}$`. It is checked on the raw TOML key, because Viper lowercases map keys: `[printers.Office]` would otherwise load silently as `office`. `[printers.*]` comes from the file only, as `[[ntfy.subscriptions]]` does. The default printer keeps its `UBERBRINGER_PRINTER_*` variables. No key reads a `UBERBRINGER_PRINTERS_*` variable, so at start one WARN line names any that is set, never its value; from stage 2a it names `UBERBRINGER_ROUTING_*` variables too. They are ours, and a Docker user could otherwise set one and never learn it does nothing. - - The accepted plans follow this default: docs/plans/remote-printers.md decisions 6 and 11 read `[agents.]` and the agent's printer tables from the file only, and docs/plans/templates.md decision 3 gives its sections the same WARN. +2. **Printer names, and no variables for named printers.** A name follows the subscriptions' rule, `^[a-z0-9][a-z0-9_-]{0,31}$`. It is checked on the raw TOML key, because Viper lowercases map keys: `[printers.Office]` would otherwise load silently as `office`. `[printers.*]` comes from the file only, as `[[ntfy.subscriptions]]` does. The default printer keeps its `UBERBRINGER_PRINTER_*` variables. No key reads a `UBERBRINGER_PRINTERS_*` variable, so at start one WARN line names any that is set, never its value; from stage 2a it names `UBERBRINGER_ROUTING_*` variables too. They are ours, and a Docker user could otherwise set one and never learn it does nothing. + - docs/plans/remote-printers.md decisions 6 and 11 read `[agents.]` and the agent's printer tables from the file only, and docs/plans/templates.md decision 3 gives its sections the same WARN. - Trade-off: a container with several printers needs a mounted config, as one with subscriptions does, and a named printer's address cannot come from a variable. - - Alternatives: bind `UBERBRINGER_PRINTERS__` after the file is read, for the printers it names (the probe shows this works; a name with `-` gives a variable no POSIX shell can set). Or declare printers by scanning the environment, which rules out `-` in names and needs a test that no printer key ends another after an `_`. The module names' rule, `^[a-z][a-z0-9-]{0,31}$`, is the other candidate pattern. -3. **Which keys belong to each printer.** Assumed: every key of today's `[printer]`: `address`, `port`, `model`, `codepage`, `paper_width`, `columns`, `box_line_spacing`, `cut_feed`, `dial_timeout`, `write_timeout`, `retries` and `retry_delay`. A `[printers.]` table starts from the same defaults as `[printer]`, not from `[printer]`'s values, and only `address` is required. `format.*`, `images.*`, `queue.*` and `ntfy.*` stay global. docs/plans/remote-printers.md decision 16 adds `agent`: a remote printer names its agent in place of `address` and `port`, and keeps the other keys. +3. **Which keys belong to each printer.** Every key of today's `[printer]`: `address`, `port`, `model`, `codepage`, `paper_width`, `columns`, `box_line_spacing`, `cut_feed`, `dial_timeout`, `write_timeout`, `retries` and `retry_delay`. A `[printers.]` table starts from the same defaults as `[printer]`, not from `[printer]`'s values, and only `address` is required. `format.*`, `images.*`, `queue.*` and `ntfy.*` stay global. docs/plans/remote-printers.md decision 16 adds `agent`: a remote printer names its agent in place of `address` and `port`, and keeps the other keys. - `model` and `codepage` are checked when the config loads, by one helper in internal/app that the start, `config get` and `preview` share. Today they are checked only at start, so `config get` passes a bad model and install.sh restarts the daemon into the error. - Two printers may not share an address and port, `[printer]` included; hosts are compared without regard to case. Each table gets its own client and connection slot, and a printer prints from one connection at a time. A second connection's data waits until the first closes, its writes stall until `write_timeout`, and its status reads time out (`503` if one of them is the default printer). Two names that resolve to one address cannot be caught. The rule covers local printers only, since main cannot see where a remote one is; the agent refuses two of its own printers at one address and port (remote-printers decision 16). - Trade-off: `format.max_lines` is global, so a multicast job that wraps into more lines on a narrower printer can fail there and print on the others. One image fetcher serves every printer. - - Alternatives: per-printer `format.*`, which nothing asks for; for a repeated address, one client shared by both lanes. -4. **One queue with a lane per printer.** Assumed: one `printqueue.Queue`. Each printer is a lane with its own waiting list, worker, renderer, sender, retries and retry delay. The submit lock, the status map, the history, the references of ntfy jobs and the store stay shared, so a job with several deliveries is one `Store.Add` commit, as job-store.md plans. `queue.size` bounds each lane, so a dead printer's backlog cannot refuse jobs for the others (question 19 for multicast and broadcast). Order is first in, first out per printer. +4. **One queue with a lane per printer.** One `printqueue.Queue`. Each printer is a lane with its own waiting list, worker, renderer, sender, retries and retry delay. The submit lock, the status map, the history, the references of ntfy jobs and the store stay shared, so a job with several deliveries is one `Store.Add` commit, as job-store.md plans. `queue.size` bounds each lane, so a dead printer's backlog cannot refuse jobs for the others (decision 19 for multicast and broadcast). Order is first in, first out per printer. A Pool of independent queues would suit unicast only: a multicast job would have a status in each queue, capacity could not be checked across them at once, history would be evicted per queue, and anycast could not move a job between channels. - Trade-off: no global order; a broadcast prints at different times on each printer. A host with three printers can hold three times `queue.size` jobs. With a durable store, unfinished content can reach N × `queue.size` × 4 MiB: about 1.2 GiB for three printers at the defaults, where job-store decision 9 counts about 400 MiB for one. A unicast rule or a `?printer=` to a dead printer still refuses jobs once its lane is full, and an ntfy subscription whose jobs go there stops reading, as it does today when the one printer is dead. - - Alternatives: formatters phase 5's Pool of independent queues. It suits unicast only: a multicast job would have a status in each queue, capacity could not be checked across them at once, history would be evicted per queue, and anycast could not move a job between channels. For capacity, one global `queue.size`. -5. **A printer removed from the config while deliveries wait for it** (job-store.md, DELIVERIES AND SEVERAL PRINTERS). It matters once the store is durable. Assumed: at restore, a queued delivery whose printer is no longer configured fails, in a synced commit, with an error naming the printer, and one WARN line by `job_id` and `printer`. Finished deliveries, `uncertain` ones included, stay as history. An anycast delivery drops the missing printers from its list and fails only when none is left (stage 3). +5. **A printer removed from the config while deliveries wait for it** (job-store.md, DELIVERIES AND SEVERAL PRINTERS). It matters once the store is durable. At restore, a queued delivery whose printer is no longer configured fails, in a synced commit, with an error naming the printer, and one WARN line by `job_id` and `printer`. Finished deliveries, `uncertain` ones included, stay as history. An anycast delivery drops the missing printers from its list and fails only when none is left (stage 3). Refusing to start would stop every printer over one, and the default printer is a room nobody chose. - 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. Settled** by docs/plans/remote-printers.md decision 16, which makes a printer remote with a key of its own, `agent`: no `kind` key and no address scheme. 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 `agent` key 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. +6. **The seam for remote printers.** docs/plans/remote-printers.md decision 16 makes a printer remote with a key of its own, `agent`: no `kind` key and no address scheme. 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 `agent` key 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. -Before stage 1b: +For stage 1b: -7. **`?printer=` on `/print` and `/preview`.** Assumed: `POST /api/v1/print` and `POST /api/v1/preview` read `printer`, as the module routes already do. An empty value means the default printer, as on the module routes today. A name matches only as configured, so `Office` is not `office`. A name that is not a configured printer, a group's name included, answers `400` `unknown_printer`. A parameter given twice, or any other parameter, answers `400` `invalid_query`. A preview renders for the named printer, or for the default printer without one. +7. **`?printer=` on `/print` and `/preview`.** `POST /api/v1/print` and `POST /api/v1/preview` read `printer`, as the module routes already do. An empty value means the default printer, as on the module routes today. A name matches only as configured, so `Office` is not `office`. A name that is not a configured printer, a group's name included, answers `400` `unknown_printer`. A parameter given twice, or any other parameter, answers `400` `invalid_query`. A preview renders for the named printer, or for the default printer without one. - Refusing other parameters is **Breaking**: a client that sends `/print?x=1` gets `400`. It matches the module routes, where a typo must not be ignored; here a mistyped `printr=office` would print in the wrong room. - Any token that may print may name any printer. A token claim that limits printers can come later. - Trade-off: the break above. A preview without `printer` lays the job out for the default printer, even when the rules would send it elsewhere; from stage 2c the JSON preview's `route` says where it would go. - - Alternatives: ignore other parameters, as today; or render a preview for the first printer of the route the rules give. -8. **A job's status with several deliveries.** Assumed: from stage 1b, every status gains `deliveries`, whatever the number of printers configured, so a client's parsing does not depend on the config. Each entry gives a delivery's `printer`, `status`, `attempts`, `started_at`, `sent_at`, `finished_at` and `error`. The job's `status` follows job-store decision 12. Beside the array, the job's own fields read: +8. **A job's status with several deliveries.** From stage 1b, every status gains `deliveries`, whatever the number of printers configured, so a client's parsing does not depend on the config. Each entry gives a delivery's `printer`, `status`, `attempts`, `started_at`, `sent_at`, `finished_at` and `error`. The job's `status` follows job-store decision 12. Beside the array, the job's own fields read: - `attempts`: the sum; - `started_at` and `sent_at`: the earliest; - `finished_at`: the latest, once every delivery has finished; - `error`: that of the first failed or `uncertain` delivery, prefixed with its printer's name when the job has more than one. - Trade-off: one more field on every status. - - Alternative: the array only on a job with several deliveries, as job-store.md's COMPATIBILITY assumes, and the job's own fields then left empty. -9. **`/healthz` per printer.** Assumed: `status` and the HTTP code follow the default printer alone, as today, and `printer` stays the default printer's health. A new `printers` array lists every printer, the default first, then by name. Each entry has `name`, `default`, `model` as configured, the fields `printer` has, and its own `pending`. `queue.pending` is the total. No address appears, since the route is public. There is no `?printer=` on `/healthz`. +9. **`/healthz` per printer.** `status` and the HTTP code follow the default printer alone, as today, and `printer` stays the default printer's health. A new `printers` array lists every printer, the default first, then by name. Each entry has `name`, `default`, `model` as configured, the fields `printer` has, and its own `pending`. `queue.pending` is the total. No address appears, since the route is public. There is no `?printer=` on `/healthz`. - The default printer is read once, and that one settled read fills both `printer` and the first entry. Two reads would queue on its one slot. With a second read 750 ms later for each, they could pass the 3-s bound, turning a `200` into a `503` `timeout`. - The others are read in parallel, each within the same bound, so a slow one cannot make the others time out. - A dial that times out reads as `timeout`, as today: Go's dial time-out error matches `context.DeadlineExceeded`. So a host that does not answer can show `timeout` rather than `unreachable`, since the 5-s dial outlasts the 3-s bound. - - docs/plans/remote-printers.md decision 10 builds on this default: `/healthz` gains `agents`, a remote printer's entry gains `agent`, and the code still follows the default printer alone. + - docs/plans/remote-printers.md decision 10 builds on this: `/healthz` gains `agents`, a remote printer's entry gains `agent`, and the code still follows the default printer alone. - Trade-off: a monitor alerts on another printer only by reading the body. A health read takes that printer's connection slot for up to 3 s and delays only its own lane. The public route now shows printer names, often room names, and models. - - Alternative: `/healthz?printer=`, whose code follows that printer, with an error for an unknown name. It goes beyond what was asked. -Before stage 2a: +For stage 2a: -10. **Expr's version, and the size it adds. Settled** by docs/plans/templates.md decision 1: `github.com/expr-lang/expr` comes in at its latest stable release, v1.18.1 (2026-11-22) at the time of writing, with govulncheck, in whichever of this plan's stage 2a and that plan's stage 1 comes first. v1.18.0 and v1.18.1 fixed five advisories rated High that affect v1.17.8, Kanrisha's pin. The binary grows by about 5.3-5.8 MB (+36-37%) on every target, armv6 included, which that decision and docs/plans/remote-printers.md decision 4 accept. +10. **Expr's version, and the size it adds.** docs/plans/templates.md decision 1: `github.com/expr-lang/expr` comes in at its latest stable release, v1.18.1 (2026-11-22) at the time of writing, with govulncheck, in whichever of this plan's stage 2a and that plan's stage 1 comes first. v1.18.0 and v1.18.1 fixed five advisories rated High that affect v1.17.8, Kanrisha's pin. The binary grows by about 5.3-5.8 MB (+36-37%) on every target, armv6 included, which that decision and docs/plans/remote-printers.md decision 4 accept. - About half is Expr itself. The rest is other packages' methods that the linker can no longer drop, because Expr calls `reflect.Value.MethodByName` with a name that is not a constant. GORM has the same effect (job-store decision 1). It applies once per binary, so with Expr linked, GORM's extra cost over plain SQL falls to about its own code. - The size was measured with v1.17.8 from the module cache. The stage that first links Expr into the binary records the size with the version it pins, from the snapshot build. - Trade-off: a larger tarball and image, and more to load on a Pi. -11. **The config's shape.** Assumed: a `[routing]` section. `[routing.groups]` maps a group's name to its printers. Each `[[routing.rules]]` has `name`, `order`, `when`, `mode`, `to` and `enabled`. A rule's name follows the printer names' rule and is unique, so logs and `route` name one rule. `to` takes a name or a list, as list keys do. `when` is best written as a TOML literal string, so Expr's double quotes need no escaping. Both come from the file only: a list of tables has no variable, and a table of lists does not fit the `name=value` form, as the probe showed. +11. **The config's shape.** A `[routing]` section. `[routing.groups]` maps a group's name to its printers. Each `[[routing.rules]]` has `name`, `order`, `when`, `mode`, `to` and `enabled`. A rule's name follows the printer names' rule and is unique, so logs and `route` name one rule. `to` takes a name or a list, as list keys do. `when` is best written as a TOML literal string, so Expr's double quotes need no escaping. Both come from the file only: a list of tables has no variable, and a table of lists does not fit the `name=value` form, as the probe showed. - Not `[[routes]]` and a top-level `[groups]`: "route" already means an HTTP route in server/routes.go, CLAUDE.md and api.md. A `[routing]` section also gives later keys a home. - - docs/plans/templates.md decisions 12 and 23 shape their rules on this default: `[[ntfy.rules]]`, and `[[webhooks.rules]]` beside the hooks in `[webhooks]`, as these sit in `[routing]` beside the groups. + - docs/plans/templates.md decisions 12 and 23 shape their rules on this: `[[ntfy.rules]]`, and `[[webhooks.rules]]` beside the hooks in `[webhooks]`, as these sit in `[routing]` beside the groups. - Trade-off: one more level in the file. - - Alternatives: `[[routes]]` and `[groups]`, which load the same way; or a key per mode (`printer`, `printers`, `group`) in place of `to`. -12. **Rule order.** Assumed: `order` is a required integer, unique across all rules, disabled ones included, lower first, as Kanrisha's priority; the first match wins. A disabled rule's `order` is unique too, so enabling it cannot break a start. It is not called `priority`, which a rule's `when` already uses for the ntfy priority. A unique `order` avoids Kanrisha's `sort.Slice`, which is not stable, so there rules of equal priority run in no fixed order. - - docs/plans/templates.md decisions 1 and 12 lean on this default: its ntfy and webhook rules take the same `order` through the shared engine. +12. **Rule order.** `order` is a required integer, unique across all rules, disabled ones included, lower first, as Kanrisha's priority; the first match wins. A disabled rule's `order` is unique too, so enabling it cannot break a start. It is not called `priority`, which a rule's `when` already uses for the ntfy priority. A unique `order` avoids Kanrisha's `sort.Slice`, which is not stable, so there rules of equal priority run in no fixed order. + - docs/plans/templates.md decisions 1 and 12 follow this: its ntfy and webhook rules take the same `order` through the shared engine. - Trade-off: inserting a rule can mean renumbering; gaps of 10 help. - - Alternatives: an optional `order`, sorted stably, ties broken by position in the file. Or the order in which the rules are written, with no number, which departs from the owner's decision that rules are ordered by priority. -13. **Groups, and what `to` takes.** Assumed: groups hold printers, never other groups, so no cycle can form. Groups and printers share one namespace, since `to` can name either; a group named like a printer, or `default`, is an error. A group is not empty, repeats no member and names configured printers. `to` by mode: +13. **Groups, and what `to` takes.** Groups hold printers, never other groups, so no cycle can form. Groups and printers share one namespace, since `to` can name either; a group named like a printer, or `default`, is an error. A group is not empty, repeats no member and names configured printers. `to` by mode: - unicast: exactly one printer; - multicast: one or more printers or groups, expanded, a repeated printer kept once; - broadcast: nothing; it means every configured printer; - anycast (stage 3): one or more printers or groups, in order, a group expanded in its member order, the first copy of a repeated printer kept. - - Trade-off: lists repeat where nested groups would not. Nesting needs a cycle check whose error names the cycle. -14. **A rule that fails to compile.** Assumed: a config error. The start fails, and so does `config get`, listing every problem with the rule's name, Expr's position and its message, for example `routing.rules[1] ("alerts").when: unknown name sorce (1:1)`. The source line Expr adds under its message is left out, since it could quote a topic. Expr's message itself can still quote a name or a constant pattern from the rule. Disabled rules are compiled too, so enabling one cannot break a start. On a reload (question 20), the new set is refused whole and the old one kept. - - This departs from the owner's decision as worded, which takes Kanrisha's "skips and logs a rule that fails to compile"; accepting this default amends it. Kanrisha's rules are database rows that must not stop the archiver. Here they sit in a file whose unknown keys already stop the start, and a skipped rule would send its jobs to the default printer without a word: paper in the wrong room. - - docs/plans/templates.md decision 1 leans on this default, and its decision 9 makes a template that fails at load a config error too. + - Trade-off: lists repeat where nested groups would not. +14. **A rule that fails to compile is a config error.** The start fails, and so does `config get`, listing every problem with the rule's name, Expr's position and its message, for example `routing.rules[1] ("alerts").when: unknown name sorce (1:1)`. The source line Expr adds under its message is left out, since it could quote a topic. Expr's message itself can still quote a name or a constant pattern from the rule. Disabled rules are compiled too, so enabling one cannot break a start. On a reload (decision 20), the new set is refused whole and the old one kept. + - This amends the owner's decision as worded, which took Kanrisha's "skips and logs a rule that fails to compile". Kanrisha's rules are database rows that must not stop the archiver. Here they sit in a file whose unknown keys already stop the start, and a skipped rule would send its jobs to the default printer without a word: paper in the wrong room. + - docs/plans/templates.md decision 1 follows this, and its decision 9 makes a template that fails at load a config error too. - Trade-off: one broken rule stops the daemon at start. - - Alternative: Kanrisha's skip and log, as the decision words it. -15. **A rule that fails at run time.** Assumed: as in Kanrisha, the rule counts as not matched and the next rule is tried. One WARN line gives the `job_id`, the rule's name, and the line and column from Expr's `*file.Error`. It never calls `Error()`, whose text carries the rule's source and quotes values from the env: the probe's `int(topic)` gave `invalid operation: int(alerts-door)`, and a topic can be a secret. An error of any other type logs the rule's name only. It is reported to Sentry once per rule per run, without the message. A panic while the env is built is recovered: logged at ERROR, reported once, and the job goes to the default printer, since on the ntfy path a panic would end the daemon. - - docs/plans/templates.md decisions 1, 8 and 14 lean on this default: a template's or an ntfy rule's failure is logged and reported the same way. +15. **A rule that fails at run time** counts as not matched, as in Kanrisha, and the next rule is tried. One WARN line gives the `job_id`, the rule's name, and the line and column from Expr's `*file.Error`. It never calls `Error()`, whose text carries the rule's source and quotes values from the env: the probe's `int(topic)` gave `invalid operation: int(alerts-door)`, and a topic can be a secret. An error of any other type logs the rule's name only. It is reported to Sentry once per rule per run, without the message. A panic while the env is built is recovered: logged at ERROR, reported once, and the job goes to the default printer, since on the ntfy path a panic would end the daemon. Refusing the job instead would lose jobs. + - docs/plans/templates.md decisions 1, 8 and 14 follow this: a template's or an ntfy rule's failure is logged and reported the same way. - Trade-off: the log does not say what went wrong; `uberbringer route` shows the whole message on the terminal. - - Alternatives: refuse the job, which is louder but loses jobs. Or list the rules that failed, by name, in the job's `route`, so that a job sent to `default` because a rule broke shows without the logs; that needs one more stored column, or a field a restart loses. -16. **What a rule sees.** Assumed: the variables under Architecture, THE ENVIRONMENT: routing facts only. No print content, no token or secret, no `ref`, no client address and no printer state. Stage 2a gives the job's source, shape and clock; stage 2c adds a notification's topic, priority and tags and the token's subject. In particular: +16. **What a rule sees.** The variables under Architecture, THE ENVIRONMENT: routing facts only. No print content, no token or secret, no `ref`, no client address and no printer state. Stage 2a gives the job's source, shape and clock; stage 2c adds a notification's topic, priority and tags and the token's subject. In particular: - `client` is the token's subject. It is free text chosen when the token is minted, and two tokens can share it. - `priority` is 0 for a job that is not a notification. With 3, ntfy's default, `priority >= 3` would match plain jobs. - A digest's `priority` is its highest row's, and its `topics` and `tags` the union of its rows'. - - `topic`, `topics` and `tags` also print on a card, and a topic can be a secret. They are in the env because routing notifications by them is the main use. The facts are used at `Submit` only: they are never kept in the job's status, logged, stored or sent to Sentry, and neither is the env or an Expr run-time message (question 15). - - Printer readiness stays out. Reading it at `Submit` would wait for each printer's connection slot, and flap with the passing states Epson printers report while cutting. It would come at the wrong moment, since the job prints later, and give another answer in a dry-run or after a restart. Only anycast acts on it, when it sends (questions 23 and 24). - - The rules of docs/plans/templates.md, for ntfy messages and webhooks, see print contents (its decision 14). A routing rule still sees routing facts only. + - `topic`, `topics` and `tags` also print on a card, and a topic can be a secret. They are in the env because routing notifications by them is the main use. The facts are used at `Submit` only: they are never kept in the job's status, logged, stored or sent to Sentry, and neither is the env or an Expr run-time message (decision 15). + - Printer readiness stays out. Reading it at `Submit` would wait for each printer's connection slot, and flap with the passing states Epson printers report while cutting. It would come at the wrong moment, since the job prints later, and give another answer in a dry-run or after a restart. Only anycast acts on it, when it sends (decisions 23 and 24). + - Print content stays out too: Expr's messages and a dry-run would then quote it, and a 4 MiB body in a string builtin can exceed Expr's memory budget, so the same rule would fail only on big jobs. The rules of docs/plans/templates.md, for ntfy messages and webhooks, see print contents (its decision 14); a routing rule still sees routing facts only. - Trade-off: no rule can say "multicast when the kitchen is out of paper". - - Alternative: content in the env too, for routing by what a job says. Expr's messages and a dry-run would then quote it, and a 4 MiB body in a string builtin can exceed Expr's memory budget, so the same rule would fail only on big jobs. -17. **Compile options and the clock. Settled** by docs/plans/templates.md decision 6, whose options are this question's, shared through `rules.Options`: `expr.DisableBuiltin("now")`, `expr.DisableBuiltin("$env")`, Expr's default node limit (10,000) and memory budget (1,000,000 per run), and `expr.Timezone` with `format.timezone` once validation has loaded the zone, since it panics on an unknown name. A routing rule adds `expr.Env(routing.Env{})` and `expr.AsBool()`, as the owner's decision has it. The clock is injected: `now` is the job's acceptance time in `format.timezone`, so a dry-run with `--at` and the tests reproduce any decision. - - The shared options carry that decision's iteration guard, so routing rules have it too: a budget of 1,000,000 iterations per run, charged by a `Patch` visitor around every predicate builtin and the right side of `in`. Expr itself has no step limit: nested predicates over large literal ranges, such as `any(1..999, any(1..999, # < 0))`, took about 30 ms, and one more level would take seconds here and minutes on a Pi, on every job. With the guard, such a rule fails at run time, as question 15 has it, instead. +17. **Compile options and the clock.** docs/plans/templates.md decision 6 shares these options through `rules.Options`: `expr.DisableBuiltin("now")`, `expr.DisableBuiltin("$env")`, Expr's default node limit (10,000) and memory budget (1,000,000 per run), and `expr.Timezone` with `format.timezone` once validation has loaded the zone, since it panics on an unknown name. A routing rule adds `expr.Env(routing.Env{})` and `expr.AsBool()`, as the owner's decision has it. The clock is injected: `now` is the job's acceptance time in `format.timezone`, so a dry-run with `--at` and the tests reproduce any decision. + - The shared options carry that decision's iteration guard, so routing rules have it too: a budget of 1,000,000 iterations per run, charged by a `Patch` visitor around every predicate builtin and the right side of `in`. Expr itself has no step limit: nested predicates over large literal ranges, such as `any(1..999, any(1..999, # < 0))`, took about 30 ms, and one more level would take seconds here and minutes on a Pi, on every job. With the guard, such a rule fails at run time, as decision 15 has it, instead. - Trade-off: a guard of our own around Expr's AST charges every predicate, though only the owner writes routing rules and they see no print content. -18. **Storing the decision.** Assumed: a route is decided once, at `Submit`, and stored; a restore never runs the rules again. The job keeps its `route`: `by` (`rule`; `query` for an explicit `?printer=`; or `default`), the rule's name and the mode, and job status shows it. An anycast delivery keeps its ordered list and the printers that got a `sending` mark (stage 3). - - This replaces job-store.md's assumption that a restored anycast delivery's list is "given again" by the rules and the config. Its `jobs` row keeps no priority, tags or client, and the rules may have changed since. +18. **Storing the decision.** A route is decided once, at `Submit`, and stored; a restore never runs the rules again. The job keeps its `route`: `by` (`rule`; `query` for an explicit `?printer=`; or `default`), the rule's name and the mode, and job status shows it. An anycast delivery keeps its ordered list and the printers that got a `sending` mark (stage 3). + - A restored anycast delivery's list is therefore not given again by the rules and the config: job-store's `jobs` row keeps no priority, tags or client, and the rules may have changed since. Evaluating stored facts again at restore would cost as many bytes, give another answer after a config change, and put topics on disk. - With SQLite, `jobs` gains `route_by`, `route_rule` and `route_mode`, and `deliveries` gains `candidates` and `sent_to`, names joined by commas, which a name cannot hold. If job-store stage 1d has not shipped when stage 2a starts, these columns join its first schema; otherwise stage 2a adds one schema step to `user_version` 2. - Trade-off: five columns; a job keeps the route it was given after the rules change. - - Alternative: store the facts as JSON and evaluate again at restore. That costs as many bytes, gives another answer after a config change, and puts topics on disk. -19. **Multicast and broadcast.** Assumed: +19. **Multicast and broadcast.** - Capacity is checked on every target lane under the submit lock. The job is accepted when at least one target lane has room. A delivery whose lane is full is inserted already `failed`, with the error "printer's queue is full", in a synced commit as any failure is. It is logged at WARN by `job_id` and `printer`, and not sent to Sentry, since a full queue is a refusal, not a fault. `Submit` answers `queue_full` only when every target lane is full. - With all-or-nothing capacity instead, a dead printer's full lane would refuse every broadcast, and every multicast that includes it, though every other printer is fine. A dead lane fills fast, since it drains one delivery per 7-27 s. On the ntfy path `queue_full` makes the subscriber stop reading, so one dead printer would stall a whole subscription, the `urgent-on-desks` example included. - Each delivery renders on its own lane with its printer's options, so an image is fetched once per delivery. Rendered bytes are never stored (job-store decision 8). - An ntfy subscription's paper budget counts jobs, not deliveries, so a multicast rule prints a budgeted receipt on each printer of its set. - `copies` applies to each delivery. - Trade-offs: a job can be `failed` on one printer while it prints on the others; its `status` says so once they finish (job-store decision 12), and `deliveries` at once. The same image URL is fetched N times and may answer differently. Lanes render in parallel, so a broadcast with large images holds N renders in memory at once, which matters on a Pi Zero. The budget does not count the second roll. - - Alternatives: all or nothing, which keeps a job whole but lets one dead printer refuse the others' jobs; render once per distinct set of options and share the bytes; one render at a time across the lanes; count deliveries in the budget. -Before stage 2b: +For stage 2b: -20. **Reloading the rules.** Assumed: SIGHUP reads the config again. The whole file must load and pass, its rules compiled; then `[routing]` takes effect at once, swapped as one set. +20. **Reloading the rules.** SIGHUP reads the config again, as the owner's decision has the rule set swapped atomically on reload. The whole file must load and pass, its rules compiled; then `[routing]` takes effect at once, swapped as one set. - The new routing is checked against the printers that are running, not the new file's. Every rule's `to` and every group member must name a printer that has a lane, or the whole reload is refused. `broadcast` means the running printers. The rules compile with the running `format.timezone`, so that `date()` and `now` agree. - Any other change is logged at WARN, by section name only and never a value, as taking effect at the next restart, and is not applied. - A file that fails, or a refused reload, keeps the old set and is logged at ERROR. Like a bad config at start, it is not sent to Sentry. @@ -157,35 +140,31 @@ Before stage 2b: - The reload also swaps docs/plans/templates.md's templates, ntfy rules and webhooks, in one snapshot with `[routing]` (its decision 17). - It also applies `[agents]`' `tokens_since`, so a revoked agent is refused without a restart, as docs/plans/remote-printers.md decision 6 expects; whichever of stage 2b and remote-printers stage 2 lands second wires it. - Trade-off: more code and tests than a restart. A new printer, and a rule for it, need a restart. Until job-store stage 1d, a restart fails the waiting jobs, which a reload does not. - - Alternative: no reload, which goes against the owner's decision ("swaps the rule set atomically on reload"). -Before stage 2c: +For stage 2c: -21. **The dry-run.** Assumed: a command, `uberbringer route`, reads the config and a job file or a module payload. It takes the facts as flags (`--source`, `--subscription`, `--client`, `--topic`, `--priority`, `--tag`, `--digest`, `--printer`, `--at`). It prints the env, each rule's result, error or "disabled" in order, and the decision. It sends nothing, reads no status and fetches nothing. The JSON preview also gains `route`, the decision the rules make for that request now, so a client can check its routing without printing. No route takes an expression from a request: Expr's advisories matter only for expressions nobody trusts. +21. **The dry-run.** A command, `uberbringer route`, reads the config and a job file or a module payload. It takes the facts as flags (`--source`, `--subscription`, `--client`, `--topic`, `--priority`, `--tag`, `--digest`, `--printer`, `--at`). It prints the env, each rule's result, error or "disabled" in order, and the decision. It sends nothing, reads no status and fetches nothing. The JSON preview also gains `route`, the decision the rules make for that request now, so a client can check its routing without printing. No route takes an expression from a request: Expr's advisories matter only for expressions nobody trusts. - Trade-off: the JSON preview shows rule and printer names to any token that may preview, tokens limited to modules included. - - Alternative: `POST /api/v1/route` for full tokens, which needs its own entry in the route table, test case, docs and schema. -Before stage 3: +For stage 3: -22. **Failover after bytes went out** (job-store decision 23). Assumed, the owner's default: the existing retry rule on that printer (`retries`, with the doubling `retry_delay`), then failover to the next printer of the list. +22. **Failover after bytes went out** (job-store decision 23): the existing retry rule on that printer (`retries`, with the doubling `retry_delay`), then failover to the next printer of the list. - The delivery's `sent_to` lists every printer that got a `sending` mark, so a person knows which paper to check. - A write error after which `Write` had taken nothing counts as nothing sent and fails over at once. That needs `Send` to report what it wrote, which it discards today. The printer stays in `sent_to` all the same: over-reporting is the safe direction, and dropping it would cost one more store write. - `attempts` counts every attempt on every printer, and each mark's attempt number goes on from the last. - The risk: the next printer prints the whole receipt. A first printer that took all of it before the error, or buffered it and prints it once its fault clears, prints it too. - Some sends that will not print show no error at all. `Write` returns once the kernel holds the bytes, so a printer that goes offline after taking them, or one that another host holds, takes the receipt without a word, and no failover happens (Investigation findings, WHAT "THE PRINTER FAILED" CAN MEAN). - - docs/plans/remote-printers.md decision 17 leans on this default: a remote `partial` outcome is today's write error, and `nothing` matches `NothingWritten`. - - Alternatives: (a) no failover after a `sending` mark: the delivery retries on that printer, then fails, and a person checks the paper; (b) failover at once after a mark, without retries: faster, with the same risk; (c) once job-store phase 5's confirmed send exists, a partial write makes the delivery `uncertain` and never resent. -23. **A status check before an anycast send.** Assumed: after the dial and before the `sending` mark, on the same connection and inside the printer's slot, anycast reads `DLE EOT`. It reads a not-ready answer again 750 ms later, as `/healthz` does. + - docs/plans/remote-printers.md decision 17 builds on this: a remote `partial` outcome is today's write error, and `nothing` matches `NothingWritten`. +23. **A status check before an anycast send.** After the dial and before the `sending` mark, on the same connection and inside the printer's slot, anycast reads `DLE EOT`. It reads a not-ready answer again 750 ms later, as `/healthz` does. - The read runs over the connection already open, so it never waits on its own slot. - - It reads `DLE EOT` only. Stage 4a's `GS r 1` is not real-time, adds up to 500 ms, and could close the connection the job is about to be written on (question 28). Near-end never decides a failover. - - A printer still not ready (offline, cover open, paper out, an error) counts as nothing sent. It is marked down (question 24), and the delivery fails over at once. + - It reads `DLE EOT` only. Stage 4a's `GS r 1` is not real-time, adds up to 500 ms, and could close the connection the job is about to be written on (decision 28). Near-end never decides a failover. + - A printer still not ready (offline, cover open, paper out, an error) counts as nothing sent. It is marked down (decision 24), and the delivery fails over at once. - A timeout or no answer sends anyway: a timeout is never a printer fault, and a printer busy with an earlier job may answer late. - - Unicast and multicast do not check, as today. The check and `/healthz` share one settle function, moved from the server to `printer`, which takes the read to use. - - Without the check, a printer out of paper most likely still takes the connection and the bytes, so the main anycast case would fall into question 22's path. That is an inference, and a paper check tests it before stage 3 starts. With the owner's OK, one short receipt goes unicast to the TM-T88IV with its paper out (or its cover open). Does the printer take the connection and the bytes, and print the receipt once the paper is loaded? + - Unicast and multicast do not check, as today, so a job for a printer that is briefly offline is still buffered for it. The check and `/healthz` share one settle function, moved from the server to `printer`, which takes the read to use. + - Without the check, a printer out of paper most likely still takes the connection and the bytes, so the main anycast case would fall into decision 22's path. That is an inference, and a paper check tests it before stage 3 starts. With the owner's OK, one short receipt goes unicast to the TM-T88IV with its paper out (or its cover open). Does the printer take the connection and the bytes, and print the receipt once the paper is loaded? - docs/plans/remote-printers.md decision 19 reads a remote printer's status through the same settle function at the agent, and this paper check decides the anycast check there too. - Trade-off: one status round trip per attempt, and up to 0.75 s more in the slot. An auto-recoverable error, such as a print head that is too hot, clears by itself, so waiting for it may beat failing over. - - Alternatives: no check; or a check on every send, unicast included, which changes today's behaviour of buffering a job for a printer that is briefly offline. -24. **A printer marked down.** An anycast delivery joins the lane of its first printer. When that printer is dead, the delivery waits behind every earlier delivery on that lane, and each of those retries before it fails. That is about 27 s each at the defaults when dials time out (four dials of 5 s, plus waits of 1, 2 and 4 s), or about 7 s when they are refused. Ten unicast jobs for a dead `office` would delay an `alerts` job by 4-5 minutes while `default` sits idle. Once the dead lane is full, `Submit` would refuse the anycast job. Anycast would fail in the very case it exists for. Assumed: +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. So: - 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). @@ -194,14 +173,12 @@ Before stage 3: - A mark only passes a printer over for a later one of the list that is not marked. When every printer left is marked, the first of them is tried as usual, so the attempt renews or clears its mark. - Rules never see the mark (invariant 4). - Trade-off: a printer that recovers within the hold gets no anycast jobs for up to 30 s, and a passing not-ready sends a job to the next printer. - - Alternatives: check capacity on any lane of the list but keep the place, which does not end the wait; put the delivery at the front of the first lane, which still waits for the dial in hand and its retries; no mark. -25. **A list that fails before any byte.** Assumed: rounds. When the last printer fails before sending, the list starts again from the top after the first printer's `retry_delay`, doubling, for up to the first printer's `retries` more rounds. - - Between rounds the delivery waits on a timer, on no lane. When the delay ends, the timer puts it on the lane of its first printer not marked down (question 24). No worker sleeps, so no lane is blocked by a delivery bound elsewhere. The timer follows the rules for a move (question 26), and at shutdown or a cancel a delivery on a timer counts as waiting. +25. **A list that fails before any byte** goes round again. When the last printer fails before sending, the list starts again from the top after the first printer's `retry_delay`, doubling, for up to the first printer's `retries` more rounds. + - Between rounds the delivery waits on a timer, on no lane. When the delay ends, the timer puts it on the lane of its first printer not marked down (decision 24). No worker sleeps, so no lane is blocked by a delivery bound elsewhere. The timer follows the rules for a move (decision 26), and at shutdown or a cancel a delivery on a timer counts as waiting. - Once the rounds are spent, one last attempt sends to the first printer without the status check, as unicast does. No other printer got bytes, so it cannot print twice. A list whose printers are all briefly not ready, such as a cover opened to change the paper, then still prints, as unicast would have. Only then does the delivery fail. - A delivery that sent bytes anywhere starts no new round. Each lane's take keeps its own 2-minute bound. - Trade-off: a failed anycast delivery can take about a minute with three printers at the defaults. - - Alternatives: one pass, then failed; or the last attempt with the check too, which loses a job that unicast would have printed. -26. **Moving a delivery.** Assumed: +26. **Moving a delivery.** - A moved delivery joins the next printer's waiting list in sequence order, ahead of later jobs, and is never refused for capacity. The first printer's slot is released before the next printer's worker takes its own, so failover never holds two slots. - A move takes the status lock, and job-store phase 2b's delivery lock once that exists. It happens only while the queue is open and the delivery is not cancelled. A failure while the delivery's context has ended (a shutdown, a cancel or its 2-minute bound) never moves it. With a durable store, dialling runs on a context that ends with the daemon, and a cancel ends the delivery's context, so their errors would otherwise look like a dead printer. Shutdown and the cancel follow their own rules, and the bound fails the delivery, as today. - It renders again only when the next printer's options key differs; with an equal key it keeps its bytes. Each lane computes its key at start from its profile and every `receipt.Options` field, since the options may come to hold fields that cannot be compared. @@ -210,39 +187,33 @@ Before stage 3: - After a `sending` mark, a moved delivery stays `sending` in the store while it waits on the next lane. A crash then turns it `uncertain` at the restart, and it is never sent, even when its write took nothing. That is the safe direction, as job-store has for a crash between the mark and the write. - At a clean shutdown, a delivery waiting on a lane after a mark fails with `sent_at` and `sent_to`, with either store. That is job-store's rule for a delivery between retries after reaching `sending`. - Job-store phase 2b's cancel leaves a delivery with any mark alone, even while it waits on the next printer. One without a mark can be cancelled wherever it waits. - - A restored queued anycast delivery starts again from the top of its stored list (question 18). + - A restored queued anycast delivery starts again from the top of its stored list (decision 18). - Trade-off: a moved delivery goes ahead of the next printer's later jobs. A receipt whose write took nothing just before a crash is lost as `uncertain`. - - Alternatives: the end of the next printer's list. Or a lazy commit back to `queued` after a write that took nothing, when no attempt sent bytes, so a restart sends it; that needs one more store method and write. -Before stage 4a: +For stage 4a: -27. **Keeping the exact model.** Assumed: `escpos.Profile` gains `Model`, the name as configured (`tm-t88iv` to `tm-t88vii`, `tm-m50ii`, `tm-t20ii`; a family name stays itself). It also gains the model's status capabilities: where paper near-end comes from (`DLE EOT 4`, `GS r 1` or nowhere), and whether `DLE EOT 3` bit 2 exists. +27. **Keeping the exact model.** `escpos.Profile` gains `Model`, the name as configured (`tm-t88iv` to `tm-t88vii`, `tm-m50ii`, `tm-t20ii`; a family name stays itself). It also gains the model's status capabilities: where paper near-end comes from (`DLE EOT 4`, `GS r 1` or nowhere), and whether `DLE EOT 3` bit 2 exists. - Only `tm-t88vii` takes near-end from `GS r 1`. Every other name keeps today's `DLE EOT 4`. The families `tm-t88` and `tm-m50` behave as the TM-T88IV and the TM-m50II; `tm-m50` (the TM-m50) and the `tm-t20` and generic profiles stay unverified. - - `Name` stays the layout family (`tm-t88`), so previews and pinned bytes do not change. + - `Name` stays the layout family (`tm-t88`), so previews, pinned bytes and the models table in docs/configuration.md do not change. - The default, `tm-t88`, keeps the TM-T88IV's status behaviour, so a TM-T88VII must be configured as `tm-t88vii` to report its near-end. - Trade-off: a TM-T88VII configured as `tm-t88` reports no near-end, as today. - - Alternative: `tm-t88vii` as a profile with a name of its own, which changes the name that previews and the models table in docs/configuration.md show. -28. **The TM-T88VII's near-end through `GS r 1`.** Assumed: `Status` sends it last, only when `DLE EOT` says online and ready, under a deadline of its own (500 ms, assumed). The anycast check (question 23) never sends it. +28. **The TM-T88VII's near-end through `GS r 1`.** `Status` sends it last, only when `DLE EOT` says online and ready, under a deadline of its own, 500 ms. The anycast check (decision 23) never sends it. - Its reply has a decoder of its own, since its fixed bits differ from `DLE EOT`'s and `Status.Apply` would refuse it. The decoder accepts the byte the TM-T88VII actually sends, since Epson's page contradicts itself. - No answer means near-end is unknown: `paper` reads as `DLE EOT 4` gave it, never `timeout`, never `503`. - The connection closes after a missed answer, since a late one could be read as the answer to the next request. Closing does not stop a late reply: the board, not TCP, routes the printer's output, so the reply can reach the next connection. There it fails the `DLE EOT` mask, since its bits 0 and 1 are both clear or both set, and reads once as unsupported (`unknown`, `200`). - Trade-off: `GS r 1` is not real-time. It is answered once the lines before it have printed, so during a long print it is usually missed. A late reply costs one `unknown` reading. - - Alternatives: automatic status (`GS a`), whose third byte may carry near-end on that model (unverified, and it arrives unasked); or the TM-T88VII's TM-T88V emulation, if it brings the bits back to `DLE EOT 4` (unknown). -29. **More status bits, and frames nobody asked for.** Assumed: `Ready()` also counts `DLE EOT 2` bit 6 (an error occurred) and `DLE EOT 3` bit 2 (a recoverable error; the TM-T88IV lacks it), read again like the rest. `Normalized()` clears `DLE EOT 2` bit 6 while `DLE EOT 1` says online, as it clears that byte's other bits, so a stale bit while cutting does not read as not ready. On the TM-T88VII the autocutter-error bit also means a paper jam; api.md says so. Automatic-status frames are left alone until stage 4a's first step shows whether they reach a port 9100 client. The UB-E02 and UB-E03 boards turn them on at power-on, and a TM-T88VII with DIP switch 2-1 on keeps them on. If they do reach the client, job-store phase 5's frame reader comes forward. +29. **More status bits, and frames nobody asked for.** `Ready()` also counts `DLE EOT 2` bit 6 (an error occurred) and `DLE EOT 3` bit 2 (a recoverable error; the TM-T88IV lacks it), read again like the rest. `Normalized()` clears `DLE EOT 2` bit 6 while `DLE EOT 1` says online, as it clears that byte's other bits, so a stale bit while cutting does not read as not ready. On the TM-T88VII the autocutter-error bit also means a paper jam; api.md says so. Automatic-status frames are left alone until stage 4a's first step shows whether they reach a port 9100 client. The UB-E02 and UB-E03 boards turn them on at power-on, and a TM-T88VII with DIP switch 2-1 on keeps them on. If they do reach the client, job-store phase 5's frame reader comes forward. - Trade-off: `/healthz` can answer `503` on a recoverable error where it answered `200`. - - Alternative: decode what is decoded today. -Before stage 4b: +For stage 4b: -30. **Per-model defaults in the profile.** Assumed: +30. **Per-model defaults in the profile.** - The default line spacing (`ESC 2`) is 30 dots, 1/6 inch, on all three printers, so it changes no byte. job-store phase 3a's drawing is its first reader and defines `Profile.LineSpacing` there. This plan adds nothing for it. - `box_line_spacing` keeps one default, 0, as calibrated on the TM-T88IV, until stage 4b's paper check finds a model whose borders need another value. Only then does `Profile` gain `BoxLineSpacing`. The key's default then becomes -1, meaning "the model's", validated from -1 to 255, since an explicit 0, and `UBERBRINGER_PRINTER_BOX_LINE_SPACING=0`, must still mean `ESC 2`. The load helper resolves -1 from the profile, so `config get` prints the value in use. - `cut_feed` stays one default for every model. `GS V 66` feeds to the printer's own cutter, and a line is the same on every model, so the cut lands alike. Only the distance from the head to the cutter (about 15 mm on the TM-T88IV to VII, about 9.5 mm on the TM-m50II) differs, and with it the next receipt's top margin, which matters for the drawn preview alone. - Trade-off: -1 is a value a user can write; the docs say what it means. - - Alternatives: a pointer (`*int`) for a key left out, which the decode hooks and `Value()` must handle; or no per-model default, with a calibrated value written into that printer's table by hand. -31. **Printer settings that change layout.** Needed before the first receipt on a new printer. Assumed: factory settings: 42/30 column mode, 80 mm paper, no automatic paper reduction and the default top margin. The owner reads each printer's status sheet when it arrives. +31. **Printer settings that change layout.** Needed before the first receipt on a new printer: factory settings, that is 42/30 column mode, 80 mm paper, no automatic paper reduction and the default top margin. The owner reads each printer's status sheet when it arrives. 58 mm paper already works through `paper_width = 360`. - Trade-off: in 48/36 column mode the width is 480 dots and Font A is 10 dots wide, so `tm-t88` and `tm-m50` would break words at the printer's edge. Paper reduction of the bottom margin would remove `cut_feed`'s blank lines. - - Alternative: profile variants for 48-column mode. 58 mm paper already works through `paper_width = 360`. ## Investigation findings @@ -283,7 +254,7 @@ KANRISHA'S ENGINE - The env is a map, with a hand-kept prototype, a third list for its form builder and a fourth in its docs, which already differ. - Reload: an API route and a NATS broadcast make every node read the rules again. Dry-run: compiles a rule that need not be loaded and evaluates it against chosen files, with no side effects. - Its tests include a concurrency test of 100 goroutines under `-race`. -- What this plan keeps: compile once against a typed env with `AsBool`; first match wins; `enabled`; a set swapped whole; a runtime error means no match; an injected clock; a dry-run that changes nothing; the concurrency test. What it changes: a struct env with `expr` tags in place of a map and its prototype (question 17); a unique `order` in place of an unstable sort (question 12); `now()` turned off (question 17); a rule that fails to compile is a config error (question 14); an `atomic.Pointer` to an immutable set in place of a lock and incremental changes; a generic engine that templates can share, as design.md's Planned next item 5 asks. +- What this plan keeps: compile once against a typed env with `AsBool`; first match wins; `enabled`; a set swapped whole; a runtime error means no match; an injected clock; a dry-run that changes nothing; the concurrency test. What it changes: a struct env with `expr` tags in place of a map and its prototype (decision 17); a unique `order` in place of an unstable sort (decision 12); `now()` turned off (decision 17); a rule that fails to compile is a config error (decision 14); an `atomic.Pointer` to an immutable set in place of a lock and incremental changes; a generic engine that templates can share, as design.md's Planned next item 5 asks. THE CONFIG LOADER - Today's loader refuses `[printers.office]` as an unknown key: a map field is one setting, and the walker refuses an entry of it that is itself a table. With a new key kind, whose entries are checked against `printers.*.`, and the per-entry default hook the subscriptions use, `[printers.kitchen]` with only `address` got every default. @@ -363,12 +334,12 @@ WHAT "THE PRINTER FAILED" CAN MEAN | A render error | none | no: a fault of the job, unless that printer's options cause it | WHERE THE REPORTS DISAGREE OR ARE UNSURE -- Rule order: the Expr track assumed the order in the file with no number; the config track a required, unique `order`. Question 12. -- Config names: the Expr track sketched `[[rules]]` and `[groups]` with a key per mode; the config track `[routing]` with `to`. Question 11. -- Reload: the Expr track assumed SIGHUP; the config track none in this plan. Question 20. -- A rule's runtime error in the log: with its message (Expr track), or never (config track), since the message quotes env values. Question 15. -- The name pattern: the module names' form (Expr track) or the subscriptions' (config track). Question 2. -- Whether an offline printer behind a UB-E02 or UB-E03 still accepts the connection and holds the bytes: an inference, unverified. Question 23's paper check, before stage 3. +- Rule order: the Expr track assumed the order in the file with no number; the config track a required, unique `order`. Decision 12. +- Config names: the Expr track sketched `[[rules]]` and `[groups]` with a key per mode; the config track `[routing]` with `to`. Decision 11. +- Reload: the Expr track assumed SIGHUP; the config track none in this plan. Decision 20. +- A rule's runtime error in the log: with its message (Expr track), or never (config track), since the message quotes env values. Decision 15. +- The name pattern: the module names' form (Expr track) or the subscriptions' (config track). Decision 2. +- Whether an offline printer behind a UB-E02 or UB-E03 still accepts the connection and holds the bytes: an inference, unverified. Decision 23's paper check, before stage 3. - `GS r 1`'s fixed bits: Epson's page contradicts itself. Stage 4a's first step reads what the TM-T88VII sends. - Whether automatic-status frames reach a port 9100 client: unverified (job-store.md says the same). Stage 4a's first step. - Whether the TM-T88VII's TM-T88V emulation brings near-end back to `DLE EOT 4`: unknown. @@ -398,11 +369,11 @@ WHAT SHIPS WHEN COMPATIBILITY - A config with `[printer]` alone loads and prints as today: one lane, no rules, every job on `default`. install.sh, the Dockerfile and `UBERBRINGER_PRINTER_*` do not change. Two changes reach every config: - - **Breaking:** `/print` and `/preview` refuse query parameters other than `printer` (question 7). - - Job status gains `deliveries` (question 8), and from stage 2a `route` (question 18). Its other fields keep their meaning. + - **Breaking:** `/print` and `/preview` refuse query parameters other than `printer` (decision 7). + - Job status gains `deliveries` (decision 8), and from stage 2a `route` (decision 18). Its other fields keep their meaning. - `?printer=default` keeps working on the module routes, and an empty `printer` still means the default printer. - `/healthz` keeps `status`, `printer` and its code; it gains `printers`. `queue.pending` becomes the total across printers. -- `queue.size` bounds each printer's queue, so a host with several printers can hold more jobs (question 4). +- `queue.size` bounds each printer's queue, so a host with several printers can hold more jobs (decision 4). - What prints does not change. TestRenderCompat and TestPaperReceipts keep passing; stage 4b changes bytes only for a model whose paper check sets a value. - A downgrade: an older binary refuses `[printers.*]` and `[routing]` as unknown keys. With a durable store: - Between job-store stage 1d and this plan's stage 2a, an older binary opens the store, and its single worker would take every waiting delivery, whatever its printer. The queue must drain first. @@ -421,19 +392,6 @@ INVARIANTS 9. printqueue, server and config never import Expr, so tools/genopenapi never compiles it. printqueue and printer never import each other. 10. job-store.md's invariants hold for each delivery. -ON ACCEPTANCE -When the owner accepts this plan, these edits are made: -- design.md: Planned next item 2 records the decisions. -- docs/plans/formatters.md: its open question goes, answered by the example under Architecture, ROUTING RULES. Its phase 5 items for a second printer and for per-model line spacing go, and so do the phase 5 Tests for the printer pool (the migration test from `[printer]` to `printers.default`, unknown keys in `[printers.x]`, two queues in parallel). Each points here. -- docs/plans/job-store.md: - - COMPATIBILITY's "Job status keeps its shape until there are several printers", and the DELIVERIES AND SEVERAL PRINTERS bullet that gives the `deliveries` array and leaves the job's own fields to this plan: point to question 8, under which every status gains `deliveries` from stage 1b. - - DELIVERIES AND SEVERAL PRINTERS: the bullet on a row that stores nothing of its route, and the anycast bullet's restored list, point to question 18; the anycast bullet's failover after a mark, to question 22; "one store, with one queue and worker per printer", to question 4; a printer removed from the config, to question 5. - - Invariant 3's "which the printers plan settles (question 23)": point to question 22. Invariant 2 reads "No byte of the job goes to the printer before its delivery's `sending` mark", since an anycast check sends `DLE EOT` before the mark. - - Question 9: point to question 4's bound with several lanes. - - Phase 2b, in case it ships after stage 3: a delivery with any `sending` mark is not cancellable, even while it waits on the next printer of an anycast list; a move takes the delivery lock (question 26). - - PRINT ACKNOWLEDGEMENT: the TM-m50II's command list includes `GS ( H` fn 48, still unverified over port 9100. The side finding's power-on part is confirmed in Epson's guides; whether the frames reach a port 9100 client is still unverified. - - Phases 3c and 4: a PNG preview uses the profile the text preview uses, the named printer's or the default's; a preview by ID uses its first delivery's printer. Phase 5's printer keys, such as `printer.confirm`, apply to each printer's table. - ## Architecture PRINTERS IN THE CONFIG (stage 1a) @@ -453,8 +411,8 @@ address = "192.0.2.12" model = "tm-m50ii" ``` -- Names and addresses here are examples. Each table starts from the printer defaults; only `address` is required (question 3). No two printers share an address and port. -- The loader gains a key kind for a table of named tables. `registerDefaults` registers its entry keys as `printers.*.`. The walker checks that each entry is a table, checks the name on the raw key, finds case clashes and checks the keys. Each entry decodes onto `DefaultPrinter()` through the per-entry default hook. No variable is bound (question 2). +- Names and addresses here are examples. Each table starts from the printer defaults; only `address` is required (decision 3). No two printers share an address and port. +- The loader gains a key kind for a table of named tables. `registerDefaults` registers its entry keys as `printers.*.`. The walker checks that each entry is a table, checks the name on the raw key, finds case clashes and checks the keys. Each entry decodes onto `DefaultPrinter()` through the per-entry default hook. No variable is bound (decision 2). - Printer order, wherever one is needed (broadcast, `/healthz`, the start-up log): the default first, then by name. The decoder does not keep a TOML table's order. LANES (stage 1a) @@ -465,9 +423,9 @@ request ─▶ Submit ─▶ route ─┼─ lane "kitchen": … (one Store.Add per job) └─ lane "office": … ─▶ TM-m50II ``` -- One `Queue` (question 4). Shared: the submit lock (the job's and its deliveries' sequence numbers, the capacity check, `Store.Add`, the appends to waiting lists), the status lock and map, the history, the references of ntfy jobs, the store and `OnFailure`. Per lane: the name, the renderer with that printer's `receipt.Options`, the sender (its `printer.Client`, with its own slot), retries and retry delay, a waiting slice in sequence order with its wake channel, and one worker. +- One `Queue` (decision 4). Shared: the submit lock (the job's and its deliveries' sequence numbers, the capacity check, `Store.Add`, the appends to waiting lists), the status lock and map, the history, the references of ntfy jobs, the store and `OnFailure`. Per lane: the name, the renderer with that printer's `receipt.Options`, the sender (its `printer.Client`, with its own slot), retries and retry delay, a waiting slice in sequence order with its wake channel, and one worker. - Lock order per lane is job-store's: the printer's slot, then the delivery lock, then the store; the status lock is innermost and never held across a store call. -- `Submit` routes first, outside the locks (stage 2a). Then, under the submit lock, it checks capacity on the target lanes (question 19), commits `Store.Add` with every delivery, and appends each delivery to its lane. +- `Submit` routes first, outside the locks (stage 2a). Then, under the submit lock, it checks capacity on the target lanes (decision 19), commits `Store.Add` with every delivery, and appends each delivery to its lane. - `Run` starts one worker per lane; shutdown covers every lane, by `Durable()`. - A store failure stops every lane. The first store error from any lane ends the others, and `Run` returns it, as an errgroup does (job-store decision 11). An idle lane must not keep `Run` alive, and no lane may send after the store broke. - Every worker log line carries `printer`. `OnFailure` gets the printer, and Sentry tags it; never content. @@ -482,14 +440,14 @@ DELIVERIES AND JOB STATUS (stages 1b-3) {"printer": "office", "status": "queued"}]} ``` -- `deliveries` from stage 1b (question 8). `route` from stage 2a (question 18), whose `by` is `rule`, `query` or `default`. An anycast delivery's `printers`, its ordered list, and `sent_to` from stage 3 (questions 22 and 26). +- `deliveries` from stage 1b (decision 8). `route` from stage 2a (decision 18), whose `by` is `rule`, `query` or `default`. An anycast delivery's `printers`, its ordered list, and `sent_to` from stage 3 (decisions 22 and 26). - The job's `status` derives from its deliveries by job-store decision 12; with one delivery it is that delivery's. - Enums go into `jsonschema` tags, held by printqueue's and the server's schema tests. `?printer=` AND THE PREVIEW (stages 1b and 2c) - `?printer=` is a direct unicast: the rules do not run, and `route.by` is `query`. It names a printer, never a group. An empty value means the default printer. -- Routes: the module routes, as today, and `POST /api/v1/print` and `POST /api/v1/preview` (question 7). `unknown_printer` and `invalid_query` keep their codes; their api.md rows cover the new routes. -- A preview renders for the named printer, or the default printer. The JSON answer gains `printer` (stage 1b) and `route` (stage 2c): the decision without queueing (question 21). +- Routes: the module routes, as today, and `POST /api/v1/print` and `POST /api/v1/preview` (decision 7). `unknown_printer` and `invalid_query` keep their codes; their api.md rows cover the new routes. +- A preview renders for the named printer, or the default printer. The JSON answer gains `printer` (stage 1b) and `route` (stage 2c): the decision without queueing (decision 21). HEALTH (stage 1b) @@ -503,21 +461,21 @@ HEALTH (stage 1b) "queue": {"pending": 3}} ``` -- The code and `status` follow the default printer, as today (question 9). The entries reuse `printer`'s fields, so the existing enum test covers them. `model` is the model as configured. The ntfy array is unchanged. +- The code and `status` follow the default printer, as today (decision 9). The entries reuse `printer`'s fields, so the existing enum test covers them. `model` is the model as configured. The ntfy array is unchanged. - The default printer is read once, and that read fills `printer` and the first entry. The others are read each on its own goroutine, through the same settle path, within the one 3-s bound. ROUTING RULES (stages 2a-2c) - Packages: - - `internal/pkg/rules` (new): a generic engine, importing only Expr. `Rule[A]` (`Name`, `Order`, `When`, `Enabled`, `Action`). `Compile[E, A]` compiles every rule against `E`'s zero value with question 17's options and joins every error, each naming its rule and position. `Set.Match(env)` returns the first enabled rule in `order` whose `when` is true, with the runtime errors of the rules before it. `Set.Explain(env)` gives every rule's result, error or "disabled", for the dry-run. `Engine` holds the current set behind an `atomic.Pointer`, with `Swap`, `Match` and `Explain`. It also exports `Options`, the compile options and the iteration guard that docs/plans/templates.md shares; whichever of this stage and that plan's stages comes first builds what it needs of the package (its decision 1). + - `internal/pkg/rules` (new): a generic engine, importing only Expr. `Rule[A]` (`Name`, `Order`, `When`, `Enabled`, `Action`). `Compile[E, A]` compiles every rule against `E`'s zero value with decision 17's options and joins every error, each naming its rule and position. `Set.Match(env)` returns the first enabled rule in `order` whose `when` is true, with the runtime errors of the rules before it. `Set.Explain(env)` gives every rule's result, error or "disabled", for the dry-run. `Engine` holds the current set behind an `atomic.Pointer`, with `Swap`, `Match` and `Explain`. It also exports `Options`, the compile options and the iteration guard that docs/plans/templates.md shares; whichever of this stage and that plan's stages comes first builds what it needs of the package (its decision 1). - `internal/pkg/routing` (new): `Env` and how it is built; the action (`Mode`, `To`) and its resolution against the printers and groups; the `printqueue.Router` it implements. - printqueue defines `Route` and `Router`; it, the server and config never import Expr. Imports: routing → rules, printqueue, receipt; rules → Expr; internal/app → routing. - config checks structure only: names, `order`, modes, `to`. The load helper in internal/app compiles the rules, so `config get` fails on a bad rule before install.sh restarts the daemon. -- At `Submit`: an explicit printer gives unicast, `by = "query"`. Otherwise the first match gives its action, with `to` expanded (question 13). No match gives unicast to the default printer, `by = "default"`. A runtime error passes to the next rule (question 15). -- `Submit` still refuses a printer with no lane (`ErrUnknownPrinter`, name assumed): a guard for a bug, once stage 2b checks reloads (question 20). The server answers `500` and reports it, as any unexpected error. ntfy.go logs it at ERROR, reports it and does not offer the message again, as it does with a receipt that fails validation, so a subscription cannot stall on it. -- Facts reach the router in `printqueue.Meta`. `Meta.Printer` comes in stage 1a. Stage 2a reads the module and the subscription from `Source`. Stage 2c adds `Meta.Facts`: client, topics, priority, tags and digest. The server fills them from the token's subject (auth.go keeps it beside the scope; never the token) and the module's built facts, since `Module.Build` returns the job with its topic, priority and tags. ntfy.go fills them from the message or the digest's rows. `Facts` are used at `Submit` only (question 16). The job's size comes from encoding it once, which `Store.Add` also takes. -- A reload swaps the set and the groups as one value, checked against the running printers (question 20, stage 2b). +- At `Submit`: an explicit printer gives unicast, `by = "query"`. Otherwise the first match gives its action, with `to` expanded (decision 13). No match gives unicast to the default printer, `by = "default"`. A runtime error passes to the next rule (decision 15). +- `Submit` still refuses a printer with no lane (`ErrUnknownPrinter`, name assumed): a guard for a bug, once stage 2b checks reloads (decision 20). The server answers `500` and reports it, as any unexpected error. ntfy.go logs it at ERROR, reports it and does not offer the message again, as it does with a receipt that fails validation, so a subscription cannot stall on it. +- Facts reach the router in `printqueue.Meta`. `Meta.Printer` comes in stage 1a. Stage 2a reads the module and the subscription from `Source`. Stage 2c adds `Meta.Facts`: client, topics, priority, tags and digest. The server fills them from the token's subject (auth.go keeps it beside the scope; never the token) and the module's built facts, since `Module.Build` returns the job with its topic, priority and tags. ntfy.go fills them from the message or the digest's rows. `Facts` are used at `Submit` only (decision 16). The job's size comes from encoding it once, which `Store.Add` also takes. +- A reload swaps the set and the groups as one value, checked against the running printers (decision 20, stage 2b). -An example, which also answers formatters.md's open question (which jobs and subscriptions go to which printer, and whether urgent messages print on both): +An example, which shows which jobs and subscriptions go to which printer, and urgent messages printed on both desks: ```toml [routing.groups] @@ -569,7 +527,7 @@ enabled = false - A subscription gets its printer through a rule on `subscription` or `source`; subscriptions gain no `printer` key. - A multicast or broadcast rule not limited by `source` or `types` sends `raw` jobs to every model; the docs warn of it. -THE ENVIRONMENT (stages 2a and 2c; question 16) +THE ENVIRONMENT (stages 2a and 2c; decision 16) `routing.Env`, a struct whose `expr` tags name the variables, built once per job at `Submit`. One type gives the compile-time prototype and the run-time values. A variable a stage has not added is an unknown name, so a rule on it fails to compile. | Variable | Type | Stage | Value | @@ -596,28 +554,28 @@ THE ENVIRONMENT (stages 2a and 2c; question 16) Rules the probe compiled and ran against this env: `source == "ntfy:alerts"`; `source startsWith "ntfy:" && priority >= 4`; `"urgent" in tags || priority == 5`; `weekday in ["sat", "sun"] || clock >= "22:00" || clock < "07:00"`; `"image" in types && bytes > 100000`; `now.Hour() >= 22`; `any(tags, # startsWith "kitchen")`; `topic matches "^alerts-"`; `module == "note" && copies > 1`. ANYCAST AND FAILOVER (stage 3) -1. At `Submit`, the delivery keeps its ordered list. It joins the lane of the first printer of the list that is not marked down and has room, else the first with room; `queue_full` comes only when every lane of the list is full (question 24). Its stored `printer` is the one to try first. -2. That lane's worker renders with its printer's options, or keeps bytes rendered for an equal options key (question 26). -3. The checked send takes the printer's slot and dials. It reads `DLE EOT` on that connection, reading a not-ready answer again (question 23). Then it calls `beforeWrite`, which commits the `sending` mark and adds the printer to `sent_to`, and writes. -4. Nothing of the job sent (the error came before `beforeWrite`, or matches `NothingWritten`): the slot is released, and the delivery moves at once to its next printer. A refused, unreachable or timed-out dial, or a printer still not ready, also marks the printer down (question 24). No store write, as job-store's JOB STATES has for a dial failure. -5. Bytes sent: the retry rule on that printer, then the move (question 22). -6. A move takes the status lock, and job-store phase 2b's delivery lock once that exists, and happens only while the queue is open and the delivery is not cancelled. A failure while the delivery's context has ended (a shutdown, a cancel or its 2-minute bound) never moves it: shutdown and the cancel follow their rules, and the bound fails the delivery, as today (question 26). -7. After the last printer, with nothing sent anywhere: a new round (question 25). The delivery waits on a timer, on no lane, and the timer puts it back on its first printer's lane; no worker sleeps. Once the rounds are spent, one last attempt sends to the first printer without the status check. With bytes sent anywhere, the delivery fails, `sent_at` and `sent_to` set. -8. While a printer is marked down, an anycast delivery passes over it to a later printer of its list that is not marked (question 24). -9. A restored queued anycast delivery starts from the top of its stored list, without printers no longer configured (questions 5 and 18). +1. At `Submit`, the delivery keeps its ordered list. It joins the lane of the first printer of the list that is not marked down and has room, else the first with room; `queue_full` comes only when every lane of the list is full (decision 24). Its stored `printer` is the one to try first. +2. That lane's worker renders with its printer's options, or keeps bytes rendered for an equal options key (decision 26). +3. The checked send takes the printer's slot and dials. It reads `DLE EOT` on that connection, reading a not-ready answer again (decision 23). Then it calls `beforeWrite`, which commits the `sending` mark and adds the printer to `sent_to`, and writes. +4. Nothing of the job sent (the error came before `beforeWrite`, or matches `NothingWritten`): the slot is released, and the delivery moves at once to its next printer. A refused, unreachable or timed-out dial, or a printer still not ready, also marks the printer down (decision 24). No store write, as job-store's JOB STATES has for a dial failure. +5. Bytes sent: the retry rule on that printer, then the move (decision 22). +6. A move takes the status lock, and job-store phase 2b's delivery lock once that exists, and happens only while the queue is open and the delivery is not cancelled. A failure while the delivery's context has ended (a shutdown, a cancel or its 2-minute bound) never moves it: shutdown and the cancel follow their rules, and the bound fails the delivery, as today (decision 26). +7. After the last printer, with nothing sent anywhere: a new round (decision 25). The delivery waits on a timer, on no lane, and the timer puts it back on its first printer's lane; no worker sleeps. Once the rounds are spent, one last attempt sends to the first printer without the status check. With bytes sent anywhere, the delivery fails, `sent_at` and `sent_to` set. +8. While a printer is marked down, an anycast delivery passes over it to a later printer of its list that is not marked (decision 24). +9. A restored queued anycast delivery starts from the top of its stored list, without printers no longer configured (decisions 5 and 18). 10. A shutdown or a cancel finds the delivery in one place: one lane or one timer. WHAT IS STORED - Stage 1a: nothing new. A delivery's `printer` is its lane's name, as job-store's schema already allows. -- Stage 2a (question 18): the route on the job (`route_by`, `route_rule`, `route_mode`), and on the delivery `candidates` and `sent_to`, written from stage 3. `printqueue.Record` and `Delivery` gain the same fields; the memory store keeps them. A delivery whose lane is full is inserted `failed`, and the insert then syncs (question 19). -- Stage 2c: nothing. Facts are never stored (question 16). +- Stage 2a (decision 18): the route on the job (`route_by`, `route_rule`, `route_mode`), and on the delivery `candidates` and `sent_to`, written from stage 3. `printqueue.Record` and `Delivery` gain the same fields; the memory store keeps them. A delivery whose lane is full is inserted `failed`, and the insert then syncs (decision 19). +- Stage 2c: nothing. Facts are never stored (decision 16). - `Store.Sending(delivery, printer, attempt, at)` already names the printer; from stage 3 it also adds it to `sent_to`, so a failover keeps the record that the first printer got bytes, which job-store.md's TELLING WHICH RECEIPTS PRINTED relies on. PROFILES AND STATUS PER MODEL (stages 4a and 4b) -- `escpos.Profile` keeps `Name`, the layout family, and gains `Model` and the status capabilities (question 27). Layout fields stay shared by the three printers. `LineSpacing` comes with job-store phase 3a; `BoxLineSpacing` comes only if a paper check needs it (question 30). -- Status: `printer.Client.Status` keeps `DLE EOT 1-4`, one request at a time. On a profile whose near-end comes from `GS r 1`, it sends that last, only when online and ready, with its own deadline and decoder, and closes the connection after a missed answer (question 28). The anycast check never sends it. `Ready()` and `Normalized()` gain question 29's bits. +- `escpos.Profile` keeps `Name`, the layout family, and gains `Model` and the status capabilities (decision 27). Layout fields stay shared by the three printers. `LineSpacing` comes with job-store phase 3a; `BoxLineSpacing` comes only if a paper check needs it (decision 30). +- Status: `printer.Client.Status` keeps `DLE EOT 1-4`, one request at a time. On a profile whose near-end comes from `GS r 1`, it sends that last, only when online and ready, with its own deadline and decoder, and closes the connection after a missed answer (decision 28). The anycast check never sends it. `Ready()` and `Normalized()` gain decision 29's bits. -THE SEAM FOR REMOTE PRINTERS (named, not built; question 6, settled) +THE SEAM FOR REMOTE PRINTERS (named, not built; decision 6, settled) - 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. @@ -628,10 +586,10 @@ THE SEAM FOR REMOTE PRINTERS (named, not built; question 6, settled) LOGGING AND PRIVACY - Worker lines gain `printer`. Each printer's start-up line gives its name, address, model, code page and paper width, as today's `listening` line gives the address: logs are private, and that line is where an operator sees which address each name uses. -- A rule's runtime error logs its name, the `job_id` and the error's line and column, never the message (question 15). A compile error gives the rule's name, the position and Expr's message, never the rule's source line (question 14). +- A rule's runtime error logs its name, the `job_id` and the error's line and column, never the message (decision 15). A compile error gives the rule's name, the position and Expr's message, never the rule's source line (decision 14). - The env and the facts are never logged, stored, kept in job status or sent to Sentry. `uberbringer route` prints the env on the terminal only. -- A reload's WARN names the sections that need a restart, never a value (question 20). -- A WARN at start names `UBERBRINGER_PRINTERS_*` and `UBERBRINGER_ROUTING_*` variables, never their values (question 2). +- A reload's WARN names the sections that need a restart, never a value (decision 20). +- A WARN at start names `UBERBRINGER_PRINTERS_*` and `UBERBRINGER_ROUTING_*` variables, never their values (decision 2). - `/healthz` shows printer names and models, never addresses. - Sentry gets the printer's name as a tag, never content, a topic or an Expr message. @@ -646,7 +604,7 @@ CONFIG, PACKAGING, DOCKER ### Stage 1a: Named printers, a lane each -**Goal.** `[printers.]` tables add printers beside `[printer]`, the printer `default`. Each printer has its own client, renderer and lane, and `preview --printer` lays a job out for any of them. No route reaches a named printer yet: every job still prints on the default printer, and a config with `[printer]` alone prints as today. Needs job-store stage 1c. Questions 1-5, and 6, settled. +**Goal.** `[printers.]` tables add printers beside `[printer]`, the printer `default`. Each printer has its own client, renderer and lane, and `preview --printer` lays a job out for any of them. No route reaches a named printer yet: every job still prints on the default printer, and a config with `[printer]` alone prints as today. Needs job-store stage 1c. Decisions 1-6. **Work.** @@ -654,8 +612,8 @@ internal/pkg/config - config.go: - `Printers map[string]PrinterConfig` (`printers`), and `DefaultPrinter()`. - The key kind for a table of named tables, its walker checks and its per-entry defaults (Architecture, PRINTERS IN THE CONFIG). No variable. - - `validatePrinter(path, p)`, made from today's printer checks, reporting `printers..`. `[printers.default]` is refused, pointing to `[printer]`. A host and port repeated across `[printer]` and `[printers.*]` is refused, hosts compared without regard to case (question 3). - - The names of any `UBERBRINGER_PRINTERS_*` variables, for internal/app's WARN (question 2). + - `validatePrinter(path, p)`, made from today's printer checks, reporting `printers..`. `[printers.default]` is refused, pointing to `[printer]`. A host and port repeated across `[printer]` and `[printers.*]` is refused, hosts compared without regard to case (decision 3). + - The names of any `UBERBRINGER_PRINTERS_*` variables, for internal/app's WARN (decision 2). - The comment on the environment prefix: named printers have no variable. - value.go: `Value()` reaches `printers..`. @@ -665,7 +623,7 @@ internal/pkg/printqueue - One waiting list and worker per lane; `Run` starts them all; shutdown covers every lane. The first store error from any lane stops every lane, and `Run` returns it. - `Meta.Printer`, the printer the job goes to; empty means the default. `Submit` refuses a name with no lane (`ErrUnknownPrinter`, name assumed), a guard for a bug: the server and the router check first. - Capacity per lane; `Pending` per printer and in total. - - A delivery's `Printer` is its lane's name. Restore puts each queued delivery on its lane; one whose printer is gone fails (question 5). + - A delivery's `Printer` is its lane's name. Restore puts each queued delivery on its lane; one whose printer is gone fails (decision 5). - `OnFailure` gains the printer; every worker log line carries `printer`. internal/app/uberbringer @@ -735,17 +693,17 @@ internal/app/uberbringer ### Stage 1b: `?printer=`, `/healthz` per printer, and deliveries in job status -**Goal.** `?printer=` sends a job to one printer on every print and preview route. `/healthz` lists every printer, and its code still follows the default printer. Job status gains `deliveries`. Needs stage 1a. Questions 7-9. +**Goal.** `?printer=` sends a job to one printer on every print and preview route. `/healthz` lists every printer, and its code still follows the default printer. Job status gains `deliveries`. Needs stage 1a. Decisions 7-9. **Work.** internal/pkg/printqueue -- queue.go: `Status.Deliveries` and the job's own fields (question 8), with their `jsonschema` tags. +- queue.go: `Status.Deliveries` and the job's own fields (decision 8), with their `jsonschema` tags. - schema_test.go: a delivery's `status` enum held to the `State` constants. internal/app/uberbringer/server - server.go: `Deps` takes the printers, the default first, each with its name, configured model, `Printer` and `Previewer`; the nil checks follow. `Jobs.Pending` per printer. -- handlers.go: `handlePrint` reads the query (question 7). `handleHealth`, `healthResponse` and `queueHealth` (question 9): the default printer read once, filling `printer` and the first entry; the others read in parallel. +- handlers.go: `handlePrint` reads the query (decision 7). `handleHealth`, `healthResponse` and `queueHealth` (decision 9): the default printer read once, filling `printer` and the first entry; the others read in parallel. - handlers_modules.go: `moduleQuery` checks `printer` against the configured names; the `defaultPrinter` constant and its "the only printer is" message go. - handlers_preview.go: `?printer=` on both preview routes; the JSON answer's `printer`. - routes.go: query parameters for `/api/v1/print` and `/api/v1/preview`; `unknown_printer` and `invalid_query` in their error lists; the descriptions of the module routes' `printer` and of `/healthz` ("depends on the printer alone"). @@ -791,40 +749,40 @@ internal/app/uberbringer **Done when.** - The full gate passes. -- With the owner's OK, a status read only: with a second printer configured at an address that refuses the connection, `/healthz` answers `200`, with that entry `unreachable`. An address with no host behind it may read `timeout` instead (question 9). -- Paper, with the owner's OK, once a second printer is on hand and its status sheet read (question 31): one short receipt with `?printer=`. It prints there only, with line breaks at 42 columns. Wait for his report. With one printer only, this check waits, and the stage is done on the fakes. +- With the owner's OK, a status read only: with a second printer configured at an address that refuses the connection, `/healthz` answers `200`, with that entry `unreachable`. An address with no host behind it may read `timeout` instead (decision 9). +- Paper, with the owner's OK, once a second printer is on hand and its status sheet read (decision 31): one short receipt with `?printer=`. It prints there only, with line breaks at 42 columns. Wait for his report. With one printer only, this check waits, and the stage is done on the fakes. ### Stage 2a: Expr rules on a job's source, shape and clock -**Goal.** Expr rules route every job without `?printer=`, in unicast, multicast and broadcast. They see the job's source, module, subscription, shape and clock. The rule set is compiled once, ordered, and held as one value the engine can swap. The decision is stored with the job and shown in its status. Needs stage 1b. Questions 11-16, 18 and 19, and 10 and 17, settled. +**Goal.** Expr rules route every job without `?printer=`, in unicast, multicast and broadcast. They see the job's source, module, subscription, shape and clock. The rule set is compiled once, ordered, and held as one value the engine can swap. The decision is stored with the job and shown in its status. Needs stage 1b. Decisions 10-19. **Work.** go.mod -- `github.com/expr-lang/expr` at its latest stable release, unless docs/plans/templates.md stage 1 has added it (question 10). Run govulncheck. `go generate` regenerates THIRD-PARTY-LICENSES.md and internal/app/uberbringer/licenses_embed.md, in the commit that first links Expr into the binary. +- `github.com/expr-lang/expr` at its latest stable release, unless docs/plans/templates.md stage 1 has added it (decision 10). Run govulncheck. `go generate` regenerates THIRD-PARTY-LICENSES.md and internal/app/uberbringer/licenses_embed.md, in the commit that first links Expr into the binary. internal/pkg/rules (new, unless docs/plans/templates.md has added it; its decision 1) -- options.go: `Options(zone)` and the iteration guard (question 17), unless templates stage 1 has added them. +- options.go: `Options(zone)` and the iteration guard (decision 17), unless templates stage 1 has added them. - rules.go: the generic engine (Architecture, ROUTING RULES), unless templates stage 2 has built it. internal/pkg/routing (new) - env.go: `Env` with stage 2a's variables and their `expr` tags (Architecture, THE ENVIRONMENT), built from the job, `Meta.Source`, the job's size, the acceptance time and the zone. -- action.go: `Mode` and `To`; `to` resolved against the printers and groups (question 13). +- action.go: `Mode` and `To`; `to` resolved against the printers and groups (decision 13). - router.go: the `printqueue.Router`. - A rule's runtime error gives one WARN line with the rule's name, the `job_id`, and the line and column from Expr's `*file.Error`, never `Error()`. Any other error type gives the rule's name only. - - One Sentry event per rule per run, through a reporter internal/app passes in (question 15). + - One Sentry event per rule per run, through a reporter internal/app passes in (decision 15). - A panic while the env is built is recovered: logged at ERROR, reported once, and the job goes to the default printer. internal/pkg/printqueue - queue.go: - `Route` (`By`, `Rule`, `Mode`, `Printers`) and the `Router` interface; `Options.Router`, nil keeping stage 1b's behaviour. - - `Submit` routes first, outside the locks, then makes one delivery per printer of the route. Capacity by question 19: a delivery whose lane is full is inserted `failed`, "printer's queue is full", and logged at WARN by `job_id` and `printer`; `queue_full` only when every target lane is full. The job's JSON is encoded once, for `bytes` and for `Store.Add`. + - `Submit` routes first, outside the locks, then makes one delivery per printer of the route. Capacity by decision 19: a delivery whose lane is full is inserted `failed`, "printer's queue is full", and logged at WARN by `job_id` and `printer`; `queue_full` only when every target lane is full. The job's JSON is encoded once, for `bytes` and for `Store.Add`. - `Status.Route`, with enum tags for `by` and `mode`. - store.go: `Record.Route`, and `Delivery.Candidates` and `Delivery.SentTo` for stage 3; the memory store keeps them. `Add` takes a delivery inserted `failed`, and then syncs. - schema_test.go: the `by` and `mode` enums. internal/pkg/jobstore, if job-store stage 1d has shipped -- A schema step to `user_version` 2 with the route and delivery columns (question 18). Otherwise job-store stage 1d's schema takes them. +- A schema step to `user_version` 2 with the route and delivery columns (decision 18). Otherwise job-store stage 1d's schema takes them. internal/pkg/config - config.go: @@ -845,13 +803,13 @@ Docs - a warning that a multicast or broadcast rule not limited by `source` or `types` sends `raw` jobs to every model; - § Environment variables: the exception names `[routing]`, and the WARN for `UBERBRINGER_ROUTING_*`. - configs/config.example.toml: a commented `[routing]` example. -- docs/ntfy.md: a subscription gets its printer through a rule on `subscription` or `source`; the paper budget counts jobs, not deliveries (question 19). +- docs/ntfy.md: a subscription gets its printer through a rule on `subscription` or `source`; the paper budget counts jobs, not deliveries (decision 19). - docs/development.md § Package layout: `internal/pkg/rules` and `internal/pkg/routing`. - docs/api.md: job status `route`; `queue_full` only when every printer of the route is full; a delivery `failed` with "printer's queue is full". - docs/swagger.json regenerated. - design.md: "Jobs remember their source", which now names the route; the stack choices, with no variable for `[routing]`, and Expr's version and the size it adds unless templates stage 1 has recorded them. - CLAUDE.md: the layout and the imports (routing → rules, printqueue, receipt; rules → Expr; internal/app → routing). -- docs/plans/job-store.md, while it is open: DELIVERIES AND SEVERAL PRINTERS and stage 1d's RECORDS name the route columns (question 18). +- docs/plans/job-store.md, while it is open: DELIVERIES AND SEVERAL PRINTERS and stage 1d's RECORDS name the route columns (decision 18). - CHANGELOG: under Added, routing rules and groups, and `route` in job status; under Changed, a multicast job is refused only when every printer's queue is full. **Tests.** @@ -899,7 +857,7 @@ internal/app/uberbringer/server ### Stage 2b: Reloading the rules -**Goal.** SIGHUP swaps in the config's `[routing]` without a restart (question 20). Needs stage 2a. +**Goal.** SIGHUP swaps in the config's `[routing]` without a restart (decision 20). Needs stage 2a. **Work.** @@ -909,7 +867,7 @@ internal/app/uberbringer - every rule's `to` and every group member must name a printer that has a lane, or the whole reload is refused at ERROR and the old set kept; `broadcast` resolves to the printers that have lanes; - each other section that changed is logged at WARN by its name only, as needing a restart; - then the rule set and the groups are swapped as one value, and one INFO line gives the number of rules; - - if docs/plans/remote-printers.md stage 2 has shipped, `[agents]`' `tokens_since` takes effect too (question 20). + - if docs/plans/remote-printers.md stage 2 has shipped, `[agents]`' `tokens_since` takes effect too (decision 20). internal/pkg/config - A comparison of two configs that leaves `[routing]` out and names the sections that differ (name assumed). @@ -941,7 +899,7 @@ Docs ### Stage 2c: Notification facts in rules, and the dry-runs -**Goal.** Rules also see a notification's topic, priority and tags, a digest's, and the token's subject. `uberbringer route` and the JSON preview show what the rules decide. Needs stage 2a. Questions 16 and 21. +**Goal.** Rules also see a notification's topic, priority and tags, a digest's, and the token's subject. `uberbringer route` and the JSON preview show what the rules decide. Needs stage 2a. Decisions 16 and 21. **Work.** @@ -959,7 +917,7 @@ internal/pkg/modules internal/app/uberbringer - ntfy.go: cards and digests carry their facts. - preview.go: `preview --module` follows `Build`'s result. -- route.go (new): `uberbringer route` (question 21). +- route.go (new): `uberbringer route` (decision 21). internal/app/uberbringer/server - auth.go: the token's subject joins the scope in Locals; never the token. @@ -967,7 +925,7 @@ internal/app/uberbringer/server - handlers_preview.go: the JSON answer's `route`; `Jobs` gains `Route`, and `fakeJobs` with it. Docs -- docs/configuration.md § routing: the variables stage 2c adds, and the example's `urgent-on-desks` rule and its group, which answers formatters' open question. +- docs/configuration.md § routing: the variables stage 2c adds, and the example's `urgent-on-desks` rule and its group. - docs/cli.md: `uberbringer route`. - docs/security.md: the token's subject becomes the rule variable `client`; the env and Expr's run-time messages are never logged; the JSON preview's `route` shows rule and printer names to tokens limited to modules. - docs/api.md: the JSON preview's `route`. @@ -995,7 +953,7 @@ internal/app/uberbringer/server ### Stage 3: Anycast with ordered failover -**Goal.** `mode = "anycast"` sends a job to the first printer of an ordered list that takes it. A failure before any byte of the job fails over at once; after bytes, question 22 decides. Needs stage 2c, and job-store stage 1c's `beforeWrite`. If job-store phase 2b has shipped, a move takes its delivery lock. Questions 22-26, and question 23's paper check before the stage starts. +**Goal.** `mode = "anycast"` sends a job to the first printer of an ordered list that takes it. A failure before any byte of the job fails over at once; after bytes, decision 22 decides. Needs stage 2c, and job-store stage 1c's `beforeWrite`. If job-store phase 2b has shipped, a move takes its delivery lock. Decisions 22-26, and decision 23's paper check before the stage starts. **Work.** @@ -1003,23 +961,23 @@ internal/pkg/printer - printer.go: - `readStatus(ctx, conn)`: the `DLE EOT` reads on an open connection. `Status` calls it after `connect`; the checked send calls it on its own connection, so it never waits on its own slot. `GS r 1`, once stage 4a adds it, belongs to `Status` alone. - `Settle(ctx, read, delay)` (name assumed): the read again of a not-ready answer, moved from server/handlers.go's `settledPrinterStatus`. `/healthz` passes `Client.Status` and its `HealthRecheckDelay`; the checked send passes a read over its own connection, and the 750-ms delay internal/app gives each lane. - - The checked send: after the dial and before `beforeWrite`, the settled read of question 23. + - The checked send: after the dial and before `beforeWrite`, the settled read of decision 23. - `Send` returns an error type (`SendError`, name assumed) holding the count `Write` took, with a method `NothingWritten() bool`. internal/pkg/printqueue - queue.go: - The send contract, in printqueue's own terms, so that neither package imports the other. A failed send that never called `beforeWrite` sent nothing. One that called it sent nothing only when its error matches, through `errors.As`, an interface printqueue declares with `NothingWritten() bool`. - Anycast deliveries (Architecture, ANYCAST AND FAILOVER). Only anycast branches on how far a send got; unicast and multicast keep today's rule of retrying every error. - - The down marks (question 24), in memory under the status lock. - - Moves (question 26): under the status lock, and the delivery lock once job-store phase 2b exists; only while the queue is open and the delivery is not cancelled; never after a failure while the delivery's context has ended. - - Round timers (question 25); shutdown and a cancel see a delivery on a timer as waiting. + - The down marks (decision 24), in memory under the status lock. + - Moves (decision 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 (decision 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). +- store.go: `Sending` adds its printer to `SentTo`; a restore drops printers no longer configured from a delivery's list (decision 5). - `Status`: an anycast delivery's `printers` and `sent_to`. internal/pkg/routing, internal/pkg/config -- `anycast` accepted; `to` kept in order, groups expanded in member order (question 13). +- `anycast` accepted; `to` kept in order, groups expanded in member order (decision 13). internal/pkg/jobstore, if it exists - Writes `candidates` at insert and `sent_to` with each `sending` mark. @@ -1057,7 +1015,7 @@ internal/pkg/printqueue, with a fake sender per printer that fails at a chosen p - the anycast job is accepted while that lane is full; - the mark clears on a success and after the hold; - with every printer of the list marked, the first is tried. -- Rounds by question 25: +- Rounds by decision 25: - no worker sleeps while a delivery waits for its round, so the last printer's lane goes on with its own jobs; - once the rounds are spent, the last attempt goes to the first printer without the check; - a delivery that sent bytes starts no new round. @@ -1086,18 +1044,18 @@ internal/app/uberbringer ### Stage 4a: The exact model, and status per model -**Goal.** The profile keeps the exact model. The TM-T88VII reports paper near-end through `GS r 1`, and status counts the bits question 29 adds. Needs only the TM-T88VII on hand, which can be the default printer of a test config until stage 1a ships. Questions 27-29. +**Goal.** The profile keeps the exact model. The TM-T88VII reports paper near-end through `GS r 1`, and status counts the bits decision 29 adds. Needs only the TM-T88VII on hand, which can be the default printer of a test config until stage 1a ships. Decisions 27-29. **Work.** -First, before any code, with the owner's OK. These are status reads only, nothing printed, and they settle the details of questions 28 and 29: +First, before any code, with the owner's OK. These are status reads only, nothing printed, and they settle the details of decisions 28 and 29: 1. On the TM-T88VII: the `GS r 1` reply byte with a full roll, and with a roll past the near-end mark if he has one, read by a probe run from outside the repository. 2. On the TM-T88IV just after power-on, and on the TM-T88VII with DIP switch 2-1 as it is set: does `/healthz` read `unknown`, a sign that automatic-status frames reach the connection? -3. The TM-T88VII's status sheet, read by the owner: column mode, paper width, paper reduction, top margin, the port 9100 time-out and DIP switch 2-1 (question 31). +3. The TM-T88VII's status sheet, read by the owner: column mode, paper width, paper reduction, top margin, the port 9100 time-out and DIP switch 2-1 (decision 31). internal/pkg/escpos -- profile.go: `Model` and the status capabilities (question 27); `LookupProfile` keeps the exact name. -- status.go: the `GS r 1` request and its decoder (question 28); question 29's bits in `Status`, `Normalized()` and `Ready()`; the comment on the TM-T88VII. +- profile.go: `Model` and the status capabilities (decision 27); `LookupProfile` keeps the exact name. +- status.go: the `GS r 1` request and its decoder (decision 28); decision 29's bits in `Status`, `Normalized()` and `Ready()`; the comment on the TM-T88VII. internal/pkg/printer - printer.go: `Status` sends `GS r 1` last when the profile says so, only when online and ready, under its own deadline, and closes the connection after a missed answer. If stage 3 has shipped, `readStatus`, which the checked send uses, stays `DLE EOT` only. @@ -1130,11 +1088,11 @@ Docs ### Stage 4b: Each new model checked on paper -**Goal.** One paper check per new model confirms its line breaks, box borders and cut. A model whose box borders need another `box_line_spacing` gets its own default in the profile (question 30). It runs once for each new model as it arrives, and needs only that printer on hand, configured as the default printer of a test config or, from stage 1a, as a named one. It needs stage 4a only when a value differs between models of one family. Questions 30 and 31. +**Goal.** One paper check per new model confirms its line breaks, box borders and cut. A model whose box borders need another `box_line_spacing` gets its own default in the profile (decision 30). It runs once for each new model as it arrives, and needs only that printer on hand, configured as the default printer of a test config or, from stage 1a, as a named one. It needs stage 4a only when a value differs between models of one family. Decisions 30 and 31. **Work.** -First, the owner reads the new printer's status sheet (question 31), if stage 4a has not. +First, the owner reads the new printer's status sheet (decision 31), if stage 4a has not. Only if the paper check finds a model that needs a value other than 0: - internal/pkg/escpos, profile.go: `BoxLineSpacing`, the model's default, with its source. diff --git a/docs/plans/remote-printers.md b/docs/plans/remote-printers.md index 76c942b..5ec6927 100644 --- a/docs/plans/remote-printers.md +++ b/docs/plans/remote-printers.md @@ -1,6 +1,6 @@ # 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. +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 decision 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) @@ -42,7 +42,7 @@ For stage 1: For stage 2: 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. + - Trade-off: the agent carries the whole server, about 20 MB once Expr is linked (printers decision 10), on boards where it uses a fraction of it. 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. @@ -66,7 +66,7 @@ For stage 2: - 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. -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). +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 decision 9). - Trade-off: the public route shows agent names, as it shows printer names. For stage 3: @@ -74,7 +74,7 @@ For stage 3: 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, 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. + - `[agent.printers.]`: `address` and `port` (9100) only, from the file only, as printers decision 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 (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. @@ -103,7 +103,7 @@ For stage 4: - 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 (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. + - The address rule of printers decision 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. 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. @@ -115,12 +115,12 @@ For stage 4: - 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. 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 decision 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. + - 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 decision 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 decision 17 says; it is not counted as a retry. - Trade-off: after a long outage the backlog prints at once, stale receipts included. -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. +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 decision 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. @@ -201,7 +201,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. +- Whether a printer behind a UB-E02 or UB-E03 takes the connection and holds the bytes while it is offline: printers decision 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. @@ -313,7 +313,7 @@ MESSAGES (stage 1; decision 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 (decision 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 decision 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`. @@ -371,7 +371,7 @@ STATUS (stage 4; decision 19) 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 (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. +- 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 decision 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 diff --git a/docs/plans/templates.md b/docs/plans/templates.md index cbf21de..7895c70 100644 --- a/docs/plans/templates.md +++ b/docs/plans/templates.md @@ -1,6 +1,6 @@ # Plan: templates and rules in Expr, for ntfy and webhooks -Status: **planned; nothing is built.** The owner accepted every proposed default on 2026-12-01 (Decisions), and design.md's Planned next item 5 records them. Each stage runs in its own session, briefed from its section: stage 1 follows decisions 1-11, stage 2 decisions 12-17, stage 3 decision 18, and stage 4 decisions 19-29. The stages run in order, except that stage 3 needs only stage 2, and stage 4 needs stages 1 and 2. This plan shares Expr with docs/plans/printers.md, whose questions still await the owner; where a stage leans on one of its assumed defaults, the decision here says so. Stage 4 leans on docs/plans/job-store.md in the same way, on its stage 1c and decision 10's duplicate check (decision 22). Every receipt printed on the live printer needs the owner's OK. Whichever stage finishes last deletes this plan, its findings with it, and design.md's Planned next item 5. +Status: **planned; nothing is built.** The owner accepted every proposed default on 2026-12-01 (Decisions), and design.md's Planned next item 5 records them. Each stage runs in its own session, briefed from its section: stage 1 follows decisions 1-11, stage 2 decisions 12-17, stage 3 decision 18, and stage 4 decisions 19-29. The stages run in order, except that stage 3 needs only stage 2, and stage 4 needs stages 1 and 2. This plan shares Expr with docs/plans/printers.md; where a stage builds on one of its decisions, the decision here says so. Stage 4 builds on docs/plans/job-store.md in the same way, on its stage 1c and decision 10's duplicate check (decision 22). Every receipt printed on the live printer needs the owner's OK. Whichever stage finishes last deletes this plan, its findings with it, and design.md's Planned next item 5. ## Decisions (owner, 2026-11-30) @@ -15,9 +15,9 @@ The owner accepted the details below on 2026-12-01. They are numbered, so the re For stage 1: -1. **Who adds Expr and the shared engine.** printers.md adds Expr and `internal/pkg/rules` in its stage 2a, which may not have shipped when this plan starts. Whichever stage comes first adds Expr, at its latest stable release (v1.18.1, 2026-11-22, at the time of writing), with govulncheck, as printers.md question 10 plans. The licence notices and the binary's size, recorded in design.md, follow in the first commit that links Expr into the binary, since the notices come from what `./cmd/uberbringer` links (design.md:296-300). Stage 1 needs only the compile options both share, `rules.Options` (name assumed); stage 2 needs the engine. If printers stage 2a has not shipped by then, stage 2 builds `internal/pkg/rules` as printers.md's Architecture, ROUTING RULES, describes it, and printers stage 2a reuses it. If printers stage 2a has shipped with its options inline, stage 1's first commit moves them into `rules.Options` with no change in behaviour. - - This leans on printers.md's assumed defaults for rule order (its question 12), compile errors (14), runtime errors (15) and compile options (17). An answer there that differs changes stage 2 here the same way. - - Trade-off: the engine's interface is fixed here before the owner has answered printers.md. The first plan to ship carries the 5.3-5.8 MB that Expr adds. +1. **Who adds Expr and the shared engine.** printers.md adds Expr and `internal/pkg/rules` in its stage 2a, which may not have shipped when this plan starts. Whichever stage comes first adds Expr, at its latest stable release (v1.18.1, 2026-11-22, at the time of writing), with govulncheck, as printers.md decision 10 plans. The licence notices and the binary's size, recorded in design.md, follow in the first commit that links Expr into the binary, since the notices come from what `./cmd/uberbringer` links (design.md:296-300). Stage 1 needs only the compile options both share, `rules.Options` (name assumed); stage 2 needs the engine. If printers stage 2a has not shipped by then, stage 2 builds `internal/pkg/rules` as printers.md's Architecture, ROUTING RULES, describes it, and printers stage 2a reuses it. If printers stage 2a has shipped with its options inline, stage 1's first commit moves them into `rules.Options` with no change in behaviour. + - This follows printers.md's decisions on rule order (its decision 12), compile errors (14), runtime errors (15) and compile options (17). + - Trade-off: the first plan to ship carries the 5.3-5.8 MB that Expr adds. 2. **What a template is.** A template is one Expr expression, in one of two forms. - `card`: the expression returns a map of a notification's fields (`title`, `message`, `markdown`, `priority`, `tags`, `topic`, `time`, `links`, `image` and `file`), and the existing card lays it out, as for the `notify` and `ntfy` modules: the priority's form, links as QR codes, markers, and every cap a card applies (design.md:116-176). On a subscription, the card is marked `(updated)` from what the subscriber knows, as today's card is. - `elements`: the expression returns a list of elements, as a `/print` job's `elements` array. Expr's map and list literals and its `map`, `filter`, `concat` and `flatten` build it, so a template can lay out any receipt the blocks can. @@ -27,7 +27,7 @@ For stage 1: 3. **Where templates live.** Templates live in the config file, as a list of tables, `[[templates]]`, read from the file only, as `[[ntfy.subscriptions]]` is. Each has `name`, `description`, `input` (`json` or `ntfy`, decision 5), `form` (`card` or `elements`), `expr`, the expression, best written as a TOML multi-line literal string so that quotes need no escaping, and `sample`, a sample payload in JSON, which is required. - A list of tables builds on the subscriptions' loader, so this plan does not wait for the named tables printers stage 1a adds, and `config get` already refuses to print one (config/value.go:28-30), samples included. - The sample needs only the fields the template reads, so a payload of many kilobytes can be cut down to a few lines. - - No variable sets `[[templates]]`, nor, from later stages, `[[ntfy.rules]]` or `[webhooks]`. At start one WARN line names any `UBERBRINGER_TEMPLATES_*` or `UBERBRINGER_WEBHOOKS_*` variable, never its value, as printers.md question 2 does for its sections. + - No variable sets `[[templates]]`, nor, from later stages, `[[ntfy.rules]]` or `[webhooks]`. At start one WARN line names any `UBERBRINGER_TEMPLATES_*` or `UBERBRINGER_WEBHOOKS_*` variable, never its value, as printers.md decision 2 does for its sections. - Trade-off: long templates make the config long, and the config holds `api.secret`, so whoever edits templates can read it. 4. **Templates and the existing modules.** Every template is also a module. It appears in `GET /api/v1/modules` with its description, prints at `POST /api/v1/print/` and previews at `POST /api/v1/preview/`, with the same query (`copies`, `printer`), answers and token scopes as `note`, `notify` and `ntfy`. A `json` template takes a JSON object as its body, as the module routes document it (server/handlers_modules.go:21-23); an `ntfy` template takes one ntfy message object, decoded leniently as the `ntfy` module does. - Template names share the modules' namespace and pattern, `^[a-z][a-z0-9-]{0,31}$` (modules/registry.go:96). A template named like a built-in module is a config error. @@ -41,7 +41,7 @@ For stage 1: - Numbers: a body is decoded with `UseNumber`, and a whole number that fits 64 bits becomes an int, any other a float. Expr's `string()` prints a float in exponent form, so order 1234567 would print as `1.234567e+06`, and a 64-bit ID would lose digits. Expr's own `fromJSON` is replaced by one that decodes the same way. - Two helper functions: `cut(s, n)`, which keeps at most `n` characters and ends a cut string with `...`, as titles are cut; and `stamp(t)`, which formats a time in `format.timezone` with `format.time_layout`, as cards print times. - Trade-off: a template cannot read anything outside its payload, such as a printer's state or a value from another message. -6. **Compile options and Expr's limits.** The options of printers.md question 17, shared through `rules.Options`: `now()` and `$env` turned off, `Timezone` set to `format.timezone` once it is known to load, and Expr's default node limit (10,000) and memory budget (1,000,000 per run). `now` is injected: the time the payload was received, so a dry-run and the tests reproduce any output. Expr does no I/O. Turning off `$env` needs v1.18 or later: v1.17.8's checker ignores it. +6. **Compile options and Expr's limits.** The options of printers.md decision 17, shared through `rules.Options`: `now()` and `$env` turned off, `Timezone` set to `format.timezone` once it is known to load, and Expr's default node limit (10,000) and memory budget (1,000,000 per run). `now` is injected: the time the payload was received, so a dry-run and the tests reproduce any output. Expr does no I/O. Turning off `$env` needs v1.18 or later: v1.17.8's checker ignores it. - Expr counts no steps, and its VM takes no context, so a run cannot be stopped from outside (Investigation findings, EXPR). The text it loops over need not be the owner's: an issue's body or a commit message comes from whoever wrote it, and a `json` template on a module route takes a body from a token limited to modules. A predicate inside another, or `in` on a list inside a predicate, is quadratic in that text. - So a run has a budget of 1,000,000 iterations. A `Patch` visitor (name of the guard assumed) wraps the list of every predicate builtin (`map`, `filter`, `all`, `any`, `none`, `one`, `count`, `sum`, `find`, `groupBy`, `sortBy`, `reduce` and the like) and the right side of `in` in a guard that charges the list's length, passed through `WithContext`. A nested predicate is charged on each pass of the outer one, so the bound is the total. A run past the budget fails, as any run that fails (decisions 8 and 15). - A run still going after 1 s is logged at WARN with the template's or rule's name, from a timer, so even a run that never ends is seen. @@ -53,7 +53,7 @@ For stage 1: - Every `image` a template builds is `optional`, as a card's are (modules/card.go:233). Its `url` may come from the payload. It is fetched by the worker through `safehttp`, like every image, so it cannot reach the host's own network unless `images.*` allows it, and a broken one prints `[image unavailable]` rather than failing the job. - Each built job is laid out by the text preview, which fetches nothing, before it is queued, so a job over `format.max_lines` fails as a template's run fails, not later in the worker. - Trade-off: a commit message over 4,096 bytes fails the receipt unless the template cuts it. A template cannot make an image required. -8. **A template that fails on a module route.** A run fails when Expr returns an error or the result fails decision 7's checks. The route answers `422` with a new code, `template_failed`, whose `details` give the template's name and, for an Expr error, the line and column, never Expr's message. The failure is logged once at WARN with the template's name and position, and reported to Sentry once per template per run, without the message, as printers.md question 15 does for a rule. A result that fails validation gives its problems' paths only, such as `elements[2] (kv)`, since a problem's text can quote the payload. +8. **A template that fails on a module route.** A run fails when Expr returns an error or the result fails decision 7's checks. The route answers `422` with a new code, `template_failed`, whose `details` give the template's name and, for an Expr error, the line and column, never Expr's message. The failure is logged once at WARN with the template's name and position, and reported to Sentry once per template per run, without the message, as printers.md decision 15 does for a rule. A result that fails validation gives its problems' paths only, such as `elements[2] (kv)`, since a problem's text can quote the payload. - Expr's messages quote values from the env, such as `invalid operation: int(alerts-door)` (printers.md, Investigation findings, EXPR), and the env holds print contents. - The error type lives in `modules` (`TemplateError`, name assumed), so the server matches it without importing templates or Expr (invariant 7). - `module_failed` stays for a built-in module's bug, which is a fault of the code; a template's failure is a fault of the config. @@ -68,7 +68,7 @@ For stage 1: For stage 2: -12. **Where ntfy rules live, and their shape.** They live in `[[ntfy.rules]]`, a list of tables read from the file only, as `[[ntfy.subscriptions]]` is. Each rule has `name`, `order`, `when`, `action`, `template`, `bypass` (decision 16) and `enabled`, as printers.md's rules have (its questions 11 and 12): a unique name by the subscriptions' rule; a unique, required `order`, lower first, disabled rules included; and the first match wins. `when` sees decision 5's `ntfy` environment, `subscription` and `updated` included, so one list serves every subscription. `template` names a template whose `input` is `ntfy`; the config refuses one that does not. +12. **Where ntfy rules live, and their shape.** They live in `[[ntfy.rules]]`, a list of tables read from the file only, as `[[ntfy.subscriptions]]` is. Each rule has `name`, `order`, `when`, `action`, `template`, `bypass` (decision 16) and `enabled`, as printers.md's rules have (its decisions 11 and 12): a unique name by the subscriptions' rule; a unique, required `order`, lower first, disabled rules included; and the first match wins. `when` sees decision 5's `ntfy` environment, `subscription` and `updated` included, so one list serves every subscription. `template` names a template whose `input` is `ntfy`; the config refuses one that does not. - Trade-off: a rule for one subscription says so in `when`. 13. **The actions, and today's settings.** There are three actions. - `print`: print the message, through `template` if it names one, or as today's card if it is empty; @@ -77,7 +77,7 @@ For stage 2: - The rules run after the server's `min_priority` filter and after `updates = "skip"`, so a skipped update reaches no rule. `drop` and `digest` end there. `print` goes on through quiet hours, then the paper budget and `bypass_priority` (ntfy/subscriber.go:497-534). So the rules decide what prints and how, and the subscription's settings still decide when. A message no rule matches prints as today. - A rule does not route. Which printer prints stays with printers.md's `[routing]` rules; where both have shipped, the routing environment gains `template`, the template's name or empty, so a routing rule can send by template. - Trade-off: a dropped message counts nowhere but the DEBUG line, and two rule lists decide one message's fate. -14. **What an ntfy rule sees, and its errors.** Unlike a routing rule, which sees routing facts only (printers.md question 16), an ntfy rule sees the message's title and text, since choosing by them is the point. Its runtime error is handled as printers.md question 15 has it: the rule does not match, the next is tried, and a WARN line gives the subscription, the rule's name and Expr's position, never the message, at most once a minute per rule. A rule's `Explain` output goes to the terminal only. +14. **What an ntfy rule sees, and its errors.** Unlike a routing rule, which sees routing facts only (printers.md decision 16), an ntfy rule sees the message's title and text, since choosing by them is the point. Its runtime error is handled as printers.md decision 15 has it: the rule does not match, the next is tried, and a WARN line gives the subscription, the rule's name and Expr's position, never the message, at most once a minute per rule. A rule's `Explain` output goes to the terminal only. - A panic while the environment is built, a rule runs or a template's result is walked is recovered, since on the subscription's goroutine it would end the daemon: logged at ERROR, reported once, and then the rule does not match, or the card prints. - Trade-off: a rule can now read print contents, which raises the stakes of a log line that quotes it; the tests send a sentinel through every path (stage 2, Tests). 15. **A template that fails on an ntfy message.** The message prints as today's card instead, so a broken template loses nothing. The failure is logged at WARN with the subscription, the template and the position, and reported once per template per run, as decision 8. A template that returns `nil` prints nothing, as a `drop` does. @@ -87,9 +87,9 @@ For stage 2: - Without `bypass`, a held message prints as a digest row, as today; docs/templates.md warns of it. - A rule's decision is made each time the subscription offers a message, and never stored. A message offered again after a full queue is decided again. - Trade-off: a `bypass` rule can print more than the budget allows, which is what `bypass_priority` already does by priority. A reload between two offers can change the decision. -17. **Reloading.** Once printers stage 2b ships, SIGHUP swaps `[[templates]]`, `[[ntfy.rules]]` and, from stage 4, `[webhooks]` together with `[routing]`, as one snapshot behind one `atomic.Pointer`. A file that fails keeps the old snapshot, as printers.md question 20 has it. Until then, a change needs a restart. +17. **Reloading.** Once printers stage 2b ships, SIGHUP swaps `[[templates]]`, `[[ntfy.rules]]` and, from stage 4, `[webhooks]` together with `[routing]`, as one snapshot behind one `atomic.Pointer`. A file that fails keeps the old snapshot, as printers.md decision 20 has it. Until then, a change needs a restart. - Each message and each request loads the snapshot once. The subscriber's decision carries an opaque handle to the compiled template, which ntfy hands back to `Handler.Message` untouched, so a reload between the two cannot leave a decision naming a template the snapshot lacks. A webhook's handler takes one value bound to one snapshot, its preset, secret, rules and templates, and uses only that. - - Templates compile with the running `format.timezone` and lay out cards with the running card options, as printers.md question 20 compiles its rules, so `stamp`, `date()` and the cards agree. A reload resets the once-per-run reports, so a template fixed and broken again is reported again. + - Templates compile with the running `format.timezone` and lay out cards with the running card options, as printers.md decision 20 compiles its rules, so `stamp`, `date()` and the cards agree. A reload resets the once-per-run reports, so a template fixed and broken again is reported again. - Trade-off: this plan adds no reload of its own. For stage 3: