"""The private socket: one connection at a time, newline-delimited JSON. Deliberately sequential. There is one cursor, so concurrency here would buy nothing but a way to interleave two warps; the broker is the only client and it holds the lease that makes its calls ordered already. A second connection simply waits in the listen backlog. Framing matches the broker's own control socket (``hhstreamd/protocol.py``): a line per message, a bounded line length so a confused peer cannot grow our read buffer, and a reply for every request including the rejected ones. """ from __future__ import annotations import json import logging import os import socket from pathlib import Path from typing import Any, Callable log = logging.getLogger("hhstream_pointer.server") #: Matches ``hhstreamd.protocol.MAX_LINE_BYTES``. Pointer requests are tiny; #: this is a ceiling, not a budget. MAX_LINE_BYTES = 1 << 20 LISTEN_BACKLOG = 8 class PointerServer: def __init__( self, socket_path: Path | str, handle: Callable[[Any], dict[str, Any]], *, socket_mode: int = 0o660, ) -> None: self.socket_path = Path(socket_path) self.handle = handle self.socket_mode = socket_mode self._sock: socket.socket | None = None def listen(self) -> None: """Bind and listen. A stale socket file is replaced, not refused: a crashed driver leaves one behind and the unit must still start.""" self.socket_path.parent.mkdir(parents=True, exist_ok=True) if self.socket_path.is_socket(): self.socket_path.unlink() sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) sock.bind(str(self.socket_path)) os.chmod(self.socket_path, self.socket_mode) sock.listen(LISTEN_BACKLOG) self._sock = sock log.info("listening on %s", self.socket_path) def serve_forever(self) -> None: assert self._sock is not None, "listen() first" while True: conn, _ = self._sock.accept() with conn: self._serve_connection(conn) def close(self) -> None: if self._sock is not None: self._sock.close() self._sock = None self.socket_path.unlink(missing_ok=True) def _serve_connection(self, conn: socket.socket) -> None: with conn.makefile("rwb") as stream: while True: line = stream.readline(MAX_LINE_BYTES + 1) if not line: return if len(line) > MAX_LINE_BYTES: _write(stream, {"ok": False, "error": "request line too long"}) return try: request = json.loads(line) except json.JSONDecodeError as exc: _write(stream, {"ok": False, "error": f"malformed JSON: {exc}"}) continue _write(stream, self.handle(request)) def _write(stream, response: dict[str, Any]) -> None: stream.write(json.dumps(response, separators=(",", ":")).encode() + b"\n") stream.flush()