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
This commit is contained in:
1 parent
c0a59f5673
commit
4af6f7072a
12 files changed
+1825
-21
No files matched your search
@@ -0,0 +1,172 @@
|
||||
"""The command line: the flag names the NixOS module passes, end to end.
|
||||
|
||||
The server and the client run as real processes here, with the fake capture
|
||||
command standing in for `grim`, so nothing needs a compositor.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
import pytest
|
||||
from helpers import FAKE_CAPTURE
|
||||
|
||||
from hhstream import client, server
|
||||
|
||||
SRC = str(pathlib.Path(__file__).resolve().parents[2] / "src")
|
||||
RUN_SERVER = [sys.executable, "-c",
|
||||
"from hhstream.server import main; raise SystemExit(main())"]
|
||||
RUN_CLIENT = [sys.executable, "-c",
|
||||
"from hhstream.client import main; raise SystemExit(main())"]
|
||||
|
||||
|
||||
def child_env() -> dict[str, str]:
|
||||
env = dict(os.environ)
|
||||
env["PYTHONPATH"] = SRC + (os.pathsep + env["PYTHONPATH"] if "PYTHONPATH" in env else "")
|
||||
return env
|
||||
|
||||
|
||||
def capture_flags(*flags: str) -> list[str]:
|
||||
"""`--capture-command` once per argv token, as the module passes it."""
|
||||
out = []
|
||||
for token in (*FAKE_CAPTURE, *flags):
|
||||
out += ["--capture-command", token]
|
||||
return out
|
||||
|
||||
|
||||
def wait_for_socket(path: str, proc: subprocess.Popen, timeout: float = 10.0) -> None:
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
if os.path.exists(path):
|
||||
return
|
||||
if proc.poll() is not None:
|
||||
raise AssertionError(f"server exited {proc.returncode}: {proc.stderr.read()}")
|
||||
time.sleep(0.05)
|
||||
raise AssertionError(f"{path} never appeared")
|
||||
|
||||
|
||||
# -- argument parsing ----------------------------------------------------
|
||||
|
||||
def test_server_defaults_match_the_contract():
|
||||
args = server.build_parser().parse_args([])
|
||||
assert args.socket == "/run/hyprland-headless-stream/stream.sock"
|
||||
assert (args.fps, args.format, args.capture_command) == (30, "png", None)
|
||||
assert server.DEFAULT_CAPTURE_COMMAND == ["grim", "-t", "png", "-"]
|
||||
|
||||
|
||||
def test_capture_command_is_one_argv_token_per_flag():
|
||||
argv = ["--capture-command", "grim", "--capture-command", "-t",
|
||||
"--capture-command", "png", "--capture-command", "-"]
|
||||
parsed = server.build_parser().parse_args(server._join_capture_tokens(argv))
|
||||
assert parsed.capture_command == ["grim", "-t", "png", "-"]
|
||||
|
||||
|
||||
def test_capture_command_also_accepts_the_equals_form():
|
||||
argv = ["--capture-command=grim", "--capture-command=-t", "--capture-command=-"]
|
||||
parsed = server.build_parser().parse_args(server._join_capture_tokens(argv))
|
||||
assert parsed.capture_command == ["grim", "-t", "-"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("bad", [["--fps", "0"], ["--fps", "-3"],
|
||||
["--format", "webp"]])
|
||||
def test_the_server_rejects_bad_flags(bad):
|
||||
with pytest.raises(SystemExit):
|
||||
server.build_parser().parse_args(bad)
|
||||
|
||||
|
||||
def test_client_defaults():
|
||||
args = client.build_parser().parse_args([])
|
||||
assert (args.socket, args.count, args.out, args.timeout) == (
|
||||
client.DEFAULT_SOCKET, 1, None, 10.0)
|
||||
|
||||
|
||||
# -- the real thing ------------------------------------------------------
|
||||
|
||||
def test_server_and_client_processes_talk_to_each_other(workdir):
|
||||
sock = str(workdir / "s.sock")
|
||||
server_proc = subprocess.Popen(
|
||||
[*RUN_SERVER, "--socket", sock, "--fps", "10", "--format", "png",
|
||||
*capture_flags("--width", "1280", "--height", "720", "--counter",
|
||||
str(workdir / "n"))],
|
||||
env=child_env(), stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
|
||||
)
|
||||
try:
|
||||
wait_for_socket(sock, server_proc)
|
||||
done = subprocess.run(
|
||||
[*RUN_CLIENT, "--socket", sock, "--count", "2",
|
||||
"--out", str(workdir / "frame.png"), "--timeout", "10"],
|
||||
env=child_env(), capture_output=True, text=True, timeout=30,
|
||||
)
|
||||
assert done.returncode == 0, done.stderr
|
||||
lines = done.stdout.splitlines()
|
||||
assert json.loads(lines[0]) == {
|
||||
"magic": "HHS1", "width": 1280, "height": 720,
|
||||
"format": "image/png", "fps": 10,
|
||||
}
|
||||
assert len(lines) == 3
|
||||
first = (workdir / "frame-1.png").read_bytes()
|
||||
second = (workdir / "frame-2.png").read_bytes()
|
||||
assert first.startswith(b"\x89PNG\r\n\x1a\n")
|
||||
assert second.startswith(b"\x89PNG\r\n\x1a\n")
|
||||
assert first != second, "the two frames should be two different captures"
|
||||
assert server_proc.poll() is None, "the server must still be running"
|
||||
finally:
|
||||
server_proc.terminate()
|
||||
out, err = server_proc.communicate(timeout=10)
|
||||
assert server_proc.returncode == 0
|
||||
assert out == "", "the server must keep its stdout clean"
|
||||
assert os.path.exists(sock) is False, "the socket file should be cleaned up"
|
||||
|
||||
|
||||
def test_the_format_flag_becomes_the_mime_type_in_the_hello(workdir):
|
||||
sock = str(workdir / "s.sock")
|
||||
server_proc = subprocess.Popen(
|
||||
[*RUN_SERVER, "--socket", sock, "--fps", "5", "--format", "jpeg",
|
||||
*capture_flags("--width", "640", "--height", "480")],
|
||||
env=child_env(), stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
|
||||
)
|
||||
try:
|
||||
wait_for_socket(sock, server_proc)
|
||||
hello, frames = client.read_stream(sock, count=1, timeout=10)
|
||||
assert hello == {"magic": "HHS1", "width": 640, "height": 480,
|
||||
"format": "image/jpeg", "fps": 5}
|
||||
assert len(frames) == 1
|
||||
finally:
|
||||
server_proc.terminate()
|
||||
server_proc.communicate(timeout=10)
|
||||
|
||||
|
||||
def test_a_broken_capture_command_does_not_kill_the_server(workdir):
|
||||
sock = str(workdir / "s.sock")
|
||||
server_proc = subprocess.Popen(
|
||||
[*RUN_SERVER, "--socket", sock, "--fps", "20", *capture_flags("--fail")],
|
||||
env=child_env(), stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
|
||||
)
|
||||
try:
|
||||
wait_for_socket(sock, server_proc)
|
||||
time.sleep(1.0)
|
||||
assert server_proc.poll() is None, "the server exited on a capture failure"
|
||||
assert os.path.exists(sock), "the socket went away"
|
||||
finally:
|
||||
server_proc.terminate()
|
||||
out, err = server_proc.communicate(timeout=10)
|
||||
assert out == ""
|
||||
assert "capture failed" in err
|
||||
assert "simulated failure" in err, "the helper's stderr should be reported"
|
||||
|
||||
|
||||
def test_the_server_exits_nonzero_when_the_socket_cannot_be_bound(workdir):
|
||||
blocked = workdir / "regular-file"
|
||||
blocked.write_text("not a socket")
|
||||
done = subprocess.run(
|
||||
[*RUN_SERVER, "--socket", str(blocked), *capture_flags()],
|
||||
env=child_env(), capture_output=True, text=True, timeout=30,
|
||||
)
|
||||
assert done.returncode == 1
|
||||
assert "cannot serve" in done.stderr
|
||||
assert blocked.read_text() == "not a socket"
|
||||
Reference in new issue
Block a user