Files
Convivo/docs/backend/printing.md
T
Lago c980effddc feat(printer): badge print queue, Pi worker, captive-portal setup, admin printing view
- migration 20261018170000: pgmq badge_print/badge_print_dlq, print_stations,
  token-gated printer RPCs (claim/complete/fail/heartbeat), admin RPCs,
  welcome_checkin enqueue; badge_print_tests.sql (101 assertions)
- apps/printer: Python worker (Playwright render -> brother_ql via pyusb),
  comitup captive-portal (Wi-Fi + HTTPS endpoint + anon key + token),
  arm64 image build + idempotent Pi setup/install scripts, 77 pytest
- apps/admin: Printing view, station management/DLQ, global printer status
  pill, Print button on Registrations, standalone print renderer entry
  (print.html -> dist-print) with bundled fonts
- docs: printing.md + architecture/schema/rpcs/tests/admin-app updates,
  apps/printer/AGENT.md operating manual
- e2e: printing.spec.ts
2026-10-18 22:25:38 +02:00

287 lines
16 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Badge Printing (queue + Raspberry Pi stations)
Staff scan an attendee's lanyard at the welcome desk; the badge is rendered,
queued in Postgres, and printed a few metres away by a headless **Raspberry Pi +
Brother QL** station. Failures retry, then land in a dead-letter queue an admin
can requeue or discard. The whole path is database-driven — there is no print
server.
Source of truth:
[`supabase/migrations/20261018170000_badge_print_queue.sql`](../../supabase/migrations/20261018170000_badge_print_queue.sql)
(queue, stations, RPCs),
[`apps/printer/`](../../apps/printer/) (Pi worker + provisioning),
[`apps/admin/`](../../apps/admin/) (print renderer + Printing view).
Operational detail for the Pi lives in
[`apps/printer/AGENT.md`](../../apps/printer/AGENT.md).
> **Status (2026-10-18):** built, verified locally and on a real Pi; **not yet
> deployed to production**. See [release record](../releases/2026-10-18.md).
## 1. Architecture
```mermaid
flowchart LR
S["Staff scan<br/>(Convivo app)"]
A["Admin → Printing /<br/>Registrations Print"]
subgraph DB["Postgres (Supabase)"]
Q[("pgmq queue<br/>badge_print")]
DLQ[("pgmq queue<br/>badge_print_dlq")]
ST[("print_stations")]
ARCH[("archive<br/>a_badge_print")]
end
subgraph PI["Raspberry Pi (Docker)"]
W["Python worker"]
R["Playwright Chromium<br/>print.html renderer"]
P["Brother QL-1110NWB<br/>(USB, brother_ql)"]
end
AD["APPE Admin<br/>Printing view + pill"]
S -->|"welcome_checkin(qr)<br/>enqueue in same tx"| Q
A -->|"enqueue_badge_print"| Q
W -->|"printer_claim_badge_job<br/>(token, long-poll 2 s)"| Q
W -->|"printer_complete_badge_job"| ARCH
W -->|"printer_fail_badge_job<br/>(retry / DLQ after 3)"| DLQ
W -->|"printer_heartbeat (10 s)"| ST
W --> R
W --> P
AD -->|"get_print_overview (5 s)"| DB
AD -->|"requeue / discard"| DLQ
```
- **Enqueue** happens in the same transaction as the check-in (or the admin
reprint), so a badge job is never lost or duplicated by the scan itself.
- The Pi **long-polls** for jobs and reports every outcome back through
token-gated RPCs. It never reads tables directly.
- The admin console polls one aggregate RPC (`get_print_overview`) for stations,
queue counters, recent jobs and dead letters.
## 2. Queues and the stations table
Two [pgmq](https://github.com/pgmq/pgmq) queues, `badge_print` (live) and
`badge_print_dlq` (dead letters), plus the `print_stations` table — column-level
detail in [schema.md](./schema.md#print_stations--badge-printer-stations).
**pgmq is unreachable from the API.** The migration revokes the schema, its
tables, sequences and functions from `public` / `anon` / `authenticated`; every
queue access goes through the RPCs below. Completed jobs stay queryable in the
pgmq archive (`a_badge_print`), which `get_print_overview` exposes as the
"recent" list.
## 3. Payload contract — `convivo.badge-print/v1`
Built by `_badge_print_payload` (see the migration) and mirrored by
`BadgePrintPayload` in
[`apps/admin/src/lib/types.ts`](../../apps/admin/src/lib/types.ts). The message
is a **self-contained badge document** — the station needs no further reads to
print:
| Field | Contents |
|---|---|
| `schema` | `"convivo.badge-print/v1"` (the worker rejects anything else) |
| `kind` | `checkin` \| `reprint` |
| `requested_at` / `requested_by` | enqueue time / staff email (null for scans by staff without an email match) |
| `event` | `{ id, name, company }` |
| `registration` | `{ id, email, type }` |
| `sample` | the badge fields the layout binds to: `full_name`, `email`, `ticket_type`, `qr_token`, `event_name`, `company` |
| `layout` | the resolved `badge_layouts` row: `{ id, name, page_width_mm, page_height_mm, elements }` |
Layout resolution: the event's **default layout that has elements**, else the
first (by `created_at`, `name`) that has elements. **No usable layout → no
payload → no job** (`welcome_checkin` silently skips; `enqueue_badge_print`
raises `no badge layout configured for this event`).
## 4. RPCs
Full behaviour lives here; [rpcs.md](./rpcs.md#badge-printing) carries the
cross-reference list.
### Admin RPCs (`security definer`, `is_admin()` inside, SQLSTATE `42501`)
| Function | Purpose |
|---|---|
| `enqueue_badge_print(p_registration_id)` | Manual reprint: queue the badge of one registration (`kind = reprint`); returns the queue msg id |
| `create_print_station(p_name)` | Register a station. Generates `cvp_<64 hex>` (32 random bytes), stores only its **SHA-256 hex digest**, returns the plaintext token **once** |
| `rename_print_station(p_id, p_name)` | Rename (trimmed, required, ≤ 80 chars). Revoked stations stay renamable so history remains readable |
| `revoke_print_station(p_id)` | Sets `revoked_at`; the token stops working immediately |
| `get_print_overview()` | Admin dashboard snapshot: stations with a derived `state`, queue counters, last 20 completed jobs, dead letters. Never exposes `qr_token` or full payloads |
| `requeue_dead_badge_print(p_msg_id)` | Push a dead letter's original payload back onto the live queue unchanged |
| `discard_dead_badge_print(p_msg_id)` | Drop a dead letter without retrying |
### Printer RPCs (token-gated, no user session)
Granted to `anon` (the Pi has no login) — the **station token is the
credential**. Each resolves the token via `_print_station_from_token`
(SHA-256 lookup, revoked/unknown → SQLSTATE `28000` → HTTP 401/403 for the
worker) and stamps `last_seen_at`.
| Function | Purpose |
|---|---|
| `printer_claim_badge_job(p_token, p_vt=120, p_wait_seconds=2)` | Long-poll for one job. `p_vt` clamped to 30–600 s; **`p_wait_seconds` clamped to 2 s** because PostgREST runs this as `anon`, whose `statement_timeout` is 3 s. A message already read > 3 times is dead-lettered instead of returned |
| `printer_complete_badge_job(p_token, p_msg_id)` | Report success → `pgmq.archive` (job leaves the queue for good) |
| `printer_fail_badge_job(p_token, p_msg_id, p_error, p_retryable)` | Retryable **and** `read_ct < 3` → `set_vt` backoff (`min(300, 15·read_ct)` s), returns `retry`; otherwise dead-letter (error capped at 2000 chars) and return `dead_letter` |
| `printer_heartbeat(p_token, p_status)` | Liveness + status beacon (blob capped at 16 KB). Returns `{ station_id, name }` — **the worker adopts its display name from this response**, so renames apply without re-provisioning |
`welcome_checkin` was re-created in the same migration: identical signature and
behaviour, plus the `badge_print` enqueue for a **genuine first check-in** only,
inside the same transaction (see [rpcs.md](./rpcs.md#welcome_checkinp_attendee_qr--attendee_email-attendee_name-already)).
## 5. Station tokens & security model
- Token format `cvp_…` (256 bits of entropy), generated server-side, shown
**once** at creation, stored only as a SHA-256 digest. A leaked database dump
does not leak usable tokens.
- The worker sends the token in the **JSON body** of each RPC call, together
with the **anon key** — which is public by design (same value baked into both
web apps), not a secret.
- `print_stations` has RLS enabled with **no policies** and no grants to
`anon` / `authenticated`: even the admin UI can only see stations through
`get_print_overview`.
- **Open-AP risk:** the Pi's comitup provisioning AP (`Convivo-Printer-<nnnn>`)
is open by design so staff can join it from a phone. While a station is in
hotspot mode it is not printing, and the token never travels over that AP —
it only talks to Convivo on a configured network.
- Revoking a station in Admin → Printing takes effect on the token's next call,
no Pi-side change needed.
## 6. Station state derivation
`get_print_overview` derives each station's `state` server-side (worst applicable
rule wins, in order):
| State | Condition |
|---|---|
| `revoked` | `revoked_at` is set |
| `offline` | never seen, or `last_seen_at` older than **45 s** (heartbeat interval is 10 s) |
| `error` | last heartbeat's printer block: not `connected`, not `ready`, or a non-empty `errors` array |
| `printing` | heartbeat `worker = "printing"` |
| `ready` | everything else |
Queue counters: `pending` (`vt <= now()`, visible for claim), `in_flight`
(`vt > now()`, claimed but not reported), `dead_letter` (DLQ size), `completed`
(archive size). The admin UI maps these to the pill and per-station hints —
see [../frontend/admin-app.md#printing](../frontend/admin-app.md#printing).
## 7. The Pi worker (`apps/printer/worker/`)
A small Python loop in Docker; every module is hardware-free and unit-tested
except the thin `printer.py` wrapper.
| Module | Role |
|---|---|
| `main.py` | `Worker` loop: heartbeat thread, informational labels, claim → render → compose → print → complete/fail |
| `rpc.py` | PostgREST client; maps 401/403/`28000` → `InvalidToken`, 5xx/network → `RpcUnavailable` (retry-safe), 4xx → `RpcError` |
| `render.py` | One reused headless **Chromium** (Playwright) serving `dist-print` on loopback; `window.renderBadge(payload, {checkinOrigin})`, then screenshots `#badge-root .badge-page` at **300 dpi** (`device_scale_factor = 300/96`). Relaunches itself once after a browser crash |
| `label.py` | Pure Pillow composition onto the **detected** roll (see §8) |
| `printer.py` | `brother_ql_next` over **pyusb** to the Brother QL-1110NWB (`usb://0x04f9:0x20a8`); status read-back mapped to the heartbeat `printer` block; `DRY_RUN=1` writes PNGs instead |
| `network.py` | Reads `/run/convivo/network.json` (written by the comitup callback); falls back to a UDP-route IP guess |
| `status_labels.py` | Optional locally-drawn "ready" / "needs Wi-Fi" labels |
| `config.py` | All settings from env (`CONVIVO_URL`, `CONVIVO_ANON_KEY`, `PRINTER_STATION_TOKEN`, `BROTHER_LABEL=auto`, `HEARTBEAT_SECONDS=10`, `WAIT_SECONDS=2`, `STATUS_LABELS=0`, …). The token is excluded from `repr` so it can never reach a log line |
Loop behaviour worth knowing:
- **Heartbeat** every 10 s on its own thread (worker state, printer status,
network, version, uptime) — this is what drives the admin pill. A successful
beat touches `/tmp/heartbeat-ok`, which the image's `HEALTHCHECK` watches.
- **Not ready** (no roll, cover open, USB gone): the worker pauses, reports
`paused` + the error in its heartbeat, and retries in 3 s — it does **not**
claim jobs, so nothing fails while the printer is broken.
- **Job outcome rules:** unsupported schema / `LayoutTooLarge` / render errors →
dead-letter immediately (retrying can't help). No roll, transport errors →
retryable. A print that reports `did_print` is **completed even if a
post-print error appeared** (e.g. the roll ran out right after) — a badge that
printed must not be reprinted.
- **Complete is sticky:** if the backend is briefly unreachable after printing,
the worker retries `complete` with backoff for up to 60 s; past that the job
stays in flight and may be redelivered (a possible duplicate beats a lost
badge).
- **Station name** comes from the heartbeat response, so Admin → Printing
renames show on the next beat without touching the Pi.
### Image & rendering
[`apps/printer/Dockerfile`](../../apps/printer/Dockerfile) builds from the
**repo root** context: a Node stage runs `npm run build:print` in `apps/admin`
(`vite.print.config.ts` → `dist-print`), and the runtime stage is
`mcr.microsoft.com/playwright/python` (Chromium preinstalled) +
`brother_ql_next` + the worker. The renderer bundle is the **same React code**
as the admin previews — see §9 — so what the admin previews is what prints.
## 8. Label / roll handling
The worker prints on whatever roll is detected (`BROTHER_LABEL=auto`);
`label.compose` fits the 300 dpi badge image to it:
- **Die-cut** (e.g. `103x164`): the badge is centred on the exact label canvas;
a few px of rounding overshoot are cropped.
- **Endless / continuous** (e.g. `103` = DK-22246): fixed width, the tape length
follows the badge.
- If the badge doesn't fit, it is **auto-rotated** 90°; if it still doesn't
fit, `LayoutTooLarge` → dead-letter with the mm dimensions in the error.
Practical consequence (see §11): a ~101×30 mm badge **cannot** be printed on a
die-cut 103×164 roll — the cutter cannot cut inside a die. Load continuous
DK-22246 for short badges; no code change is needed.
## 9. Admin surface (summary)
The **Printing** view (stations, queue counters, recent jobs with **Reprint**,
dead letters with **Requeue** / **Discard**, add/rename/revoke station), the
always-visible **printer status pill** in the sidebar, the **Print** button on
Registrations rows, and the standalone print renderer entry (`print.html` →
`window.renderBadge`) are documented in
[../frontend/admin-app.md#printing](../frontend/admin-app.md#printing).
## 10. Pi provisioning & the Wi-Fi portal
[`apps/printer/pi/install.sh`](../../apps/printer/pi/install.sh) (from a dev
machine) cross-builds the arm64 image, uploads setup + image tarball to
`/var/tmp/convivo-setup` (the Pi's `/tmp` is a tiny tmpfs) and runs
[`setup.sh`](../../apps/printer/pi/setup.sh) as root. The setup is idempotent
and staged (`STAGE_APP` / `STAGE_WIFI_PORTAL` / `REBOOT`):
- base system (hostname, timezone, timesyncd — no RTC on the Pi, TLS fails
until the clock syncs), hardware watchdog, journald cap, Wi-Fi power-save off;
- Docker Engine + log caps;
- USB printer access: blacklist `usblp`, **mask `ipp-usb`** (it claims the
QL-1110NWB's IPP-over-USB interfaces and libusb then fails "Resource busy");
- the worker container (`/opt/convivo-printer`, host network, USB device
cgroup rules so a replugged printer works without a restart);
- **Wi-Fi provisioning portal (comitup):** installs comitup, which exposes the
open AP **`Convivo-Printer-<nnnn>`** with a captive portal at
**http://10.41.0.1**. A comitup callback writes `/run/convivo/network.json`
(`HOTSPOT` / `CONNECTING` / `CONNECTED` + SSID + IP) for the worker. A Convivo
captive portal (`apps/printer/portal/portal.py`) extends that flow so staff
can **pick any Wi-Fi network and optionally set the Convivo URL / anon key /
station token** from their phone — operational detail in
[`apps/printer/AGENT.md`](../../apps/printer/AGENT.md).
## 11. Troubleshooting (lessons learned)
| Symptom | Cause → fix |
|---|---|
| Badge won't print on a die-cut roll / cut lands mid-badge | Die-cut 103×164 labels **cannot be cut shorter** than the die. Use continuous DK-22246 (`103`) for short badges |
| `Resource busy` opening the printer | `ipp-usb` grabbed the USB interfaces → `systemctl mask ipp-usb` (setup.sh does this) |
| Install fails writing the image tarball | The Pi's `/tmp` is a small tmpfs → install uploads to `/var/tmp/convivo-setup` |
| Hotspot AP appears but hands out no DHCP after a setup run | `systemctl daemon-reexec` breaks running comitup's D-Bus proxy → setup only re-execs when its config actually changed **and restarts comitup** afterwards |
| Worker suddenly runs an old image | A Docker restart bounces the container on whatever image is loaded → setup restarts Docker only on `daemon.json` changes; re-run setup to update the image |
| Claim RPC returns HTTP 500 `57014` (query canceled) | Supabase `anon` has a **3 s statement_timeout** → the claim long-poll is clamped to 2 s server-side and `WAIT_SECONDS` defaults to 2 |
| Pill says offline right after plugging in the Pi | Clock skew: no RTC → wait for `systemd-timesyncd`, heartbeat older than 45 s reads offline |
## 12. Tests
- **SQL:** [`supabase/tests/badge_print_tests.sql`](../../supabase/tests/badge_print_tests.sql)
— rollback-only, **101 assertions**; run it **combined with the migration**
(idempotent, works before and after apply):
```sh
(echo 'begin;'; \
cat supabase/migrations/20261018170000_badge_print_queue.sql; \
sed '/^begin;$/d' supabase/tests/badge_print_tests.sql) \
| docker exec -i supabase_db_Convivo psql -X -U postgres -d postgres -v ON_ERROR_STOP=1
```
- **Worker unit tests:** `pytest apps/printer/tests` — **77 passing**
(56 test functions, 77 with parametrization; no hardware or browser needed).
- **Browser:** [`e2e/tests/printing.spec.ts`](../../e2e/tests/printing.spec.ts)
— 15 API-mocked Playwright tests for the pill, Printing view, station
lifecycle and the Print button.
Run commands in [tests.md](./tests.md#badge-print-queue-regression).