diff --git a/src/hhstreamd/ipc.py b/src/hhstreamd/ipc.py new file mode 100644 index 0000000..45cae3d --- /dev/null +++ b/src/hhstreamd/ipc.py @@ -0,0 +1,589 @@ +"""Asking the compositor what it actually has, instead of guessing. + +The broker launches applications and then reports on them. Until now it had no +way to see the other side: every session's ``workspace`` and ``window`` were +``null`` because nothing in the daemon could talk to Hyprland. This module is +that voice. It is deliberately the *only* place that knows the compositor's +wire format, so a Hyprland upgrade is one file to re-read. + +Three decisions shape everything here. + +**Degrade, never guess.** Every failure — no instance directory, two instance +directories and no signature, a socket that is gone, a connection refused, a +reply that is not the JSON it claims to be — is :class:`CompositorUnavailable`. +Nothing returns an empty list, a ``None`` or a plausible-looking default to +stand in for "I could not ask", because a caller that cannot tell those apart +will write a guess into a session record and the operator will believe it. + +**Parse defensively, inside the defined shape.** Hyprland's JSON has gained, +renamed and re-typed keys across releases, so a missing key is a *defined* +value (``None``, ``0``, ``-1``) and never a ``KeyError`` reaching the caller. +The exception is a key whose absence makes the record meaningless — a client +with no ``address`` — which is a malformed reply, not a degraded one. + +**One connection per request, a held connection for events.** That is what +``hyprctl`` does and what Hyprland expects: it reads a request, writes the +reply and closes. The event socket is the opposite — a stream that must stay +open, blocking, for as long as the caller reads it. When it ends, it raises: +an event stream that stops is a failure the caller must see, because a broker +that quietly stops being told about closed windows looks identical to a broker +watching an idle desktop. +""" + +from __future__ import annotations + +import json +import os +import socket +import stat +from collections.abc import Iterator +from dataclasses import dataclass +from pathlib import Path + +#: Hyprland names its per-instance directory after this variable, and every +#: process it starts inherits it. It is the strongest hint available. +SIGNATURE_ENV = "HYPRLAND_INSTANCE_SIGNATURE" + +#: ``/hypr//`` holds both sockets (CONTRACT §5). +INSTANCE_SUBDIR = "hypr" +REQUEST_SOCKET_NAME = ".socket.sock" +EVENT_SOCKET_NAME = ".socket2.sock" + +#: Requests are local, synchronous and tiny. The compositor answers at once or +#: it is wedged; this only bounds the pathological case where it accepts the +#: connection and then stops. It is a class attribute so a test can shorten it +#: without widening ``__init__``, whose signature is frozen by the contract. +REQUEST_TIMEOUT_S = 2.0 + +#: Field names for the events a session broker joins on, in payload order. The +#: payload is positional and comma-separated, and the *last* named field keeps +#: any remaining commas — window titles contain them, which is precisely why a +#: naive ``split(",")`` loses the end of a title. +_EVENT_FIELDS: dict[str, tuple[str, ...]] = { + "openwindow": ("address", "workspace", "class", "title"), + "closewindow": ("address",), + "movewindow": ("address", "workspace"), + "movewindowv2": ("address", "workspace_id", "workspace"), + "windowtitle": ("address",), + "windowtitlev2": ("address", "title"), + "activewindow": ("class", "title"), + "activewindowv2": ("address",), + "changefloatingmode": ("address", "floating"), + "urgent": ("address",), + "pin": ("address", "pinned"), + "fullscreen": ("state",), + "workspace": ("name",), + "workspacev2": ("id", "name"), + "createworkspace": ("name",), + "createworkspacev2": ("id", "name"), + "destroyworkspace": ("name",), + "destroyworkspacev2": ("id", "name"), + "moveworkspace": ("name", "monitor"), + "moveworkspacev2": ("id", "name", "monitor"), + "renameworkspace": ("id", "name"), + "activespecial": ("name", "monitor"), + "focusedmon": ("monitor", "workspace"), + "monitoradded": ("name",), + "monitoraddedv2": ("id", "name", "description"), + "monitorremoved": ("name",), +} + + +class CompositorUnavailable(Exception): + """No request socket, or the compositor refused. Callers degrade, never guess.""" + + +@dataclass(frozen=True) +class Monitor: + name: str + x: int + y: int + width: int + height: int + scale: float + active_workspace_id: int | None + + +@dataclass(frozen=True) +class Workspace: + id: int + name: str + monitor: str | None + windows: int + is_special: bool + + +@dataclass(frozen=True) +class Client: + address: str + pid: int + workspace_id: int | None + monitor: str | None + class_: str + initial_class: str + title: str + stable_id: str + visible: bool + + +@dataclass(frozen=True) +class CursorPos: + x: int + y: int + + +@dataclass(frozen=True) +class Event: + name: str + data: dict + + +def _as_int(value: object, default: int) -> int: + """An int, or ``default`` for anything that is not plainly one. + + Hyprland has shipped ids as numbers and as numeric strings; ``bool`` is + excluded because ``True`` is not a workspace id. + """ + + if isinstance(value, bool): + return default + if isinstance(value, int): + return value + if isinstance(value, float): + return int(value) + if isinstance(value, str): + try: + return int(value.strip()) + except ValueError: + return default + return default + + +def _as_float(value: object, default: float) -> float: + if isinstance(value, bool): + return default + if isinstance(value, (int, float)): + return float(value) + if isinstance(value, str): + try: + return float(value.strip()) + except ValueError: + return default + return default + + +def _as_str(value: object) -> str: + """A string, or "" — never ``None`` leaking into a field typed ``str``.""" + + if isinstance(value, str): + return value + if value is None: + return "" + return str(value) + + +def _optional_name(value: object) -> str | None: + """A monitor name, or ``None`` when the reply did not carry one. + + ``clients -j`` reports ``monitor`` as a numeric *index* while + ``workspaces -j`` reports it as a *name*; both are coerced to text so the + field means "what the compositor said" and ``None`` keeps its single + meaning of "the compositor said nothing". + """ + + if value is None or value == "": + return None + if isinstance(value, bool): + return None + if isinstance(value, (int, float)): + return str(int(value)) + if isinstance(value, str): + return value + return None + + +def _nested_id(value: object) -> int | None: + """``{"id": 3, "name": "3"}`` -> ``3``; anything else -> ``None``.""" + + if isinstance(value, dict): + raw = value.get("id") + if isinstance(raw, bool): + return None + if isinstance(raw, int): + return raw + if isinstance(raw, (float, str)): + parsed = _as_int(raw, -(2**62)) + return None if parsed == -(2**62) else parsed + return None + + +def _entries(payload: object, what: str) -> list[dict]: + """The list of objects a ``-j`` listing must be, or a malformed reply.""" + + if not isinstance(payload, list): + raise CompositorUnavailable(f"{what}: expected a JSON list, got {type(payload).__name__}") + out = [] + for item in payload: + if not isinstance(item, dict): + raise CompositorUnavailable( + f"{what}: expected objects in the list, got {type(item).__name__}" + ) + out.append(item) + return out + + +def _monitor(raw: dict) -> Monitor: + name = raw.get("name") + if not isinstance(name, str) or not name: + raise CompositorUnavailable("monitors: an entry has no name") + return Monitor( + name=name, + x=_as_int(raw.get("x"), 0), + y=_as_int(raw.get("y"), 0), + width=_as_int(raw.get("width"), 0), + height=_as_int(raw.get("height"), 0), + scale=_as_float(raw.get("scale"), 1.0), + # Older replies nest the active workspace; a monitor with none (an + # output just created and not yet populated) legitimately has no id. + active_workspace_id=_nested_id(raw.get("activeWorkspace")), + ) + + +def _workspace(raw: dict) -> Workspace: + if "id" not in raw: + raise CompositorUnavailable("workspaces: an entry has no id") + ident = _as_int(raw.get("id"), -(2**62)) + if ident == -(2**62): + raise CompositorUnavailable(f"workspaces: entry id is not a number ({raw.get('id')!r})") + name = _as_str(raw.get("name")) + special = raw.get("special") + return Workspace( + id=ident, + name=name, + monitor=_optional_name(raw.get("monitor")), + windows=_as_int(raw.get("windows"), 0), + # Hyprland did not always report ``special``. Where it does not, the + # two things that have always been true of a special workspace are + # its negative id and its ``special:`` name prefix. + is_special=( + bool(special) + if isinstance(special, bool) + else (ident < 0 or name.startswith("special")) + ), + ) + + +def _client(raw: dict) -> Client: + address = raw.get("address") + if not isinstance(address, str) or not address: + raise CompositorUnavailable("clients: an entry has no address") + initial_class = _as_str(raw.get("initialClass")) + pid = _as_int(raw.get("pid"), -1) + mapped = raw.get("mapped") + hidden = raw.get("hidden") + return Client( + address=address, + # -1, not 0: no process has it, so an unknown pid cannot be mistaken + # for a real one by code that only checks for falsiness. + pid=pid, + workspace_id=_nested_id(raw.get("workspace")), + monitor=_optional_name(raw.get("monitor")), + class_=_as_str(raw.get("class")), + initial_class=initial_class, + title=_as_str(raw.get("title")), + # The contract names a stable id but Hyprland publishes none. The + # initial class plus the pid is the closest honest thing: the launcher + # sets the class per session, the pid is the session's process, and + # unlike ``address`` the pair survives a window being remapped. It + # falls back to the address rather than ever being empty. + stable_id=f"{initial_class}:{pid}" if initial_class and pid > 0 else address, + # "Visible" is mapped-and-not-hidden; a missing key must not make a + # live window look gone, so absence reads as mapped. + visible=(True if mapped is None else bool(mapped)) and not bool(hidden), + ) + + +def parse_event(line: str) -> Event: + """``"name>>a,b,c"`` -> :class:`Event`. + + The payload is positional, so :data:`_EVENT_FIELDS` names the fields for + the events the broker joins on and the last named field absorbs any + remaining commas (titles contain them). ``raw`` and ``args`` are always + present, so an event this module does not know is still usable rather than + discarded, and nothing is hidden behind the naming. + + A line with no ``>>`` is a malformed reply, not an event with an odd name: + :class:`CompositorUnavailable`. + """ + + text = line.rstrip("\r\n") + name, separator, payload = text.partition(">>") + if not separator or not name: + raise CompositorUnavailable(f"event line has no name>>payload separator: {text!r}") + + data: dict = {"raw": payload} + if payload == "": + # An empty payload carried nothing; naming fields here would invent + # values ("" is not a window address) for an event like + # ``configreloaded>>`` that has no arguments at all. + data["args"] = [] + return Event(name=name, data=data) + + fields = _EVENT_FIELDS.get(name) + if fields: + parts = payload.split(",", len(fields) - 1) + data["args"] = list(parts) + data.update(zip(fields, parts)) + else: + data["args"] = payload.split(",") + return Event(name=name, data=data) + + +class HyprlandIPC: + """A client for one compositor instance's request and event sockets.""" + + #: Overridable per instance; ``__init__``'s signature is frozen, so this is + #: how a caller (or a test) bounds a wedged compositor differently. + request_timeout_s: float = REQUEST_TIMEOUT_S + + def __init__(self, request_socket: Path, event_socket: Path | None = None) -> None: + self.request_socket = Path(request_socket) + self.event_socket = Path(event_socket) if event_socket is not None else None + self._event_sock: socket.socket | None = None + + @classmethod + def discover(cls, runtime_dir: Path, signature: str | None = None) -> "HyprlandIPC": + """Locate the instance under ``runtime_dir`` and return a client for it. + + The signature comes from the argument, else the environment, else the + *single* directory under ``/hypr/``. Two instances and no + signature raises: picking one would silently aim the broker's queries, + and later its pointer, at the wrong desktop. + """ + + hypr = Path(runtime_dir) / INSTANCE_SUBDIR + chosen = signature or os.environ.get(SIGNATURE_ENV) or None + if chosen is not None: + chosen = chosen.strip() or None + if chosen is not None and ("/" in chosen or chosen in (".", "..")): + raise CompositorUnavailable( + f"instance signature is not a directory name: {chosen!r}" + ) + if chosen is None: + chosen = cls._sole_instance(hypr) + + directory = hypr / chosen + request = directory / REQUEST_SOCKET_NAME + try: + mode = request.stat().st_mode + except OSError as exc: + raise CompositorUnavailable( + f"compositor request socket {request}: {exc.strerror or exc}" + ) from exc + if not stat.S_ISSOCK(mode): + raise CompositorUnavailable(f"compositor request socket {request} is not a socket") + return cls(request, directory / EVENT_SOCKET_NAME) + + @staticmethod + def _sole_instance(hypr: Path) -> str: + """The one directory under ``/hypr``, or a refusal.""" + + try: + with os.scandir(hypr) as entries: + names = sorted(e.name for e in entries if e.is_dir()) + except OSError as exc: + raise CompositorUnavailable( + f"compositor instance dir {hypr}: {exc.strerror or exc}; is the compositor running?" + ) from exc + if not names: + raise CompositorUnavailable( + f"compositor instance dir {hypr} holds no instance; is the compositor running?" + ) + if len(names) > 1: + raise CompositorUnavailable( + f"compositor instance dir {hypr} holds {len(names)} instances " + f"({', '.join(names)}); set {SIGNATURE_ENV} or pass a signature" + ) + return names[0] + + # -- the request socket ------------------------------------------------ + + def _wire(self, command: str) -> str: + """The bytes Hyprland expects for ``command``. + + Hyprland reads everything before the *first* ``/`` as output flags, so + a command is sent with a leading ``/`` — otherwise ``dispatch exec + /usr/bin/foo`` would be read as the flags ``dispatch exec `` followed + by a request of ``usr/bin/foo``. A command whose first word already + carries a prefix (``j/clients``) is passed through untouched, which is + what makes :meth:`query` able to reach anything this module does not + wrap. + """ + + text = command.strip() + if not text: + raise CompositorUnavailable("empty request") + first = text.split(None, 1)[0] + return text if "/" in first else "/" + text + + def _request(self, command: str) -> str: + """Send one request, read the whole reply, close. Raises on any failure.""" + + wire = self._wire(command) + sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + try: + sock.settimeout(self.request_timeout_s) + try: + sock.connect(str(self.request_socket)) + except OSError as exc: + raise CompositorUnavailable( + f"compositor request socket {self.request_socket}: {exc.strerror or exc}" + ) from exc + try: + sock.sendall(wire.encode()) + # Half-close: the reply ends at EOF, and a compositor that + # waits for more input would otherwise deadlock against a + # client waiting for more output. + sock.shutdown(socket.SHUT_WR) + chunks = [] + while True: + chunk = sock.recv(65536) + if not chunk: + break + chunks.append(chunk) + except socket.timeout as exc: + raise CompositorUnavailable( + f"compositor did not answer {command!r} within {self.request_timeout_s}s" + ) from exc + except OSError as exc: + raise CompositorUnavailable( + f"compositor connection lost during {command!r}: {exc.strerror or exc}" + ) from exc + finally: + sock.close() + # errors="replace" because a window title is arbitrary user data and a + # decoding accident must not masquerade as the compositor being down. + return b"".join(chunks).decode("utf-8", errors="replace") + + def _json(self, command: str, what: str) -> object: + text = self._request(command) + if not text.strip(): + raise CompositorUnavailable(f"{what}: empty reply") + try: + return json.loads(text) + except ValueError as exc: + # Hyprland answers an unknown or rejected request in plain text, so + # this is also where "that command does not exist here" lands. + raise CompositorUnavailable( + f"{what}: reply is not JSON ({exc}): {text[:120]!r}" + ) from exc + + def query(self, command: str) -> str: + """The raw request socket, for anything this module does not wrap.""" + + return self._request(command) + + def version(self) -> str: + """The compositor's own version banner, verbatim. + + Text, not ``version -j``: the banner is what every Hyprland has + answered, and parsing it into parts here would be this module guessing + at a shape that has changed. + """ + + text = self._request("version").strip() + if not text: + raise CompositorUnavailable("version: empty reply") + return text + + def monitors(self) -> list[Monitor]: + entries = _entries(self._json("j/monitors", "monitors"), "monitors") + return [_monitor(raw) for raw in entries] + + def workspaces(self) -> list[Workspace]: + entries = _entries(self._json("j/workspaces", "workspaces"), "workspaces") + return [_workspace(raw) for raw in entries] + + def clients(self) -> list[Client]: + return [_client(raw) for raw in _entries(self._json("j/clients", "clients"), "clients")] + + def cursorpos(self) -> CursorPos: + payload = self._json("j/cursorpos", "cursorpos") + if not isinstance(payload, dict) or "x" not in payload or "y" not in payload: + raise CompositorUnavailable( + f"cursorpos: expected an object with x and y, got {payload!r}" + ) + sentinel = -(2**62) + x = _as_int(payload.get("x"), sentinel) + y = _as_int(payload.get("y"), sentinel) + if x == sentinel or y == sentinel: + raise CompositorUnavailable(f"cursorpos: x and y are not numbers: {payload!r}") + return CursorPos(x=x, y=y) + + # -- the event socket -------------------------------------------------- + + def events(self) -> Iterator[Event]: + """Blocking iteration over the event stream. + + The connection is made here rather than on the first ``next()``, so a + missing event socket is reported to the caller that asked for the + stream instead of to whatever later happens to iterate it. The + iterator never ends quietly: EOF raises :class:`CompositorUnavailable`, + because a compositor that stopped talking and a desktop where nothing + happens must not look the same. + """ + + if self.event_socket is None: + raise CompositorUnavailable("no event socket was configured for this instance") + sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + try: + sock.settimeout(self.request_timeout_s) + sock.connect(str(self.event_socket)) + except OSError as exc: + sock.close() + raise CompositorUnavailable( + f"compositor event socket {self.event_socket}: {exc.strerror or exc}" + ) from exc + # Blocking from here on: an idle desktop sends nothing for hours and a + # read timeout would turn that into a false failure. + sock.settimeout(None) + self._close_event_sock() + self._event_sock = sock + return self._iter_events(sock) + + def _iter_events(self, sock: socket.socket) -> Iterator[Event]: + buffer = b"" + while True: + try: + chunk = sock.recv(65536) + except OSError as exc: + raise CompositorUnavailable( + f"compositor event socket {self.event_socket}: {exc.strerror or exc}" + ) from exc + if not chunk: + # A trailing fragment is a truncated event, never an event. + raise CompositorUnavailable( + f"compositor event stream ended ({self.event_socket})" + + (f"; {len(buffer)} bytes left unterminated" if buffer else "") + ) + buffer += chunk + while b"\n" in buffer: + line, buffer = buffer.split(b"\n", 1) + yield parse_event(line.decode("utf-8", errors="replace")) + + def _close_event_sock(self) -> None: + sock, self._event_sock = self._event_sock, None + if sock is None: + return + try: + # shutdown first: closing alone does not wake a thread already + # blocked in recv, and unblocking it is the point of close(). + sock.shutdown(socket.SHUT_RDWR) + except OSError: + pass + sock.close() + + def close(self) -> None: + """Drop the event stream. Idempotent; request sockets are per-call.""" + + self._close_event_sock() diff --git a/tests/ipc/conftest.py b/tests/ipc/conftest.py new file mode 100644 index 0000000..ca3c9ff --- /dev/null +++ b/tests/ipc/conftest.py @@ -0,0 +1,264 @@ +"""A real compositor-shaped socket, because the sockets are what break. + +Nothing here mocks :mod:`socket`. Each helper binds an actual ``AF_UNIX`` +listener in a temporary directory laid out the way Hyprland lays one out +(``/hypr//.socket.sock``) and answers canned bytes, so the +tests drive the client's real connect, half-close, read-to-EOF and timeout +paths. A mocked socket would pass while the thing that actually fails in +production — a path that is gone, a peer that closes early, a reply that is +plain text where JSON was promised — went untested. + +``AF_UNIX`` caps a path at 108 bytes, so the sockets live in a shallow +``mkdtemp`` rather than under ``tmp_path``, whose name encodes the test's. +""" + +from __future__ import annotations + +import shutil +import socket +import tempfile +import threading +from pathlib import Path + +import pytest + +#: Linux's sun_path is 108 bytes including the NUL. +SUN_PATH_MAX = 107 + +#: Returned by a handler that should keep the connection open and say nothing, +#: which is how a wedged compositor behaves and the only way to reach the +#: client's read timeout. +HANG = object() + +#: Shapes taken from Hyprland's own ``-j`` output. Trimmed to the keys the +#: client reads, plus a few it must ignore. +MONITORS_JSON = """ +[{"id": 0, "name": "HEADLESS-2", "description": "headless", "make": "", "model": "", + "x": 0, "y": 0, "width": 1280, "height": 720, "refreshRate": 60.0, "scale": 1.0, + "transform": 0, "focused": true, "activeWorkspace": {"id": 1000, "name": "1000"}, + "specialWorkspace": {"id": 0, "name": ""}, "dpmsStatus": true}, + {"id": 1, "name": "HEADLESS-3", "x": 1280, "y": 0, "width": 800, "height": 600, + "scale": 1.5, "focused": false}] +""" + +WORKSPACES_JSON = """ +[{"id": 1000, "name": "1000", "monitor": "HEADLESS-2", "monitorID": 0, "windows": 1, + "hasfullscreen": false, "lastwindow": "0x5d3d1c0", "lastwindowtitle": "foot"}, + {"id": -99, "name": "special:quarantine", "monitor": "HEADLESS-2", "windows": 0}] +""" + +CLIENTS_JSON = """ +[{"address": "0x5d3d1c0", "mapped": true, "hidden": false, "at": [0, 0], + "size": [1280, 720], "workspace": {"id": 1000, "name": "1000"}, "floating": false, + "monitor": 0, "class": "foot", "initialClass": "hh-foot-v7r4li", + "title": "hermes: ~, build, and notes", "initialTitle": "foot", "pid": 4242, + "xwayland": false, "pinned": false, "fullscreen": 0}, + {"address": "0x5d4aa10", "mapped": false, "hidden": true, "class": "chromium", + "initialClass": "", "title": "", "pid": 0, "monitor": null}] +""" + +CURSORPOS_JSON = '{"x": 640, "y": 360}' + +VERSION_TEXT = ( + "Hyprland 0.41.2 built from branch at commit 0000000 (). Date: 2026-01-01\n" + "Tag: v0.41.2, commits: 5000\n\nflags: (if any)\ndebug\n" +) + +#: What a well-behaved compositor answers, keyed by the bare command. +GOOD_REPLIES = { + "monitors": MONITORS_JSON, + "workspaces": WORKSPACES_JSON, + "clients": CLIENTS_JSON, + "cursorpos": CURSORPOS_JSON, + "version": VERSION_TEXT, +} + + +def check_path(path: Path) -> None: + if len(str(path).encode()) > SUN_PATH_MAX: + pytest.skip(f"socket path too long for AF_UNIX ({len(str(path))} bytes): {path}") + + +class RequestServer: + """One listening request socket, answering through a handler. + + The handler is called with ``(flags, command)`` split the way Hyprland + splits them — everything before the first ``/`` is flags — and returns the + reply, ``None`` to close without answering, or :data:`HANG`. + """ + + def __init__(self, path: Path, handler) -> None: + check_path(path) + self.path = path + self.handler = handler + self.requests: list[tuple[str, str]] = [] + self._stop = threading.Event() + self._sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + self._sock.bind(str(path)) + self._sock.listen(8) + self._sock.settimeout(0.05) + self._thread = threading.Thread(target=self._serve, daemon=True) + self._thread.start() + + def _serve(self) -> None: + while not self._stop.is_set(): + conn = self._accept() + if conn is None: + continue + try: + self._handle(conn) + finally: + conn.close() + + def _accept(self): + """``None`` on a poll timeout, so :meth:`stop` is not waited out. + + Closing a listening socket does not reliably wake a thread blocked in + ``accept``, which would make every test pay the join timeout. + """ + + try: + conn, _ = self._sock.accept() + except (TimeoutError, socket.timeout): + return None + except OSError: + self._stop.set() + return None + return conn + + def _handle(self, conn: socket.socket) -> None: + # The client half-closes after writing, so the request ends at EOF. + conn.settimeout(5.0) + received = b"" + while True: + try: + chunk = conn.recv(4096) + except OSError: + return + if not chunk: + break + received += chunk + text = received.decode("utf-8", errors="replace") + flags, separator, command = text.partition("/") + if not separator: + flags, command = "", text + self.requests.append((flags, command)) + reply = self.handler(flags, command) + if reply is HANG: + self._stop.wait(5.0) + return + if reply is None: + return + data = reply.encode() if isinstance(reply, str) else reply + try: + conn.sendall(data) + except OSError: + pass + + def stop(self) -> None: + self._stop.set() + self._sock.close() + self._thread.join(timeout=5.0) + + +class EventServer: + """One listening event socket that writes chunks, then closes or holds. + + Chunks are written as given — not line by line — so a test can split an + event across two writes and prove the client reassembles it. + """ + + def __init__(self, path: Path, chunks, close_after: bool = True) -> None: + check_path(path) + self.path = path + self.chunks = [c.encode() if isinstance(c, str) else c for c in chunks] + self.close_after = close_after + self.connections = 0 + self._stop = threading.Event() + self._sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + self._sock.bind(str(path)) + self._sock.listen(8) + self._sock.settimeout(0.05) + self._thread = threading.Thread(target=self._serve, daemon=True) + self._thread.start() + + def _serve(self) -> None: + while not self._stop.is_set(): + try: + conn, _ = self._sock.accept() + except (TimeoutError, socket.timeout): + continue + except OSError: + return + self.connections += 1 + try: + for chunk in self.chunks: + conn.sendall(chunk) + # Let the client see this write on its own, so a chunk + # boundary inside a line is a real boundary. + self._stop.wait(0.01) + if not self.close_after: + self._stop.wait(5.0) + except OSError: + pass + finally: + conn.close() + + def stop(self) -> None: + self._stop.set() + self._sock.close() + self._thread.join(timeout=5.0) + + +@pytest.fixture +def runtime_dir(): + """A shallow temporary directory standing in for ``/run/hypr-stream``.""" + + path = Path(tempfile.mkdtemp(prefix="hhipc")) + try: + yield path + finally: + shutil.rmtree(path, ignore_errors=True) + + +@pytest.fixture +def instance(runtime_dir): + """``/hypr/`` for one instance, created.""" + + directory = runtime_dir / "hypr" / "a1b2c3_1700000000" + directory.mkdir(parents=True) + return directory + + +@pytest.fixture +def servers(instance): + """Factory for request/event servers on one instance, stopped at teardown.""" + + started: list = [] + + def start(handler=None, event_chunks=None, close_after=True): + request = None + events = None + if handler is not None: + request = RequestServer(instance / ".socket.sock", handler) + started.append(request) + if event_chunks is not None: + events = EventServer(instance / ".socket2.sock", event_chunks, close_after) + started.append(events) + return request, events + + try: + yield start + finally: + for server in started: + server.stop() + + +@pytest.fixture +def good_handler(): + """Answers every wrapped command the way a live compositor does.""" + + def handler(flags, command): + return GOOD_REPLIES.get(command.strip(), "unknown request") + + return handler diff --git a/tests/ipc/test_discovery.py b/tests/ipc/test_discovery.py new file mode 100644 index 0000000..7be09b3 --- /dev/null +++ b/tests/ipc/test_discovery.py @@ -0,0 +1,131 @@ +"""Finding the instance, and refusing to pick one when there is a choice. + +Two instances and no signature is the dangerous case: a broker that guessed +would aim its queries — and later its pointer — at someone else's desktop. +""" + +from __future__ import annotations + +import socket + +import pytest + +from hhstreamd.ipc import SIGNATURE_ENV, CompositorUnavailable, HyprlandIPC + + +def bind(path): + """A bound, listening socket at ``path``, so discovery sees a real one.""" + + sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + sock.bind(str(path)) + sock.listen(1) + return sock + + +def test_single_instance_is_discovered(runtime_dir, instance, monkeypatch): + monkeypatch.delenv(SIGNATURE_ENV, raising=False) + sock = bind(instance / ".socket.sock") + try: + ipc = HyprlandIPC.discover(runtime_dir) + finally: + sock.close() + assert ipc.request_socket == instance / ".socket.sock" + assert ipc.event_socket == instance / ".socket2.sock" + + +def test_no_instance_directory_at_all(runtime_dir, monkeypatch): + monkeypatch.delenv(SIGNATURE_ENV, raising=False) + with pytest.raises(CompositorUnavailable) as caught: + HyprlandIPC.discover(runtime_dir) + assert str(runtime_dir / "hypr") in str(caught.value) + + +def test_zero_instances_under_hypr(runtime_dir, monkeypatch): + monkeypatch.delenv(SIGNATURE_ENV, raising=False) + (runtime_dir / "hypr").mkdir() + with pytest.raises(CompositorUnavailable, match="no instance"): + HyprlandIPC.discover(runtime_dir) + + +def test_two_instances_without_a_signature_refuses(runtime_dir, instance, monkeypatch): + monkeypatch.delenv(SIGNATURE_ENV, raising=False) + other = runtime_dir / "hypr" / "deadbee_1700000001" + other.mkdir() + bind(instance / ".socket.sock").close() + with pytest.raises(CompositorUnavailable) as caught: + HyprlandIPC.discover(runtime_dir) + message = str(caught.value) + assert "2 instances" in message + assert instance.name in message and other.name in message + assert SIGNATURE_ENV in message + + +def test_two_instances_with_an_explicit_signature(runtime_dir, instance, monkeypatch): + monkeypatch.delenv(SIGNATURE_ENV, raising=False) + other = runtime_dir / "hypr" / "deadbee_1700000001" + other.mkdir() + sock = bind(other / ".socket.sock") + try: + ipc = HyprlandIPC.discover(runtime_dir, signature=other.name) + finally: + sock.close() + assert ipc.request_socket == other / ".socket.sock" + + +def test_signature_from_the_environment(runtime_dir, instance, monkeypatch): + other = runtime_dir / "hypr" / "deadbee_1700000001" + other.mkdir() + monkeypatch.setenv(SIGNATURE_ENV, other.name) + sock = bind(other / ".socket.sock") + try: + ipc = HyprlandIPC.discover(runtime_dir) + finally: + sock.close() + assert ipc.request_socket == other / ".socket.sock" + + +def test_explicit_signature_beats_the_environment(runtime_dir, instance, monkeypatch): + monkeypatch.setenv(SIGNATURE_ENV, "not_this_one") + sock = bind(instance / ".socket.sock") + try: + ipc = HyprlandIPC.discover(runtime_dir, signature=instance.name) + finally: + sock.close() + assert ipc.request_socket == instance / ".socket.sock" + + +def test_signature_naming_a_missing_instance(runtime_dir, instance, monkeypatch): + monkeypatch.setenv(SIGNATURE_ENV, "gone_1700000002") + with pytest.raises(CompositorUnavailable, match="request socket"): + HyprlandIPC.discover(runtime_dir) + + +def test_instance_without_a_request_socket(runtime_dir, instance, monkeypatch): + monkeypatch.delenv(SIGNATURE_ENV, raising=False) + with pytest.raises(CompositorUnavailable) as caught: + HyprlandIPC.discover(runtime_dir) + assert ".socket.sock" in str(caught.value) + + +def test_a_regular_file_is_not_a_socket(runtime_dir, instance, monkeypatch): + monkeypatch.delenv(SIGNATURE_ENV, raising=False) + (instance / ".socket.sock").write_text("not a socket") + with pytest.raises(CompositorUnavailable, match="is not a socket"): + HyprlandIPC.discover(runtime_dir) + + +def test_a_signature_cannot_be_a_path(runtime_dir, instance): + with pytest.raises(CompositorUnavailable, match="not a directory name"): + HyprlandIPC.discover(runtime_dir, signature="../../elsewhere") + + +def test_an_empty_environment_signature_falls_through(runtime_dir, instance, monkeypatch): + """An exported-but-empty variable is no signature, not a signature of "".""" + + monkeypatch.setenv(SIGNATURE_ENV, "") + sock = bind(instance / ".socket.sock") + try: + ipc = HyprlandIPC.discover(runtime_dir) + finally: + sock.close() + assert ipc.request_socket == instance / ".socket.sock" diff --git a/tests/ipc/test_events.py b/tests/ipc/test_events.py new file mode 100644 index 0000000..b35f22a --- /dev/null +++ b/tests/ipc/test_events.py @@ -0,0 +1,197 @@ +"""Event parsing, and a stream that must fail loudly when it stops. + +The payload cases here are the ones that bite: a title full of commas (the +whole reason the last field absorbs the rest of the line), an event with no +payload at all, an event this module has never heard of, and a line delivered +in two pieces by the kernel. +""" + +from __future__ import annotations + +import threading +import time + +import pytest + +from hhstreamd.ipc import CompositorUnavailable, HyprlandIPC, parse_event + + +def test_openwindow_names_its_fields(): + event = parse_event("openwindow>>0x5d3d1c0,1000,foot,hermes: ~") + assert event.name == "openwindow" + assert event.data["address"] == "0x5d3d1c0" + assert event.data["workspace"] == "1000" + assert event.data["class"] == "foot" + assert event.data["title"] == "hermes: ~" + assert event.data["args"] == ["0x5d3d1c0", "1000", "foot", "hermes: ~"] + assert event.data["raw"] == "0x5d3d1c0,1000,foot,hermes: ~" + + +def test_a_title_keeps_its_commas(): + """A naive split(",") loses the end of the title; this is that regression.""" + + event = parse_event("openwindow>>0x1,1000,foot,hermes: ~, build, and notes") + assert event.data["title"] == "hermes: ~, build, and notes" + assert len(event.data["args"]) == 4 + + +def test_windowtitle_v2_absorbs_commas_too(): + event = parse_event("windowtitlev2>>0x1,a,b,c") + assert event.data == { + "raw": "0x1,a,b,c", + "args": ["0x1", "a,b,c"], + "address": "0x1", + "title": "a,b,c", + } + + +def test_an_empty_payload_names_nothing(): + """``configreloaded>>`` carried no values; "" is not a value.""" + + event = parse_event("configreloaded>>") + assert event.name == "configreloaded" + assert event.data == {"raw": "", "args": []} + + +def test_a_single_field_event(): + event = parse_event("monitorremoved>>HEADLESS-3") + assert event.data["name"] == "HEADLESS-3" + assert event.data["args"] == ["HEADLESS-3"] + + +def test_a_short_payload_names_only_what_arrived(): + """An older Hyprland sending fewer fields must not invent the rest.""" + + event = parse_event("openwindow>>0x1,1000") + assert event.data["address"] == "0x1" + assert event.data["workspace"] == "1000" + assert "class" not in event.data + assert "title" not in event.data + + +def test_an_unknown_event_is_still_usable(): + event = parse_event("somethingnew>>a,b,c") + assert event.name == "somethingnew" + assert event.data == {"raw": "a,b,c", "args": ["a", "b", "c"]} + + +def test_trailing_newline_is_not_part_of_the_payload(): + assert parse_event("workspace>>1000\n").data["name"] == "1000" + assert parse_event("workspace>>1000\r\n").data["name"] == "1000" + + +@pytest.mark.parametrize("line", ["workspace", "", " ", ">>1000", "workspace>1000"]) +def test_a_line_with_no_separator_is_malformed(line): + with pytest.raises(CompositorUnavailable, match="name>>payload"): + parse_event(line) + + +@pytest.fixture +def ipc(instance): + client = HyprlandIPC(instance / ".socket.sock", instance / ".socket2.sock") + yield client + client.close() + + +def test_the_stream_yields_events_then_raises_at_eof(servers, ipc): + chunks = [ + "openwindow>>0x1,1000,foot,hermes: ~, build\n", + # One line split across two writes: the client must reassemble it + # rather than parse half of it. + "closewin", + "dow>>0x1\nworkspacev2>>1000,1000\n", + ] + servers(event_chunks=chunks) + + stream = ipc.events() + first = next(stream) + assert first.name == "openwindow" + assert first.data["title"] == "hermes: ~, build" + assert next(stream).name == "closewindow" + third = next(stream) + assert (third.data["id"], third.data["name"]) == ("1000", "1000") + + # The compositor closed. An iterator that merely stopped would be + # indistinguishable from an idle desktop. + with pytest.raises(CompositorUnavailable, match="event stream ended"): + next(stream) + + +def test_an_unterminated_tail_is_reported(servers, ipc): + servers(event_chunks=["openwindow>>0x1,1000,foot,t\nhalf-an-ev"]) + stream = ipc.events() + assert next(stream).name == "openwindow" + with pytest.raises(CompositorUnavailable, match="unterminated"): + next(stream) + + +def test_a_malformed_line_in_the_stream(servers, ipc): + servers(event_chunks=["this is not an event\n"]) + stream = ipc.events() + with pytest.raises(CompositorUnavailable, match="name>>payload"): + next(stream) + + +def test_a_missing_event_socket(instance, ipc): + with pytest.raises(CompositorUnavailable) as caught: + ipc.events() + assert ".socket2.sock" in str(caught.value) + + +def test_no_event_socket_configured(instance): + ipc = HyprlandIPC(instance / ".socket.sock") + with pytest.raises(CompositorUnavailable, match="no event socket"): + ipc.events() + + +def test_the_connection_is_made_by_events_not_by_the_first_next(servers, ipc): + """So the caller that asked for the stream is the one told it failed.""" + + _, events = servers(event_chunks=["workspace>>1000\n"], close_after=False) + stream = ipc.events() + # ``connect`` returns as soon as the listen backlog takes it, so the + # server's own accept lags by a scheduling quantum; the claim is that the + # connection exists before anything iterates, not that it is instantaneous. + deadline = time.monotonic() + 5.0 + while events.connections == 0 and time.monotonic() < deadline: + time.sleep(0.01) + assert events.connections == 1 + assert next(stream).name == "workspace" + + +def test_close_unblocks_a_waiting_reader(servers, ipc): + """A blocked reader must end when the broker shuts the client down. + + ``close()`` shuts the socket down rather than only closing it, because a + bare close does not wake a thread already sitting in ``recv``. + """ + + servers(event_chunks=["workspace>>1000\n"], close_after=False) + stream = ipc.events() + assert next(stream).name == "workspace" + + outcome = [] + + def read_until_it_fails(): + try: + next(stream) + except BaseException as exc: # noqa: BLE001 - recorded, then asserted + outcome.append(exc) + + reader = threading.Thread(target=read_until_it_fails, daemon=True) + reader.start() + # The reader is blocked in recv on an open, silent socket. + reader.join(timeout=0.2) + assert reader.is_alive() + + ipc.close() + reader.join(timeout=5.0) + assert not reader.is_alive() + assert isinstance(outcome[0], CompositorUnavailable) + + +def test_close_is_idempotent(servers, ipc): + servers(event_chunks=["workspace>>1000\n"], close_after=False) + ipc.events() + ipc.close() + ipc.close() diff --git a/tests/ipc/test_requests.py b/tests/ipc/test_requests.py new file mode 100644 index 0000000..3354631 --- /dev/null +++ b/tests/ipc/test_requests.py @@ -0,0 +1,240 @@ +"""The request socket, against a real listener. + +Every test here connects over ``AF_UNIX`` to a socket the fixture bound, so the +failures that matter — a path that is gone, a peer that refuses, a peer that +closes mid-reply, a peer that never answers — are produced rather than +simulated. +""" + +from __future__ import annotations + +import socket + +import pytest + +from hhstreamd.ipc import CompositorUnavailable, CursorPos, HyprlandIPC + +from conftest import HANG + + +@pytest.fixture +def ipc(instance): + client = HyprlandIPC(instance / ".socket.sock", instance / ".socket2.sock") + yield client + client.close() + + +def test_version_is_the_banner_verbatim(servers, good_handler, ipc): + request, _ = servers(good_handler) + assert ipc.version().startswith("Hyprland 0.41.2 built from branch") + assert "Tag: v0.41.2" in ipc.version() + # Text, not JSON, and the command carries a leading "/" so an argument + # containing a slash could never be read as output flags. + assert request.requests[0] == ("", "version") + + +def test_monitors(servers, good_handler, ipc): + request, _ = servers(good_handler) + monitors = ipc.monitors() + assert [m.name for m in monitors] == ["HEADLESS-2", "HEADLESS-3"] + first = monitors[0] + assert (first.x, first.y, first.width, first.height) == (0, 0, 1280, 720) + assert first.scale == 1.0 + assert first.active_workspace_id == 1000 + # The second monitor carries no activeWorkspace at all: a defined None. + assert monitors[1].active_workspace_id is None + assert monitors[1].scale == 1.5 + assert request.requests == [("j", "monitors")] + + +def test_workspaces(servers, good_handler, ipc): + servers(good_handler) + workspaces = ipc.workspaces() + assert [w.id for w in workspaces] == [1000, -99] + assert workspaces[0].monitor == "HEADLESS-2" + assert workspaces[0].windows == 1 + assert workspaces[0].is_special is False + # No "special" key in this reply: the negative id and the name prefix are + # what every Hyprland has agreed on. + assert workspaces[1].is_special is True + + +def test_clients(servers, good_handler, ipc): + request, _ = servers(good_handler) + clients = ipc.clients() + assert len(clients) == 2 + foot, chromium = clients + assert foot.address == "0x5d3d1c0" + assert foot.pid == 4242 + assert foot.workspace_id == 1000 + assert foot.class_ == "foot" + assert foot.initial_class == "hh-foot-v7r4li" + # A title with commas in it survives whole; the broker shows this to a user. + assert foot.title == "hermes: ~, build, and notes" + assert foot.stable_id == "hh-foot-v7r4li:4242" + assert foot.visible is True + # clients -j reports the monitor as an index, not a name; the field is text + # so that None keeps its one meaning of "the reply said nothing". + assert foot.monitor == "0" + + assert chromium.visible is False + assert chromium.monitor is None + assert chromium.workspace_id is None + assert chromium.stable_id == "0x5d4aa10" + assert request.requests == [("j", "clients")] + + +def test_cursorpos(servers, good_handler, ipc): + servers(good_handler) + assert ipc.cursorpos() == CursorPos(x=640, y=360) + + +def test_query_passes_a_command_through_untouched(servers, ipc): + seen = [] + + def handler(flags, command): + seen.append((flags, command)) + return "ok" + + servers(handler) + assert ipc.query("dispatch exec /usr/bin/true") == "ok" + # The slash in the argument must not be read as a flag separator. + assert seen == [("", "dispatch exec /usr/bin/true")] + + +def test_query_keeps_an_explicit_flag_prefix(servers, ipc): + seen = [] + + def handler(flags, command): + seen.append((flags, command)) + return "[]" + + servers(handler) + assert ipc.query("j/devices") == "[]" + assert seen == [("j", "devices")] + + +def test_an_empty_request_is_refused_before_connecting(ipc): + with pytest.raises(CompositorUnavailable, match="empty request"): + ipc.query(" ") + + +@pytest.mark.parametrize("method", ["monitors", "workspaces", "clients", "cursorpos"]) +def test_plain_text_where_json_was_promised(servers, ipc, method): + """What Hyprland answers for a command it does not know.""" + + servers(lambda flags, command: "unknown request") + with pytest.raises(CompositorUnavailable, match="not JSON"): + getattr(ipc, method)() + + +def test_a_json_object_where_a_list_belongs(servers, ipc): + servers(lambda flags, command: '{"monitors": []}') + with pytest.raises(CompositorUnavailable, match="expected a JSON list"): + ipc.monitors() + + +def test_a_list_of_scalars(servers, ipc): + servers(lambda flags, command: '["HEADLESS-2"]') + with pytest.raises(CompositorUnavailable, match="expected objects"): + ipc.monitors() + + +def test_a_client_without_an_address_is_malformed(servers, ipc): + """The one key whose absence makes the record meaningless.""" + + servers(lambda flags, command: '[{"class": "foot", "pid": 1}]') + with pytest.raises(CompositorUnavailable, match="no address"): + ipc.clients() + + +def test_a_monitor_without_a_name_is_malformed(servers, ipc): + servers(lambda flags, command: '[{"width": 1280}]') + with pytest.raises(CompositorUnavailable, match="no name"): + ipc.monitors() + + +def test_a_workspace_without_an_id_is_malformed(servers, ipc): + servers(lambda flags, command: '[{"name": "1000"}]') + with pytest.raises(CompositorUnavailable, match="no id"): + ipc.workspaces() + + +def test_missing_keys_degrade_rather_than_raise_keyerror(servers, ipc): + """A reply from a Hyprland that reports less than this one expects.""" + + servers(lambda flags, command: '[{"address": "0x1"}]') + (client,) = ipc.clients() + assert client.pid == -1 + assert client.workspace_id is None + assert client.monitor is None + assert (client.class_, client.initial_class, client.title) == ("", "", "") + assert client.stable_id == "0x1" + # Nothing said it was unmapped, so it is not reported as gone. + assert client.visible is True + + +def test_cursorpos_without_coordinates(servers, ipc): + servers(lambda flags, command: '{"ok": true}') + with pytest.raises(CompositorUnavailable, match="x and y"): + ipc.cursorpos() + + +def test_cursorpos_with_non_numeric_coordinates(servers, ipc): + servers(lambda flags, command: '{"x": "left", "y": null}') + with pytest.raises(CompositorUnavailable, match="not numbers"): + ipc.cursorpos() + + +def test_connection_closed_mid_reply(servers, ipc): + """The compositor dies while writing: a truncated reply, never a guess.""" + + servers(lambda flags, command: '[{"address": "0x5d3d1c0", "pid": 4242, "cla') + with pytest.raises(CompositorUnavailable, match="not JSON"): + ipc.clients() + + +def test_connection_closed_with_no_reply_at_all(servers, ipc): + servers(lambda flags, command: None) + with pytest.raises(CompositorUnavailable, match="empty reply"): + ipc.workspaces() + with pytest.raises(CompositorUnavailable, match="empty reply"): + ipc.version() + + +def test_missing_socket(instance): + ipc = HyprlandIPC(instance / ".socket.sock") + with pytest.raises(CompositorUnavailable) as caught: + ipc.clients() + assert str(instance / ".socket.sock") in str(caught.value) + + +def test_nothing_listening(instance, ipc): + """A socket left behind by a compositor that is gone: ECONNREFUSED.""" + + stale = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + stale.bind(str(instance / ".socket.sock")) + try: + with pytest.raises(CompositorUnavailable, match="request socket"): + ipc.monitors() + finally: + stale.close() + + +def test_a_compositor_that_never_answers(servers, ipc): + """Accepted, then silence: the read timeout, exercised for real.""" + + servers(lambda flags, command: HANG) + ipc.request_timeout_s = 0.3 + with pytest.raises(CompositorUnavailable, match="did not answer"): + ipc.clients() + + +def test_each_request_is_its_own_connection(servers, good_handler, ipc): + """What hyprctl does, and what the compositor expects: no session state.""" + + request, _ = servers(good_handler) + ipc.monitors() + ipc.clients() + ipc.clients() + assert request.requests == [("j", "monitors"), ("j", "clients"), ("j", "clients")]