"""The impure half of containers: running the plans and reading the result back. :mod:`hhstreamd.containers` decides *what* a container is — argv lists, a workspace slot, an output name — and deliberately cannot run any of it. This module is the other side of that line: it owns the compositor connection, turns a :class:`~hhstreamd.containers.ContainerPlan` into real outputs and rules, and then asks the compositor what actually happened. Keeping the two apart is what lets every placement decision be unit-tested without a compositor, and confines everything that *needs* one to a single file. Three decisions worth finding here. **Commands go over the request socket, not through ``hyprctl``.** The plans are ``["hyprctl", "keyword", ...]`` argv lists, and running them literally would mean a subprocess per command, ``hyprctl`` on the broker's ``PATH``, and ``HYPRLAND_INSTANCE_SIGNATURE``/``XDG_RUNTIME_DIR`` set correctly in its environment — three ways to fail that have nothing to do with the compositor. ``hyprctl`` itself does exactly one thing with those arguments: it joins them with spaces and writes them to ``/hypr//.socket.sock``, which is the socket this broker already holds open for queries. So :meth:`dispatch` sends the argv's *content* down the socket ``hyprctl`` would have used. The plan is still the authority on what runs and in what order; only the transport is ours. **Read back, never assume.** Every mutation is followed by a query (PLAN §4.2). ``create`` returns what the compositor says the window's workspace and output are, not what the rule asked for — a rule that did not bind is the failure mode this exists to catch, and a record that repeated our intention back to us would hide it. **Degrade, never guess.** No compositor means :meth:`available` is false and every lifecycle verb carries on without one: a container of ``state: "degraded"``, with every field it could not verify left ``None``. Nothing here ever invents an output name, a workspace number or a window. """ from __future__ import annotations import logging from dataclasses import dataclass from pathlib import Path from typing import Any from . import containers from .ipc import Client, CompositorUnavailable, HyprlandIPC log = logging.getLogger("hhstreamd.container_host") #: Where a window that matched no container lands (PLAN §5.2). A special #: workspace, so it is hidden rather than shown on whatever output is in front. DEFAULT_QUARANTINE_WORKSPACE = "special:quarantine" #: The container's size (CONTRACT-sessions.md §5). DEFAULT_MODE = (1280, 720) #: Hyprland answers a successful ``keyword``/``output`` with this, and anything #: else with prose. Matched case-insensitively and with whitespace stripped. OK_REPLY = "ok" @dataclass(frozen=True) class ContainerFacts: """What the compositor says about a session's window, after the fact. Every field is ``None`` when the compositor did not say: there is no window yet, or no workspace carries a monitor name. ``output`` is the monitor the *window* is on, which is not necessarily the output we created — and when the two differ, the rule did not bind and the caller must say so. """ workspace: int | None output: str | None window: dict[str, Any] | None foreground: bool | None class ContainerHost: """One compositor instance, and the containers this broker owns in it.""" def __init__( self, runtime_dir: Path | str | None, *, allocator: containers.WorkspaceAllocator, signature: str | None = None, mode: tuple[int, int] = DEFAULT_MODE, quarantine_workspace: str = DEFAULT_QUARANTINE_WORKSPACE, ipc: HyprlandIPC | None = None, ) -> None: self.runtime_dir = None if runtime_dir is None else Path(runtime_dir) self.allocator = allocator self.mode = mode self.quarantine_workspace = quarantine_workspace self._wanted_signature = signature self._ipc = ipc self._signature: str | None = signature self._last_error: str | None = None if ipc is not None: self._signature = signature or _signature_of(ipc) # -- the connection --------------------------------------------------- def ipc(self) -> HyprlandIPC: """The client for this instance, discovering it if we have none. Rediscovery is a ``stat`` and is attempted on every call that needs the compositor, so a compositor that comes back is picked up without a broker restart. The signature, once known, is reused: a second instance appearing must not silently move the broker's containers to a different desktop. """ if self._ipc is not None: return self._ipc if self.runtime_dir is None: raise CompositorUnavailable( "no compositor runtime directory is configured; containers are disabled" ) client = HyprlandIPC.discover(self.runtime_dir, self._wanted_signature or self._signature) self._ipc = client self._signature = _signature_of(client) self._last_error = None log.info("compositor instance %s at %s", self._signature, client.request_socket) return client @property def signature(self) -> str | None: """The instance signature, or ``None`` if we never reached one.""" return self._signature @property def last_error(self) -> str | None: return self._last_error def available(self) -> bool: """True if the compositor answered just now. Never cached as true. ``version`` is the cheapest round trip that proves the socket is a live compositor and not a leftover inode. """ try: self.ipc().version() except CompositorUnavailable as exc: self._degrade(exc) return False return True def _degrade(self, exc: CompositorUnavailable) -> None: self._last_error = str(exc) # Drop the client: its socket path may be stale, and the next call # should rediscover rather than keep failing against a dead instance. self._ipc = None # -- running plans ---------------------------------------------------- def dispatch(self, argv: list[str]) -> str: """Run one ``["hyprctl", ...]`` argv over the request socket. The reply is checked: Hyprland answers ``ok`` to a command it carried out and prose to one it refused, and an unchecked dispatch is how a container ends up recorded as created when the compositor declined. """ if not argv or argv[0] != "hyprctl": raise ValueError(f"not a hyprctl plan entry: {argv!r}") command = " ".join(argv[1:]) reply = self.ipc().query(command).strip() if reply.lower() != OK_REPLY and reply != "": raise CompositorUnavailable(f"compositor refused {command!r}: {reply[:200]!r}") return reply def run_plan(self, plan: list[list[str]]) -> None: """Run argv lists in the order given. Stops at the first refusal.""" for argv in plan: self.dispatch(argv) def install_quarantine(self) -> bool: """Install the catch-all backstop. Returns False when it is disabled. **Called once at broker start-up, before any session's container exists.** Hyprland applies window rules in the order they were declared and this one matches every class, so installing it after a per-session rule would override that rule and sweep the session's own window into the special workspace. The ordering cannot live in :mod:`hhstreamd.containers`, which runs nothing; it lives here, in the one caller that could get it wrong. """ argv = containers.quarantine_argv(self.quarantine_workspace) if argv is None: log.info("the quarantine backstop is disabled; unmatched windows stay where they land") return False self.run_plan(argv) return True # -- containers ------------------------------------------------------- def create(self, session_id: str, app_id: str) -> containers.ContainerPlan: """Allocate a slot and build the session's container. The slot is released again if the compositor refuses part way through, because a half-built container must not also leak a workspace number. Whatever *was* created is left for :meth:`remove` and for the start-up scan: deleting an output while the compositor is misbehaving is how one failure becomes two. """ workspace = self.allocator.allocate() plan = containers.container_plan( session_id, workspace, self.mode[0], self.mode[1], app_id ) try: self.run_plan(plan.create) except (CompositorUnavailable, ValueError): self.allocator.release(workspace) raise return plan def remove(self, output: str) -> None: """Remove one output of ours. Refuses a name we could not have made.""" if not containers.contains_output(output): raise ValueError( f"refusing to remove output {output!r}: not one this broker creates" ) self.dispatch(["hyprctl", "output", "remove", output]) def release(self, workspace: int | None) -> None: """Give a workspace slot back, tolerating one we never held. Unlike the allocator's own ``release``, this is called from teardown paths that also run for sessions started before the broker restarted, or in degraded mode, where there is no slot to return. Losing a slot is a leak; raising here would abort a teardown that has already killed the application. """ if workspace is None: return try: self.allocator.release(workspace) except KeyError: log.debug("workspace %s was not held by this allocator", workspace) def reserve(self, workspaces: list[int]) -> list[int]: """Re-take slots a previous broker handed out. Returns what was taken. The allocator's frozen interface (CONTRACT-sessions.md §3.2) has ``allocate``, ``release`` and ``in_use`` and no way to say "this one is already mine", which adoption needs: the records restored at start-up name workspaces that must not be handed to a new session. Allocating from the bottom until each wanted slot has come up, then giving back the ones we did not want, reserves them through the interface that exists. The band is a few entries wide, so the cost is nothing; the alternative is a second free list beside the allocator's, which is the drift the allocator exists to prevent. """ wanted = {w for w in workspaces if isinstance(w, int) and not isinstance(w, bool)} if not wanted: return [] # Slots this allocator already holds are already reserved. Without # this, a second reconcile walks the band looking for a number it has # itself taken, exhausts it, and reports the band full. taken: list[int] = sorted(wanted & set(self.allocator.in_use())) wanted -= set(taken) if not wanted: return taken spare: list[int] = [] while wanted - set(taken): try: slot = self.allocator.allocate() except containers.NoSlots: missing = sorted(wanted - set(taken)) log.error( "cannot reserve adopted workspaces %s: the band is full; a new " "session could be given one of them", missing, ) break (taken if slot in wanted else spare).append(slot) for slot in spare: self.allocator.release(slot) return sorted(taken) # -- reading back ----------------------------------------------------- def read_back(self, app_id: str, pid: int | None = None) -> ContainerFacts | None: """What the compositor says about this session's window, or ``None``. ``None`` means no window has appeared yet, which is not a failure: an application takes time to map one, and the caller polls. A window is matched by its ``initial_class`` — the stamp the rule also matches — and failing that by pid, so a session whose toolkit ignored the stamp is still *observed*, even though its rule will not have bound. """ client = self._find(app_id, pid) if client is None: return None workspace_monitor = {w.id: w.monitor for w in self.ipc().workspaces()} output = workspace_monitor.get(client.workspace_id) if client.workspace_id else None foreground: bool | None = None if output is not None: for monitor in self.ipc().monitors(): if monitor.name == output: # "Foreground" is the monitor-active-workspace join, not # the client's own `visible` flag: it answers "is anything # — a human, the frame server — actually looking at this", # which a mapped window on a hidden workspace is not. foreground = monitor.active_workspace_id == client.workspace_id break return ContainerFacts( workspace=client.workspace_id, output=output, window={ "stable_id": client.stable_id, "address": client.address, "class": client.class_, "initial_class": client.initial_class, "title": client.title, "pid": client.pid, }, foreground=foreground, ) def _find(self, app_id: str, pid: int | None) -> Client | None: by_pid: Client | None = None for client in self.ipc().clients(): if client.initial_class == app_id: return client if pid is not None and pid > 0 and client.pid == pid: by_pid = client return by_pid def survivors(self, app_id: str, output: str | None) -> list[dict[str, Any]]: """Windows of ours the compositor still has after a teardown. Either identity counts: a window still carrying the session's class, or any window still sitting on the output we were about to remove. Both mean the teardown did not finish, and the caller reports them instead of claiming success (PLAN §4.5). """ on_output: set[int] = set() if output is not None: on_output = { workspace.id for workspace in self.ipc().workspaces() if workspace.monitor == output } found = [] for client in self.ipc().clients(): if client.initial_class == app_id or ( client.workspace_id is not None and client.workspace_id in on_output ): found.append( { "address": client.address, "pid": client.pid, "class": client.class_, "initial_class": client.initial_class, "workspace": client.workspace_id, } ) return found def our_outputs(self) -> list[str]: """Live outputs whose names this broker could have created. :func:`hhstreamd.containers.contains_output` is the whole filter, and it is the only thing standing between the start-up scan and somebody else's monitor. A name it rejects is never returned, so it can never be removed. """ return sorted(m.name for m in self.ipc().monitors() if containers.contains_output(m.name)) def _signature_of(client: HyprlandIPC) -> str | None: """The instance signature, read back off the socket path we connected to. ``HyprlandIPC.discover`` resolves the signature (from the argument, the environment, or the single instance directory) but does not report which one it chose, and the record has to carry it so a restarted broker re-attaches to the same instance. The socket lives at ``/hypr//.socket.sock``, so its parent directory is the answer. """ parent = client.request_socket.parent return parent.name or None