Receipt printer
Note
Image
Ready.
"""Web server for printing from the website; launched via `./receipt.py serve`. Runs on the machine the printer is cabled to. nginx on the web host gates /receipt/ on the site's admin session (auth_request), strips the prefix and 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. """ 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, Query, UploadFile from fastapi.responses import HTMLResponse, JSONResponse from pydantic import BaseModel, Field import receipt 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): text: str = Field(min_length=1, max_length=MAX_NOTE_CHARS) timestamp: bool = False size: int = Field(default=1, ge=min(receipt.TEXT_SIZES), le=max(receipt.TEXT_SIZES)) @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( x_receipt_token.encode(), token.encode() ): raise HTTPException(401, "Missing or invalid token.") def require_page_request(x_requested_with: str | None = Header(default=None)) -> None: if x_requested_with != CSRF_HEADER_VALUE: raise HTTPException(403, "Requests must come from the receipt page.") 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)] @app.get("/healthz") def healthz() -> dict: return {"ok": True} @app.get("/", response_class=HTMLResponse, dependencies=authed) def page() -> str: return PAGE @app.get("/api/status", dependencies=authed) def status() -> JSONResponse: 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, 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." ) 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 def serve(args: argparse.Namespace) -> int: import uvicorn token = os.environ.get(TOKEN_ENV, "") if len(token) < MIN_TOKEN_CHARS: print( f"Set {TOKEN_ENV} to a random secret of at least {MIN_TOKEN_CHARS} characters " "(e.g. `openssl rand -hex 32`); nginx on the web host sends the same value.", file=sys.stderr, ) return 1 host, sep, port = args.listen.rpartition(":") if not sep or not port.isdigit(): print(f"--listen must be host:port, got {args.listen!r}.", file=sys.stderr) return 1 # Never run the sudo connect script from a request: the service expects the # printer link to be configured persistently (see README). 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 PAGE = """
Ready.