"""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 collections 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 #: The verb needs the pointer lease and this session does not hold it. #: Distinct from BUSY, which is "someone else holds it": an agent that #: sees 9 must acquire, one that sees 8 must wait. NO_LEASE = 9 #: An IPC or output operation failed. **The session is not lost** — it #: keeps running in degraded mode — so this must never be confused with a #: session failure, which is what a shared code would do. COMPOSITOR = 10 #: 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, # The workspace band is full. A policy refusal and not a compositor # failure: the compositor is fine, the broker is at its budget. "container_budget": ExitCode.POLICY, "refused": ExitCode.POLICY, # 7 — timed out "timeout": ExitCode.TIMEOUT, "readiness_timeout": ExitCode.TIMEOUT, # 8 — busy "busy": ExitCode.BUSY, "already_managed": ExitCode.BUSY, "pointer_busy": ExitCode.BUSY, # 9 — the lease is required and not held "no_lease": ExitCode.NO_LEASE, # 10 — the compositor side failed; the session itself is fine "compositor": ExitCode.COMPOSITOR, "compositor_unavailable": ExitCode.COMPOSITOR, "no_container": ExitCode.COMPOSITOR, "driver_unavailable": ExitCode.COMPOSITOR, "driver_refused": ExitCode.COMPOSITOR, } 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) # -------------------------------------------------------------------------- # Verbs and `request_id` idempotency (PLAN §8) # -------------------------------------------------------------------------- #: Every verb the daemon answers. The container and pointer verbs are dotted #: and the original eight are not, because the original eight are frozen #: (CONTRACT-sessions.md §4: "existing verbs are unchanged") and renaming them #: would break every agent for a cosmetic gain. VERBS = ( "ping", "start", "list", "status", "touch", "kill", "gc", "adopt", "logs", "container.list", "container.reconcile", "pointer.acquire", "pointer.move", "pointer.button", "pointer.click", "pointer.scroll", "pointer.release", "pointer.state", ) #: Verbs whose reply is remembered by ``request_id``, so a caller that died #: before reading the reply can retry without the mutation happening twice. #: #: The read verbs are absent deliberately: they are idempotent already, so a #: retry costs nothing, and a cached ``list`` would be a stale one. Every #: ``pointer.*`` verb that moves something is here, because a retried click is #: a second click — the one failure an agent cannot undo. MUTATING_VERBS = frozenset( { "start", "touch", "kill", "adopt", "gc", "container.reconcile", "pointer.acquire", "pointer.move", "pointer.button", "pointer.click", "pointer.scroll", "pointer.release", } ) #: How many completed replies are kept. Bounded because a client chooses the #: ids: an unbounded cache is memory a peer controls. DEDUP_ENTRIES = 64 class IdempotencyCache: """The last N mutating replies, by ``request_id``. A retry returns *the recorded answer*, including a recorded failure: an agent that retries a ``start`` which was refused by policy must see the refusal again, not a second attempt that might succeed and leave it with an application it has no id for. Replies are returned with ``deduplicated: true`` so the caller can tell a replay from a fresh answer rather than having to infer it. """ def __init__(self, capacity: int = DEDUP_ENTRIES) -> None: self.capacity = capacity self._entries: collections.OrderedDict[str, dict[str, Any]] = collections.OrderedDict() def lookup(self, op: str, request_id: Any) -> dict[str, Any] | None: """The recorded reply for this id, or ``None`` to go ahead and do it.""" if not isinstance(request_id, str) or op not in MUTATING_VERBS: return None recorded = self._entries.get(request_id) if recorded is None: return None return {**recorded, "deduplicated": True} def remember(self, op: str, request_id: Any, response: dict[str, Any]) -> None: if not isinstance(request_id, str) or op not in MUTATING_VERBS: return self._entries[request_id] = dict(response) self._entries.move_to_end(request_id) while len(self._entries) > self.capacity: self._entries.popitem(last=False) def __len__(self) -> int: return len(self._entries) # -------------------------------------------------------------------------- # 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