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:
+81
-22
@@ -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):
|
||||
|
||||
Reference in New Issue
Block a user