"""PostgREST RPC client for the token-gated printer functions.""" from __future__ import annotations import logging from typing import Any import httpx from .config import Config log = logging.getLogger("worker.rpc") # SQLSTATE raised by _print_station_from_token for invalid/revoked tokens. INVALID_TOKEN_CODE = "28000" class RpcError(Exception): """RPC returned an unexpected response.""" class InvalidToken(RpcError): """The station token is invalid or revoked (HTTP 401/403 or SQLSTATE 28000).""" class RpcUnavailable(RpcError): """Network failure, timeout or 5xx — the backend may come back.""" class Rpc: def __init__(self, cfg: Config, client: httpx.Client | None = None): self._token = cfg.station_token self._base = f"{cfg.convivo_url}/rest/v1/rpc" self._vt = cfg.vt_seconds self._client = client or httpx.Client( headers={ "apikey": cfg.convivo_anon_key, "Authorization": f"Bearer {cfg.convivo_anon_key}", "Content-Type": "application/json", }, timeout=httpx.Timeout(30.0), ) def close(self) -> None: self._client.close() def _call(self, fn: str, params: dict[str, Any], timeout: float) -> Any: try: resp = self._client.post(f"{self._base}/{fn}", json=params, timeout=timeout) except httpx.HTTPError as err: raise RpcUnavailable(f"{fn}: {type(err).__name__}") from err if resp.status_code in (401, 403): raise InvalidToken(f"{fn}: rejected ({resp.status_code})") if resp.status_code >= 500: raise RpcUnavailable(f"{fn}: HTTP {resp.status_code}") if resp.status_code >= 400: try: body = resp.json() except ValueError: body = {} if str(body.get("code", "")) == INVALID_TOKEN_CODE: raise InvalidToken(f"{fn}: invalid station token") detail = str(body.get("message", ""))[:200] raise RpcError(f"{fn}: HTTP {resp.status_code} {detail}".strip()) try: return resp.json() except ValueError as err: raise RpcError(f"{fn}: non-JSON response") from err def claim(self, wait_seconds: int) -> list[dict[str, Any]]: # Long-poll: the server waits up to wait_seconds before answering. rows = self._call( "printer_claim_badge_job", {"p_token": self._token, "p_vt": self._vt, "p_wait_seconds": wait_seconds}, timeout=wait_seconds + 15, ) return rows if isinstance(rows, list) else [] def complete(self, msg_id: int) -> bool: return bool(self._call("printer_complete_badge_job", {"p_token": self._token, "p_msg_id": msg_id}, 20)) def fail(self, msg_id: int, error: str, retryable: bool = False) -> str: result = self._call( "printer_fail_badge_job", {"p_token": self._token, "p_msg_id": msg_id, "p_error": error, "p_retryable": retryable}, 20, ) return str(result) def heartbeat(self, status: dict[str, Any]) -> dict[str, Any]: result = self._call("printer_heartbeat", {"p_token": self._token, "p_status": status}, 15) return result if isinstance(result, dict) else {}