Send each print as one job, queue web prints, and harden deploys
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:
+158
-34
@@ -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);
|
||||
|
||||
Reference in New Issue
Block a user