"""Wire format and the exit-code table (DESIGN.md §1.6, §3.4). Newline-delimited JSON over a unix ``SOCK_STREAM`` socket: one request object, one response object, connection closed. This module is shared by the daemon and by the CLI handlers, so the framing and the exit-code mapping exist exactly once. It imports nothing outside the standard library and nothing from the rest of ``hhstreamd``. """ from __future__ import annotations import enum import json from typing import Any PROTOCOL_VERSION = 1 #: A single request or response line may not exceed this many bytes, including #: the terminating newline. A peer that sends more is answered with #: ``message_too_large`` and disconnected rather than being allowed to grow the #: daemon's read buffer without bound. MAX_LINE_BYTES = 1 << 20 # 1 MiB class ProtocolError(Exception): """A frame could not be read or decoded. ``error`` is the machine-readable name reported to the peer. """ def __init__(self, error: str, reason: str) -> None: super().__init__(reason) self.error = error self.reason = reason # -------------------------------------------------------------------------- # Exit codes (DESIGN.md §1.6). Frozen: agents branch on these. # -------------------------------------------------------------------------- class ExitCode(enum.IntEnum): OK = 0 USAGE = 2 NO_SUCH_SESSION = 3 BAD_STATE = 4 DAEMON_UNREACHABLE = 5 POLICY = 6 TIMEOUT = 7 BUSY = 8 #: Machine-readable error names, grouped by the exit code they map to. Every #: ``{"ok": false, "error": ...}`` the daemon can emit appears here; anything #: unknown falls back to :data:`ExitCode.BAD_STATE` (see :func:`exit_code_for`). EXIT_CODE_FOR_ERROR: dict[str, ExitCode] = { # 2 — usage "bad_request": ExitCode.USAGE, "unknown_op": ExitCode.USAGE, "unsupported_version": ExitCode.USAGE, "message_too_large": ExitCode.USAGE, "invalid_argument": ExitCode.USAGE, # 3 — no such session "no_such_session": ExitCode.NO_SUCH_SESSION, "no_such_process": ExitCode.NO_SUCH_SESSION, # 4 — not in a usable state "session_exited": ExitCode.BAD_STATE, "session_killed": ExitCode.BAD_STATE, "session_reaped": ExitCode.BAD_STATE, "session_starting": ExitCode.BAD_STATE, "compositor_lost": ExitCode.BAD_STATE, "bad_state": ExitCode.BAD_STATE, "pid_reuse_detected": ExitCode.BAD_STATE, # The session's identity could not be established either way, so the # daemon refused rather than signalling blind (BUG-02 item 5). "identity_unknown": ExitCode.BAD_STATE, # 5 — daemon unreachable (produced by the client, never by the daemon) "daemon_unreachable": ExitCode.DAEMON_UNREACHABLE, # 6 — refused by policy "not_allowlisted": ExitCode.POLICY, "argument_refused": ExitCode.POLICY, "session_cap_reached": ExitCode.POLICY, "refused": ExitCode.POLICY, # 7 — timed out "timeout": ExitCode.TIMEOUT, "readiness_timeout": ExitCode.TIMEOUT, # 8 — busy "busy": ExitCode.BUSY, "already_managed": ExitCode.BUSY, } def exit_code_for(error: str | None) -> ExitCode: """Map a machine-readable error name to its frozen exit code. An unrecognised name maps to :data:`ExitCode.BAD_STATE`: a caller that does not know what went wrong should still be told the session is not usable, which is strictly safer than reporting success. """ if not error: return ExitCode.OK return EXIT_CODE_FOR_ERROR.get(error, ExitCode.BAD_STATE) # -------------------------------------------------------------------------- # Message construction # -------------------------------------------------------------------------- def request(op: str, **fields: Any) -> dict[str, Any]: """Build a request object with the protocol version attached.""" msg: dict[str, Any] = {"v": PROTOCOL_VERSION, "op": op} msg.update({k: v for k, v in fields.items() if v is not None}) return msg def ok(**fields: Any) -> dict[str, Any]: return {"ok": True, **fields} def error(err: str, reason: str, *, hint: str | None = None, **fields: Any) -> dict[str, Any]: """Build an error reply. ``error`` is the machine field agents branch on, ``reason`` the human one (DESIGN.md §1.6). """ msg: dict[str, Any] = {"ok": False, "error": err, "reason": reason} if hint is not None: msg["hint"] = hint msg.update(fields) return msg # -------------------------------------------------------------------------- # Framing # -------------------------------------------------------------------------- def encode(message: dict[str, Any]) -> bytes: """Serialise one message to a single newline-terminated line. ``ensure_ascii`` keeps the line free of raw newlines inside strings by construction, so the framing cannot be broken by a session id, an argv element or an error message. """ line = json.dumps(message, ensure_ascii=True, separators=(",", ":")).encode("ascii") if len(line) + 1 > MAX_LINE_BYTES: raise ProtocolError("message_too_large", f"message is {len(line)} bytes") return line + b"\n" def decode(line: bytes) -> dict[str, Any]: """Parse one frame (with or without its trailing newline) into a dict.""" if len(line) > MAX_LINE_BYTES: raise ProtocolError("message_too_large", f"frame is {len(line)} bytes") text = line.rstrip(b"\n") if not text.strip(): raise ProtocolError("bad_request", "empty frame") try: obj = json.loads(text) except (UnicodeDecodeError, json.JSONDecodeError) as exc: raise ProtocolError("bad_request", f"malformed JSON: {exc}") from exc if not isinstance(obj, dict): raise ProtocolError("bad_request", f"expected a JSON object, got {type(obj).__name__}") return obj def decode_request(line: bytes) -> dict[str, Any]: """Parse and validate a request frame: an object with a known ``v`` and ``op``.""" obj = decode(line) version = obj.get("v", PROTOCOL_VERSION) if version != PROTOCOL_VERSION: raise ProtocolError( "unsupported_version", f"protocol version {version!r} is not supported (daemon speaks {PROTOCOL_VERSION})", ) op = obj.get("op") if not isinstance(op, str) or not op: raise ProtocolError("bad_request", "request has no 'op' field") return obj