Record the owner's acceptance of the job-store plan

The owner accepted every proposed default of docs/plans/job-store.md on
2026-12-01. Its open questions become numbered decisions, without the
alternatives, and design.md's Planned next item 1 records them.
Decisions 7 and 21 keep the wording that the remote-printers plan had
already settled. Each stage now follows its decisions, and the
"(assumed)" marks on the plan's own defaults go.

The other plans cite job-store decisions in place of questions:
printers.md, remote-printers.md, templates.md and ntfy.md. Templates
decision 22 now follows job-store decision 10 rather than leaning on an
assumed default.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
57_WolveandClaude Opus 5.5 committed 2026-12-01 11:03:30 -06:00
1 parent a06c12a202
commit f302b76ef4
6 files changed
+181 -154

No files matched your search

+37 -3
View File
@@ -443,9 +443,43 @@ Formatters phase 5 is split into features of their own, each planned in
not yet written is described here until it is.
1. **Job store and print previews**: `docs/plans/job-store.md` (written;
its open questions await the owner). It includes cancelling a waiting
job, `Queue.Cancel`, so that an ntfy `message_delete` can cancel one,
and a job made of one delivery per printer.
the owner accepted every proposed default, 2026-12-01).
- Jobs survive a restart in SQLite, through `modernc.org/sqlite` and
`database/sql`, not GORM: WAL mode, one connection, exclusive
locking. `jobs.db` lives in `[state] dir`, which replaces
`ntfy.state_dir` and keeps the ntfy state files too; empty keeps the
queue in memory. modernc's exact `modernc.org/libc` is the one
exception to "latest stable", held by a gate check.
- A job has one delivery per printer, each with its own state. A
delivery's `sending` mark is synced before its first byte, and one
found in `sending` at start ends `uncertain`, a new terminal status,
never sent again. Failures, cancels and ntfy jobs are synced too; an
insert from the HTTP routes is not, so a power cut can lose it but
never print it twice. A store write that fails mid-run stops the
daemon.
- Queued jobs print in order after a restart, however old. The store
keeps the validated job as JSON, never rendered bytes or tokens;
statuses are kept by `queue.history`, content within
`queue.content_bytes` (64 MiB).
- ntfy and webhook jobs are checked against the last 512 source and
reference pairs of their source, so a replay after a crash never
prints twice. A digest gets a reference of its own, saved before it
is submitted.
- A job's status derives from its deliveries: once all have finished,
`uncertain` over `failed` over `done`.
- The Docker image keeps a store in `/var/lib/uberbringer`
(**Breaking** for a container that cannot write there). CI builds
the ARM targets.
- `GET /api/v1/jobs` lists the history and `DELETE /api/v1/jobs/{id}`
cancels a waiting job, for full tokens. An ntfy `message_delete`
cancels the waiting receipts of its notification (`Queue.Cancel`);
`message_clear` does not, and the subscriber filters priorities
itself.
- A PNG preview draws the paper one pixel per dot, box drawing from
the cell geometry and other glyphs from a bitmap font. Stored jobs
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.
+122 -129
View File
@@ -1,6 +1,6 @@
# Plan: persistent job store and image previews
Status: **planning; nothing is built.** 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-3, 1b needs 4, 1c needs 5, 6 and 8-12, 1d needs 13-15, phase 2 needs 16, phase 2b needs 17 and 18, phase 3 needs 19 and phase 4 needs 20. Questions 7 and 21 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. Phases 3a-3c need nothing from phases 1 and 2, so they can come first if the owner wants previews sooner. Phase 2b needs phase 1 but not phase 2, so it can come before phase 2. design.md's Planned next item 1 says this plan is written and its questions await the owner; once the owner accepts the plan, that item records his answers.
Status: **planned; nothing is built.** The owner accepted every proposed default on 2026-12-01 (Decisions), and design.md's Planned next item 1 records them. Each stage runs in its own session, briefed from its section: stage 1a follows decisions 1-3, stage 1b decision 4, stage 1c decisions 5-12, stage 1d decisions 13-15, phase 2 decision 16, phase 2b decisions 17 and 18, phase 3 decision 19 and phase 4 decision 20; phase 5 holds decisions 21-23. Phases 3a-3c need nothing from phases 1 and 2, so they can come first if the owner wants previews sooner. Phase 2b needs phase 1 but not phase 2, so it can come before phase 2. Every check on the live printer needs the owner's OK.
## Decisions (owner, 2026-11-30)
@@ -33,106 +33,100 @@ Status: **planning; nothing is built.** Each stage runs in its own session, brie
The owner also asked a question, which is not a decision: **does a store that keeps data in memory and syncs it to disk later, such as BadgerDB, cut disk IO?** Hosts may be Raspberry-Pi-class with SD cards, which wear. "Does keeping data in memory cut IO?" under Investigation findings answers it.
## 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. Decisions 7 and 21 follow docs/plans/remote-printers.md decisions 17 and 24.
Each has the default the plan assumes unless the owner says otherwise.
For stage 1a:
Before stage 1a:
1. **The store.** SQLite through `modernc.org/sqlite` (v1.63.0 today) and `database/sql`, with about 8 hand-written statements; not GORM.
- What SQLite buys here: crash recovery and torn writes are handled by SQLite rather than by our code; it is the owner's stated preference; and it leaves room for queries later. The design itself runs none: every status lives in memory, the store is read by sequence number only, and exclusive locking (decision 3) keeps even the `sqlite3` CLI from reading `jobs.db` while the daemon runs.
- Not GORM, though it writes the same bytes and fsyncs as plain SQL (measured). Its pure-Go dialector, `github.com/glebarez/sqlite` v1.11.0, has had no release since 2024-03-14 and asks for maintainers (issue #152). A plain `go get` of it pulls in SQLite 3.41.2, and it cannot share a binary with `modernc.org/sqlite`. GORM's default logger prints SQL with its values, which would log print contents. It adds about 10 MB to the daemon against 4 MB, because one reflective call in GORM stops the linker dropping unused methods anywhere in the binary; Expr makes the same call (docs/plans/printers.md, Investigation findings, EXPR), so once Expr is in the binary (docs/plans/templates.md, decision 1) that part of the gap goes.
- Trade-off: on the measures alone the home-grown journal wins: the fewest bytes and syncs, no dependency, the same behaviour on every platform. At the device the gap is smaller than the logical bytes suggest, because each sync also rewrites a 4 KiB block and roughly 12-20 KiB of ext4 journal: SQLite writes about 3-5× the journal's bytes, not about 30× (estimates, COMPARED). At 500 jobs a day the candidates write between about 8 and 120 MiB a day.
- The store comes in at its latest stable release.
2. **Hardware for the measurements.** The owner runs stage 1a's probe on one Pi-class host with an SD card, and on an ARMv6 board if he has one. modernc's own CI names no ARMv6 target, and there are old SIGSEGV reports for linux/arm. Without an ARMv6 run, the armv6 tarball ships the store untested on hardware, and the CHANGELOG says so.
3. **SQLite's locking mode.** `locking_mode=EXCLUSIVE` and one connection. There is no `-shm` file and no mmap, and a second daemon on the same directory fails at start. Trade-off: reads wait behind writes and their fsyncs, and no other process, the `sqlite3` CLI or a later read-only `uberbringer` command included, can read the database while the daemon runs. Statuses stay in memory, so only the worker and previews by ID read the database.
1. **The store.** Assumed: SQLite through `modernc.org/sqlite` (v1.63.0 today) and `database/sql`, with about 8 hand-written statements; not GORM.
- What SQLite buys here: crash recovery and torn writes are handled by SQLite rather than by our code; it is the owner's stated preference; and it leaves room for queries later. The design itself runs none: every status lives in memory, the store is read by sequence number only, and exclusive locking (question 3) keeps even the `sqlite3` CLI from reading `jobs.db` while the daemon runs.
- On the measures alone the home-grown journal wins: the fewest bytes and syncs, no dependency, the same behaviour on every platform. At the device the gap is smaller than the logical bytes suggest, because each sync also rewrites a 4 KiB block and roughly 12-20 KiB of ext4 journal: SQLite writes about 3-5× the journal's bytes, not about 30× (estimates, COMPARED). At 500 jobs a day the candidates write between about 8 and 120 MiB a day.
- GORM on SQLite, the first choice, writes the same bytes and fsyncs as plain SQL (measured). But it adds about 10 MB to the daemon against 4 MB (+67% against +26%), because one reflective call in GORM stops the linker dropping unused methods anywhere in the binary. Expr makes the same call (docs/plans/printers.md, Investigation findings, EXPR), and the owner has accepted linking it (docs/plans/templates.md, decision 1), so once Expr is in the binary GORM's extra cost over plain SQL falls to about its own code. Its pure-Go dialector, `github.com/glebarez/sqlite` v1.11.0, has had no release since 2024-03-14 and asks for maintainers (issue #152). A plain `go get` of it pulls in SQLite 3.41.2, and it cannot share a binary with `modernc.org/sqlite`. GORM's default logger prints SQL with its values, which would log print contents.
- bbolt v1.5.0 adds only 0.25 MB and no new dependency. It writes 2.4-5× SQLite's bytes and needs 2 fdatasyncs per commit, and mixing synced and unsynced commits can corrupt it, so it cannot leave the cheap writes unsynced.
- A home-grown append-only journal writes least (about 2 KB and 1 fsync per job) and adds no dependency. The cost is our own recovery and compaction code and its tests.
- BadgerDB v4.9.6 is not recommended by the research: it adds 8.4 MB, allocates 86 MiB of heap at Open by default, is never built for 32-bit ARM by its CI, and does not sync on Windows.
- Whichever store is chosen comes in at its latest stable release.
2. **Hardware for the measurements.** Assumed: the owner runs stage 1a's probe on one Pi-class host with an SD card, and on an ARMv6 board if he has one. modernc's own CI names no ARMv6 target, and there are old SIGSEGV reports for linux/arm. Without an ARMv6 run, the armv6 tarball ships the store untested on hardware, and the CHANGELOG says so.
3. **SQLite's locking mode.** Assumed: `locking_mode=EXCLUSIVE` and one connection. There is no `-shm` file and no mmap, and a second daemon on the same directory fails at start. Trade-off: reads wait behind writes and their fsyncs, and no other process, the `sqlite3` CLI or a later read-only `uberbringer` command included, can read the database while the daemon runs. Statuses stay in memory, so only the worker and previews by ID read the database.
For stage 1b:
Before stage 1b:
4. **Config key and directory.** Assumed: a top-level `[state] dir` (`UBERBRINGER_STATE_DIR`) holds `jobs.db` and the `ntfy-<name>.json` files and replaces `ntfy.state_dir`. Empty keeps the queue in memory, as today, for Windows development and tests.
- No release has shipped `ntfy.state_dir` (it is under `[Unreleased]` only), so there is no compatibility shim unless the owner says a host has it set. Unknown keys in the file are errors, so a config with `[ntfy] state_dir`, which install.sh writes into every new config today, then stops the daemon at start until the line is changed.
4. **Config key and directory.** A top-level `[state] dir` (`UBERBRINGER_STATE_DIR`) holds `jobs.db` and the `ntfy-<name>.json` files and replaces `ntfy.state_dir`. Empty keeps the queue in memory, as today, for Windows development and tests.
- No release has shipped `ntfy.state_dir` (it is under `[Unreleased]` only), so there is no compatibility shim. Unknown keys in the file are errors, so a config with `[ntfy] state_dir`, which install.sh writes into every new config today, then stops the daemon at start until the line is changed.
- Trade-off: one key ties ntfy state to the job store. Every host with a subscription also gets the durable store and its disk writes.
- Alternatives: reuse `ntfy.state_dir`, so that an ntfy-named key controls the job store; or add a separate `queue.store` path, two keys for one directory.
Before stage 1c:
For stage 1c:
5. **Must an accepted job survive a power cut?** Assumed: not for jobs from the HTTP routes. Their insert commits without a sync. It survives a crash of the daemon, and the next synced commit makes it durable too. A power cut within about 30-35 s of a `202` can lose a job that was never sent, as today, but never prints it twice. Yes costs a second fsync per job.
5. **An accepted job need not survive a power cut.** Jobs from the HTTP routes commit their insert without a sync. It survives a crash of the daemon, and the next synced commit makes it durable too. A power cut within about 30-35 s of a `202` can lose a job that was never sent, as today, but never prints it twice. A synced insert would cost a second fsync per job.
- Jobs from ntfy subscriptions do commit with a sync. The subscriber records a message as handled in its own state file, synced within a second, so a lost insert would lose the message for good. Their number is bounded by each subscription's paper budget, apart from messages at or above `bypass_priority`.
6. **An age limit for queued jobs.** The owner decided that queued jobs survive a restart. Assumed: they print in submission order however old, and waiting jobs stay queued at a clean stop as after a crash, since a stop and a start is a restart too. docs/plans/remote-printers.md decision 18 builds on this default: a remote printer's deliveries wait however long its agent is offline. Trade-off: after a long outage, stale receipts print, such as a notification from hours before. An age limit would be a new key.
7. **The job that was being sent at the crash. Settled** by docs/plans/remote-printers.md decision 17, which ends a remote send whose outcome stays unknown as `uncertain` and never sends it again; design.md's Planned next item 3 records it. A job found in `sending` at start takes the same new terminal status, `uncertain`, whose `error` says the receipt may have printed. It is never resent; a client or a person sends it again if the paper shows it missing. The name is not `unknown`, which `/healthz` already uses for a printer that gives no status. Trade-off: a new status value reaches clients that switch on `status`, so it is listed under **Breaking**.
8. **What is stored.** Assumed: the job as validated, a `receipt.Job` in JSON after any module built it. Not the rendered bytes, not the module payload, never the token.
6. **No age limit for queued jobs.** The owner decided that queued jobs survive a restart. They print in submission order however old, and waiting jobs stay queued at a clean stop as after a crash, since a stop and a start is a restart too. docs/plans/remote-printers.md decision 18 builds on this: a remote printer's deliveries wait however long its agent is offline. Trade-off: after a long outage, stale receipts print, such as a notification from hours before. An age limit would be a new key (phase 5).
7. **The job that was being sent at the crash ends `uncertain`,** as docs/plans/remote-printers.md decision 17 ends a remote send whose outcome stays unknown. It is a new terminal status, whose `error` says the receipt may have printed. It is never resent; a client or a person sends it again if the paper shows it missing. The name is not `unknown`, which `/healthz` already uses for a printer that gives no status. Trade-off: a new status value reaches clients that switch on `status`, so it is listed under **Breaking**.
8. **What is stored.** The job as validated, a `receipt.Job` in JSON after any module built it. Not the rendered bytes, not the module payload, never the token.
- Rendered bytes are never needed to resume, since a job that reached `sending` is never resent. Storing them would cost up to 256,000 bytes per image, repeat the body for each copy, and need the raw spans and the render context to be read back.
- Trade-offs: a preview by ID re-renders the job under today's config, so it cannot show exactly what was sent; and a queued job resumed after a restart renders under the config of that moment and fetches its images again.
- Either way, 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.** Assumed: 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.
- Trade-off: `webserver.body_limit` (4 MiB) × 1000 jobs is about 4 GB, too much for an SD card and more than bbolt's 2 GB map on 32-bit ARM, so a count alone cannot bound it.
- 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.
- An age limit, for privacy, would be another key.
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. Assumed:
- 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.
- 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.
- Webhook jobs with a delivery ID take part too, as docs/plans/templates.md decision 22 has it; that decision leans on this default. The ID is the sender's, read only after the delivery's signature passed.
- Webhook jobs with a delivery ID take part too, as docs/plans/templates.md decision 22 has it. The ID is the sender's, read only after the delivery's signature passed.
- The queue keeps the last 512 (source, reference) pairs of each subscription and each hook with their job IDs, apart from the statuses, so `queue.history = 0` cannot defeat the check.
- A digest gets a reference of its own, a TypeID with the prefix `digest`, in place of the fixed `digest`, minted when the digest is made. The subscriber saves the digest with its reference before it submits it, so a restart submits the same digest under the same reference. The window also exists today, for a digest that printed in that second; stage 1c closes it. The saved digest is kept apart from messages held after it: were they added to a digest whose job was queued before the crash, the duplicate check would answer with that job, and they would never print. A rule's digest (docs/plans/templates.md, decision 18) gets its reference and its save the same way; whichever of stage 1c and templates stage 3 lands second covers it.
- Trade-off: a digest can cost one more state save, two fsyncs.
11. **A store write that fails after start** (disk full, an I/O error, corruption found mid-run). Assumed: the daemon stops.
11. **A store write that fails after start** (disk full, an I/O error, corruption found mid-run) stops the daemon.
- The queue stops and `Run` returns the error, which stops the daemon; it is logged once at ERROR and reported to Sentry once. Memory changes only after the store has committed, so no client reads a status the store lacks, and a job keeps the state the store last recorded: one that had not reached `sending` stays queued and prints once after the restart.
- The request whose insert failed gets `500` `internal_error`; later ones get `shutting_down`. ntfy messages wait: the subscriber retries any `Submit` error and offers the message again after the restart.
- systemd restarts the daemon after 5 s, at most 3 times in 60 s (`StartLimitBurst=3`), then leaves the unit failed.
- Trade-off: the API is down until someone acts. The alternative keeps it up in a "store broken" mode: `Submit` refuses with a new code, `503` `store_unavailable`, reported to Sentry once, and the worker sends nothing more. That is more API and one more mode to test. Today a failing `Submit` is a `500` and a Sentry event on every request.
12. **A job's status from its deliveries.** A job has one delivery per printer, and its API `status` derives from theirs (Architecture, DELIVERIES AND SEVERAL PRINTERS). Each job has one delivery until the printers plan lands, but the schema and the `Store` interface carry deliveries from stage 1c, so the rule is settled with them. 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. Assumed:
- Trade-off: the API is down until someone acts.
12. **A job's status from its deliveries.** A job has one delivery per printer, and its API `status` derives from theirs (Architecture, DELIVERIES AND SEVERAL PRINTERS). Each job has one delivery until the printers plan lands, but the schema and the `Store` interface carry deliveries from stage 1c, so the rule is settled with them. 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.
- Cancelled deliveries 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;
- `printing` while any is unfinished, once one has been taken or has finished;
- 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`.
- Trade-off: a client that reads only `status` learns that one printer failed only once the others have finished; the `deliveries` array shows each printer at once. The alternative reads `failed` as soon as any delivery fails, which a client may take as final while another printer still prints.
- Trade-off: a client that reads only `status` learns that one printer failed only once the others have finished; the `deliveries` array shows each printer at once.
Before stage 1d:
For stage 1d:
13. **The libc pin.** modernc requires the exact `modernc.org/libc` its go.mod pins (v1.80.1 for v1.63.0; the latest libc is v1.82.14). Assumed: the owner accepts this exception to "latest stable" for libc alone, which then moves only with `modernc.org/sqlite`. Stage 1d records it in CLAUDE.md's dependency rule and in design.md, and adds a gate check, since a routine `go get -u` would otherwise move libc and break the driver silently. The other new indirect modules are `modernc.org/mathutil`, `modernc.org/memory`, `github.com/dustin/go-humanize`, `github.com/ncruces/go-strftime` and `github.com/remyoudompheng/bigfft`; bigfft has no tagged release, so it comes in at a pseudo-version, as a few indirect modules in go.mod already do. This question falls away if question 1 picks another store.
14. **The Docker image's state directory.** Assumed: the image sets `UBERBRINGER_STATE_DIR=/var/lib/uberbringer`, so every container keeps a job store there, and it declares no `VOLUME`; docs/docker.md asks for a named volume, or a bind mount owned by `10001:10001`. This is **Breaking**: a container started with `--read-only` and no volume, or with a bind mount owned by root, stops at start where 0.2.0 ran, since today only containers with subscriptions touch the directory. Trade-off: a `VOLUME` would give such containers an anonymous volume and let them start, but anonymous volumes pile up, and a new container silently starts with an empty one.
15. **Operational defaults.** Each assumed:
- A store that cannot be opened stops the daemon with an error naming the file, and docs/install.md and docs/docker.md give the steps to move it aside. A damaged ntfy state file, by contrast, means a fresh start with a warning. Trade-off: starting with an empty store would silently forget the waiting jobs and which jobs were in doubt.
13. **The libc pin.** modernc requires the exact `modernc.org/libc` its go.mod pins (v1.80.1 for v1.63.0; the latest libc is v1.82.14). The owner accepts this exception to "latest stable" for libc alone, which then moves only with `modernc.org/sqlite`. Stage 1d records it in CLAUDE.md's dependency rule and in design.md, and adds a gate check, since a routine `go get -u` would otherwise move libc and break the driver silently. The other new indirect modules are `modernc.org/mathutil`, `modernc.org/memory`, `github.com/dustin/go-humanize`, `github.com/ncruces/go-strftime` and `github.com/remyoudompheng/bigfft`; bigfft has no tagged release, so it comes in at a pseudo-version, as a few indirect modules in go.mod already do.
14. **The Docker image's state directory.** The image sets `UBERBRINGER_STATE_DIR=/var/lib/uberbringer`, so every container keeps a job store there, and it declares no `VOLUME`; docs/docker.md asks for a named volume, or a bind mount owned by `10001:10001`. This is **Breaking**: a container started with `--read-only` and no volume, or with a bind mount owned by root, stops at start where 0.2.0 ran, since today only containers with subscriptions touch the directory. A `VOLUME` would let such containers start, but anonymous volumes pile up, and a new container would silently start with an empty one.
15. **Operational defaults.**
- A store that cannot be opened stops the daemon with an error naming the file, and docs/install.md and docs/docker.md give the steps to move it aside. A damaged ntfy state file, by contrast, means a fresh start with a warning. Starting with an empty store would silently forget the waiting jobs and which jobs were in doubt.
- The stop timeout must exceed `printer.write_timeout` plus about 10 s (Architecture, JOB STATES). The unit keeps systemd's 90 s default, enough at the default 30-s write; docs/docker.md asks Docker users, whose default is 10 s, for `--stop-timeout 40` at the defaults. Trade-off: a shorter timeout kills a write, which leaves its job `uncertain`, never doubled.
- `UMask=0077` in the unit, so the WAL and any later file are 0600 like the database. Trade-off: none known; the state directory is 0700 already.
- CI and the gate gain a `CGO_ENABLED=0` build of linux/arm (GOARM=6) and linux/arm64, and the libc check (question 13). Trade-off: a longer CI run; today nothing compiles the arm targets before a release tag.
- `UMask=0077` in the unit, so the WAL and any later file are 0600 like the database; the state directory is 0700 already.
- CI and the gate gain a `CGO_ENABLED=0` build of linux/arm (GOARM=6) and linux/arm64, and the libc check (decision 13). Trade-off: a longer CI run; today nothing compiles the arm targets before a release tag.
Before phase 2:
For phase 2:
16. **A history listing.** Assumed: yes, `GET /api/v1/jobs`, newest first, for full tokens only. A listing shows every client's jobs, so tokens limited to modules do not get it. Trade-off: more API to keep; without it, a client must remember its own job IDs. Its details, also assumed:
16. **A history listing.** `GET /api/v1/jobs`, newest first, for full tokens only. A listing shows every client's jobs, so tokens limited to modules do not get it. Trade-off: more API to keep. Its details:
- `status`, `source`, `before` (a job ID; the page starts after it) and `limit` (1-100, default 50) in the query. A `before` that names a job no longer kept answers `invalid_query`, so paging never skips jobs silently.
- Job status gains `ref`, so a client can find the job an ntfy message became.
- `/healthz`'s `queue` gains `uncertain`: the jobs found `uncertain` at the latest start, those with a delivery that `Load` turned from `sending`. From remote-printers stage 4 it also counts the jobs a remote send has left `uncertain` since that start. A clean restart sets it back to 0, so it does not stay up for about 1,000 jobs. Alternatives: a time window, or a route that marks a job checked.
- `/healthz`'s `queue` gains `uncertain`: the jobs found `uncertain` at the latest start, those with a delivery that `Load` turned from `sending`. From remote-printers stage 4 it also counts the jobs a remote send has left `uncertain` since that start. A clean restart sets it back to 0, so it does not stay up for about 1,000 jobs.
Before phase 2b:
For phase 2b:
17. **Cancelling over HTTP.** Assumed: yes, `DELETE /api/v1/jobs/{id}`, for full tokens only, since a token limited to modules could otherwise cancel other clients' jobs. It cancels each delivery that has not reached `sending` and answers `200` with the status. A job with nothing left to cancel, every delivery having reached `sending`, finished or been cancelled, answers `200` with its status if any delivery is cancelled, so a repeated request answers as the first did, and `409` with a new code, `job_started`, if none is; an unknown ID answers `job_not_found`. Trade-off: more API, and the first route that changes a job already queued; without it, only an ntfy `message_delete` cancels.
18. **Which ntfy events cancel.** Each assumed:
- `message_clear`, which ntfy sends when a notification is dismissed or marked read, cancels nothing and drops no held message. The subscriber goes on skipping it as an event that prints nothing and recording it as dealt with: its ID joins the seen set, the cursor moves as for any message (during a replay, not before the first keepalive: docs/plans/ntfy.md decision 2), and the state is saved within a second. Trade-off: a notification already read on a phone still prints while it waits. Cancelling on it would let any client of the topic that reads or dismisses the notification stop its receipt.
- A subscription with `min_priority` 4 or 5 receives no `message_delete` today. ntfy applies the `priority=` filter to deletes and clears too (`queryFilter.Pass` in its server/types.go), and a delete carries no priority, so it counts as 3. Assumed: the subscriber stops sending `priority=` and leaves out lower priorities itself, as `deliver` already does. The JSON stream and the WebSocket build their query with one function (docs/plans/ntfy.md decision 8), so both stop sending it, and that plan leans on this default. Trade-off: the server then sends every message of the topics, and the subscriber reads and drops those below `min_priority`. The alternative keeps the server's filter, and such a subscription cannot cancel.
- A `message_delete` older than `max_backlog` still cancels: that check leaves out stale receipts, and a delete prints nothing. So a delete made during a long outage cancels a job restored after it (question 6). A delete the server no longer keeps is lost, and its job prints.
17. **Cancelling over HTTP.** `DELETE /api/v1/jobs/{id}`, for full tokens only, since a token limited to modules could otherwise cancel other clients' jobs. It cancels each delivery that has not reached `sending` and answers `200` with the status. A job with nothing left to cancel, every delivery having reached `sending`, finished or been cancelled, answers `200` with its status if any delivery is cancelled, so a repeated request answers as the first did, and `409` with a new code, `job_started`, if none is; an unknown ID answers `job_not_found`. Trade-off: more API, and the first route that changes a job already queued.
18. **Which ntfy events cancel.**
- `message_clear`, which ntfy sends when a notification is dismissed or marked read, cancels nothing and drops no held message. The subscriber goes on skipping it as an event that prints nothing and recording it as dealt with: its ID joins the seen set, the cursor moves as for any message (during a replay, not before the first keepalive: docs/plans/ntfy.md decision 2), and the state is saved within a second. Cancelling on it would let any client of the topic that reads or dismisses the notification stop its receipt. Trade-off: a notification already read on a phone still prints while it waits.
- A subscription with `min_priority` 4 or 5 receives no `message_delete` today. ntfy applies the `priority=` filter to deletes and clears too (`queryFilter.Pass` in its server/types.go), and a delete carries no priority, so it counts as 3. So the subscriber stops sending `priority=` and leaves out lower priorities itself, as `deliver` already does. The JSON stream and the WebSocket build their query with one function (docs/plans/ntfy.md decision 8), so both stop sending it. Trade-off: the server then sends every message of the topics, and the subscriber reads and drops those below `min_priority`.
- A `message_delete` older than `max_backlog` still cancels: that check leaves out stale receipts, and a delete prints nothing. So a delete made during a long outage cancels a job restored after it (decision 6). A delete the server no longer keeps is lost, and its job prints.
Before phase 3:
For phase 3:
19. **The preview image.** Assumed: PNG, one pixel per printer dot (512 wide on the TM-T88), black on white, the cut as a dashed line where the paper is cut, asked for with `Accept: image/png` on the preview routes; text stays the default.
19. **The preview image.** PNG, one pixel per printer dot (512 wide on the TM-T88), black on white, the cut as a dashed line where the paper is cut, asked for with `Accept: image/png` on the preview routes; text stays the default.
- Images: a `base64` image is drawn from its data, and a `url` image is fetched through safehttp, as printing does, so the picture shows the dithered image. All of one preview's fetches share one deadline, 30 s; an image that failed or is still loading then is drawn as a crossed box. Trade-off: a PNG preview holds its request while it fetches and contacts the image host. That reverses three statements, which phase 3c rewrites: design.md's "a preview never fetches anything" and "a slow or broken image URL holds no HTTP request", and api.md's "prints nothing and fetches no images". The text and JSON previews still fetch nothing.
- Glyphs: box drawing and shading are drawn from the cell geometry, so lines run through the cell's centre to its edges and meet their neighbours, and shading is a dot pattern. Every other glyph comes from an embedded bitmap font, turned into Go tables by a generator. The font must cover the rest of cp437, cp850, cp858 and cp1252, come at 12×24 for Font A (9×17 for Font B, or the nearest size padded to it), and have a licence that allows embedding. Candidates: Terminus (OFL) and Spleen (BSD), both with a 12×24 size; their coverage of these code pages is unchecked. Trade-off: the font's licence ships in the repository. An outline font from `golang.org/x/image` needs no new file, but rasterised to 12×24 or 9×17 its lines do not meet at the cell edges, and box joins are what the owner checks on paper.
- Glyphs: box drawing and shading are drawn from the cell geometry, so lines run through the cell's centre to its edges and meet their neighbours, and shading is a dot pattern; box joins are what the owner checks on paper. Every other glyph comes from an embedded bitmap font, turned into Go tables by a generator. The font must cover the rest of cp437, cp850, cp858 and cp1252, come at 12×24 for Font A (9×17 for Font B, or the nearest size padded to it), and have a licence that allows embedding. Candidates: Terminus (OFL) and Spleen (BSD), both with a 12×24 size; their coverage of these code pages is unchecked. Trade-off: the font's licence ships in the repository.
- Size: the line count does not bound the picture. An image, a QR code or a barcode counts as one line, yet one image may be 4,000 dots tall (`images.max_height`), text may be 8 times as tall, and a job holds up to 500 elements in up to 5 copies. A picture is capped at 100,000 dots, about 14 m of paper at 180 dpi and 6.4 MB at one bit per dot and 512 dots; a taller one answers `422` with a new code, `preview_too_long`. Trade-off: a receipt that prints can be too long to preview.
- The printer encodes QR codes itself, so the preview's code can differ from the paper in pattern and, for data the printer packs more densely, in size.
- The CLI gains `uberbringer preview --png <file>`.
Before phase 4:
For phase 4:
20. **Previews by ID: source and scope.** Assumed: the stored job re-rendered (question 8), for full tokens only, since the answer is print content and a token limited to modules could otherwise read other clients' receipts. A job whose content was pruned (question 9) answers `410` with a new code, `job_content_expired`. As a PNG it loads its images as question 19 says.
20. **Previews by ID: source and scope.** The stored job re-rendered (decision 8), for full tokens only, since the answer is print content and a token limited to modules could otherwise read other clients' receipts. A job whose content was pruned (decision 9) answers `410` with a new code, `job_content_expired`. As a PNG it loads its images as decision 19 says.
Later:
For phase 5, later:
21. **Epson's process-ID acknowledgement** (`GS ( H` fn 48) on models that have it. **Settled** by docs/plans/remote-printers.md decision 24, which builds it at the agent only with this plan's phase 5, on the owner's word (its stage 6): not in phases 1-4; phase 5, if the owner says yes after a paper test. 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 in the store.** Assumed: no; 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. Assumed: unchanged. docs/plans/remote-printers.md decision 17 leans on this default: 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). The owner's 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.
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.
## Investigation findings
@@ -142,7 +136,7 @@ THE ONE WRITE THAT MATTERS
- A TCP write returns when the kernel has the bytes, not when they print. No store can record "printed" at the moment of sending.
- What a store can do is record `sending` durably before the first byte goes out. A job found in `sending` after a restart is in doubt and is never resent; a job still `queued` never reached the printer.
- A process crash (panic, OOM kill, kill -9) loses nothing already written, because the page cache survives. A power cut or a kernel crash loses writes not yet synced: Linux writes dirty data back about 30-35 s after it changed (a 30-s expiry, checked every 5 s). On a Pi, pulling the plug is the common crash.
- So the `sending` mark must be synced before the first byte, whatever the store. Most other writes may be lazy: losing one makes a job read as `uncertain`, or loses a job never sent, but never prints one twice. The exception is `failed`: rolled back to `queued`, a job its client was told had failed would print after the restart (Architecture). The minimum is one fsync per job and one per failure, or two per job if an accepted job must survive a power cut (question 5).
- So the `sending` mark must be synced before the first byte, whatever the store. Most other writes may be lazy: losing one makes a job read as `uncertain`, or loses a job never sent, but never prints one twice. The exception is `failed`: rolled back to `queued`, a job its client was told had failed would print after the restart (Architecture). The minimum is one fsync per job and one per failure, or two per job if an accepted job must survive a power cut (decision 5).
- Every durability claim assumes the device honours a flush. SQLite's docs warn that "most consumer-grade mass storage devices lie about syncing". SD cards are suspect, and no source names specific cards.
SQLITE IN WAL MODE
@@ -162,8 +156,8 @@ SQLITE IN WAL MODE
| Policy | fsyncs per job |
|---|---|
| FULL for `sending`, `failed` and inserts from ntfy (assumed) | 1 + 0.04, plus 1 per failed job and per ntfy job |
| FULL for every insert too (question 5 answered yes) | 2 + 0.04, plus 1 per failed job |
| FULL for `sending`, `failed` and inserts from ntfy (decision 5) | 1 + 0.04, plus 1 per failed job and per ntfy job |
| FULL for every insert too (not decision 5) | 2 + 0.04, plus 1 per failed job |
| FULL for every commit | 3 + 0.04, or 4 with the pruning as its own commit |
| NORMAL for every commit | 0.04, with no guard against a second print after a power cut |
@@ -247,7 +241,7 @@ COMPARED (per job: accepted, sending, done with pruning; a 1.5 KB body; 1000 job
| Queries | SQL | key order; TypeIDs sort by time | our own maps | key order |
- The device estimates add, for each sync, a rewritten 4 KiB block and roughly 12-20 KiB of ext4 journal to the logical bytes; stage 1a measures them. On that measure SQLite writes about 3-5× the journal's bytes, where the logical bytes differ about 30×.
- At 500 jobs a day, fsyncs a day: SQLite with the assumed policy about 520, plus failures and ntfy jobs; the journal 500-1,500; SQLite with FULL for everything about 1,500 plus checkpoints; bbolt 2,000-3,000. For scale, saving every ntfy keepalive would have cost about 1,900 synced writes a day per subscription, which is why that cursor is saved at most every 10 minutes.
- At 500 jobs a day, fsyncs a day: SQLite with decision 5's policy about 520, plus failures and ntfy jobs; the journal 500-1,500; SQLite with FULL for everything about 1,500 plus checkpoints; bbolt 2,000-3,000. For scale, saving every ntfy keepalive would have cost about 1,900 synced writes a day per subscription, which is why that cursor is saved at most every 10 minutes.
DOES KEEPING DATA IN MEMORY CUT IO?
Only by not syncing. Badger's saving with `SyncWrites=false` comes from leaving its memory-mapped log to kernel writeback, so that several commits landing in one 4 KiB page within the 30-35 s window reach the disk once. Every candidate can make the same trade: SQLite with `synchronous=NORMAL`, or a journal without fdatasync (bbolt's `NoSync` can corrupt its file). A process crash loses nothing in any of them; a power cut loses up to about 30-35 s of commits. If those include a `sending` mark, the restarted daemon sees the job as `queued` and prints it again. So the saving comes from the sync policy, not from the store, and the `sending` mark must be synced regardless. The cheapest correct policy, syncing `sending` and letting most other writes ride on it, is natural in SQLite's WAL and in a journal, works in Badger on Linux only, and cannot be done safely in bbolt.
@@ -309,13 +303,13 @@ COMPATIBILITY
- 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).
- 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 (question 14, **Breaking**).
- 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 (question 23).
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).
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.
@@ -325,11 +319,11 @@ INVARIANTS
JOB STATES
A job has one or more deliveries, one per printer it goes to (DELIVERIES AND SEVERAL PRINTERS). The states below are a delivery's: each delivery runs through them on its own, with its own attempts, `sent_at` and error. Until the printers plan lands, each job has one delivery, for the printer `default`, and the job's API `status` is that delivery's, as the table shows; with several deliveries it derives from all of them (question 12).
A job has one or more deliveries, one per printer it goes to (DELIVERIES AND SEVERAL PRINTERS). The states below are a delivery's: each delivery runs through them on its own, with its own attempts, `sent_at` and error. Until the printers plan lands, each job has one delivery, for the printer `default`, and the job's API `status` is that delivery's, as the table shows; with several deliveries it derives from all of them (decision 12).
| Stored state of a delivery | Written | Synced | API `status` | After a restart |
|---|---|---|---|---|
| `queued` | on `Submit`, with its job, before the `202` | for ntfy jobs only (question 5) | `queued` | queued again, in submission order |
| `queued` | on `Submit`, with its job, before the `202` | for ntfy jobs only (decision 5) | `queued` | queued again, in submission order |
| (taken: rendering, waiting for the printer's slot, dialling, or between retries that never reached `sending`) | not stored; the stored state stays `queued` | – | `printing` | still `queued`: nothing was sent |
| `sending`, attempt n | after the connection opens, before the first byte; the first sets `sent_at` | **yes** | `printing` | `uncertain`, never resent |
| `done` | after the write returned in full | no | `done` | history |
@@ -339,21 +333,21 @@ A job has one or more deliveries, one per printer it goes to (DELIVERIES AND SEV
- A dial failure writes nothing, because the mark is written only once a connection is open. Retries while the printer is offline cost no disk writes, and such a job stays safe to retry.
- A lost lazy write only weakens a status: a `done` rolled back to `sending` reads `uncertain`, and a lost insert loses a job never sent. Neither prints twice. `failed` is synced, because a `failed` rolled back to `queued` would print after the restart, after its client was told it failed and may have sent it again. Failures are rare, so the sync costs little. `cancelled` is synced for the same reason: rolled back to `queued`, a job would print after a client was told it was cancelled.
- Memory changes only after the store's commit returns. A store write that fails stops the daemon (question 11), and the job keeps the state the store last recorded.
- Memory changes only after the store's commit returns. A store write that fails stops the daemon (decision 11), and the job keeps the state the store last recorded.
- If the `sending` commit fails, the connection closes with no byte written.
- A crash between the `sending` commit and the write leaves an `uncertain` job that never printed. That is the safe direction.
- Retries after a write error stay as today (question 23; design.md accepts that a receipt that failed part-way can print part of itself twice). Each attempt commits its own `sending` mark with its number; `sent_at` keeps the first.
- Shutdown with a durable store (assumed):
- Retries after a write error stay as today (decision 23; design.md accepts that a receipt that failed part-way can print part of itself twice). Each attempt commits its own `sending` mark with its number; `sent_at` keeps the first.
- Shutdown with a durable store:
- Waiting jobs stay `queued`.
- A job that has not reached `sending` is abandoned and stays `queued`: one still rendering (its image fetches run one after another, up to the job's 2-minute bound), waiting for the printer's slot, dialling, or waiting between retries that never reached the printer. Rendering and connecting stop when the daemon stops; nothing was sent.
- A job between its `sending` commit and the end of its write finishes. So the stop takes at most `printer.write_timeout` (30 s by default) and two commits.
- A job waiting between retries after an attempt reached `sending` fails, as today, and its `sent_at` shows that bytes went out.
- Shutdown with the memory store stays as today: the job in hand finishes on its detached context, rendering included, and waiting jobs fail, since the process forgets them anyway.
- The stop timeout must therefore exceed `printer.write_timeout` plus about 10 s (question 15). A SIGKILL mid-write leaves the job `uncertain`.
- The stop timeout must therefore exceed `printer.write_timeout` plus about 10 s (decision 15). A SIGKILL mid-write leaves the job `uncertain`.
STORE FAILURES (question 11)
STORE FAILURES (decision 11)
- A store that cannot be opened stops the daemon with an error naming the file. The steps in docs/install.md and docs/docker.md: stop the daemon, move `jobs.db` and `jobs.db-wal` aside together, start it again (`systemctl reset-failed uberbringer` first if systemd stopped restarting it). The stored jobs are forgotten, and which of the last receipts printed must be checked against the paper by hand.
- After Open, any failed store write stops the daemon, as question 11 describes. Nothing is retried, since a write that failed once (a full disk, a damaged page) seldom succeeds a moment later.
- After Open, any failed store write stops the daemon, as decision 11 describes. Nothing is retried, since a write that failed once (a full disk, a damaged page) seldom succeeds a moment later.
TELLING WHICH RECEIPTS PRINTED BEFORE A CRASH
Each delivery's state tells what reached its printer:
@@ -363,13 +357,13 @@ Each delivery's state tells what reached its printer:
- `uncertain`: may have printed. At start the daemon logs one WARN line per delivery that start turned `uncertain` (`Load` says which) with its `job_id`, `printer`, `source` and `ref`, never its content, and from phase 2 `/healthz` counts their jobs. A delivery found `uncertain` at an earlier start is not logged again. A remote attempt whose outcome stays unknown turns `uncertain` during the run, with a WARN line of its own (docs/plans/remote-printers.md, decision 17). A person checks the paper; a reprint is always a new request.
- `cancelled` (phase 2b): never reached the printer.
ACKNOWLEDGEMENT, WHERE THE PRINTER HAS IT (phase 5, question 21, settled)
ACKNOWLEDGEMENT, WHERE THE PRINTER HAS IT (phase 5, decision 21)
- The rendered bytes do not change. `GS ( H 48 <id>` is appended at send time, after the final cut, with a fresh 4-byte ID for each attempt from a counter in the store. Stored and previewed bytes never hold it, which matters because `escpos.Interpret` refuses any `GS (` other than `GS ( k`.
- The connection stays open while the daemon reads frames, classified by the first byte under the mask 0x93, and polls `DLE EOT` every few seconds. The polling also keeps the network board's idle time-out (300 s on the UB-E02 and UB-E03) away. It ends when the matching ID arrives, or after a time-out set by the job's printing time.
- The send then has one of four outcomes: not sent (safe to retry), partly written, written but unconfirmed, or confirmed. Only a confirmation adds `confirmed_at` to the status. A time-out gives `uncertain`, never `failed`, and never a resend.
- After a restart, a job in `sending` or awaiting its ID is still `uncertain`. Turning acknowledgement off leaves the store exactly as safe.
- For a printer behind an agent, it runs at the agent, which owns the connection (docs/plans/remote-printers.md, decision 24).
- Holding the connection until the receipt prints would make `/healthz` time out (3 s) during long prints. While a job holds the connection, `/healthz` reports the status that connection last polled, with its age (assumed).
- Holding the connection until the receipt prints would make `/healthz` time out (3 s) during long prints. While a job holds the connection, `/healthz` reports the status that connection last polled, with its age.
THE STORE INTERFACE (printqueue)
printqueue defines the interface and an in-memory implementation and imports no database. A new package, `internal/pkg/jobstore`, implements it on disk, and internal/app wires it in. The engine can change without touching the queue. A sketch; stage 1c settles the names:
@@ -432,11 +426,11 @@ type Store interface {
}
```
- The queue keeps every retained status in memory, as today (about 1,100 at the defaults), and loads them at start. A job's status derives from its deliveries (question 12); with one delivery it is that delivery's. Status, the listing and the duplicate check read memory. The store is read at start, by the worker for the content of the job it takes, and by previews by ID. The queue decides retention and tells the store what to drop.
- The queue keeps every retained status in memory, as today (about 1,100 at the defaults), and loads them at start. A job's status derives from its deliveries (decision 12); with one delivery it is that delivery's. Status, the listing and the duplicate check read memory. The store is read at start, by the worker for the content of the job it takes, and by previews by ID. The queue decides retention and tells the store what to drop.
- Locks: a submit lock covers the sequence number, the capacity check, `Add` and the append to the waiting list. The status lock guards the status map and the waiting list; it is innermost and never held across a store call, so `Status` and `Pending` never wait for a commit. From phase 2b, a delivery lock orders every change of a delivery's state after its insert: the `sending` mark in `beforeWrite`, the worker's `Finish` and the cancel. Each checks the delivery's state in memory, commits and changes memory without releasing it. The orders are the submit lock, then the store; and the printer's connection slot, then the delivery lock, then the store. The cancel never takes the slot, so it cannot deadlock with a send, but its synced commit can delay a send waiting in `beforeWrite`, and with it `/healthz`. The store never calls back into the queue. Every state change commits first, then changes memory.
- The waiting list is a slice in sequence order, guarded by the status lock, with a channel that wakes the worker. It replaces today's `jobs` channel, whose capacity is `Size`, so it can hold a restored backlog. `Pending` reads its length and the capacity check runs against it. If more jobs were stored than `queue.size` now allows (after the key was lowered), all of them load, and `Submit` answers `queue_full` until the backlog falls below the size.
- `Submit` takes no context, here or in the server's `Jobs` and `ntfySubmitter`. `Add` runs on a background context (assumed): an insert that has begun finishes or fails, whatever the client does meanwhile.
- `Meta` gains a flag, set by ntfy subscriptions only, that marks its `Ref` as unique at its source, and `Sequence`, a card's ntfy notification (RECORDS), which phase 2b's cancel matches. A unique `Submit` commits with a sync (question 5). If the queue already holds that source and reference (question 10), `Submit` stores nothing and returns the earlier job's status, or a status with only its ID and source once that was pruned.
- `Submit` takes no context, here or in the server's `Jobs` and `ntfySubmitter`. `Add` runs on a background context: an insert that has begun finishes or fails, whatever the client does meanwhile.
- `Meta` gains a flag, set by ntfy subscriptions only, that marks its `Ref` as unique at its source, and `Sequence`, a card's ntfy notification (RECORDS), which phase 2b's cancel matches. A unique `Submit` commits with a sync (decision 5). If the queue already holds that source and reference (decision 10), `Submit` stores nothing and returns the earlier job's status, or a status with only its ID and source once that was pruned.
- `Sender.Send(ctx, data, beforeWrite func() error)`: `printer.Client` calls `beforeWrite` after the dial, before it computes the write deadline and writes, so a slow sync does not use up `write_timeout`. The queue passes a function that calls `Store.Sending` for the delivery and sets its `sent_at` on the first attempt. The synced commit runs while the printer's connection slot is held, so a slow flush, or a checkpoint that commit triggers, also delays `/healthz` (3 s). The store checkpoints when `Idle` is called, so an automatic checkpoint seldom lands on a `sending` commit.
- Restore before start: serve.go opens the store, which takes its lock, and the queue loads it before `group.Go` starts the worker, the server and the subscribers. So restored jobs go ahead of new ones, the sequence continues from the highest stored, restored statuses answer at once, and a second instance on the same directory fails before it reads the `ntfy-<name>.json` files.
- `Load` returns no content, so a backlog of up to `queue.size` × 4 MiB is not read into memory at start; the worker reads each job's content when it takes it. A stored job that no longer passes strict `DecodeJob` (after a downgrade or a field change) then fails with an error, logged by `job_id`, and is never dropped silently. Its content is never logged.
@@ -444,7 +438,7 @@ type Store interface {
- With SQLite's single connection, a `Submit` waits for its insert and may wait behind the worker's synced commit or a checkpoint. On an SD card that wait is unmeasured until stage 1a.
- The `State` constants stay in queue.go, the one file printqueue's schema test parses; `StoredState` is a separate type in store.go.
RECORDS (SQLite, if question 1 holds)
RECORDS (SQLite, decision 1)
```sql
-- PRAGMA user_version = 1 marks this schema; a later schema steps from it.
@@ -490,43 +484,42 @@ CREATE TABLE refs ( -- unique jobs, for the duplicate check
- Times are Unix nanoseconds, so a status reads the same after a restart as before it.
- A `seq`, a job's or a delivery's, can repeat after every row was pruned (`queue.history = 0`). Nothing outside the store's own rows refers to a `seq`, so that is harmless; `refs` holds job IDs, and a later counter, such as the acknowledgement's, keeps its own.
- A delivery's `done` and the pruning of the oldest jobs share one commit.
- One connection: the store takes a `*sql.Conn` at Open and holds it for its life, with the pool at one open and one idle connection and no lifetime limits, since `synchronous`, `locking_mode` and the lock belong to a connection. The pragmas are set by the connector (or the DSN's `_pragma`), so any new connection gets them too. An error on the held connection is a store failure (question 11).
- One connection: the store takes a `*sql.Conn` at Open and holds it for its life, with the pool at one open and one idle connection and no lifetime limits, since `synchronous`, `locking_mode` and the lock belong to a connection. The pragmas are set by the connector (or the DSN's `_pragma`), so any new connection gets them too. An error on the held connection is a store failure (decision 11).
- The DSN is built through the connector API, or escaped, since `state.dir` may hold spaces, `#` or `?`.
- Pragmas at open: `journal_mode=WAL`, `locking_mode=EXCLUSIVE` (question 3), `synchronous=NORMAL`, `temp_store=MEMORY`, `journal_size_limit` of 4 MiB, `secure_delete=FAST`, and `auto_vacuum=NONE` before the tables exist. `wal_autocheckpoint` stays at 1000.
- Pragmas at open: `journal_mode=WAL`, `locking_mode=EXCLUSIVE` (decision 3), `synchronous=NORMAL`, `temp_store=MEMORY`, `journal_size_limit` of 4 MiB, `secure_delete=FAST`, and `auto_vacuum=NONE` before the tables exist. `wal_autocheckpoint` stays at 1000.
- A synced commit runs `PRAGMA synchronous=FULL`, commits, and restores NORMAL in a defer, so a failed statement never leaves the connection at FULL. `Sending`, `failed`, inserts of unique jobs and, from phase 2b, `cancelled` commit this way.
- Open, in order: create the file 0600 if it is missing; set the pragmas; run `PRAGMA quick_check`, which only reads (the whole file, 2-48 MiB at the sizes in the findings), since SQLite otherwise finds a damaged page only when a statement reads it, mid-run; refuse a `user_version` newer than the binary knows, naming both; run each schema step in one synced transaction that also sets `user_version`; write once, so a second instance fails at once.
- `Idle` runs `PRAGMA wal_checkpoint(PASSIVE)`.
- `sqlite.Fdatasync(true)` on Linux, once stage 1a has shown that the unit's syscall filter allows `fdatasync`.
- Nothing else in the process opens the file, since any close drops SQLite's locks.
- A test hook, an unexported function the package's own tests set, runs inside each commit and reads `PRAGMA synchronous`, so tests see which commits ran at FULL.
- With bbolt or the journal (question 1), the same jobs and deliveries become buckets keyed by sequence number, or journal lines. The interface does not change.
RETENTION
- Statuses: every unfinished job and the last `queue.history` finished ones, as today. A job is finished once every delivery is; a `cancelled` delivery counts as finished (phase 2b).
- Content: every unfinished job's, every `uncertain` job's while its status is kept, and finished jobs' newest first up to `queue.content_bytes` (question 9). Dropping content keeps the status; a preview of that job answers `410`.
- References of unique jobs: the newest 512 per source, whatever happens to their statuses (question 10).
- Content: every unfinished job's, every `uncertain` job's while its status is kept, and finished jobs' newest first up to `queue.content_bytes` (decision 9). Dropping content keeps the status; a preview of that job answers `410`.
- References of unique jobs: the newest 512 per source, whatever happens to their statuses (decision 10).
- Pruning happens in the commit that finishes what pushes a job or content out: a delivery's `Finish`, or from phase 2b a `Cancel`. A job goes with all its deliveries.
API
- Stage 1c: `status` gains `uncertain`, in the `State` enum's `jsonschema` tag, printqueue's schema test, docs/api.md, swagger.json and the CHANGELOG under **Breaking**. Status gains `sent_at` (assumed name), set once an attempt was about to write to the printer. A store failure in `Submit` is an unexpected error: `500` `internal_error`, logged and reported once, the job not accepted, and the daemon stops (question 11).
- Stage 1c: `status` gains `uncertain`, in the `State` enum's `jsonschema` tag, printqueue's schema test, docs/api.md, swagger.json and the CHANGELOG under **Breaking**. Status gains `sent_at` (name assumed), set once an attempt was about to write to the printer. A store failure in `Submit` is an unexpected error: `500` `internal_error`, logged and reported once, the job not accepted, and the daemon stops (decision 11).
- Stage 1d: a job kept in the store answers its status after a restart instead of `job_not_found`.
- Phase 2 (question 16): `GET /api/v1/jobs` with `status`, `source`, `before` and `limit` in the query. It answers `{"jobs": [...], "next": "job_..."}`, newest first by sequence number. Bad values answer `invalid_query`, whose api.md row ("On a module route") is reworded. The generator documents every query parameter as a string today, so an enum or integer parameter needs a field on `Param` and a generator change. Job status gains `ref`. `/healthz`'s `queue` gains `uncertain`; the status code still depends on the printer alone.
- Phase 2b (question 17): `DELETE /api/v1/jobs/{id}`, for full tokens, answers `200` with the status, or `409` with the new code `job_started` when no delivery is left to cancel and none is cancelled. `status` gains `cancelled`, a new enum value, so the CHANGELOG lists it under **Breaking**, as it does `uncertain`. `DELETE /api/v1/print` still answers `405`, api.md's example for `method_not_allowed`.
- Phase 3c (question 19): `Accept: image/png` on `POST /api/v1/preview` and `POST /api/v1/preview/{module}`. Text stays the answer to `*/*`. A picture over the height cap answers `422` `preview_too_long`. The generator needs a PNG body schema (`contentMediaType: image/png`). The compress middleware sits in front of these routes; phase 3c checks that it leaves PNG alone.
- Phase 4 (question 20): `GET /api/v1/jobs/{id}/preview`, as text, JSON or PNG by `Accept`, as the POST preview answers, with the new code `410` `job_content_expired`.
- Phase 2 (decision 16): `GET /api/v1/jobs` with `status`, `source`, `before` and `limit` in the query. It answers `{"jobs": [...], "next": "job_..."}`, newest first by sequence number. Bad values answer `invalid_query`, whose api.md row ("On a module route") is reworded. The generator documents every query parameter as a string today, so an enum or integer parameter needs a field on `Param` and a generator change. Job status gains `ref`. `/healthz`'s `queue` gains `uncertain`; the status code still depends on the printer alone.
- Phase 2b (decision 17): `DELETE /api/v1/jobs/{id}`, for full tokens, answers `200` with the status, or `409` with the new code `job_started` when no delivery is left to cancel and none is cancelled. `status` gains `cancelled`, a new enum value, so the CHANGELOG lists it under **Breaking**, as it does `uncertain`. `DELETE /api/v1/print` still answers `405`, api.md's example for `method_not_allowed`.
- Phase 3c (decision 19): `Accept: image/png` on `POST /api/v1/preview` and `POST /api/v1/preview/{module}`. Text stays the answer to `*/*`. A picture over the height cap answers `422` `preview_too_long`. The generator needs a PNG body schema (`contentMediaType: image/png`). The compress middleware sits in front of these routes; phase 3c checks that it leaves PNG alone.
- Phase 4 (decision 20): `GET /api/v1/jobs/{id}/preview`, as text, JSON or PNG by `Accept`, as the POST preview answers, with the new code `410` `job_content_expired`.
- Every route is an entry in the table in `server/routes.go`, written there in OpenAPI form (`{id}`; api.md writes `:id`), with its case in TestRoutesConform. Every code goes into `server/errors.go`, the table in docs/api.md and the regenerated swagger.json.
CONFIG, PACKAGING, INSTALL.SH, DOCKER, WINDOWS
- Config (question 4): `[state] dir`, with no default, required with an ntfy subscription, empty keeping the queue in memory. Stage 1c adds `queue.content_bytes`, default 67108864 (64 MiB), 0 to 1 GiB, an `int64` so 32-bit ARM can hold it. Each gets its default, validation, `configs/config.example.toml` entry and docs/configuration.md. `ntfy.state_dir` goes, and its `[Unreleased]` CHANGELOG entry is edited rather than listed as Breaking.
- Config (decision 4): `[state] dir`, with no default, required with an ntfy subscription, empty keeping the queue in memory. Stage 1c adds `queue.content_bytes`, default 67108864 (64 MiB), 0 to 1 GiB, an `int64` so 32-bit ARM can hold it. Each gets its default, validation, `configs/config.example.toml` entry and docs/configuration.md. `ntfy.state_dir` goes, and its `[Unreleased]` CHANGELOG entry is edited rather than listed as Breaking.
- Files: `<dir>/jobs.db` and `<dir>/jobs.db-wal` (no `-shm` in exclusive mode), and `<dir>/ntfy-<name>.json`.
- The unit already has `StateDirectory=uberbringer` with mode 0700. Add `UMask=0077` (question 15), and reword the comment that names `ntfy.state_dir`.
- The unit already has `StateDirectory=uberbringer` with mode 0700. Add `UMask=0077` (decision 15), and reword the comment that names `ntfy.state_dir`.
- install.sh writes `[state] dir = "/var/lib/uberbringer"` into new configs. Re-runs keep the config, so an older config keeps the memory queue until the owner adds the line; docs/install.md says so.
- Docker (question 14): `UBERBRINGER_STATE_DIR=/var/lib/uberbringer` replaces `UBERBRINGER_NTFY_STATE_DIR`, and the comment says the directory holds the job store and the ntfy state. docs/docker.md asks for a named volume there, or a bind mount owned by `10001:10001`, not a Docker Desktop bind mount, since WAL needs a local filesystem, and for a stop timeout above `printer.write_timeout` plus 10 s (`--stop-timeout 40` at the defaults).
- Docker (decision 14): `UBERBRINGER_STATE_DIR=/var/lib/uberbringer` replaces `UBERBRINGER_NTFY_STATE_DIR`, and the comment says the directory holds the job store and the ntfy state. docs/docker.md asks for a named volume there, or a bind mount owned by `10001:10001`, not a Docker Desktop bind mount, since WAL needs a local filesystem, and for a stop timeout above `printer.write_timeout` plus 10 s (`--stop-timeout 40` at the defaults).
- Windows is for development only. modernc builds there and its WAL works (spike); it syncs with FlushFileBuffers. `state.dir` has no default, so `go run` and the tests keep the memory queue unless a directory is set.
- Builds: nothing in CI compiles the arm targets today. Stage 1d adds the arm builds and the libc check to `test.yml`, the Makefile's `check` and CLAUDE.md's gate (question 15).
- Builds: nothing in CI compiles the arm targets today. Stage 1d adds the arm builds and the libc check to `test.yml`, the Makefile's `check` and CLAUDE.md's gate (decision 15).
LOGGING AND PRIVACY
- Print contents now rest on disk: 0600 files in a 0700 directory, `secure_delete=FAST`, and retention by question 9. docs/configuration.md says so.
- Print contents now rest on disk: 0600 files in a 0700 directory, `secure_delete=FAST`, and retention by decision 9. docs/configuration.md says so.
- No SQL is logged, and statements take parameters. Store errors name the operation and the job, never a value. If GORM is chosen, its logger is silenced.
- At start, one INFO line gives the number of jobs resumed, and one WARN line names each delivery that start turned `uncertain` by `job_id`, `printer`, `source` and `ref`.
- A store failure is an unexpected error: logged once at ERROR and reported to Sentry once, without content.
@@ -540,7 +533,7 @@ DELIVERIES AND SEVERAL PRINTERS
- 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.
- A job's API `status` derives from its deliveries (question 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. Assumed:
- 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;
- `printing` while any is unfinished, once one has been taken or has finished;
@@ -548,7 +541,7 @@ DELIVERIES AND SEVERAL PRINTERS
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 (question 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.
- 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.
- 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.
@@ -560,13 +553,13 @@ THE PREVIEW IMAGE (phase 3)
- `escpos.Interpret` keeps what drawing needs: line spacing (`ESC 2`, `ESC 3`) and feeds, the alignment of codes and images, the QR module size and correction level, the barcode height, module width and HRI position, and each raster image's bits. Today it drops all of these. The text and JSON previews do not change.
- `escpos.Profile` gains the geometry drawing needs, so that layout keeps coming from the profile: the glyph heights of Fonts A and B; the vertical motion unit, which `ESC 3` and the feed of `GS V` count in; the default line spacing (`ESC 2`); and the distance from the print head to the cutter, so that the dashed cut line falls where the paper is cut, which is where `printer.cut_feed` moved it. The tm-t88 values come from the TM-T88IV's Technical Reference Guide. The other profiles get values for their resolution (`tm-t20`, `generic-80mm` and `generic-58mm` are 203 dpi), marked unverified until checked on paper. Rendering does not read these fields, so no printed byte changes. Formatters phase 5's "default line spacing per model" is the same field.
- A new package, `internal/pkg/paper` (name assumed), draws those lines into a 1-bit image as wide as the profile's dots. The image is a type of its own that implements `image.PalettedImage` with one bit per dot, which `image/png` writes as 1-bit rows; an `image.Paletted` takes a byte per dot, about 30 MB for 60,000 rows. It draws:
- glyphs in Font A and B, at sizes 1-8, bold, underlined (1 and 2) and inverted, for every code page (question 19);
- glyphs in Font A and B, at sizes 1-8, bold, underlined (1 and 2) and inverted, for every code page (decision 19);
- QR codes from an encoder, at the printer's module size;
- EAN-13, EAN-8, UPC-A, UPC-E, CODE39 and CODE128, with their digits;
- raster images copied dot for dot;
- cuts as dashed lines, and raw spans as a hatched band with a label, since a 1-bit picture has no grey;
- nothing past the height cap (question 19).
- `receipt.Renderer.PreviewImage` renders the job with its images loaded as question 19 says, reads the bytes back with `Interpret` and draws them. Imports: receipt → paper → escpos.
- nothing past the height cap (decision 19).
- `receipt.Renderer.PreviewImage` renders the job with its images loaded as decision 19 says, reads the bytes back with `Interpret` and draws them. Imports: receipt → paper → escpos.
## Phases
@@ -577,7 +570,7 @@ THE PREVIEW IMAGE (phase 3)
**Work.** Nothing in the repository changes. The session writes a probe under the scratch directory, cross-compiles it, and gives the owner the binaries and the commands. The owner runs them, with his OK, never on the workstation.
The probe, `jobprobe`, one Go module outside the repository:
- The store question 1 chose, at the version stage 1d will pin. For SQLite: `modernc.org/sqlite` with its pinned libc, one connection, and the pragmas and schema under RECORDS (`jobs`, `deliveries`, `content` and `refs`), created fresh in `-dir`.
- The store decision 1 chose, at the version stage 1d will pin. For SQLite: `modernc.org/sqlite` with its pinned libc, one connection, and the pragmas and schema under RECORDS (`jobs`, `deliveries`, `content` and `refs`), created fresh in `-dir`.
- Flags: `-dir`, `-jobs` (default 200), `-body` (bytes of JSON per job, default 1500), `-history` (default 1000), `-deliveries` (per job, default 1; 3 shows what a broadcast to three printers costs), and `-fdatasync` for modernc's `Fdatasync(true)`.
- Setup, not measured: `-history` finished jobs, each with its deliveries, so pruning runs as it would in steady state.
- Per job, as the daemon will: the job, its deliveries and its content inserted in one commit at NORMAL; for each delivery, the `sending` mark at FULL, then `done` on that delivery's row alone at NORMAL, the last of them in one commit with the pruning of the oldest job, its deliveries and its content. At the end, one timed `PRAGMA wal_checkpoint(PASSIVE)`.
@@ -591,17 +584,17 @@ The probe, `jobprobe`, one Go module outside the repository:
On the owner's host, otherwise idle, since the device counters include every process's writes:
1. Run it as a transient unit with the unit's sandbox, once with and once without `-fdatasync`: `systemd-run --wait --pipe -p DynamicUser=yes -p StateDirectory=jobprobe -p ProtectSystem=strict -p PrivateTmp=yes -p PrivateDevices=yes -p MemoryDenyWriteExecute=yes -p SystemCallFilter=@system-service -p SystemCallErrorNumber=EPERM -p SystemCallArchitectures=native ./jobprobe -dir /var/lib/jobprobe`. A call the filter refuses fails the run with EPERM, so this tests `fdatasync`, the file locks, `pwrite` and `ftruncate` for real.
2. As a cross-check, `systemd-analyze syscall-filter @system-service` lists `fsync`, `fdatasync`, `fcntl`, `pwrite64` and `ftruncate`.
3. The same on an ARMv6 board, if he has one (question 2).
3. The same on an ARMv6 board, if he has one (decision 2).
**Tests.** A 20-job run on the workstation (Windows, without device counters) shows that the probe works. Nothing heavier runs there.
**Done when.**
- The owner has run the probe and reported its output, and the numbers are in Investigation findings.
- If ARMv6 fails, or the numbers differ much from the findings, the owner has answered question 1 again.
- If ARMv6 fails, or the numbers differ much from the findings, the owner has looked at decision 1 again.
### Stage 1b: `[state] dir`
**Goal.** `[state] dir` replaces `ntfy.state_dir` (question 4). Nothing else changes: the directory is still used only by ntfy subscriptions.
**Goal.** `[state] dir` replaces `ntfy.state_dir` (decision 4). Nothing else changes: the directory is still used only by ntfy subscriptions.
**Work.**
@@ -642,7 +635,7 @@ internal/pkg/printqueue
- store.go: `Record`, `Delivery`, `StoredState`, `Store`, `Loaded`, `UniqueRef`, `ErrContentGone`, and the memory store. A test option makes the memory store report itself durable, so that a second `Queue` on the same store stands for a restart.
- queue.go:
- The submit and status locks and the waiting list (Architecture, THE STORE INTERFACE). `Submit` checks capacity, commits `Add`, then makes the job visible to the worker, so a failed `Add` leaves nothing queued.
- Each job gets one delivery, for the printer `default`. The worker works on that delivery: `Sending` and `Finish` name it by its `seq`. A job's status derives from its deliveries by question 12's rule, written for any number of them.
- Each job gets one delivery, for the printer `default`. The worker works on that delivery: `Sending` and `Finish` name it by its `seq`. A job's status derives from its deliveries by decision 12's rule, written for any number of them.
- `Restore`, called before `Run`: records back into memory, queued jobs onto the waiting list in sequence order, and one WARN line per delivery that `Load` turned `uncertain`.
- The worker reads a job's content from the store when it takes it; one that no longer decodes fails.
- `beforeWrite` calls `Sending` and sets `sent_at`. `failed` and unique inserts commit with a sync. Every state change commits, then changes memory. A store error stops the worker, and `Run` returns it.
@@ -657,7 +650,7 @@ internal/pkg/printer
- `Send(ctx, data, beforeWrite)` calls it after `connect`, before the write deadline and `Write`. An error closes the connection with nothing written.
internal/pkg/ntfy
- A digest gets its reference, a TypeID with the prefix `digest`, when it is made. The subscriber keeps the digest, its rows, count and reference, in the saved state apart from the held set, saves before it calls `Digest`, and drops it once `Digest` succeeds. While a digest waits, new messages are held for the next one, as they are held today while other messages are. A restart with a saved digest submits that digest again first, with the same rows and reference, so the queue's duplicate check (question 10) finds it if it was queued before the crash. `Digest` carries the reference.
- A digest gets its reference, a TypeID with the prefix `digest`, when it is made. The subscriber keeps the digest, its rows, count and reference, in the saved state apart from the held set, saves before it calls `Digest`, and drops it once `Digest` succeeds. While a digest waits, new messages are held for the next one, as they are held today while other messages are. A restart with a saved digest submits that digest again first, with the same rows and reference, so the queue's duplicate check (decision 10) finds it if it was queued before the crash. `Digest` carries the reference.
- message.go: `Notification()` (name assumed) returns `<topic>/<sequence>`, the key of the notification a message or a delete belongs to, since sequence IDs are per topic; it is empty when `Sequence()` is.
internal/pkg/config
@@ -692,7 +685,7 @@ internal/pkg/printqueue, with the memory store and a wrapper that fails or block
- A unique job submitted twice gives one job, also after its status was pruned with `History: 0`; the same reference on a job that is not unique gives two.
- A stored job that no longer decodes fails, logged by ID, without its content.
- Retention by count and by content bytes; unfinished and `uncertain` content is never dropped; dropped content gives `ErrContentGone`.
- A job's status from its deliveries, by question 12's rule, as a table test over records with one, two and three deliveries in every mix of states. The queue makes one delivery per job, so records with several are put into the memory store by hand and restored; they come back whole.
- A job's status from its deliveries, by decision 12's rule, as a table test over records with one, two and three deliveries in every mix of states. The queue makes one delivery per job, so records with several are put into the memory store by hand and restored; they come back whole.
- TestMetaInStatusAndLogs still finds no content in the logs.
- schema_test: `uncertain` in the enum.
@@ -719,7 +712,7 @@ internal/app/uberbringer
**Work.**
go.mod
- `modernc.org/sqlite` at its latest stable release, with the exact `modernc.org/libc` its go.mod pins, and the indirect modules question 13 names. With bbolt (question 1), `go.etcd.io/bbolt` at its latest stable release. Run govulncheck.
- `modernc.org/sqlite` at its latest stable release, with the exact `modernc.org/libc` its go.mod pins, and the indirect modules decision 13 names. Run govulncheck.
tools
- A small program, `tools/libcpin` (name assumed), that fails when `go list -m modernc.org/libc` differs from the libc that `modernc.org/sqlite` requires in `go mod graph`. It runs as `go run ./tools/libcpin`, so it works from PowerShell and in CI alike.
@@ -734,12 +727,12 @@ internal/app/uberbringer
Packaging
- packaging/uberbringer.service: `UMask=0077`; the comment says the state directory holds the job store and the ntfy state.
- Dockerfile: the comments (question 14).
- Dockerfile: the comments (decision 14).
- `.gitea/workflows/test.yml`: `CGO_ENABLED=0` builds of linux/arm (GOARM=6) and linux/arm64, and `go run ./tools/libcpin`; its header comment, which says branch pushes build no binaries.
- Makefile: the same two steps in `check`.
Docs
- design.md: replace "The queue lives in memory, on purpose" with the store the owner chose, the state machine, the sync policy and store failures, with stage 1a's numbers. Update the diagram ("printqueue (memory, 1 worker)") and "no database", the ntfy paragraph that says waiting jobs are lost, and the statement that ESC/POS has no acknowledgement. Record the libc exception (question 13). Planned next item 1 keeps only what is left to build.
- design.md: replace "The queue lives in memory, on purpose" with the store the owner chose, the state machine, the sync policy and store failures, with stage 1a's numbers. Update the diagram ("printqueue (memory, 1 worker)") and "no database", the ntfy paragraph that says waiting jobs are lost, and the statement that ESC/POS has no acknowledgement. Record the libc exception (decision 13). Planned next item 1 keeps only what is left to build.
- The docs:
- docs/configuration.md: `state.dir` now holds the job store too; a privacy note.
- docs/install.md and docs/docker.md: the state directory, a named volume or a bind mount owned by `10001:10001`, and the stop timeout.
@@ -749,7 +742,7 @@ Docs
- docs/configuration.md: a downgrade note.
- docs/development.md: the layout (`internal/pkg/jobstore`, `tools/libcpin`), the `make check` steps, and "CI and releases", which says test.yml builds no binaries.
- docs/api.md: job status (what survives a restart) and the `job_not_found` row.
- CHANGELOG: under Added, jobs survive a restart; under **Breaking**, that with a state directory waiting jobs print after a restart instead of failing, and the Docker image's store (question 14); the downgrade note.
- CHANGELOG: under Added, jobs survive a restart; under **Breaking**, that with a state directory waiting jobs print after a restart instead of failing, and the Docker image's store (decision 14); the downgrade note.
- CLAUDE.md: the layout and the imports (jobstore → printqueue; internal/app → jobstore); the gate's new steps, and line 75's "It builds no binaries"; the libc exception beside the rule that dependencies are at their latest stable release.
- docs/swagger.json regenerated, if anything changed.
@@ -784,7 +777,7 @@ Crash tests use fault injection like the above, never kill loops or soaks on the
### Phase 2: The API for stored jobs
**Goal.** Clients can see the history and the jobs in doubt (question 16).
**Goal.** Clients can see the history and the jobs in doubt (decision 16).
**Work.**
@@ -816,7 +809,7 @@ Docs
### Phase 2b: Cancelling waiting jobs
**Goal.** A job's deliveries that have not reached `sending` can be cancelled: through `DELETE /api/v1/jobs/{id}` (question 17), and through an ntfy `message_delete` for the notification it came from. A `message_clear` cancels nothing (question 18). A cancelled delivery never reaches the printer, and a delivery that has reached `sending` goes on.
**Goal.** A job's deliveries that have not reached `sending` can be cancelled: through `DELETE /api/v1/jobs/{id}` (decision 17), and through an ntfy `message_delete` for the notification it came from. A `message_clear` cancels nothing (decision 18). A cancelled delivery never reaches the printer, and a delivery that has reached `sending` goes on.
**Work.**
@@ -831,8 +824,8 @@ internal/pkg/printqueue
- The worker's `Finish` takes the lock too, which also orders the pruning it carries. For a delivery that has not reached `sending` (a render error, every dial failing, a job that no longer decodes, and with several printers an anycast list run out), it writes nothing when the delivery is cancelled.
- 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 (question 11).
- A cancelled job counts as finished for retention. An ntfy job keeps its reference (question 10), so a replay after a restart does not queue it again.
- A store error stops the queue (decision 11).
- 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.
internal/pkg/jobstore
@@ -840,12 +833,12 @@ internal/pkg/jobstore
internal/pkg/ntfy
- subscriber.go:
- `deliver` handles a `message_delete` before its check for printable messages, which skips every other event that prints nothing ("ntfy event skipped"). It calls the handler's new method, `Delete(ctx, m)` (name assumed), with the event; an error is retried as a `Message` error is. It then drops the held rows of the event's notification and updates the held count in `Status`. `dealt` then records the event as it records any other: its ID joins the seen set, the cursor moves as for any message, and the state is saved within a second. `message_clear` stays skipped (question 18).
- `message` lets a `message_delete` past the `max_backlog` check (question 18).
- The query no longer holds `priority=`, on either transport, since both build it with one function (docs/plans/ntfy.md decision 8); `deliver` goes on leaving out messages below `MinPriority`, and `LastMessageAt` counts only those at or above it. `MinPriority`'s doc comment says the subscriber filters (question 18).
- `deliver` handles a `message_delete` before its check for printable messages, which skips every other event that prints nothing ("ntfy event skipped"). It calls the handler's new method, `Delete(ctx, m)` (name assumed), with the event; an error is retried as a `Message` error is. It then drops the held rows of the event's notification and updates the held count in `Status`. `dealt` then records the event as it records any other: its ID joins the seen set, the cursor moves as for any message, and the state is saved within a second. `message_clear` stays skipped (decision 18).
- `message` lets a `message_delete` past the `max_backlog` check (decision 18).
- The query no longer holds `priority=`, on either transport, since both build it with one function (docs/plans/ntfy.md decision 8); `deliver` goes on leaving out messages below `MinPriority`, and `LastMessageAt` counts only those at or above it. `MinPriority`'s doc comment says the subscriber filters (decision 18).
- `printed` is keyed by `Notification()` too, so an update in one topic is not taken for one in another.
- The `Handler` interface gains `Delete`; the fake handler in fake_test.go implements it.
- ratelimit.go: `DigestRow` gains `Sequence`, saved with the held set, and `held` gains `drop(topic, sequence)`, which removes the rows of that topic and sequence and lowers `Count` by as many; an empty sequence drops nothing. A held set left empty is reset, so no digest prints. Messages past `MaxDigestRows` are only counted, without a row, so a delete cannot find them and they stay in the count (assumed). A digest already made, which the saved state keeps apart until `Digest` succeeds (stage 1c), is left alone: it may be queued already. The messages a rule holds for its own digest (docs/plans/templates.md, decision 18) are a second held set, which drops the same way; whichever of this phase and templates stage 3 lands second covers it.
- ratelimit.go: `DigestRow` gains `Sequence`, saved with the held set, and `held` gains `drop(topic, sequence)`, which removes the rows of that topic and sequence and lowers `Count` by as many; an empty sequence drops nothing. A held set left empty is reset, so no digest prints. Messages past `MaxDigestRows` are only counted, without a row, so a delete cannot find them and they stay in the count. A digest already made, which the saved state keeps apart until `Digest` succeeds (stage 1c), is left alone: it may be queued already. The messages a rule holds for its own digest (docs/plans/templates.md, decision 18) are a second held set, which drops the same way; whichever of this phase and templates stage 3 lands second covers it.
internal/app/uberbringer
- ntfy.go: `ntfySubmitter` gains `CancelSequence`. The new `ntfyPrinter.Delete` calls `CancelSequence("ntfy:"+name, m.Notification())` and logs each cancelled job at INFO with `subscription`, `ref` and `job_id`. A digest already queued is not cancelled: its reference is the digest's, and it may hold other messages.
@@ -854,7 +847,7 @@ internal/app/uberbringer
internal/app/uberbringer/server
- The route `DELETE /api/v1/jobs/{id}` in the table, for full tokens; its handler, answering `200` with the status, `409` `job_started` or `404` `job_not_found`; `Jobs` gains `Cancel`, and `fakeJobs` with it; its case in TestRoutesConform.
- errors.go: `409` `job_started`, for a job whose every delivery has reached `sending` or finished, none of them cancelled.
- Unchanged: the `ntfy` module route (`POST /api/v1/print/ntfy`) still answers `204` to `message_delete`. Its jobs carry a request ID, so nothing ties them to the message (assumed).
- Unchanged: the `ntfy` module route (`POST /api/v1/print/ntfy`) still answers `204` to `message_delete`. Its jobs carry a request ID, so nothing ties them to the message.
Docs
- docs/api.md: the route table, a "Cancel a job" section, the `job_started` row in the error table, and the Job status section (`cancelled`).
@@ -872,7 +865,7 @@ internal/pkg/printqueue, with the memory store and the wrapper from stage 1c:
- The cancel against the `sending` mark, ordered by the wrapper blocking one commit and then the other, never by timing: when the cancel commits first, `beforeWrite` fails and the fake Sender writes nothing; when the mark commits first, `Cancel` returns `ErrStarted` and the job prints.
- The cancel against the worker's own `Finish` of a delivery that has not reached `sending` (a render error, the last dial failing), ordered the same way: whichever commits first is the final state, and memory agrees with the store.
- A job in its write, between retries after reaching `sending`, or done, failed or `uncertain` gives `ErrStarted`.
- A record with two deliveries, put into the memory store by hand, one in `sending` and one queued: the cancel cancels the queued one, the other goes on, and the status follows question 12. A second cancel returns the status, not `ErrStarted`.
- A record with two deliveries, put into the memory store by hand, one in `sending` and one queued: the cancel cancels the queued one, the other goes on, and the status follows decision 12. A second cancel returns the status, not `ErrStarted`.
- The `cancelled` commit is synced. When it fails, memory keeps `queued`, the queue stops, and after a restart the job prints once.
- A cancel that pushes the oldest finished job past `History` drops it in the same commit.
- `CancelSequence` cancels only that source's jobs with that notification: not another subscription's, nor one with the same sequence in another topic, nor an HTTP job whose `ref` happens to match. An empty sequence cancels nothing, with digests and HTTP jobs waiting.
@@ -916,7 +909,7 @@ internal/pkg/escpos
internal/pkg/paper (new; name assumed)
- The 1-bit image type.
- draw.go: lines into the image, as wide as the profile; text, rules, raster images, cuts and raw spans; the height cap, with an error the server maps to `preview_too_long`.
- glyphs: box drawing and shading from the cell geometry; every other glyph from a bitmap font, as Go tables written by a generator (`tools/genglyphs`, name assumed) from the font's file, committed with its licence. The session first checks the candidates against question 19's criteria; if none meets them, it stops and asks the owner.
- glyphs: box drawing and shading from the cell geometry; every other glyph from a bitmap font, as Go tables written by a generator (`tools/genglyphs`, name assumed) from the font's file, committed with its licence. The session first checks the candidates against decision 19's criteria; if none meets them, it stops and asks the owner.
**Tests.**
- Golden PNGs in testdata: `examples/blocks.json`; a glyph sheet per code page; every style and size; Font B; inverted text; box joins and shading; an image whose drawn dots equal its raster bits; a cut at the profile's cutter distance; a raw span; each block of docs/plans/blocks.md that has shipped, banners and spans drawn at a run's `W` and `H`.
@@ -935,7 +928,7 @@ internal/pkg/paper (new; name assumed)
internal/pkg/paper
- qr.go: an encoder, either a pure-Go dependency at its latest stable release or our own code, chosen in this phase on the same terms as the store (size, upkeep, pure Go). A dependency comes in at its latest stable release, with govulncheck run after it.
- barcode.go: EAN-13, EAN-8, UPC-A, UPC-E, CODE39 and CODE128, with their digits. Hand-written tables are assumed.
- barcode.go: EAN-13, EAN-8, UPC-A, UPC-E, CODE39 and CODE128, with their digits. The tables are hand-written.
**Tests.**
- A QR code per correction level, whose module count is at most `escpos.QRModules`, and equal to it for data only byte mode holds, since an encoder that picks a denser mode gives a smaller code.
@@ -947,7 +940,7 @@ internal/pkg/paper
### Phase 3c: The image preview in the API and the CLI
**Goal.** The preview routes and the CLI answer with the picture (question 19).
**Goal.** The preview routes and the CLI answer with the picture (decision 19).
**Work.**
@@ -982,7 +975,7 @@ Docs
### Phase 4: Previews of stored jobs
**Goal.** `GET /api/v1/jobs/{id}/preview` shows a submitted job, as text, JSON or PNG (question 20).
**Goal.** `GET /api/v1/jobs/{id}/preview` shows a submitted job, as text, JSON or PNG (decision 20).
**Work.**
@@ -1012,7 +1005,7 @@ Docs
**Work.**
- Epson's acknowledgement (question 21). First, each with the owner's OK and one short receipt at a time:
- Epson's acknowledgement (decision 21). First, each with the owner's OK and one short receipt at a time:
1. Does the TM-T88IV, through its board, answer `37 22 ID 00` on port 9100 for a receipt ending in `GS ( H 48 "0001"` after the cut? Check that it printed and cut once, and how long after the cut the answer came.
2. Does the answer come after the knife? A long feed before the cut shows it.
3. Does an answer sent after the host closed the connection reach the next one?
@@ -1024,11 +1017,11 @@ Docs
- 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.
- The partial-write choice (question 23), once the confirmed send reports the bytes written.
- ntfy state in the store (question 22).
- 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`.
- A reprint route for `uncertain` jobs, `POST /api/v1/jobs/{id}/reprint`, which queues a new job from the stored content.
- An age limit for queued jobs or stored content (questions 6 and 9).
- An age limit for queued jobs or stored content (decisions 6 and 9).
**Tests.**
+1 -1
View File
@@ -194,7 +194,7 @@ INVARIANTS
9. ntfy never imports modules.
OTHER PLANS
- docs/plans/job-store.md phase 2b drops `priority=` from `connect` (its question 18). Both transports build their query with one function, so whichever lands second keeps that. A `message_delete` reaches `deliver` the same way on both.
- docs/plans/job-store.md phase 2b drops `priority=` from `connect` (its decision 18). Both transports build their query with one function, so whichever lands second keeps that. A `message_delete` reaches `deliver` the same way on both.
- docs/plans/templates.md stages 2 and 3 change `deliver`, which both transports reach the same way.
- docs/plans/remote-printers.md shares fasthttp/websocket (its decision 5). Its `stream_close_delay` is for Überbringer's own Caddy site; this plan's is for the ntfy server's.
+14 -14
View File
@@ -28,12 +28,12 @@ Questions 6, 10 and 17 are settled by plans the owner has accepted since, and sa
failure the second, then the third. A failure before any byte was sent
fails over at once. After bytes were sent, the assumed default is the
existing retry rule on that printer, then failover. job-store.md
question 23 names the double-print risk this carries; this plan settles
decision 23 names the double-print risk this carries; this plan settles
it as an open question (question 22).
- **A multicast or broadcast job is one job with several deliveries,** one
per printer, each tracked on its own. job-store.md already plans that
model (its DELIVERIES AND SEVERAL PRINTERS section, question 12 on a
job's status from its deliveries, and question 23). This plan builds on
model (its DELIVERIES AND SEVERAL PRINTERS section, decision 12 on a
job's status from its deliveries, and decision 23). This plan builds on
it and does not redesign the store.
- **An explicit `?printer=` on a request is a direct unicast.**
- **A job that matches no rule goes to the default printer,** so today's
@@ -60,7 +60,7 @@ Before stage 1a:
- Trade-off: `format.max_lines` is global, so a multicast job that wraps into more lines on a narrower printer can fail there and print on the others. One image fetcher serves every printer.
- Alternatives: per-printer `format.*`, which nothing asks for; for a repeated address, one client shared by both lanes.
4. **One queue with a lane per printer.** Assumed: one `printqueue.Queue`. Each printer is a lane with its own waiting list, worker, renderer, sender, retries and retry delay. The submit lock, the status map, the history, the references of ntfy jobs and the store stay shared, so a job with several deliveries is one `Store.Add` commit, as job-store.md plans. `queue.size` bounds each lane, so a dead printer's backlog cannot refuse jobs for the others (question 19 for multicast and broadcast). Order is first in, first out per printer.
- Trade-off: no global order; a broadcast prints at different times on each printer. A host with three printers can hold three times `queue.size` jobs. With a durable store, unfinished content can reach N × `queue.size` × 4 MiB: about 1.2 GiB for three printers at the defaults, where job-store question 9 counts about 400 MiB for one. A unicast rule or a `?printer=` to a dead printer still refuses jobs once its lane is full, and an ntfy subscription whose jobs go there stops reading, as it does today when the one printer is dead.
- 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).
- Trade-off: renaming a printer fails what waits for it.
@@ -74,7 +74,7 @@ Before stage 1b:
- Any token that may print may name any printer. A token claim that limits printers can come later.
- Trade-off: the break above. A preview without `printer` lays the job out for the default printer, even when the rules would send it elsewhere; from stage 2c the JSON preview's `route` says where it would go.
- Alternatives: ignore other parameters, as today; or render a preview for the first printer of the route the rules give.
8. **A job's status with several deliveries.** Assumed: from stage 1b, every status gains `deliveries`, whatever the number of printers configured, so a client's parsing does not depend on the config. Each entry gives a delivery's `printer`, `status`, `attempts`, `started_at`, `sent_at`, `finished_at` and `error`. The job's `status` follows job-store question 12. Beside the array, the job's own fields read:
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:
- `attempts`: the sum;
- `started_at` and `sent_at`: the earliest;
- `finished_at`: the latest, once every delivery has finished;
@@ -92,7 +92,7 @@ Before stage 1b:
Before 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.
- About half is Expr itself. The rest is other packages' methods that the linker can no longer drop, because Expr calls `reflect.Value.MethodByName` with a name that is not a constant. GORM has the same effect (job-store question 1). It applies once per binary, so with Expr linked, GORM's extra cost over plain SQL falls to about its own code.
- 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.
@@ -139,10 +139,10 @@ Before stage 2a:
19. **Multicast and broadcast.** Assumed:
- Capacity is checked on every target lane under the submit lock. The job is accepted when at least one target lane has room. A delivery whose lane is full is inserted already `failed`, with the error "printer's queue is full", in a synced commit as any failure is. It is logged at WARN by `job_id` and `printer`, and not sent to Sentry, since a full queue is a refusal, not a fault. `Submit` answers `queue_full` only when every target lane is full.
- With all-or-nothing capacity instead, a dead printer's full lane would refuse every broadcast, and every multicast that includes it, though every other printer is fine. A dead lane fills fast, since it drains one delivery per 7-27 s. On the ntfy path `queue_full` makes the subscriber stop reading, so one dead printer would stall a whole subscription, the `urgent-on-desks` example included.
- Each delivery renders on its own lane with its printer's options, so an image is fetched once per delivery. Rendered bytes are never stored (job-store question 8).
- 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 question 12), and `deliveries` at once. The same image URL is fetched N times and may answer differently. Lanes render in parallel, so a broadcast with large images holds N renders in memory at once, which matters on a Pi Zero. The budget does not count the second roll.
- 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:
@@ -167,7 +167,7 @@ Before stage 2c:
Before stage 3:
22. **Failover after bytes went out** (job-store question 23). Assumed, the owner's default: the existing retry rule on that printer (`retries`, with the doubling `retry_delay`), then failover to the next printer of the list.
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.
- 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.
@@ -206,7 +206,7 @@ Before stage 3:
- A move takes the status lock, and job-store phase 2b's delivery lock once that exists. It happens only while the queue is open and the delivery is not cancelled. A failure while the delivery's context has ended (a shutdown, a cancel or its 2-minute bound) never moves it. With a durable store, dialling runs on a context that ends with the daemon, and a cancel ends the delivery's context, so their errors would otherwise look like a dead printer. Shutdown and the cancel follow their own rules, and the bound fails the delivery, as today.
- It renders again only when the next printer's options key differs; with an equal key it keeps its bytes. Each lane computes its key at start from its profile and every `receipt.Options` field, since the options may come to hold fields that cannot be compared.
- A render error moves on only to a printer whose key differs, since it would fail the same way on the others. With none left, the delivery fails.
- A moved delivery counts as taken from its first take until it finishes, so a job never reads `printing`, then `queued`, then `printing` (job-store question 12).
- A moved delivery counts as taken from its first take until it finishes, so a job never reads `printing`, then `queued`, then `printing` (job-store decision 12).
- After a `sending` mark, a moved delivery stays `sending` in the store while it waits on the next lane. A crash then turns it `uncertain` at the restart, and it is never sent, even when its write took nothing. That is the safe direction, as job-store has for a crash between the mark and the write.
- At a clean shutdown, a delivery waiting on a lane after a mark fails with `sent_at` and `sent_to`, with either store. That is job-store's rule for a delivery between retries after reaching `sending`.
- Job-store phase 2b's cancel leaves a delivery with any mark alone, even while it waits on the next printer. One without a mark can be cancelled wherever it waits.
@@ -469,7 +469,7 @@ request ─▶ Submit ─▶ route ─┼─ lane "kitchen": …
- Lock order per lane is job-store's: the printer's slot, then the delivery lock, then the store; the status lock is innermost and never held across a store call.
- `Submit` routes first, outside the locks (stage 2a). Then, under the submit lock, it checks capacity on the target lanes (question 19), commits `Store.Add` with every delivery, and appends each delivery to its lane.
- `Run` starts one worker per lane; shutdown covers every lane, by `Durable()`.
- A store failure stops every lane. The first store error from any lane ends the others, and `Run` returns it, as an errgroup does (job-store question 11). An idle lane must not keep `Run` alive, and no lane may send after the store broke.
- 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.
DELIVERIES AND JOB STATUS (stages 1b-3)
@@ -483,7 +483,7 @@ DELIVERIES AND JOB STATUS (stages 1b-3)
```
- `deliveries` from stage 1b (question 8). `route` from stage 2a (question 18), whose `by` is `rule`, `query` or `default`. An anycast delivery's `printers`, its ordered list, and `sent_to` from stage 3 (questions 22 and 26).
- The job's `status` derives from its deliveries by job-store question 12; with one delivery it is that delivery's.
- 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)
@@ -639,7 +639,7 @@ CONFIG, PACKAGING, DOCKER
- New keys: `[printers.<name>]` (stage 1a), `[routing.groups]` and `[[routing.rules]]` (stage 2a), each with its default, validation, `configs/config.example.toml` entry and docs/configuration.md entry. All are read from the file only.
- Printers and routing are documented in docs/configuration.md, § printers and § routing, not on a page of their own, so the release archives, README's Documentation table and CLAUDE.md's "Read first" need no new entry.
- install.sh and the Dockerfile do not change. A container with named printers or rules mounts a config, as one with subscriptions does.
- The stop timeout must exceed the largest `write_timeout` of any printer plus 10 s, since each lane finishes the write in hand (job-store question 15). docs/install.md says so for the unit, and docs/docker.md for `--stop-timeout` (stage 1a).
- The stop timeout must exceed the largest `write_timeout` of any printer plus 10 s, since each lane finishes the write in hand (job-store decision 15). docs/install.md says so for the unit, and docs/docker.md for `--stop-timeout` (stage 1a).
- The unit gains `ExecReload` in stage 2b.
## Phases
@@ -876,7 +876,7 @@ internal/pkg/config
- No variable sets `routing`; a `UBERBRINGER_ROUTING_*` variable is named for the WARN.
internal/pkg/printqueue
- A multicast job gets one delivery per printer in one `Add`, and its status follows job-store question 12.
- A multicast job gets one delivery per printer in one `Add`, and its status follows job-store decision 12.
- A multicast job with one target lane full is accepted: that delivery is `failed`, "printer's queue is full", in a synced commit, and the others are queued. With every target lane full, `queue_full`.
- The route is stored and restored with the job, and a restore never calls the Router.
+4 -4
View File
@@ -108,13 +108,13 @@ For stage 4:
17. **A remote send and its outcomes.** the sequence under Architecture, A REMOTE SEND. An attempt ends in one of four outcomes:
- `done`: written in full.
- `nothing`: no byte reached the printer. The agent says so (a refused dial, a printer not ready at the anycast check, a write that took nothing, a go-ahead it never acted on), or the go-ahead never left main's writer queue. It matches printqueue's `NothingWritten`, so retries and failover treat it as today's dial failure.
- `partial`: some bytes went out before a write error. It is today's write error, and job-store question 23's retry rule applies.
- `partial`: some bytes went out before a write error. It is today's write error, and job-store decision 23's retry rule applies.
- `unknown`: the go-ahead was written and no outcome came back. Main never sends that delivery again. It waits for `result` on the link that carried the go-ahead. If that link drops, it asks the agent's journal on the next link, within the delivery's 2-minute bound (decision 13 says when `none` counts). With no answer, the delivery ends `uncertain`, and one WARN line names it.
- An outcome is a string. A missing, empty or unknown one reads as `unknown`, never `nothing`, and `none` is a value of its own, sent only in reply to `query`.
- Main waits for `opened` up to the dial timeout plus 10 s. At main's shutdown, an attempt before its `sending` mark sends `Abort` and stays queued; one past its mark gets its `Go` and waits for `result` up to the write timeout plus 10 s, then ends `uncertain`.
- This adds one path that writes `uncertain` during a run; job-store writes it only at start. A lost lazy write of it still reads `uncertain` after a restart, so it needs no sync.
- Trade-off: a receipt that printed but whose answer was lost needs a person to check the paper.
18. **Deliveries while an agent is offline.** a lane whose printer's agent is offline takes nothing; its deliveries wait queued, in order, and are taken once the agent is back, however long that is, as job-store question 6 has waiting jobs print however old.
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.
- 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.
@@ -142,8 +142,8 @@ For stage 5:
For stage 6, later:
24. **Epson's acknowledgement at the agent** (job-store question 21). built only with job-store phase 5, and for remote printers at the agent, which owns the connection. The agent appends `GS ( H 48 <id>` after the bytes, waits for the matching reply and answers `done` with `confirmed`. A capability in `Hello` says it can. Its IDs are counted per printer by the agent; they never cross the link.
- Trade-off: as job-store question 21: the printer's connection stays open until the receipt is out, and a missed reply is still `unknown`.
24. **Epson's acknowledgement at the agent** (job-store decision 21). built only with job-store phase 5, and for remote printers at the agent, which owns the connection. The agent appends `GS ( H 48 <id>` after the bytes, waits for the matching reply and answers `done` with `confirmed`. A capability in `Hello` says it can. Its IDs are counted per printer by the agent; they never cross the link.
- Trade-off: as job-store decision 21: the printer's connection stays open until the receipt is out, and a missed reply is still `unknown`.
## Investigation findings
+3 -3
View File
@@ -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 question 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, 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.
## Decisions (owner, 2026-11-30)
@@ -122,8 +122,8 @@ For stage 4:
- `gitlab` and `standard` refuse a timestamp more than 5 minutes from the host's clock, `401` `invalid_signature`. The specification leaves the window open. A Raspberry Pi without a clock that boots with the wrong time refuses them until its clock is set; docs/templates.md says to start the daemon after the time is synced.
- A delivery's ID, where its preset has one, becomes the job's reference, with the source `hook:<name>`. An ID longer than 128 bytes, or with a byte that is not visible ASCII, is ignored, and the ID and the header values are copied out of fasthttp's buffers, as the request ID is.
- The ID is reserved under a lock before the rules run, so a second delivery with it, sent while the first is in hand, waits and gets the first's answer. It is recorded with the job's ID after a `202`, and as "nothing printed" after a `204`, so a repeat gets the same answer. After any other answer it is released, so a retry runs again.
- Until job-store stage 1c has shipped, each hook keeps its last 512 IDs in memory. Once it has, hook jobs join its duplicate check (job-store question 10), which runs in `Submit` under the submit lock and replaces the memory for jobs that were queued.
- This leans on job-store question 10's assumed default, which leaves the HTTP routes' jobs out because a client chooses their reference. A hook's ID is read only after its signature passed, which is why hook jobs may join.
- Until job-store stage 1c has shipped, each hook keeps its last 512 IDs in memory. Once it has, hook jobs join its duplicate check (job-store decision 10), which runs in `Submit` under the submit lock and replaces the memory for jobs that were queued.
- This follows job-store decision 10, which leaves the HTTP routes' jobs out because a client chooses their reference. A hook's ID is read only after its signature passed, which is why hook jobs may join.
- What it covers: a GitHub redelivery keeps its ID, and so do a Standard Webhooks retry and GitLab's retries, so none prints twice. Gitea and Forgejo give each attempt a new ID, a manual replay included, so a replay prints again, as the person replaying asked. GitHub's ID is not signed, so someone who captured a whole request could send it again under a new ID; only `gitlab` and `standard` sign theirs.
- Trade-off: without the job store, a restart forgets the IDs.
23. **Webhook rules.** They are `[[webhooks.rules]]`, shaped as `[[ntfy.rules]]` (decision 12) less `bypass`, seeing decision 5's `json` environment with `hook`, `event`, `delivery` and `headers` set. Actions are `print`, which needs `template`, and `drop`. A hook's own `template` key is what prints when no rule matches; a hook without one prints nothing then. So a hook for one kind of event needs no rule, and `event == "push"` picks Gitea's pushes out of everything else. `template` names a template whose `input` is `json`.