diff --git a/src/hhstreamd/containers.py b/src/hhstreamd/containers.py new file mode 100644 index 0000000..d4f07da --- /dev/null +++ b/src/hhstreamd/containers.py @@ -0,0 +1,304 @@ +"""Spatial containers: one headless output and one workspace per session. + +A session used to be a process group and nothing more, so every application +landed on whichever workspace the compositor happened to be showing. Two +sessions then shared a screen: a capture of one caught the other's windows, and +a pointer aimed at one could land in the other. A container fixes that by +giving the session a place of its own — a dedicated headless output, a numbered +workspace bound to that output as its default and marked persistent so it +survives the window closing, and a window rule that pins anything the session +spawns there. + +**This module computes command lines and nothing else.** It does not run them, +does not talk to a socket, does not read a file, does not look at a clock and +does not import :mod:`hhstreamd.ipc`. That separation is deliberate: the +compositor is the part that cannot be tested without a compositor, so every +decision that *can* be made in a pure function is made here, where a unit test +can assert the exact argv list. The broker executes what comes back. + +Three properties the callers depend on: + +**Byte-identical output for identical arguments.** The ``create`` list is +emitted in a fixed order — create the output, bind the workspace, pin the +window, then set the mode — that does not depend on the inputs, and no set or +dict is ever iterated to build a command. The only thing a caller can vary is +what it passes in, in the order the signature names: nothing else here is a +source of order. So ``container_plan`` is safe to call twice and diff, which is +how ``container.reconcile`` decides whether a live container matches its plan. + +**Argv lists, never strings.** These values reach a compositor that will act on +them, so there is no shell, no quoting and no interpolation of a caller's string +into a command *word*. The one place caller data lands inside a word is a rule +body (``workspace 1000, monitor:hh-x``), where a comma or a newline would end +one field and begin another — which is why the validation below is a control and +not a style preference. + +**Validation raises, and names the value.** A session id that is not +``[a-z0-9-]``, a non-positive size, an empty app id: all :class:`ValueError`. +The broker mints its own ids and sizes, so a rejection here means a bug upstream +of us, and a message that quotes the offending value is what makes that bug +findable. +""" + +from __future__ import annotations + +import re +from dataclasses import dataclass + +#: Every output this broker creates carries it. A start-up scan uses the prefix +#: to tell its own orphans — outputs left behind by a crash — from the outputs a +#: human or another tool made, which it must not remove. +OUTPUT_PREFIX = "hh-" + +#: Session ids as the broker mints them. Deliberately narrower than "a safe +#: command word": lowercase, digits and the dash, so the name is also a legal +#: Hyprland output name and a regex literal with nothing to escape. +SESSION_ID_RE = re.compile(r"\A[a-z0-9-]+\Z") + +#: An application's window class, which we do not mint — it is whatever the +#: toolkit reports, so it has to allow the shapes real classes take +#: (``org.gnome.Nautilus``, ``Alacritty``, ``firefox-esr``). It still excludes +#: every character that could end a field in a rule body or a line in the +#: request: comma, space, quote, newline, ``$``, ``^``. +APP_ID_RE = re.compile(r"\A[A-Za-z0-9._+-]+\Z") + + +class NoSlots(Exception): + """The workspace band is full. The caller refuses the session; it never reuses.""" + + +@dataclass(frozen=True, slots=True) +class ContainerPlan: + """What a session's container is, and the two command lists that realise it. + + ``create`` and ``teardown`` are complete argv lists in the order they must + run. ``teardown`` is not the reverse of ``create``: removing the output is + enough, because the workspace and window rules are keywords that die with + the compositor's configuration and name an output that no longer exists. + """ + + output: str + workspace: int + mode: tuple[int, int] + create: list[list[str]] + teardown: list[list[str]] + + +def output_name(session_id: str) -> str: + """``hh-`` — the name of the session's headless output.""" + + return OUTPUT_PREFIX + _checked_session_id(session_id) + + +def contains_output(name: str) -> bool: + """True only for an output name this broker could have created. + + Used by the start-up scan, which removes what it recognises. So it is + strict in the direction that matters: a bare ``hh-``, a trailing newline or + an upper-case suffix is *not* one of ours, and a scan that answered True + would delete someone else's output. + """ + + if not name.startswith(OUTPUT_PREFIX): + return False + return SESSION_ID_RE.match(name[len(OUTPUT_PREFIX) :]) is not None + + +def app_id_for(session_id: str) -> str: + """The bare ``hh-`` the launcher sets as the app's class. + + Same string as the output name, and that is the point: the launcher stamps + it on the application (``--class``, ``app_id``) and + :func:`container_plan` anchors it into the window rule, so the window finds + its own workspace with no lookup and no race against the window appearing. + """ + + return OUTPUT_PREFIX + _checked_session_id(session_id) + + +def container_plan( + session_id: str, + workspace: int, + width: int, + height: int, + app_id: str, +) -> ContainerPlan: + """The commands that create and tear down one session's container. + + ``app_id`` is passed in rather than derived from ``session_id`` because the + rule has to match whatever class the application actually reports: it is + :func:`app_id_for` for a well-behaved app the launcher could stamp, and the + app's own class for one that ignores the stamp. + """ + + name = output_name(session_id) + slot = _checked_int(workspace, "workspace", minimum=1) + w = _checked_int(width, "width", minimum=1) + h = _checked_int(height, "height", minimum=1) + match = _checked_app_id(app_id) + return ContainerPlan( + output=name, + workspace=slot, + mode=(w, h), + create=[ + # The output first: the workspace rule below names it, and a rule + # for an output that does not exist yet binds to nothing. + ["hyprctl", "output", "create", "headless", name], + # `default:true` makes this the workspace the output shows, and + # `persistent:true` keeps it alive when the last window closes — a + # container that evaporated between two applications would send the + # next window back to the shared screen. + [ + "hyprctl", + "keyword", + "workspace", + f"{slot}, monitor:{name}, default:true, persistent:true", + ], + # Anchored (`^...$`) so a class that merely contains the app id + # cannot claim another session's workspace. `initial_class` rather + # than the live class: applications rename their window, and the + # placement has to be decided when it is mapped. + [ + "hyprctl", + "keyword", + "windowrule", + f"match:initial_class ^{match}$, workspace {slot}, monitor {name}", + ], + # Last, because the mode applies to an output that now exists and + # already has its workspace; setting it earlier would resize a + # screen that is about to be replaced. + ["hyprctl", "keyword", "monitor", f"{name},{w}x{h},auto,1"], + ], + teardown=[["hyprctl", "output", "remove", name]], + ) + + +def quarantine_plan(quarantine_workspace: str) -> ContainerPlan | None: + """The backstop rule: a window that matched no container goes here. + + Without it, a window with an unexpected class — a dialog spawned by a + helper process, a toolkit that rewrites its class — lands on whatever + workspace is in front, which is the leak containers exist to prevent. The + rule matches every class and is therefore emitted *before* the per-session + rules, which are anchored and more specific. + + ``quarantine_workspace`` is a workspace *name* (``special:quarantine``), not + a slot out of the allocator's band, so the returned plan carries no output + and no mode: it is a rule, not a container. An empty or blank name means + the operator turned the backstop off, and the answer is ``None`` rather than + a plan with an empty command list — a caller that gets a plan should always + have something to run. + """ + + target = quarantine_workspace.strip() + if not target: + return None + _checked_rule_value(target, "quarantine_workspace") + return ContainerPlan( + output="", + workspace=0, + mode=(0, 0), + create=[ + [ + "hyprctl", + "keyword", + "windowrule", + f"match:initial_class .*, workspace {target}", + ] + ], + # A keyword rule cannot be unset one at a time, and this one is not + # per-session anyway: it is installed once at start-up and goes away + # with the compositor. + teardown=[], + ) + + +class WorkspaceAllocator: + """Hands out workspace slots from a fixed band, lowest free first. + + Lowest-free rather than monotonic so a long-lived broker's numbers stay + small and readable (``hyprctl workspaces`` is something a human reads), and + so the band is a real bound: ``count`` slots means at most ``count`` + containers, with exhaustion surfacing as :class:`NoSlots` at allocation + rather than as a collision later. + """ + + def __init__(self, base: int, count: int) -> None: + self._base = _checked_int(base, "base", minimum=1) + self._count = _checked_int(count, "count", minimum=1) + self._used: set[int] = set() + + def allocate(self) -> int: + """The lowest free slot in ``[base, base + count)``. Raises :class:`NoSlots`.""" + + for slot in range(self._base, self._base + self._count): + if slot not in self._used: + self._used.add(slot) + return slot + raise NoSlots( + f"workspace band {self._base}..{self._base + self._count - 1} is full " + f"({self._count} in use)" + ) + + def release(self, workspace: int) -> None: + """Give a slot back. A slot we never handed out raises :class:`KeyError`. + + Loudly, because the two ways to get here are a double release and a + caller releasing someone else's slot, and both mean the registry and + this allocator have drifted. Swallowing it would hand the same + workspace to two sessions a few minutes later, which is the leak that is + hard to trace back. + """ + + if workspace not in self._used: + raise KeyError( + f"workspace {workspace} was not allocated by this allocator " + f"(in use: {sorted(self._used)})" + ) + self._used.discard(workspace) + + def in_use(self) -> list[int]: + """Allocated slots, ascending. Sorted because callers log and diff it.""" + + return sorted(self._used) + + +def _checked_session_id(session_id: str) -> str: + if not isinstance(session_id, str) or not SESSION_ID_RE.match(session_id): + raise ValueError( + f"session id {session_id!r} is not [a-z0-9-]+; it names an output and " + "goes into a compositor command" + ) + return session_id + + +def _checked_app_id(app_id: str) -> str: + if not isinstance(app_id, str) or not app_id: + raise ValueError(f"app id {app_id!r} is empty; a window rule needs a class to match") + if not APP_ID_RE.match(app_id): + raise ValueError( + f"app id {app_id!r} is not [A-Za-z0-9._+-]+; a window rule body is " + "comma-separated, so anything else could forge a rule field" + ) + return app_id + + +def _checked_rule_value(value: str, label: str) -> str: + # Same reasoning as an app id, one rule field over: this ends up inside a + # `workspace ` field, where a comma starts the next field. The colon + # is allowed because `special:quarantine` needs it. + if not re.match(r"\A[A-Za-z0-9._:+-]+\Z", value): + raise ValueError( + f"{label} {value!r} is not [A-Za-z0-9._:+-]+; it is interpolated into " + "a comma-separated rule body" + ) + return value + + +def _checked_int(value: int, label: str, *, minimum: int) -> int: + # bool is an int in Python, and `True` would silently become workspace 1. + if not isinstance(value, int) or isinstance(value, bool): + raise ValueError(f"{label} {value!r} is not an int") + if value < minimum: + raise ValueError(f"{label} {value!r} is not >= {minimum}") + return value diff --git a/tests/containers/test_allocator.py b/tests/containers/test_allocator.py new file mode 100644 index 0000000..ab30a59 --- /dev/null +++ b/tests/containers/test_allocator.py @@ -0,0 +1,106 @@ +"""The workspace allocator: lowest free, reuse after release, and loud bugs.""" + +from __future__ import annotations + +import pytest + +from hhstreamd.containers import NoSlots, WorkspaceAllocator + + +def test_allocates_the_band_from_its_base_upwards() -> None: + alloc = WorkspaceAllocator(1000, 4) + + assert [alloc.allocate() for _ in range(4)] == [1000, 1001, 1002, 1003] + assert alloc.in_use() == [1000, 1001, 1002, 1003] + + +def test_a_released_slot_is_reused_before_a_higher_free_one() -> None: + alloc = WorkspaceAllocator(1000, 4) + for _ in range(3): + alloc.allocate() + + alloc.release(1001) + + assert alloc.in_use() == [1000, 1002] + assert alloc.allocate() == 1001 + assert alloc.allocate() == 1003 + assert alloc.in_use() == [1000, 1001, 1002, 1003] + + +def test_a_full_band_raises_no_slots_and_stays_unchanged() -> None: + alloc = WorkspaceAllocator(1000, 2) + alloc.allocate() + alloc.allocate() + + with pytest.raises(NoSlots) as exc: + alloc.allocate() + assert "1000..1001" in str(exc.value) + assert alloc.in_use() == [1000, 1001] + + # Exhaustion is not terminal: a release makes the slot available again. + alloc.release(1000) + assert alloc.allocate() == 1000 + + +def test_releasing_a_slot_we_never_handed_out_is_a_key_error() -> None: + alloc = WorkspaceAllocator(1000, 2) + alloc.allocate() + + # Inside the band but free, and outside the band: both are caller bugs, and + # a silent no-op would let two sessions share a workspace later. + with pytest.raises(KeyError) as free_slot: + alloc.release(1001) + assert "1001" in str(free_slot.value) + + with pytest.raises(KeyError): + alloc.release(7) + + assert alloc.in_use() == [1000] + + +def test_a_double_release_raises() -> None: + alloc = WorkspaceAllocator(1000, 2) + slot = alloc.allocate() + alloc.release(slot) + + with pytest.raises(KeyError): + alloc.release(slot) + assert alloc.in_use() == [] + + +def test_in_use_is_ascending_whatever_the_allocation_order() -> None: + alloc = WorkspaceAllocator(1000, 3) + a, b, c = alloc.allocate(), alloc.allocate(), alloc.allocate() + alloc.release(b) + alloc.release(a) + alloc.allocate() + alloc.allocate() + + assert alloc.in_use() == [1000, 1001, 1002] + assert c == 1002 + + +def test_a_band_must_be_a_real_band() -> None: + with pytest.raises(ValueError) as count: + WorkspaceAllocator(1000, 0) + assert "count" in str(count.value) + + with pytest.raises(ValueError) as base: + WorkspaceAllocator(0, 4) + assert "base" in str(base.value) + + with pytest.raises(ValueError) as kind: + WorkspaceAllocator(1000, 2.5) # type: ignore[arg-type] + assert "count" in str(kind.value) + assert "is not an int" in str(kind.value) + + +def test_two_allocators_do_not_share_state() -> None: + # The set is per-instance; a class attribute here would hand the same + # workspace to two brokers' containers. + first = WorkspaceAllocator(1000, 2) + second = WorkspaceAllocator(1000, 2) + + assert first.allocate() == 1000 + assert second.allocate() == 1000 + assert first.in_use() == second.in_use() == [1000] diff --git a/tests/containers/test_plan.py b/tests/containers/test_plan.py new file mode 100644 index 0000000..0a77c0e --- /dev/null +++ b/tests/containers/test_plan.py @@ -0,0 +1,223 @@ +"""Container plans: the exact argv lists, and the validation that guards them. + +The argv lists are asserted whole rather than probed for substrings. These +commands are the only thing this module produces, nobody here runs them, and a +test that accepted "contains the output name" would pass on a command that +silently changed shape under a refactor. +""" + +from __future__ import annotations + +import pytest + +from hhstreamd.containers import ( + ContainerPlan, + app_id_for, + contains_output, + container_plan, + output_name, + quarantine_plan, +) + + +def test_create_is_the_four_commands_in_order() -> None: + plan = container_plan("foot-aaaaaa", 1000, 1280, 720, "hh-foot-aaaaaa") + + assert plan.create == [ + ["hyprctl", "output", "create", "headless", "hh-foot-aaaaaa"], + [ + "hyprctl", + "keyword", + "workspace", + "1000, monitor:hh-foot-aaaaaa, default:true, persistent:true", + ], + [ + "hyprctl", + "keyword", + "windowrule", + "match:initial_class ^hh-foot-aaaaaa$, workspace 1000, monitor hh-foot-aaaaaa", + ], + ["hyprctl", "keyword", "monitor", "hh-foot-aaaaaa,1280x720,auto,1"], + ] + + +def test_teardown_removes_the_output_and_nothing_else() -> None: + plan = container_plan("foot-aaaaaa", 1000, 1280, 720, "hh-foot-aaaaaa") + + assert plan.teardown == [["hyprctl", "output", "remove", "hh-foot-aaaaaa"]] + + +def test_plan_describes_what_it_built() -> None: + plan = container_plan("x1", 1007, 1920, 1080, "org.gnome.Nautilus") + + assert isinstance(plan, ContainerPlan) + assert (plan.output, plan.workspace, plan.mode) == ("hh-x1", 1007, (1920, 1080)) + + +def test_a_foreign_class_is_matched_as_given() -> None: + # The rule has to match what the toolkit reports, which is not always the + # id the launcher stamped. + plan = container_plan("x1", 1001, 800, 600, "org.gnome.Nautilus") + + assert plan.create[2] == [ + "hyprctl", + "keyword", + "windowrule", + "match:initial_class ^org.gnome.Nautilus$, workspace 1001, monitor hh-x1", + ] + + +def test_identical_arguments_give_byte_identical_commands() -> None: + first = container_plan("foot-aaaaaa", 1000, 1280, 720, "hh-foot-aaaaaa") + second = container_plan("foot-aaaaaa", 1000, 1280, 720, "hh-foot-aaaaaa") + + assert first == second + assert first.create == second.create + assert first.teardown == second.teardown + + +def test_output_name_and_app_id_are_the_same_string() -> None: + assert output_name("foot-aaaaaa") == "hh-foot-aaaaaa" + assert app_id_for("foot-aaaaaa") == "hh-foot-aaaaaa" + + +@pytest.mark.parametrize( + "name", + [ + "hh-foot-aaaaaa", + "hh-x", + "hh-1000", + ], +) +def test_contains_output_claims_our_own_names(name: str) -> None: + assert contains_output(name) is True + + +@pytest.mark.parametrize( + "name", + [ + "HEADLESS-1", # the compositor's own + "eDP-1", + "hh", + "hh-", # no session id: not something the broker ever created + "hh-Foot", # upper case is outside the minted alphabet + "hh-foot\n", # a trailing newline is not a name, it is two lines + "hh-foot aaaa", + " hh-foot", + "xhh-foot", + "", + ], +) +def test_contains_output_refuses_everything_else(name: str) -> None: + # A scan removes what this says is ours, so a false positive deletes an + # output the broker did not create. + assert contains_output(name) is False + + +@pytest.mark.parametrize( + "bad", + ["", "Foot", "foot_aaaa", "foot aaaa", "hh-foot;rm", "foot\n", "../x", "é"], +) +def test_a_session_id_outside_the_alphabet_is_refused(bad: str) -> None: + with pytest.raises(ValueError) as exc: + output_name(bad) + assert repr(bad) in str(exc.value) + assert "[a-z0-9-]" in str(exc.value) + + with pytest.raises(ValueError) as app_exc: + app_id_for(bad) + assert repr(bad) in str(app_exc.value) + + with pytest.raises(ValueError) as plan_exc: + container_plan(bad, 1000, 1280, 720, "hh-x") + assert repr(bad) in str(plan_exc.value) + + +@pytest.mark.parametrize("width,height", [(0, 720), (1280, 0), (-1, 720), (1280, -720)]) +def test_a_non_positive_mode_is_refused(width: int, height: int) -> None: + with pytest.raises(ValueError) as exc: + container_plan("x1", 1000, width, height, "hh-x1") + message = str(exc.value) + offender = width if width < 1 else height + assert repr(offender) in message + assert ("width" in message) or ("height" in message) + assert ">= 1" in message + + +def test_a_fractional_mode_is_refused() -> None: + # 1280.5 would reach the compositor as "1280.5x720"; a mode is pixels. + with pytest.raises(ValueError) as exc: + container_plan("x1", 1000, 1280.5, 720, "hh-x1") # type: ignore[arg-type] + assert "width" in str(exc.value) + assert "is not an int" in str(exc.value) + + +def test_a_boolean_workspace_is_refused() -> None: + # True is an int in Python and would quietly become workspace 1. + with pytest.raises(ValueError) as exc: + container_plan("x1", True, 1280, 720, "hh-x1") # type: ignore[arg-type] + assert "workspace" in str(exc.value) + assert "is not an int" in str(exc.value) + + +@pytest.mark.parametrize("workspace", [0, -1]) +def test_a_non_positive_workspace_is_refused(workspace: int) -> None: + with pytest.raises(ValueError) as exc: + container_plan("x1", workspace, 1280, 720, "hh-x1") + assert "workspace" in str(exc.value) + assert repr(workspace) in str(exc.value) + + +def test_an_empty_app_id_is_refused() -> None: + with pytest.raises(ValueError) as exc: + container_plan("x1", 1000, 1280, 720, "") + assert "app id" in str(exc.value) + assert "''" in str(exc.value) + + +@pytest.mark.parametrize( + "bad", + [ + "hh-x1, workspace 1001", # a forged second rule field + "hh-x1$, monitor eDP-1", + "hh x1", + "hh-x1\nkeyword monitor eDP-1,disable", + "^hh-x1$", + "hh-x1'", + ], +) +def test_an_app_id_that_could_forge_a_rule_field_is_refused(bad: str) -> None: + with pytest.raises(ValueError) as exc: + container_plan("x1", 1000, 1280, 720, bad) + assert repr(bad) in str(exc.value) + assert "[A-Za-z0-9._+-]" in str(exc.value) + + +def test_quarantine_plan_is_the_catch_all_keyword() -> None: + plan = quarantine_plan("special:quarantine") + + assert plan is not None + assert plan.create == [ + [ + "hyprctl", + "keyword", + "windowrule", + "match:initial_class .*, workspace special:quarantine", + ] + ] + # A rule, not a container: nothing to remove, no output, no mode. + assert plan.teardown == [] + assert (plan.output, plan.workspace, plan.mode) == ("", 0, (0, 0)) + + +@pytest.mark.parametrize("disabled", ["", " ", "\n"]) +def test_quarantine_plan_is_none_when_disabled(disabled: str) -> None: + assert quarantine_plan(disabled) is None + + +@pytest.mark.parametrize("bad", ["special:quarantine, monitor eDP-1", "a b", "q\n1", "q'"]) +def test_a_quarantine_workspace_that_could_forge_a_field_is_refused(bad: str) -> None: + with pytest.raises(ValueError) as exc: + quarantine_plan(bad) + assert "quarantine_workspace" in str(exc.value) + assert repr(bad.strip()) in str(exc.value)