Files
hyprland-headless-stream-pl…/tests/unit/helpers.py
HermenixandClaude Opus 5 4af6f7072a server, client: implement the v1 frame protocol end to end
Fill in the bodies the skeleton left as NotImplementedError, to docs/CONTRACT.md:

- protocol: the `\n`-terminated JSON Hello and the `<ascii length>\n<payload>`
  frame, both directions. Malformed input raises (ValueError for a bad length
  prefix, EOFError for a truncated payload), never hangs on endless garbage and
  never silently truncates; a huge length prefix is not pre-allocated.
- capture: CommandCapture runs the configured command and reports a missing
  binary, a non-zero exit, a timeout and empty output as CaptureError, with the
  helper's stderr folded into the message so nothing leaks to the server's own
  stdio. The Hello's pixel size is read from the frame's PNG/JPEG header, so no
  compositor query is needed and an injected fake command behaves the same.
- server: one capture thread holding only the newest frame plus one thread per
  client, which is what drops frames for a slow client instead of queueing
  them. Survives a client dying mid-write, keeps the socket up across capture
  failures, withholds the Hello until a size is known, replaces a stale socket
  file (but never a non-socket one) and publishes it mode 0660.
- client: fetch()/read_stream() and the CLI, with --out suffixing per frame.

--capture-command folds its separated form into `--flag=value` before argparse
sees it, so the contract's default `grim -t png -` can actually be passed: its
tokens start with a dash.

Unit tests under tests/unit cover framing round-trips (including a payload
containing `\n` and a zero-length frame), truncated and garbage prefixes, a
stalled client not blocking a second one, a client dying mid-frame, frames being
dropped rather than queued, and every capture failure mode. A fake capture
command stands in for grim, so nothing needs a compositor or a GPU. They are
deliberately not wired into flake.nix: `checks` belongs to another workstream.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FYJ8ZQ5AZaDErYTwXZe7N9
2026-09-28 05:35:17 +00:00

65 lines
2.1 KiB
Python

"""Test doubles: an in-process capture backend and the fake capture command."""
from __future__ import annotations
import pathlib
import socket
import struct
import sys
import threading
import time
from fake_capture import png_bytes # noqa: F401 (re-exported for the tests)
from hhstream.capture import CaptureError
#: argv prefix for the fake `grim`; append its flags.
FAKE_CAPTURE = [sys.executable, str(pathlib.Path(__file__).with_name("fake_capture.py"))]
class FakeCapture:
"""A `CaptureBackend` with no subprocess: deterministic, fast, scriptable."""
def __init__(self, frames=None, size=(1280, 720), fail_until=0, delay=0.0):
self.frames = list(frames) if frames else [png_bytes(4, 2)]
self._size = size
self.fail_until = fail_until
self.delay = delay
self.calls = 0
self._lock = threading.Lock()
def grab(self) -> bytes:
with self._lock:
self.calls += 1
call = self.calls
if self.delay:
time.sleep(self.delay)
if call <= self.fail_until:
raise CaptureError(f"simulated capture failure {call}")
return self.frames[(call - 1 - self.fail_until) % len(self.frames)]
def size(self) -> tuple[int, int]:
if self.calls <= self.fail_until:
raise CaptureError("size is not known yet")
return self._size
def distinct_frames(count: int) -> list[bytes]:
"""`count` unique, decodable PNGs, in order."""
return [png_bytes(4, 2, (i % 251, (i * 7) % 251, (i * 13) % 251))
for i in range(1, count + 1)]
def connect(path: str, timeout: float = 5.0, rcvbuf: int | None = None) -> socket.socket:
conn = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
if rcvbuf is not None:
conn.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, rcvbuf)
conn.settimeout(timeout)
conn.connect(path)
return conn
def abort(conn: socket.socket) -> None:
"""Close with SO_LINGER 0: the peer sees the connection torn down, not EOF."""
conn.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack("ii", 1, 0))
conn.close()