Send each print as one job, queue web prints, and harden deploys
CI / test (3.10) (push) Failing after 56s
CI / test (3.12) (push) Failing after 42s
CI / test (3.13) (push) Failing after 47s

Render every print to a complete ESC/POS payload (reset, content, cut)
and send it once over a fresh connection. Only the connect is retried,
so a link that drops mid-job can no longer print a partial image followed
by a full one, and no text size leaks into the next job. Prints are
capped at about 1 m of paper: tall images shrink, over-long notes are
refused.

Replace the argparse/stdout plumbing with PrinterConfig, InvalidJob and
PrinterUnavailable, and one run_command() dispatcher shared by the CLI
and TUI. Status now really connects; before, escpos's lazy open meant
the web server always reported the printer ready. Rendering with the
TM-T20II profile makes QR centering take effect.

The web server validates and renders jobs in the request (400 on bad
input), queues them for a single worker and answers 202; the page
long-polls /api/jobs/{id}, so no request outlives nginx's proxy timeout
while its job still prints. Status reports busy instead of waiting, and
jobs are logged with the nginx user.

update.sh tests new commits in a scratch worktree before touching the
live clone, and rolls back if /healthz doesn't answer after the restart.
The unit runs from the venv, and the web server defaults to localhost.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-23 22:07:58 +01:00
co-authored by Claude Opus 5.5
parent 30d1b83817
commit 597bace442
10 changed files with 778 additions and 436 deletions
+9 -8
View File
@@ -5,19 +5,20 @@ CLI that prints images, notes, and QR codes to an Epson TM-T20II thermal receipt
## Layout
- `receipt.py` — the CLI; subcommand per `cmd_*` function
- `receipt_tui.py` — Textual TUI (`tui` subcommand); thin layer over the `cmd_*` handlers via `receipt.run_action()`, which connects fresh per action and captures stdout/stderr for the log panel. `textual` is an optional dependency (`[tui]` extra); the CLI works without it
- `receipt_web.py` — FastAPI server (`serve` subcommand, `[web]` extra) behind the site's nginx `/receipt/` over Tailscale; requires the `X-Receipt-Token` header nginx adds, and `X-Requested-With: receipt` on POSTs. Serializes jobs with a lock around `run_action()`; uploads print from memory. Always runs with `no_setup` (no sudo; the printer must already be reachable). Deployed on stppi, which is online over Wi-Fi and has the printer cabled to its `eth0` (printer 192.168.192.168, Pi 192.168.192.10 via the `receipt-printer` nmcli profile)
- `deploy/` — systemd user units; `update.sh` (run by `receipt-update.timer`) fast-forwards the server's clone from Gitea, runs the tests, and restarts `receipt-web`, rolling back if they fail. Pushing to Gitea `master` is the deploy
- `connect_receipt.sh` — brings up the printer's network interface (needs sudo); run automatically before any print over Ethernet. The TUI runs it with output captured (`setup_network_quiet`) so it can't corrupt the screen
- `receipt_tui.py` — Textual TUI (`tui` subcommand); thin layer over the `cmd_*` handlers via `receipt.run_action()`, which captures stdout/stderr for the log panel and returns an `ActionResult` (rc, output, error kind). `textual` is an optional dependency (`[tui]` extra); the CLI works without it
- `receipt_web.py` — FastAPI server (`serve` subcommand, `[web]` extra) behind the site's nginx `/receipt/` over Tailscale; requires the `X-Receipt-Token` header nginx adds, and `X-Requested-With: receipt` on POSTs. POSTs render the job in the request (`InvalidJob` → 400), queue the bytes in a `PrintQueue` and answer 202; one worker thread sends them, and the page long-polls `/api/jobs/{id}`. `/api/status` only tries the printer lock, so it never waits behind a print. Uploads print from memory. Always runs with `no_setup` (no sudo; the printer must already be reachable). Deployed on stppi, which is online over Wi-Fi and has the printer cabled to its `eth0` (printer 192.168.192.168, Pi 192.168.192.10 via the `receipt-printer` nmcli profile)
- `deploy/` — systemd user units; `update.sh` (run by `receipt-update.timer`) tests the new Gitea commit in a scratch worktree, then fast-forwards the server's clone, restarts `receipt-web` and rolls back if `/healthz` doesn't answer. Pushing to Gitea `master` is the deploy
- `connect_receipt.sh` — brings up the printer's network interface (needs sudo); run automatically before any print over Ethernet. The TUI runs it with output captured (`PrinterConfig.quiet_setup`, set by `run_action()`) so it can't corrupt the screen
- `tests/` — pytest suite; uses `FakePrinter` + mocked `requests`, never touches hardware or network
## Conventions
- Printer/network constants live at the top of `receipt.py`; IP/port overridable via `--ip`/`--port` or `RECEIPT_PRINTER_IP`/`RECEIPT_PRINTER_PORT`
- Images are prepared in memory (`prepare_for_print`: white-composite alpha → resize to 576px → autocontrast → 1-bit dither); nothing is written except the `img/` download cache
- `print_image()` reconnects and retries once on failure and returns the (possibly new) printer handle — callers must rebind `p`
- Commands that don't need the printer (`list`, `clean`) or handle their own connection (`status`, `tui`, `serve`) are dispatched in `main()` before connecting
- `--no-setup` (`args.no_setup`) skips the connect script everywhere it would run; check it with `needs_setup(args)`
- Every print is `render_*()` → bytes → `send(config, payload)`: `render()` builds the job on an escpos `Dummy` (ESC @ first, cut last), and `send()` connects fresh, writes it once and closes. Only the connect is retried; a mid-job drop raises `PrinterUnavailable` and is never replayed. `cmd_*` handlers take a `PrinterConfig`, not a printer handle
- User errors raise `InvalidJob`, printer trouble raises `PrinterUnavailable`; `main()`, `run_action()` and the web server turn them into messages / status codes
- Images are prepared in memory (`prepare_for_print`: white-composite alpha → resize to 576px → autocontrast → 1-bit dither); nothing is written except the `img/` download cache. `MAX_PRINT_HEIGHT_DOTS` caps paper per job (tall images shrink, long notes are refused)
- `run_command()` dispatches every subcommand except `tui`/`serve`, for both `main()` and `run_action()` (via the `PRINT_COMMANDS` registry)
- `--no-setup` (`PrinterConfig.no_setup`) skips the connect script everywhere it would run; check it with `config.needs_setup`
## Checks
+10 -11
View File
@@ -64,7 +64,9 @@ fortune | ./receipt.py note
./receipt.py --ip 10.0.0.5 --port 9100 status
```
Images are prepared for thermal output automatically: transparency is composited onto white, then the image is resized to full width, autocontrast-stretched, and Floyd-Steinberg dithered.
Images are prepared for thermal output automatically: transparency is composited onto white, then the image is resized to full width, autocontrast-stretched, and Floyd-Steinberg dithered. Nothing prints longer than about 1 m: a very tall image is shrunk to that height (and centered), and a note that long is refused.
Each print is rendered to one complete ESC/POS job (printer reset, content, cut) and sent over a fresh connection. A failed connect is retried once; a connection that drops mid-job is reported, never resent, so a flaky link can't print the same thing twice.
## Printing from the website
@@ -98,13 +100,10 @@ sudo nmcli con add type ethernet ifname eth0 con-name receipt-printer connection
"$(openssl rand -hex 32)" "$(tailscale ip -4)" > ~/.config/receipt-web.env)
```
3. Install the units, point the server at the venv, and start everything at boot:
3. Install the units (the server runs from the venv) and start everything at boot:
```bash
cp deploy/receipt-web.service deploy/receipt-update.{service,timer} ~/.config/systemd/user/
mkdir -p ~/.config/systemd/user/receipt-web.service.d
printf '[Service]\nExecStart=\nExecStart=%%h/Coding/receipt_maker/.venv/bin/python %%h/Coding/receipt_maker/receipt.py serve\n' \
> ~/.config/systemd/user/receipt-web.service.d/venv.conf
systemctl --user daemon-reload
systemctl --user enable --now receipt-web receipt-update.timer
sudo loginctl enable-linger "$USER"
@@ -112,18 +111,18 @@ sudo nmcli con add type ethernet ifname eth0 con-name receipt-printer connection
4. On stpvm, set `RECEIPT_WEB_UPSTREAM=<tailscale ip>:8765` in web_server's `.env`, then `docker compose up -d nginx`.
Jobs run one at a time. If the server machine is off, the site shows "printer machine offline".
Jobs are checked and rendered when submitted (a bad note or image is rejected straight away), then queued and printed one at a time. The page shows each job as queued, printing, then done or failed, and the status pill shows "printer busy" during a print rather than waiting for it. Each job is logged to the service's journal with the signed-in user nginx forwards. If the server machine is off, the site shows "printer machine offline".
### Automatic updates
`receipt-update.timer` runs `deploy/update.sh` every 5 minutes. When `master` on Gitea has moved, the script:
1. fast-forwards the clone
2. reinstalls the dependencies if `pyproject.toml` changed
3. runs the tests
4. restarts `receipt-web`
1. runs the tests on the new commit in a scratch worktree (with a throwaway venv if `pyproject.toml` changed)
2. fast-forwards the clone and, if needed, reinstalls the dependencies
3. restarts `receipt-web`
4. waits up to 20 s for `/healthz` to answer
If the tests fail, the clone goes back to the previous commit, the old code keeps serving, and that commit is skipped until a newer one is pushed. Its output is in `journalctl --user -u receipt-update`. Pushing to Gitea is the whole deploy.
If the tests fail, the live clone is never touched. If `/healthz` doesn't answer, the previous commit is put back and restarted. Either way, the old code keeps serving and that commit is skipped until a newer one is pushed. Its output is in `journalctl --user -u receipt-update`. Pushing to Gitea is the whole deploy.
## Development
+1 -1
View File
@@ -15,7 +15,7 @@ Wants=network-online.target
[Service]
EnvironmentFile=%h/.config/receipt-web.env
ExecStart=/usr/bin/python3 %h/Coding/receipt_maker/receipt.py serve
ExecStart=%h/Coding/receipt_maker/.venv/bin/python %h/Coding/receipt_maker/receipt.py serve
# Binding fails until Tailscale has brought its address up; just retry.
Restart=always
RestartSec=5
+42 -13
View File
@@ -3,9 +3,10 @@
# when the code changed. Run every few minutes by receipt-update.timer on the
# machine the service runs on.
#
# The tests gate the restart: if they fail on the new commit, the clone goes
# back to the old one, the service keeps running the old code, and that
# commit is skipped until a newer one lands.
# The new commit is tested in a scratch worktree first, so the live clone and
# venv never hold untested code. After the restart, /healthz must answer or
# the old commit is put back. Either failure skips that commit until a newer
# one lands.
set -euo pipefail
cd "$(dirname "$0")/.."
@@ -19,18 +20,46 @@ if [ "$(cat "$failed_marker" 2>/dev/null)" = "$new" ]; then
exit 0
fi
git merge --ff-only --quiet "$new"
if ! git diff --quiet "$old" "$new" -- pyproject.toml; then
.venv/bin/pip install --quiet '.[web,dev]'
fi
if ! output=$(.venv/bin/python -m pytest -q -p no:cacheprovider 2>&1); then
echo "$output" | tail -n 20
echo "Tests failed on $(git rev-parse --short "$new"); staying on $(git rev-parse --short "$old")." >&2
git reset --quiet --hard "$old"
fail() {
echo "$1 on $(git rev-parse --short "$new"); staying on $(git rev-parse --short "$old")." >&2
echo "$new" >"$failed_marker"
exit 1
}
deps_changed() { ! git diff --quiet "$old" "$new" -- pyproject.toml; }
scratch=$(mktemp -d)
trap 'git worktree remove --force "$scratch" 2>/dev/null; rm -rf "$scratch"; git worktree prune' EXIT
git worktree add --quiet --detach "$scratch" "$new"
python=$PWD/.venv/bin/python
if deps_changed; then
# New dependencies get a throwaway venv; the live one is only touched once they pass.
python3 -m venv "$scratch/.venv"
"$scratch/.venv/bin/pip" install --quiet "$scratch[web,dev]"
python=$scratch/.venv/bin/python
fi
# pytest's pythonpath = ["."] makes the worktree's modules win over any installed copy.
if ! output=$(cd "$scratch" && "$python" -m pytest -q -p no:cacheprovider 2>&1); then
echo "$output" | tail -n 20
fail "Tests failed"
fi
git merge --ff-only --quiet "$new"
deps_changed && .venv/bin/pip install --quiet '.[web,dev]'
systemctl --user restart receipt-web
echo "Updated $(git rev-parse --short "$old") -> $(git rev-parse --short "$new")."
listen=$(sed -n 's/^RECEIPT_WEB_LISTEN=//p' "$HOME/.config/receipt-web.env" 2>/dev/null)
healthz="http://${listen:-127.0.0.1:8765}/healthz"
for _ in {1..20}; do
if curl -fsS --max-time 2 "$healthz" >/dev/null 2>&1; then
echo "Updated $(git rev-parse --short "$old") -> $(git rev-parse --short "$new")."
exit 0
fi
sleep 1
done
journalctl --user -u receipt-web -n 20 --no-pager >&2 || true
git reset --quiet --hard "$old"
deps_changed && .venv/bin/pip install --quiet '.[web,dev]'
systemctl --user restart receipt-web
fail "$healthz didn't answer after the restart"
+253 -170
View File
@@ -12,6 +12,8 @@ import random
import subprocess
import sys
import textwrap
from collections.abc import Callable
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
from typing import BinaryIO
@@ -47,12 +49,15 @@ DEFAULT_PRINTER_IP = _env_ip()
DEFAULT_PRINTER_PORT = _env_port()
USB_VENDOR_ID = 0x04B8
USB_PRODUCT_ID = 0x0202
PRINTER_PROFILE = "TM-T20II" # python-escpos profile; its 576px media width lets center= work
PRINT_WIDTH_PX = 576 # printable width of the TM-T20II at 203 dpi
TEXT_COLUMNS = 48 # font A columns on 80mm paper
TEXT_SIZES = (1, 2, 3) # note character magnifications; columns shrink to match
LINE_HEIGHT_DOTS = 30 # default line spacing (3.75 mm) at size 1
MAX_PRINT_HEIGHT_DOTS = 8000 # about 1 m of paper; longer jobs are shrunk or refused
HTTP_TIMEOUT = 15 # seconds
MAX_IMAGE_BYTES = 16 * 1024 * 1024 # cap on a single downloaded or uploaded image
DEFAULT_WEB_LISTEN = "100.107.152.119:8765" # stppi's Tailscale IP; nginx on stpvm proxies here
DEFAULT_WEB_LISTEN = "127.0.0.1:8765" # deployments set RECEIPT_WEB_LISTEN to their Tailscale IP
BASE_DIR = Path(__file__).resolve().parent
IMG_DIR = BASE_DIR / "img"
@@ -67,20 +72,56 @@ PRINTABLE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp", ".bmp"}
Image.MAX_IMAGE_PIXELS = 32_000_000
def setup_network(args: argparse.Namespace | None = None) -> None:
"""Bring up the printer's network interface via the connect script."""
env = os.environ.copy()
if args and not getattr(args, "usb", False):
env["RECEIPT_PRINTER_IP"] = args.ip
env["RECEIPT_PRINTER_PORT"] = str(args.port)
subprocess.run(["bash", str(CONNECT_SCRIPT)], env=env, check=True) # noqa: S603, S607
class InvalidJob(Exception):
"""The job itself can't be printed (nothing to print, too long, not an image)."""
def setup_network_quiet(args: argparse.Namespace) -> None:
"""Run the connect script with output captured, so callers can redirect it (TUI, web)."""
class PrinterUnavailable(Exception):
"""The printer couldn't be reached, or the link dropped during a job."""
@dataclass(frozen=True)
class PrinterConfig:
"""How to reach the printer; built from the CLI's global options."""
ip: str = DEFAULT_PRINTER_IP
port: int = DEFAULT_PRINTER_PORT
usb: bool = False
no_setup: bool = False
quiet_setup: bool = False # capture the connect script's output (TUI); no sudo prompt
@classmethod
def from_args(cls, args: argparse.Namespace) -> PrinterConfig:
return cls(
ip=getattr(args, "ip", DEFAULT_PRINTER_IP),
port=getattr(args, "port", DEFAULT_PRINTER_PORT),
usb=getattr(args, "usb", False),
no_setup=getattr(args, "no_setup", False),
quiet_setup=getattr(args, "quiet_setup", False),
)
@property
def needs_setup(self) -> bool:
"""Ethernet needs the connect script, unless no_setup says the link is already up."""
return not self.usb and not self.no_setup
@property
def target(self) -> str:
return "USB" if self.usb else f"{self.ip}:{self.port}"
def setup_network(config: PrinterConfig) -> None:
"""Bring up the printer's network interface via the connect script.
With quiet_setup the output is captured and re-printed, so callers that
redirect stdout (the TUI) see it instead of it landing on the terminal.
"""
env = os.environ.copy()
env["RECEIPT_PRINTER_IP"] = args.ip
env["RECEIPT_PRINTER_PORT"] = str(args.port)
env["RECEIPT_PRINTER_IP"] = config.ip
env["RECEIPT_PRINTER_PORT"] = str(config.port)
if not config.quiet_setup:
subprocess.run(["bash", str(CONNECT_SCRIPT)], env=env, check=True) # noqa: S603, S607
return
bash_path = str(CONNECT_SCRIPT) # noqa: S607 - fixed project script
result = subprocess.run( # noqa: S603
["/bin/bash", bash_path],
@@ -98,22 +139,74 @@ def setup_network_quiet(args: argparse.Namespace) -> None:
raise RuntimeError(f"connect script failed (exit {result.returncode})")
def needs_setup(args: argparse.Namespace) -> bool:
"""Ethernet needs the connect script, unless --no-setup says the link is already up."""
return not args.usb and not getattr(args, "no_setup", False)
def get_printer(args: argparse.Namespace) -> printer.Escpos:
if args.usb:
def get_printer(config: PrinterConfig) -> printer.Escpos:
if config.usb:
return printer.Usb(USB_VENDOR_ID, USB_PRODUCT_ID)
return printer.Network(args.ip, port=args.port)
return printer.Network(config.ip, port=config.port)
def close_quietly(p: printer.Escpos) -> None:
"""Close a printer handle, ignoring errors from an already-dead socket."""
with contextlib.suppress(Exception):
p.close()
def connect(config: PrinterConfig) -> printer.Escpos:
"""Open a printer connection, rerunning setup and retrying once on failure.
escpos connects lazily on first write, so open() is called here: a
connection failure must surface before any of a job's bytes are sent.
"""
for attempt in (1, 2):
try:
if config.needs_setup:
setup_network(config)
p = get_printer(config)
p.open()
return p
except (OSError, escpos_exceptions.Error, subprocess.SubprocessError, RuntimeError) as e:
if attempt == 2:
raise PrinterUnavailable(f"can't reach {config.target}: {e}") from e
print(f"Connect failed ({e}); retrying...", file=sys.stderr)
raise AssertionError("unreachable")
def send(config: PrinterConfig, payload: bytes) -> None:
"""Send one rendered job over a fresh connection.
Only the connect is retried. Once bytes have gone out, a failure is
reported rather than replayed, so a dropped link can't print a job twice.
"""
p = connect(config)
try:
p._raw(payload) # escpos's raw-write hook; the payload is already complete ESC/POS
except (OSError, escpos_exceptions.Error) as e:
raise PrinterUnavailable(
f"the link to {config.target} dropped mid-job, so it may have printed partially ({e})"
) from e
finally:
close_quietly(p)
def render(build: Callable[[printer.Escpos], None]) -> bytes:
"""Render a job to bytes: printer reset, the job, then a cut.
ESC @ comes first so no mode an earlier job left set (e.g. text size) leaks in.
"""
job = printer.Dummy(profile=PRINTER_PROFILE)
job.hw("INIT")
build(job)
job.cut()
return job.output
def prepare_for_print(img_path: Path | BinaryIO) -> Image.Image:
"""Load an image resized to full printer width and dithered for thermal output.
Transparency is composited onto white (thermal paper), then the image is
autocontrast-stretched and Floyd-Steinberg dithered to 1-bit.
autocontrast-stretched and Floyd-Steinberg dithered to 1-bit. An image that
would print taller than MAX_PRINT_HEIGHT_DOTS is shrunk to that height and
centered instead.
"""
with Image.open(img_path) as img:
img.load() # DecompressionBombError and truncated files surface here, inside `with`
@@ -122,9 +215,18 @@ def prepare_for_print(img_path: Path | BinaryIO) -> Image.Image:
background = Image.new("RGBA", rgba.size, "white")
img = Image.alpha_composite(background, rgba)
width, height = img.size
new_width = PRINT_WIDTH_PX
new_height = max(1, round(PRINT_WIDTH_PX * height / width))
resized = img.resize((PRINT_WIDTH_PX, new_height), Image.LANCZOS)
return ImageOps.autocontrast(resized.convert("L")).convert("1")
if new_height > MAX_PRINT_HEIGHT_DOTS:
new_width = max(1, round(MAX_PRINT_HEIGHT_DOTS * width / height))
new_height = MAX_PRINT_HEIGHT_DOTS
resized = img.resize((new_width, new_height), Image.LANCZOS)
gray = ImageOps.autocontrast(resized.convert("L"))
if new_width < PRINT_WIDTH_PX:
canvas = Image.new("L", (PRINT_WIDTH_PX, new_height), 255)
canvas.paste(gray, ((PRINT_WIDTH_PX - new_width) // 2, 0))
gray = canvas
return gray.convert("1")
def wrap_text(text: str, columns: int = TEXT_COLUMNS) -> str:
@@ -135,6 +237,55 @@ def wrap_text(text: str, columns: int = TEXT_COLUMNS) -> str:
return "\n".join(lines)
def render_note(text: str, timestamp: bool = False, size: int = 1) -> bytes:
if not text.strip():
raise InvalidJob("Nothing to print.")
lines = wrap_text(text, TEXT_COLUMNS // size).split("\n")
header_lines = 2 if timestamp else 0
if (len(lines) * size + header_lines) * LINE_HEIGHT_DOTS > MAX_PRINT_HEIGHT_DOTS:
max_lines = (MAX_PRINT_HEIGHT_DOTS // LINE_HEIGHT_DOTS - header_lines) // size
raise InvalidJob(
f"Note is too long: {len(lines)} lines at size {size}, the limit is {max_lines}."
)
def build(p: printer.Escpos) -> None:
if timestamp:
p.textln(datetime.now().strftime("%Y-%m-%d %H:%M"))
p.textln("-" * TEXT_COLUMNS)
if size > 1:
p.set(custom_size=True, width=size, height=size)
p.textln("\n".join(lines))
return render(build)
def render_image(source: Path | BinaryIO, caption: str | None = None) -> bytes:
try:
prepared = prepare_for_print(source)
except (OSError, SyntaxError, ValueError, Image.DecompressionBombError) as e:
raise InvalidJob(f"Not a printable image: {e}") from e
def build(p: printer.Escpos) -> None:
if caption:
p.textln(wrap_text(caption))
p.image(prepared, impl="bitImageColumn")
return render(build)
def render_qr(content: str, caption: str | None = None) -> bytes:
if not content:
raise InvalidJob("Nothing to encode.")
def build(p: printer.Escpos) -> None:
if caption:
p.textln(wrap_text(caption))
# Size 8 is the largest module size that reliably fits 576px with quiet zones.
p.qr(content, size=8, center=True)
return render(build)
def _printable(thread: dict) -> bool:
"""True when the thread's OP image is safe to cache and print.
@@ -208,35 +359,7 @@ def cached_images() -> list[Path]:
)
def close_quietly(p: printer.Escpos) -> None:
"""Close a printer handle, ignoring errors from an already-dead socket."""
with contextlib.suppress(Exception):
p.close()
def print_image(
p: printer.Escpos, img_path: Path | BinaryIO, args: argparse.Namespace
) -> printer.Escpos:
"""Print an image, reconnecting and retrying once if the printer drops.
Returns the (possibly reconnected) printer so the caller keeps a live handle.
"""
prepared = prepare_for_print(img_path)
try:
p.image(prepared, impl="bitImageColumn")
except (OSError, escpos_exceptions.Error) as e:
print(f"Print failed ({e}); reconnecting...", file=sys.stderr)
close_quietly(p)
if needs_setup(args):
setup_network(args)
p = get_printer(args)
# Record it so main() closes the live handle, not the one it opened.
args._printer = p
p.image(prepared, impl="bitImageColumn")
return p
def cmd_image(p: printer.Escpos, args: argparse.Namespace) -> int:
def cmd_image(config: PrinterConfig, args: argparse.Namespace) -> int:
printed = 0
for _ in range(args.count):
img = download_random_bant_image()
@@ -244,9 +367,12 @@ def cmd_image(p: printer.Escpos, args: argparse.Namespace) -> int:
# Keep going: one skipped image shouldn't discard the rest of the run.
print("No printable image found; skipping.", file=sys.stderr)
continue
p.textln(img.stem)
p = print_image(p, img, args)
p.cut()
try:
payload = render_image(img, caption=img.stem)
except InvalidJob as e:
print(f"Skipping {img.name}: {e}", file=sys.stderr)
continue
send(config, payload)
printed += 1
if printed == 0:
print("No images printed.", file=sys.stderr)
@@ -254,82 +380,50 @@ def cmd_image(p: printer.Escpos, args: argparse.Namespace) -> int:
return 0
def cmd_note(p: printer.Escpos, args: argparse.Namespace) -> int:
def cmd_note(config: PrinterConfig, args: argparse.Namespace) -> int:
text = args.text
if text is None or text == "-":
text = sys.stdin.read().rstrip("\n")
if not text:
print("Nothing to print.", file=sys.stderr)
return 1
if args.timestamp:
p.textln(datetime.now().strftime("%Y-%m-%d %H:%M"))
p.textln("-" * TEXT_COLUMNS)
size = getattr(args, "size", 1)
if size > 1:
p.set(custom_size=True, width=size, height=size)
p.textln(wrap_text(text, TEXT_COLUMNS // size))
if size > 1:
p.set(normal_textsize=True) # the mode outlives this connection
p.cut()
send(config, render_note(text, args.timestamp, getattr(args, "size", 1)))
return 0
def cmd_print(p: printer.Escpos, args: argparse.Namespace) -> int:
# `data` is an in-memory upload (web server); it is never written to disk.
def cmd_print(config: PrinterConfig, args: argparse.Namespace) -> int:
# `data` is in-memory image bytes; it is never written to disk.
data = getattr(args, "data", None)
if data is not None:
source: Path | BinaryIO = io.BytesIO(data)
elif args.path.is_file():
source = args.path
else:
print(f"File not found: {args.path}", file=sys.stderr)
return 1
if args.message:
p.textln(wrap_text(args.message))
p = print_image(p, source, args)
p.cut()
raise InvalidJob(f"File not found: {args.path}")
send(config, render_image(source, args.message))
return 0
def cmd_qr(p: printer.Escpos, args: argparse.Namespace) -> int:
if args.message:
p.textln(wrap_text(args.message))
# Size 8 is the largest module size that reliably fits 576px with quiet zones.
p.qr(args.content, size=8, center=True)
p.cut()
def cmd_qr(config: PrinterConfig, args: argparse.Namespace) -> int:
send(config, render_qr(args.content, args.message))
return 0
def cmd_reprint(p: printer.Escpos, args: argparse.Namespace) -> int:
def cmd_reprint(config: PrinterConfig, args: argparse.Namespace) -> int:
images = cached_images()
if not images:
print("Image cache is empty.", file=sys.stderr)
return 1
raise InvalidJob("Image cache is empty.")
if args.name:
matches = [f for f in images if f.name == args.name or f.stem == args.name]
if not matches:
print(f"No cached image named {args.name!r}. Try './receipt.py list'.", file=sys.stderr)
return 1
raise InvalidJob(f"No cached image named {args.name!r}. Try './receipt.py list'.")
target = matches[0]
else:
target = images[0]
p.textln(target.stem)
p = print_image(p, target, args)
p.cut()
send(config, render_image(target, caption=target.stem))
return 0
def cmd_status(args: argparse.Namespace) -> int:
try:
if needs_setup(args):
setup_network(args)
p = get_printer(args)
p.close()
except Exception as e:
print(f"Printer unreachable: {e}", file=sys.stderr)
return 1
target = "USB" if args.usb else f"{args.ip}:{args.port}"
print(f"Printer reachable ({target}).")
def cmd_status(config: PrinterConfig) -> int:
close_quietly(connect(config))
print(f"Printer reachable ({config.target}).")
return 0
@@ -377,52 +471,63 @@ def cmd_clean(yes: bool = False) -> int:
return 0
def run_action(command: str, base: argparse.Namespace, **params) -> tuple[int, str]:
"""Run a command handler, capturing its terminal output (used by the TUI and web server).
Mirrors main(): every action connects fresh, so a dropped printer never
leaves the caller holding a dead handle. redirect_stdout is process-global,
so concurrent callers must serialize.
"""
args = argparse.Namespace(**{**vars(base), **params, "command": command})
buf = io.StringIO()
with contextlib.redirect_stdout(buf), contextlib.redirect_stderr(buf):
try:
rc = _dispatch(command, args)
except Exception as e:
print(f"Error: {e}")
rc = 1
return rc, buf.getvalue().rstrip()
PRINT_COMMANDS = {
"image": cmd_image,
"note": cmd_note,
"print": cmd_print,
"qr": cmd_qr,
"reprint": cmd_reprint,
}
def _dispatch(command: str, args: argparse.Namespace) -> int:
def run_command(command: str, args: argparse.Namespace) -> int:
"""Run one subcommand. InvalidJob, PrinterUnavailable and download errors propagate."""
if command == "list":
return cmd_list()
# No TTY to prompt on: the button press is the confirmation.
if command == "clean":
return cmd_clean(yes=True)
return cmd_clean(getattr(args, "yes", False))
config = PrinterConfig.from_args(args)
if command == "status":
if needs_setup(args):
setup_network_quiet(args)
# Already up; cmd_status must not rerun the script with uncaptured output.
args = argparse.Namespace(**{**vars(args), "no_setup": True})
return cmd_status(args)
if needs_setup(args):
setup_network_quiet(args)
handlers = {
"image": cmd_image,
"note": cmd_note,
"print": cmd_print,
"qr": cmd_qr,
"reprint": cmd_reprint,
}
p = get_printer(args)
# print_image() may reconnect and stash the new handle here; close whichever is live.
args._printer = p
try:
return handlers[command](p, args)
finally:
close_quietly(args._printer)
return cmd_status(config)
return PRINT_COMMANDS[command](config, args)
@dataclass(frozen=True)
class ActionResult:
rc: int
output: str
error: str | None = None # "invalid", "unavailable" or "failed" whenever rc != 0
def run_action(command: str, base: argparse.Namespace, **params) -> ActionResult:
"""Run a command with its terminal output captured (used by the TUI).
Every action connects fresh, so a dropped printer never leaves the caller
holding a dead handle. redirect_stdout is process-global, so concurrent
callers must serialize.
"""
# No TTY to prompt on: the button press is the confirmation.
defaults = {"yes": True} if command == "clean" else {}
args = argparse.Namespace(
**{**vars(base), **defaults, **params, "command": command, "quiet_setup": True}
)
buf = io.StringIO()
error = None
with contextlib.redirect_stdout(buf), contextlib.redirect_stderr(buf):
try:
rc = run_command(command, args)
except InvalidJob as e:
print(e)
rc, error = 1, "invalid"
except PrinterUnavailable as e:
print(f"Printer unavailable: {e}")
rc, error = 1, "unavailable"
except Exception as e:
print(f"Error: {e}")
rc, error = 1, "failed"
if rc != 0 and error is None:
error = "failed"
return ActionResult(rc, buf.getvalue().rstrip(), error)
def _valid_ip(value: str) -> str:
@@ -556,43 +661,21 @@ def main() -> int:
)
return 1
return serve(args)
if args.command == "list":
return cmd_list()
if args.command == "clean":
return cmd_clean(args.yes)
if args.command == "status":
return cmd_status(args)
try:
if needs_setup(args):
setup_network(args)
p = get_printer(args)
except Exception as e:
print(f"Could not connect to printer: {e}", file=sys.stderr)
return run_command(args.command, args)
except InvalidJob as e:
print(e, file=sys.stderr)
return 1
except PrinterUnavailable as e:
print(f"Printer unavailable: {e}", file=sys.stderr)
return 1
commands = {
"image": cmd_image,
"note": cmd_note,
"print": cmd_print,
"qr": cmd_qr,
"reprint": cmd_reprint,
}
# print_image() may reconnect and stash the new handle on args; close whichever is live.
args._printer = p
try:
return commands[args.command](p, args)
except requests.RequestException as e:
print(f"Download failed: {e}", file=sys.stderr)
return 1
except KeyboardInterrupt:
print("Aborted.", file=sys.stderr)
return 130
except (OSError, escpos_exceptions.Error, Image.UnidentifiedImageError) as e:
print(f"Print failed: {e}", file=sys.stderr)
return 1
finally:
close_quietly(args._printer)
if __name__ == "__main__":
+3 -3
View File
@@ -126,7 +126,7 @@ class ReceiptApp(App):
yield Footer()
def on_mount(self) -> None:
target = "USB" if self.base_args.usb else f"{self.base_args.ip}:{self.base_args.port}"
target = receipt.PrinterConfig.from_args(self.base_args).target
self.log_panel.write(f"[dim]Printer target: {target}[/dim]")
self.refresh_cache_list()
@@ -199,10 +199,10 @@ class ReceiptApp(App):
self.call_from_thread(self.set_buttons_disabled, True)
self.call_from_thread(self.log_panel.write, f"[bold]$ {command}[/bold]")
try:
rc, output = receipt.run_action(command, self.base_args, **params)
result = receipt.run_action(command, self.base_args, **params)
finally:
self.call_from_thread(self.set_buttons_disabled, False)
self.call_from_thread(self.report, command, rc, output)
self.call_from_thread(self.report, command, result.rc, result.output)
def report(self, command: str, rc: int, output: str) -> None:
if output:
+158 -34
View File
@@ -5,6 +5,10 @@ Runs on the machine the printer is cabled to. nginx on the web host gates
forwards here over Tailscale, adding X-Receipt-Token. Nothing is served
without that token, so reaching this port directly is not enough.
Jobs are rendered and validated in the request (bad input is a 400 at once),
then queued: POST answers 202 with a job id and the page long-polls
/api/jobs/{id}, so no request waits behind another print long enough for
nginx's proxy timeout to report a failure while the job still prints.
Uploads are printed from memory and never written to disk.
"""
@@ -13,13 +17,17 @@ from __future__ import annotations
import argparse
import hmac
import io
import logging
import os
import queue
import secrets
import sys
import threading
from collections import OrderedDict
from dataclasses import dataclass
from fastapi import Depends, FastAPI, File, Form, Header, HTTPException, UploadFile
from fastapi import Depends, FastAPI, File, Form, Header, HTTPException, Query, UploadFile
from fastapi.responses import HTMLResponse, JSONResponse
from PIL import Image
from pydantic import BaseModel, Field
import receipt
@@ -28,9 +36,15 @@ TOKEN_ENV = "RECEIPT_WEB_TOKEN" # noqa: S105 - env var name, not a secret
MIN_TOKEN_CHARS = 16
MAX_NOTE_CHARS = 4000
MAX_CAPTION_CHARS = 500
MAX_QUEUED = 10 # jobs waiting for the printer; more is a 503
MAX_JOB_HISTORY = 50 # finished jobs kept for polling
MAX_WAIT_SECONDS = 25 # long-poll cap, well under nginx's 90 s proxy_read_timeout
# Sent by the page's fetch(). A cross-site form can't set it, and a cross-site
# fetch that sets it needs a CORS preflight, which nginx's auth gate refuses.
CSRF_HEADER_VALUE = "receipt"
FINISHED = ("done", "failed")
log = logging.getLogger("receipt_web")
class Note(BaseModel):
@@ -39,11 +53,86 @@ class Note(BaseModel):
size: int = Field(default=1, ge=min(receipt.TEXT_SIZES), le=max(receipt.TEXT_SIZES))
def create_app(base: argparse.Namespace, token: str) -> FastAPI:
# One job at a time: run_action's stdout capture is process-global and the
# printer takes a single connection.
lock = threading.Lock()
@dataclass
class Job:
id: str
kind: str
user: str | None
state: str = "queued" # queued -> printing -> done | failed
message: str = ""
error: str | None = None # "unavailable" or "failed" when state is failed
def public(self) -> dict:
return {k: getattr(self, k) for k in ("id", "kind", "state", "message", "error")}
class PrintQueue:
"""Rendered jobs waiting for the printer, sent one at a time by a worker thread.
The printer takes a single connection, so the worker holds printer_lock
for each send; the status check only tries the lock, so it never waits
behind a long print.
"""
def __init__(self, config: receipt.PrinterConfig):
self.config = config
self.printer_lock = threading.Lock()
self._changed = threading.Condition()
self._jobs: OrderedDict[str, Job] = OrderedDict()
self._pending: queue.Queue[tuple[Job, bytes]] = queue.Queue(MAX_QUEUED)
threading.Thread(target=self._work, name="print-worker", daemon=True).start()
@property
def queued(self) -> int:
return self._pending.qsize()
def submit(self, kind: str, payload: bytes, user: str | None) -> Job:
job = Job(secrets.token_hex(8), kind, user)
try:
self._pending.put_nowait((job, payload))
except queue.Full:
raise HTTPException(503, "The print queue is full; try again shortly.") from None
with self._changed:
self._jobs[job.id] = job
while len(self._jobs) > MAX_JOB_HISTORY:
self._jobs.popitem(last=False)
log.info("job %s: %s queued by %s", job.id, kind, user or "unknown")
return job
def wait(self, job_id: str, timeout: float) -> Job | None:
"""The job, once finished or after timeout seconds; None if unknown."""
with self._changed:
job = self._jobs.get(job_id)
if job is not None:
self._changed.wait_for(lambda: job.state in FINISHED, timeout)
return job
def _update(self, job: Job, state: str, message: str = "", error: str | None = None) -> None:
with self._changed:
job.state, job.message, job.error = state, message, error
self._changed.notify_all()
def _work(self) -> None:
while True:
job, payload = self._pending.get()
self._update(job, "printing")
with self.printer_lock:
try:
receipt.send(self.config, payload)
except receipt.PrinterUnavailable as e:
self._update(job, "failed", f"Printer unavailable: {e}", "unavailable")
except Exception as e:
log.exception("job %s failed", job.id)
self._update(job, "failed", f"Error: {e}", "failed")
else:
self._update(job, "done", "Printed.")
log.info("job %s: %s %s", job.id, job.state, job.message)
def create_app(config: receipt.PrinterConfig, token: str) -> FastAPI:
jobs = PrintQueue(config)
app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None)
app.state.jobs = jobs
def require_token(x_receipt_token: str | None = Header(default=None)) -> None:
if x_receipt_token is None or not hmac.compare_digest(
@@ -55,10 +144,14 @@ def create_app(base: argparse.Namespace, token: str) -> FastAPI:
if x_requested_with != CSRF_HEADER_VALUE:
raise HTTPException(403, "Requests must come from the receipt page.")
def run(command: str, **params) -> JSONResponse:
with lock:
rc, output = receipt.run_action(command, base, **params)
return JSONResponse({"ok": rc == 0, "output": output}, status_code=200 if rc == 0 else 502)
def render(build, *args) -> bytes:
try:
return build(*args)
except receipt.InvalidJob as e:
raise HTTPException(400, str(e)) from None
def accepted(job: Job) -> JSONResponse:
return JSONResponse({"ok": True, "job": job.public()}, status_code=202)
authed = [Depends(require_token)]
posting = [Depends(require_token), Depends(require_page_request)]
@@ -73,31 +166,46 @@ def create_app(base: argparse.Namespace, token: str) -> FastAPI:
@app.get("/api/status", dependencies=authed)
def status() -> JSONResponse:
return run("status")
if jobs.queued or not jobs.printer_lock.acquire(blocking=False):
busy = f"Printing ({jobs.queued} more queued)."
return JSONResponse({"ok": True, "busy": True, "output": busy})
try:
receipt.close_quietly(receipt.connect(config))
except receipt.PrinterUnavailable as e:
body = {"ok": False, "output": f"Printer unavailable: {e}"}
return JSONResponse(body, status_code=503)
finally:
jobs.printer_lock.release()
reachable = f"Printer reachable ({config.target})."
return JSONResponse({"ok": True, "busy": False, "output": reachable})
@app.get("/api/jobs/{job_id}", dependencies=authed)
def job_status(
job_id: str, wait: float = Query(default=0, ge=0, le=MAX_WAIT_SECONDS)
) -> dict:
job = jobs.wait(job_id, wait)
if job is None:
raise HTTPException(404, "No such job (the server may have restarted).")
return {"ok": True, "job": job.public()}
@app.post("/api/note", dependencies=posting)
def note(body: Note) -> JSONResponse:
if not body.text.strip():
raise HTTPException(400, "Nothing to print.")
return run("note", text=body.text, timestamp=body.timestamp, size=body.size)
def note(body: Note, x_remote_user: str | None = Header(default=None)) -> JSONResponse:
payload = render(receipt.render_note, body.text, body.timestamp, body.size)
return accepted(jobs.submit("note", payload, x_remote_user or None))
@app.post("/api/image", dependencies=posting)
def image(
file: UploadFile = File(...), # noqa: B008 - FastAPI's declaration idiom
message: str = Form(default="", max_length=MAX_CAPTION_CHARS),
x_remote_user: str | None = Header(default=None),
) -> JSONResponse:
data = file.file.read(receipt.MAX_IMAGE_BYTES + 1)
if len(data) > receipt.MAX_IMAGE_BYTES:
raise HTTPException(
413, f"Image exceeds the {receipt.MAX_IMAGE_BYTES // 1024 // 1024} MB cap."
)
# Reject non-images here, as a 400, rather than as a print failure.
try:
with Image.open(io.BytesIO(data)) as img:
img.verify()
except (Image.DecompressionBombError, OSError, SyntaxError, ValueError) as e:
raise HTTPException(400, f"Not a printable image: {e}") from None
return run("print", path=None, data=data, message=message.strip() or None)
payload = render(receipt.render_image, io.BytesIO(data), message.strip() or None)
return accepted(jobs.submit("image", payload, x_remote_user or None))
return app
@@ -119,8 +227,14 @@ def serve(args: argparse.Namespace) -> int:
return 1
# Never run the sudo connect script from a request: the service expects the
# printer link to be configured persistently (see README).
base = argparse.Namespace(**{**vars(args), "no_setup": True})
uvicorn.run(create_app(base, token), host=host.strip("[]"), port=int(port))
config = receipt.PrinterConfig(ip=args.ip, port=args.port, usb=args.usb, no_setup=True)
# Our own handler, not basicConfig: escpos logs chatty INFO lines through the root logger.
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter("%(name)s: %(message)s"))
log.addHandler(handler)
log.setLevel(logging.INFO)
log.propagate = False
uvicorn.run(create_app(config, token), host=host.strip("[]"), port=int(port))
return 0
@@ -251,28 +365,38 @@ async function call(path, init) {
}
let detail = body.detail;
if (Array.isArray(detail)) detail = detail.map((d) => d.msg).join("; ");
return {ok: res.ok && body.ok !== false, text: body.output || detail || res.statusText};
return {ok: res.ok && body.ok !== false, text: body.output || detail || res.statusText,
job: body.job, busy: body.busy};
}
async function checkStatus() {
const pill = $("status");
pill.textContent = "checking…"; pill.className = "pill";
const r = await call("api/status");
pill.textContent = r.ok ? "printer ready" : "printer offline";
pill.textContent = r.busy ? "printer busy" : r.ok ? "printer ready" : "printer offline";
pill.className = "pill " + (r.ok ? "ok" : "err");
pill.title = r.text;
}
async function submit(form, path, init) {
// POST answers 202 with a queued job; long-poll it until it finishes.
async function submit(path, init) {
const buttons = document.querySelectorAll("button");
buttons.forEach((b) => b.disabled = true);
show("Printing…");
show("Sending…");
let job = null;
try {
const r = await call(path, init);
show(r.ok ? (r.text || "Printed.") : r.text, r.ok ? "ok" : "err");
return r.ok;
let r = await call(path, init);
while (r.ok && r.job && !["done", "failed"].includes(r.job.state)) {
job = r.job;
show(job.state === "queued" ? "Queued…" : "Printing…");
r = await call("api/jobs/" + job.id + "?wait=20");
}
if (!r.ok || !r.job) { show(r.text, "err"); return false; }
const ok = r.job.state === "done";
show(r.job.message, ok ? "ok" : "err");
return ok;
} catch (e) {
show("Request failed: " + e, "err");
show("Request failed: " + e + (job ? " (the job may still print)" : ""), "err");
return false;
} finally {
buttons.forEach((b) => b.disabled = false);
@@ -281,7 +405,7 @@ async function submit(form, path, init) {
$("note-form").addEventListener("submit", async (e) => {
e.preventDefault();
const ok = await submit(e.target, "api/note", {
const ok = await submit("api/note", {
method: "POST",
headers: {"Content-Type": "application/json"},
body: JSON.stringify({text: $("note").value, timestamp: $("timestamp").checked,
@@ -318,7 +442,7 @@ $("image-form").addEventListener("submit", async (e) => {
const data = new FormData();
data.append("file", picked, picked.name || "pasted.png");
data.append("message", $("caption").value);
await submit(e.target, "api/image", {method: "POST", body: data});
await submit("api/image", {method: "POST", body: data});
});
$("status").addEventListener("click", checkStatus);
+31 -16
View File
@@ -2,30 +2,45 @@
import argparse
from escpos import printer
import receipt
class FakePrinter:
"""Records escpos calls instead of talking to hardware."""
"""Records the connection lifecycle and raw job payloads instead of talking to hardware."""
def __init__(self):
def __init__(self, fail_open=0, fail_raw=False):
self.calls = []
self.payloads = []
self.fail_open = fail_open # how many open() calls raise before one succeeds
self.fail_raw = fail_raw
def textln(self, text=""):
self.calls.append(("textln", text))
def open(self):
self.calls.append("open")
if self.fail_open:
self.fail_open -= 1
raise OSError("no route to printer")
def image(self, img, **kwargs):
self.calls.append(("image", img))
def qr(self, content, **kwargs):
self.calls.append(("qr", content))
def set(self, **kwargs):
self.calls.append(("set", kwargs))
def cut(self):
self.calls.append(("cut", None))
def _raw(self, data):
self.calls.append("raw")
if self.fail_raw:
raise OSError("connection reset")
self.payloads.append(data)
def close(self):
self.calls.append(("close", None))
self.calls.append("close")
def escpos_bytes(build):
"""What the given escpos calls render to, for asserting on payloads."""
p = printer.Dummy(profile=receipt.PRINTER_PROFILE)
build(p)
return p.output
INIT = escpos_bytes(lambda p: p.hw("INIT"))
CUT = escpos_bytes(lambda p: p.cut())
def make_args(**overrides):
+190 -158
View File
@@ -2,7 +2,7 @@ import argparse
import io
import pytest
from conftest import FakePrinter, make_args
from conftest import CUT, INIT, FakePrinter, escpos_bytes, make_args
from PIL import Image
import receipt
@@ -124,53 +124,121 @@ def test_download_skips_unprintable_formats(tmp_path, monkeypatch):
assert receipt.download_random_bant_image() is None
def test_cmd_note_wraps_and_cuts():
@pytest.fixture
def fake_printer(monkeypatch):
p = FakePrinter()
rc = receipt.cmd_note(p, make_args(text="hello " * 20))
monkeypatch.setattr(receipt, "get_printer", lambda config: p)
return p
CONFIG = receipt.PrinterConfig(usb=True) # usb avoids the network setup script
def test_render_note_is_one_reset_job_with_one_cut():
payload = receipt.render_note("hello " * 20)
assert payload.startswith(INIT)
assert payload.endswith(CUT)
assert payload.count(CUT) == 1
assert receipt.wrap_text("hello " * 20).encode() in payload
def test_render_note_large_size_wraps_narrower():
payload = receipt.render_note("hello " * 20, size=2)
big = escpos_bytes(lambda p: p.set(custom_size=True, width=2, height=2))
assert payload.startswith(INIT + big)
assert receipt.wrap_text("hello " * 20, receipt.TEXT_COLUMNS // 2).encode() in payload
def test_render_note_timestamp_header():
payload = receipt.render_note("hi", timestamp=True)
assert b"-" * receipt.TEXT_COLUMNS in payload
assert payload.index(b"-" * receipt.TEXT_COLUMNS) < payload.index(b"hi\n")
@pytest.mark.parametrize("text", ["", " \n "])
def test_render_note_rejects_empty(text):
with pytest.raises(receipt.InvalidJob, match="Nothing to print"):
receipt.render_note(text)
def test_render_note_rejects_over_paper_budget():
max_lines = receipt.MAX_PRINT_HEIGHT_DOTS // receipt.LINE_HEIGHT_DOTS // 3
receipt.render_note("x\n" * max_lines, size=3) # exactly at the limit is fine
with pytest.raises(receipt.InvalidJob, match="too long"):
receipt.render_note("x\n" * (max_lines + 1), size=3)
def test_cmd_note_sends_once_and_closes(fake_printer):
rc = receipt.cmd_note(CONFIG, make_args(text="hello"))
assert rc == 0
assert p.calls[0][0] == "textln"
assert all(len(line) <= receipt.TEXT_COLUMNS for line in p.calls[0][1].split("\n"))
assert p.calls[-1] == ("cut", None)
assert fake_printer.calls == ["open", "raw", "close"]
assert b"hello" in fake_printer.payloads[0]
def test_cmd_note_large_size_wraps_narrower_and_resets():
p = FakePrinter()
rc = receipt.cmd_note(p, make_args(text="hello " * 20, size=2))
def test_cmd_qr_prints_content_and_caption(fake_printer):
rc = receipt.cmd_qr(CONFIG, make_args(content="https://example.com", message="scan me"))
assert rc == 0
assert p.calls[0] == ("set", {"custom_size": True, "width": 2, "height": 2})
assert all(len(line) <= receipt.TEXT_COLUMNS // 2 for line in p.calls[1][1].split("\n"))
assert p.calls[2:] == [("set", {"normal_textsize": True}), ("cut", None)]
# The QR raster as escpos renders it; the caption already selected the codepage.
expected_qr = escpos_bytes(lambda p: p.qr("https://example.com", size=8, center=True))
assert b"scan me" in fake_printer.payloads[0]
assert expected_qr.removeprefix(b"\x1bt\x00") in fake_printer.payloads[0]
def test_cmd_note_timestamp_header():
p = FakePrinter()
rc = receipt.cmd_note(p, make_args(text="hi", timestamp=True))
def test_send_retries_a_failed_connect(monkeypatch):
p = FakePrinter(fail_open=1)
monkeypatch.setattr(receipt, "get_printer", lambda config: p)
assert rc == 0
kinds = [c[0] for c in p.calls]
assert kinds == ["textln", "textln", "textln", "cut"] # date, rule, note, cut
receipt.send(CONFIG, b"job")
assert p.calls == ["open", "open", "raw", "close"]
assert p.payloads == [b"job"]
def test_cmd_note_rejects_empty():
p = FakePrinter()
rc = receipt.cmd_note(p, make_args(text=""))
def test_send_gives_up_after_two_failed_connects(monkeypatch):
p = FakePrinter(fail_open=2)
monkeypatch.setattr(receipt, "get_printer", lambda config: p)
assert rc == 1
assert p.calls == []
with pytest.raises(receipt.PrinterUnavailable, match="can't reach"):
receipt.send(CONFIG, b"job")
assert "raw" not in p.calls
def test_cmd_qr_prints_content_and_caption():
p = FakePrinter()
rc = receipt.cmd_qr(p, make_args(content="https://example.com", message="scan me"))
def test_send_never_replays_after_a_mid_job_drop(monkeypatch):
p = FakePrinter(fail_raw=True)
monkeypatch.setattr(receipt, "get_printer", lambda config: p)
assert rc == 0
assert ("qr", "https://example.com") in p.calls
assert ("textln", "scan me") in p.calls
with pytest.raises(receipt.PrinterUnavailable, match="partially"):
receipt.send(CONFIG, b"job")
assert p.calls == ["open", "raw", "close"] # one attempt; a retry could print it twice
def test_cmd_reprint_picks_most_recent(tmp_path, monkeypatch):
def test_connect_reruns_setup_on_retry(monkeypatch):
p = FakePrinter(fail_open=1)
setups = []
monkeypatch.setattr(receipt, "get_printer", lambda config: p)
monkeypatch.setattr(receipt, "setup_network", setups.append)
receipt.connect(receipt.PrinterConfig())
assert len(setups) == 2
def test_connect_skips_setup_with_no_setup(monkeypatch):
monkeypatch.setattr(receipt, "get_printer", lambda config: FakePrinter())
monkeypatch.setattr(
receipt, "setup_network", lambda config: pytest.fail("should not run the connect script")
)
receipt.connect(receipt.PrinterConfig(no_setup=True))
def test_cmd_reprint_picks_most_recent(fake_printer, tmp_path, monkeypatch):
img_dir = tmp_path / "img"
img_dir.mkdir()
older = img_dir / "old.png"
@@ -183,35 +251,33 @@ def test_cmd_reprint_picks_most_recent(tmp_path, monkeypatch):
os.utime(newer, (2000, 2000))
monkeypatch.setattr(receipt, "IMG_DIR", img_dir)
p = FakePrinter()
rc = receipt.cmd_reprint(p, make_args())
rc = receipt.cmd_reprint(CONFIG, make_args())
assert rc == 0
assert ("textln", "new") in p.calls
assert b"new\n" in fake_printer.payloads[0]
def test_cmd_reprint_by_stem(tmp_path, monkeypatch):
def test_cmd_reprint_by_stem(fake_printer, tmp_path, monkeypatch):
img_dir = tmp_path / "img"
img_dir.mkdir()
Image.new("RGB", (10, 10)).save(img_dir / "12345.png")
monkeypatch.setattr(receipt, "IMG_DIR", img_dir)
p = FakePrinter()
rc = receipt.cmd_reprint(p, make_args(name="12345"))
rc = receipt.cmd_reprint(CONFIG, make_args(name="12345"))
assert rc == 0
assert ("textln", "12345") in p.calls
assert b"12345\n" in fake_printer.payloads[0]
def test_cmd_reprint_unknown_name(tmp_path, monkeypatch):
def test_cmd_reprint_unknown_name(fake_printer, tmp_path, monkeypatch):
img_dir = tmp_path / "img"
img_dir.mkdir()
Image.new("RGB", (10, 10)).save(img_dir / "12345.png")
monkeypatch.setattr(receipt, "IMG_DIR", img_dir)
p = FakePrinter()
assert receipt.cmd_reprint(p, make_args(name="nope")) == 1
assert p.calls == []
with pytest.raises(receipt.InvalidJob, match="No cached image"):
receipt.cmd_reprint(CONFIG, make_args(name="nope"))
assert fake_printer.calls == []
def test_parser_handles_all_subcommands():
@@ -269,27 +335,30 @@ def test_cmd_clean_nothing_to_do(tmp_path, monkeypatch):
assert receipt.cmd_clean(yes=True) == 0
def test_cmd_image_continues_past_failures(monkeypatch):
def test_cmd_image_continues_past_failures(fake_printer, monkeypatch):
monkeypatch.setattr(receipt, "download_random_bant_image", lambda: None)
p = FakePrinter()
assert receipt.cmd_image(p, make_args(count=2)) == 1 # nothing printed
assert p.calls == []
assert receipt.cmd_image(CONFIG, make_args(count=2)) == 1 # nothing printed
assert fake_printer.calls == []
def test_cmd_image_prints_and_cuts(monkeypatch, tmp_path):
from PIL import Image
def test_cmd_image_sends_each_image_as_its_own_job(fake_printer, monkeypatch, tmp_path):
img = tmp_path / "1.png"
Image.new("RGB", (10, 10)).save(img)
monkeypatch.setattr(receipt, "download_random_bant_image", lambda: img)
monkeypatch.setattr(receipt, "prepare_for_print", lambda p: Image.new("1", (576, 10)))
p = FakePrinter()
assert receipt.cmd_image(p, make_args(count=2)) == 0
kinds = [c[0] for c in p.calls]
assert kinds.count("image") == 2
assert kinds.count("cut") == 2
assert receipt.cmd_image(CONFIG, make_args(count=2)) == 0
assert len(fake_printer.payloads) == 2
assert all(job.startswith(INIT) and job.count(CUT) == 1 for job in fake_printer.payloads)
def test_cmd_image_skips_a_corrupt_download(fake_printer, monkeypatch, tmp_path):
bad = tmp_path / "1.png"
bad.write_bytes(b"not an image")
monkeypatch.setattr(receipt, "download_random_bant_image", lambda: bad)
assert receipt.cmd_image(CONFIG, make_args(count=1)) == 1
assert fake_printer.payloads == []
def test_download_size_cap(tmp_path, monkeypatch):
@@ -326,97 +395,58 @@ def test_wrap_unbreakable_long_token():
assert all(len(line) <= receipt.TEXT_COLUMNS for line in wrapped.split("\n"))
def test_print_image_retries_once_on_failure(monkeypatch, tmp_path):
class Flaky:
def __init__(self, tag):
self.tag = tag
self.calls = []
def test_prepare_for_print_shrinks_very_tall_images(tmp_path):
src = tmp_path / "strip.png"
Image.new("RGB", (100, 10_000), "gray").save(src) # would be 57600 dots at full width
def image(self, img, **kwargs):
self.calls.append("image")
if self.tag == 1:
raise OSError("dropped")
prepared = receipt.prepare_for_print(src)
def close(self):
self.calls.append("close")
def textln(self, t):
self.calls.append(("textln", t))
def cut(self):
self.calls.append("cut")
first = Flaky(1)
second = Flaky(2)
monkeypatch.setattr(receipt, "get_printer", lambda args: second)
monkeypatch.setattr(receipt, "setup_network", lambda args: None)
args = make_args()
img = tmp_path / "x.png"
Image.new("RGB", (10, 10)).save(img)
monkeypatch.setattr(receipt, "prepare_for_print", lambda p: Image.new("1", (576, 10)))
p = receipt.print_image(first, img, args)
assert p is second # caller keeps the live handle
assert "close" in first.calls
assert second.calls == ["image"]
assert args._printer is second # main() closes this one
assert prepared.size == (receipt.PRINT_WIDTH_PX, receipt.MAX_PRINT_HEIGHT_DOTS)
assert prepared.getpixel((0, 0)) == 255 # white margin around the centered strip
def test_print_image_retry_skips_setup_with_no_setup(monkeypatch):
class Flaky(FakePrinter):
def image(self, img, **kwargs):
raise OSError("dropped")
second = FakePrinter()
monkeypatch.setattr(receipt, "get_printer", lambda args: second)
monkeypatch.setattr(
receipt, "setup_network", lambda args: pytest.fail("should not run the connect script")
)
monkeypatch.setattr(receipt, "prepare_for_print", lambda p: Image.new("1", (576, 10)))
p = receipt.print_image(Flaky(), "unused", make_args(usb=False, no_setup=True))
assert p is second
def test_render_image_rejects_non_images():
with pytest.raises(receipt.InvalidJob, match="Not a printable image"):
receipt.render_image(io.BytesIO(b"not an image"))
def test_cmd_print_from_memory(tmp_path):
def test_cmd_print_from_memory(fake_printer, tmp_path):
buf = io.BytesIO()
Image.new("RGBA", (40, 20), (0, 0, 0, 0)).save(buf, "PNG")
p = FakePrinter()
rc = receipt.cmd_print(p, make_args(path=None, data=buf.getvalue(), message="cap"))
rc = receipt.cmd_print(CONFIG, make_args(path=None, data=buf.getvalue(), message="cap"))
assert rc == 0
assert [c[0] for c in p.calls] == ["textln", "image", "cut"]
assert p.calls[1][1].size[0] == receipt.PRINT_WIDTH_PX
payload = fake_printer.payloads[0]
assert payload.startswith(INIT)
assert payload.index(b"cap\n") < payload.index(b"\x1b*") # caption, then the bit image
assert payload.endswith(CUT)
assert list(tmp_path.iterdir()) == []
# ---- run_action (shared by the TUI and the web server) ----
def test_cmd_print_missing_file(fake_printer, tmp_path):
with pytest.raises(receipt.InvalidJob, match="File not found"):
receipt.cmd_print(CONFIG, make_args(path=tmp_path / "nope.png"))
assert fake_printer.calls == []
@pytest.fixture
def fake_printer(monkeypatch):
p = FakePrinter()
monkeypatch.setattr(receipt, "get_printer", lambda args: p)
return p
def test_cmd_status_actually_connects(monkeypatch):
p = FakePrinter(fail_open=2)
monkeypatch.setattr(receipt, "get_printer", lambda config: p)
with pytest.raises(receipt.PrinterUnavailable):
receipt.cmd_status(receipt.PrinterConfig(no_setup=True))
# ---- run_action (used by the TUI) ----
def test_run_action_note(fake_printer):
rc, output = receipt.run_action("note", make_args(), text="hello", timestamp=False)
result = receipt.run_action("note", make_args(), text="hello", timestamp=False)
assert rc == 0
assert ("textln", "hello") in fake_printer.calls
assert fake_printer.calls[-2] == ("cut", None)
assert fake_printer.calls[-1] == ("close", None) # handle released after action
def test_run_action_qr(fake_printer):
rc, _ = receipt.run_action("qr", make_args(), content="https://example.com", message=None)
assert rc == 0
assert ("qr", "https://example.com") in fake_printer.calls
assert result.rc == 0 and result.error is None
assert b"hello" in fake_printer.payloads[0]
assert fake_printer.calls[-1] == "close" # handle released after action
def test_run_action_reprint_uses_cache(fake_printer, tmp_path, monkeypatch):
@@ -425,55 +455,57 @@ def test_run_action_reprint_uses_cache(fake_printer, tmp_path, monkeypatch):
Image.new("RGB", (10, 10)).save(img_dir / "12345.png")
monkeypatch.setattr(receipt, "IMG_DIR", img_dir)
rc, _ = receipt.run_action("reprint", make_args(), name="12345")
result = receipt.run_action("reprint", make_args(), name="12345")
assert rc == 0
assert ("textln", "12345") in fake_printer.calls
assert result.rc == 0
assert b"12345\n" in fake_printer.payloads[0]
def test_run_action_captures_output_and_errors(monkeypatch):
def boom(args):
raise OSError("no printer")
def test_run_action_classifies_printer_errors(monkeypatch):
monkeypatch.setattr(receipt, "get_printer", lambda config: FakePrinter(fail_open=2))
monkeypatch.setattr(receipt, "get_printer", boom)
result = receipt.run_action("note", make_args(), text="hi", timestamp=False)
rc, output = receipt.run_action("note", make_args(), text="hi", timestamp=False)
assert (result.rc, result.error) == (1, "unavailable")
assert "no route to printer" in result.output
assert rc == 1
assert "no printer" in output
def test_run_action_classifies_invalid_jobs(fake_printer):
result = receipt.run_action("note", make_args(), text=" ", timestamp=False)
assert (result.rc, result.error) == (1, "invalid")
assert result.output == "Nothing to print."
assert fake_printer.calls == []
def test_run_action_list_needs_no_printer(monkeypatch, tmp_path):
monkeypatch.setattr(receipt, "IMG_DIR", tmp_path / "img")
monkeypatch.setattr(receipt, "get_printer", lambda args: pytest.fail("should not connect"))
monkeypatch.setattr(receipt, "get_printer", lambda config: pytest.fail("should not connect"))
rc, output = receipt.run_action("list", make_args())
result = receipt.run_action("list", make_args())
assert rc == 0
assert "empty" in output
assert result.rc == 0
assert "empty" in result.output
def test_run_action_runs_setup_quietly_once(fake_printer, monkeypatch):
configs = []
monkeypatch.setattr(receipt, "setup_network", configs.append)
result = receipt.run_action("status", make_args(usb=False))
assert result.rc == 0
assert [c.quiet_setup for c in configs] == [True] # captured, so it can't corrupt the TUI
assert "reachable" in result.output
def test_run_action_no_setup_skips_connect_script(fake_printer, monkeypatch):
def fail(args):
pytest.fail("should not run the connect script")
monkeypatch.setattr(
receipt, "setup_network", lambda config: pytest.fail("should not run the connect script")
)
monkeypatch.setattr(receipt, "setup_network", fail)
monkeypatch.setattr(receipt, "setup_network_quiet", fail)
rc, _ = receipt.run_action(
result = receipt.run_action(
"note", make_args(usb=False, no_setup=True), text="hi", timestamp=False
)
assert rc == 0
def test_run_action_status_runs_connect_script_once(fake_printer, monkeypatch):
calls = []
monkeypatch.setattr(receipt, "setup_network_quiet", lambda args: calls.append("quiet"))
monkeypatch.setattr(receipt, "setup_network", lambda args: calls.append("loud"))
rc, output = receipt.run_action("status", make_args(usb=False))
assert rc == 0
assert calls == ["quiet"] # captured; cmd_status doesn't rerun it uncaptured
assert "reachable" in output
assert result.rc == 0
+81 -22
View File
@@ -1,7 +1,7 @@
import io
import pytest
from conftest import FakePrinter, make_args
from conftest import CUT, INIT, FakePrinter, make_args
from PIL import Image
import receipt
@@ -19,14 +19,25 @@ HEADERS = {"X-Receipt-Token": TOKEN, "X-Requested-With": "receipt"}
@pytest.fixture
def fake_printer(monkeypatch):
p = FakePrinter()
monkeypatch.setattr(receipt, "get_printer", lambda args: p)
monkeypatch.setattr(receipt, "get_printer", lambda config: p)
return p
@pytest.fixture
def client():
base = make_args(usb=False, no_setup=True)
return TestClient(receipt_web.create_app(base, TOKEN))
config = receipt.PrinterConfig(no_setup=True)
return TestClient(receipt_web.create_app(config, TOKEN))
def finished_job(client, res):
"""Wait for the job a POST queued and return its final record."""
assert res.status_code == 202, res.text
job = res.json()["job"]
res = client.get(f"/api/jobs/{job['id']}?wait=5", headers=HEADERS)
assert res.status_code == 200
job = res.json()["job"]
assert job["state"] in receipt_web.FINISHED
return job
def png_bytes(size=(20, 10)):
@@ -70,17 +81,25 @@ def test_post_needs_page_header(client, fake_printer):
def test_note_prints(client, fake_printer):
res = client.post("/api/note", headers=HEADERS, json={"text": "hello", "timestamp": False})
assert res.status_code == 200
assert res.json()["ok"] is True
assert ("textln", "hello") in fake_printer.calls
assert fake_printer.calls[-2:] == [("cut", None), ("close", None)]
job = finished_job(client, res)
assert (job["state"], job["message"]) == ("done", "Printed.")
assert fake_printer.calls == ["open", "raw", "close"]
assert b"hello" in fake_printer.payloads[0]
def test_note_size(client, fake_printer):
res = client.post("/api/note", headers=HEADERS, json={"text": "hello", "size": 3})
assert res.status_code == 200
assert ("set", {"custom_size": True, "width": 3, "height": 3}) in fake_printer.calls
finished_job(client, res)
assert receipt.render_note("hello", size=3) == fake_printer.payloads[0]
def test_note_over_paper_budget_is_400(client, fake_printer):
res = client.post("/api/note", headers=HEADERS, json={"text": "x\n" * 1000, "size": 3})
assert res.status_code == 400
assert "too long" in res.json()["detail"]
assert fake_printer.calls == []
@pytest.mark.parametrize("size", [0, 4])
@@ -103,7 +122,50 @@ def test_status_reports_reachable(client, fake_printer):
res = client.get("/api/status", headers=HEADERS)
assert res.status_code == 200
assert res.json()["busy"] is False
assert "reachable" in res.json()["output"]
assert fake_printer.calls == ["open", "close"] # a real connect, not just a handle
def test_status_unreachable_is_503(client, monkeypatch):
monkeypatch.setattr(receipt, "get_printer", lambda config: FakePrinter(fail_open=2))
res = client.get("/api/status", headers=HEADERS)
assert res.status_code == 503
assert res.json()["ok"] is False
def test_status_does_not_wait_behind_a_print(client, fake_printer):
jobs = client.app.state.jobs
with jobs.printer_lock: # as if the worker were mid-print
res = client.get("/api/status", headers=HEADERS)
assert res.json()["busy"] is True
assert fake_printer.calls == []
def test_unknown_job_is_404(client):
assert client.get("/api/jobs/nope", headers=HEADERS).status_code == 404
def test_job_records_the_nginx_user(client, fake_printer):
res = client.post(
"/api/note", headers={**HEADERS, "X-Remote-User": "adam"}, json={"text": "hi"}
)
finished_job(client, res)
assert client.app.state.jobs._jobs[res.json()["job"]["id"]].user == "adam"
def test_full_queue_is_503(client, fake_printer, monkeypatch):
jobs = client.app.state.jobs
monkeypatch.setattr(jobs, "_pending", receipt_web.queue.Queue(1))
jobs._pending.put_nowait(("placeholder", b"")) # the worker is parked on the old queue
res = client.post("/api/note", headers=HEADERS, json={"text": "hi"})
assert res.status_code == 503
def test_image_prints_from_memory(client, fake_printer):
@@ -114,11 +176,10 @@ def test_image_prints_from_memory(client, fake_printer):
data={"message": "caption"},
)
assert res.status_code == 200, res.text
kinds = [c[0] for c in fake_printer.calls]
assert kinds == ["textln", "image", "cut", "close"]
assert fake_printer.calls[0] == ("textln", "caption")
assert fake_printer.calls[1][1].size[0] == receipt.PRINT_WIDTH_PX
assert finished_job(client, res)["state"] == "done"
payload = fake_printer.payloads[0]
assert payload.startswith(INIT) and payload.endswith(CUT)
assert b"caption\n" in payload
def test_image_rejects_non_image(client, fake_printer):
@@ -141,16 +202,14 @@ def test_image_rejects_oversize(client, fake_printer, monkeypatch):
assert fake_printer.calls == []
def test_printer_error_is_502(client, monkeypatch):
def boom(args):
raise OSError("no printer")
monkeypatch.setattr(receipt, "get_printer", boom)
def test_printer_error_fails_the_job(client, monkeypatch):
monkeypatch.setattr(receipt, "get_printer", lambda config: FakePrinter(fail_open=2))
res = client.post("/api/note", headers=HEADERS, json={"text": "hi"})
assert res.status_code == 502
assert res.json() == {"ok": False, "output": "Error: no printer"}
job = finished_job(client, res)
assert (job["state"], job["error"]) == ("failed", "unavailable")
assert "no route to printer" in job["message"]
def test_serve_refuses_without_token(monkeypatch, capsys):