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
254 lines
9.8 KiB
Python
254 lines
9.8 KiB
Python
"""The server's obligations from docs/CONTRACT.md, none of which need a GPU."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import os
|
|
import socket
|
|
import stat
|
|
import threading
|
|
import time
|
|
|
|
import pytest
|
|
from helpers import (FAKE_CAPTURE, FakeCapture, abort, connect, distinct_frames,
|
|
png_bytes)
|
|
|
|
from hhstream import protocol
|
|
from hhstream.capture import CommandCapture
|
|
from hhstream.server import FrameServer
|
|
|
|
HELLO_WAIT = 5.0
|
|
|
|
|
|
def read_hello(conn, timeout=HELLO_WAIT):
|
|
conn.settimeout(timeout)
|
|
return protocol.read_hello(conn.makefile("rb"))
|
|
|
|
|
|
def test_fps_must_be_positive(sock_path):
|
|
for bad in (0, -1, True, 1.5):
|
|
with pytest.raises(ValueError):
|
|
FrameServer(sock_path, FakeCapture(), bad)
|
|
|
|
|
|
def test_two_clients_each_get_their_own_hello_and_frames(sock_path, serve):
|
|
capture = FakeCapture(frames=distinct_frames(20), size=(1280, 720))
|
|
with serve(sock_path, capture, fps=30):
|
|
first, second = connect(sock_path), connect(sock_path)
|
|
streams = [first.makefile("rb"), second.makefile("rb")]
|
|
hellos = [protocol.read_hello(s) for s in streams]
|
|
assert hellos[0] == hellos[1] == {
|
|
"magic": "HHS1", "width": 1280, "height": 720,
|
|
"format": "image/png", "fps": 30,
|
|
}
|
|
for stream in streams:
|
|
for _ in range(3):
|
|
payload = protocol.read_frame(stream)
|
|
assert payload and payload.startswith(b"\x89PNG\r\n\x1a\n")
|
|
first.close()
|
|
second.close()
|
|
|
|
|
|
def test_a_client_arriving_later_is_served_too(sock_path, serve):
|
|
with serve(sock_path, FakeCapture(frames=distinct_frames(50)), fps=50):
|
|
early = connect(sock_path)
|
|
early_stream = early.makefile("rb")
|
|
protocol.read_hello(early_stream)
|
|
assert protocol.read_frame(early_stream)
|
|
time.sleep(0.3) # let a pile of frames go by
|
|
late = connect(sock_path)
|
|
late_stream = late.makefile("rb")
|
|
assert protocol.read_hello(late_stream)["width"] == 1280
|
|
assert protocol.read_frame(late_stream) # not made to wait for a backlog
|
|
early.close()
|
|
late.close()
|
|
|
|
|
|
def test_a_stalled_client_does_not_block_another(sock_path, serve):
|
|
"""Contract: a stalled client is slowed, not queued -- and it is alone."""
|
|
big = png_bytes(1024, 1024, (1, 2, 3), level=0) # ~3 MiB, fills any buffer
|
|
assert len(big) > 2 << 20
|
|
with serve(sock_path, FakeCapture(frames=[big]), fps=20):
|
|
stalled = connect(sock_path, rcvbuf=2048)
|
|
assert read_hello(stalled)["width"] == 1280
|
|
# ...and now `stalled` reads nothing at all, so the server's write to it
|
|
# blocks part-way through a frame.
|
|
time.sleep(0.5)
|
|
|
|
started = time.monotonic()
|
|
healthy = connect(sock_path)
|
|
stream = healthy.makefile("rb")
|
|
assert protocol.read_hello(stream)["width"] == 1280
|
|
assert len(protocol.read_frame(stream)) == len(big)
|
|
assert len(protocol.read_frame(stream)) == len(big)
|
|
assert time.monotonic() - started < HELLO_WAIT, "the stall spread"
|
|
healthy.close()
|
|
stalled.close()
|
|
|
|
|
|
def test_frames_are_dropped_for_a_slow_client_not_queued(sock_path, serve):
|
|
frames = distinct_frames(400)
|
|
index_of = {payload: i for i, payload in enumerate(frames, start=1)}
|
|
capture = FakeCapture(frames=frames)
|
|
with serve(sock_path, capture, fps=100) as server:
|
|
conn = connect(sock_path)
|
|
stream = conn.makefile("rb")
|
|
protocol.read_hello(stream)
|
|
seen = []
|
|
for _ in range(3):
|
|
time.sleep(0.2) # far slower than 100 fps
|
|
seen.append(index_of[protocol.read_frame(stream)])
|
|
conn.close()
|
|
assert server.frames_captured > len(seen) + 2, "capture did not outrun the client"
|
|
assert seen == sorted(seen)
|
|
assert seen[-1] > len(seen), f"frames were queued, not dropped: {seen}"
|
|
|
|
|
|
def test_server_survives_a_client_dying_mid_frame(sock_path, serve):
|
|
big = png_bytes(1024, 1024, (9, 9, 9), level=0)
|
|
with serve(sock_path, FakeCapture(frames=[big]), fps=20) as server:
|
|
doomed = connect(sock_path, rcvbuf=2048)
|
|
stream = doomed.makefile("rb")
|
|
assert protocol.read_hello(stream)["width"] == 1280
|
|
assert len(stream.read(4096)) == 4096 # a fragment of the first frame
|
|
abort(doomed) # torn down mid-frame, with an RST
|
|
|
|
survivor = connect(sock_path)
|
|
survivor_stream = survivor.makefile("rb")
|
|
assert protocol.read_hello(survivor_stream)["width"] == 1280
|
|
assert len(protocol.read_frame(survivor_stream)) == len(big)
|
|
survivor.close()
|
|
assert server.ready.is_set()
|
|
|
|
|
|
def test_server_survives_many_clients_connecting_and_vanishing(sock_path, serve):
|
|
with serve(sock_path, FakeCapture(frames=distinct_frames(10)), fps=50):
|
|
for _ in range(25):
|
|
conn = connect(sock_path)
|
|
protocol.read_hello(conn.makefile("rb"))
|
|
abort(conn)
|
|
survivor = connect(sock_path)
|
|
stream = survivor.makefile("rb")
|
|
assert protocol.read_hello(stream)["width"] == 1280
|
|
assert protocol.read_frame(stream)
|
|
survivor.close()
|
|
|
|
|
|
def test_bytes_sent_by_a_client_are_read_and_ignored(sock_path, serve):
|
|
with serve(sock_path, FakeCapture(frames=distinct_frames(10)), fps=30):
|
|
conn = connect(sock_path)
|
|
conn.sendall(b"v2 control channel?\n" * 500)
|
|
stream = conn.makefile("rb")
|
|
assert protocol.read_hello(stream)["magic"] == "HHS1"
|
|
assert protocol.read_frame(stream)
|
|
conn.sendall(b"more chatter")
|
|
assert protocol.read_frame(stream)
|
|
conn.close()
|
|
|
|
|
|
def test_capture_failure_keeps_the_server_up_and_holds_the_hello(sock_path, serve,
|
|
workdir):
|
|
"""Contract: no compositor -> keep the socket up, retry, send no Hello yet."""
|
|
gate = workdir / "gate"
|
|
capture = CommandCapture(
|
|
[*FAKE_CAPTURE, "--gate", str(gate), "--width", "800", "--height", "600"],
|
|
timeout=10,
|
|
)
|
|
with serve(sock_path, capture, fps=20) as server:
|
|
waiting = connect(sock_path, timeout=1.0)
|
|
with pytest.raises(TimeoutError):
|
|
protocol.read_hello(waiting.makefile("rb"))
|
|
assert server.capture_failures > 0
|
|
assert server.frames_captured == 0
|
|
waiting.close()
|
|
|
|
gate.write_text("the compositor is up now\n")
|
|
recovered = connect(sock_path)
|
|
stream = recovered.makefile("rb")
|
|
hello = protocol.read_hello(stream)
|
|
assert (hello["width"], hello["height"]) == (800, 600)
|
|
assert protocol.read_frame(stream).startswith(b"\x89PNG\r\n\x1a\n")
|
|
recovered.close()
|
|
assert server.frames_captured > 0
|
|
|
|
|
|
def test_capture_failing_in_the_middle_does_not_break_the_stream(sock_path, serve):
|
|
capture = FakeCapture(frames=distinct_frames(10))
|
|
with serve(sock_path, capture, fps=50) as server:
|
|
conn = connect(sock_path)
|
|
stream = conn.makefile("rb")
|
|
protocol.read_hello(stream)
|
|
assert protocol.read_frame(stream)
|
|
capture.fail_until = capture.calls + 20 # a burst of failures
|
|
time.sleep(0.3)
|
|
assert server.capture_failures >= 1
|
|
assert protocol.read_frame(stream) # recovers without a reconnect
|
|
conn.close()
|
|
|
|
|
|
def test_a_stale_socket_file_does_not_prevent_startup(sock_path, serve):
|
|
stale = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
|
stale.bind(sock_path)
|
|
stale.close()
|
|
assert stat.S_ISSOCK(os.lstat(sock_path).st_mode)
|
|
with serve(sock_path, FakeCapture(), fps=20):
|
|
conn = connect(sock_path)
|
|
assert protocol.read_hello(conn.makefile("rb"))["magic"] == "HHS1"
|
|
conn.close()
|
|
|
|
|
|
def test_the_socket_is_mode_0660(sock_path, serve):
|
|
with serve(sock_path, FakeCapture(), fps=20):
|
|
assert stat.S_IMODE(os.stat(sock_path).st_mode) == 0o660
|
|
|
|
|
|
def test_a_non_socket_file_in_the_way_is_never_deleted(workdir):
|
|
precious = workdir / "precious"
|
|
precious.write_text("someone else's data")
|
|
server = FrameServer(str(precious), FakeCapture(), 20)
|
|
with pytest.raises(OSError):
|
|
server.serve_forever()
|
|
assert precious.read_text() == "someone else's data"
|
|
|
|
|
|
def test_the_socket_path_is_created_and_removed_around_the_run(workdir, serve):
|
|
path = workdir / "nested" / "dir" / "s.sock"
|
|
with serve(str(path), FakeCapture(), fps=20):
|
|
assert path.is_socket()
|
|
assert not path.exists(), "the socket file outlived the server"
|
|
|
|
|
|
def test_stop_releases_the_client_threads(sock_path, serve):
|
|
with serve(sock_path, FakeCapture(frames=distinct_frames(5)), fps=30) as server:
|
|
conn = connect(sock_path)
|
|
stream = conn.makefile("rb")
|
|
protocol.read_hello(stream)
|
|
assert protocol.read_frame(stream)
|
|
server.stop()
|
|
deadline = time.monotonic() + 5
|
|
while time.monotonic() < deadline:
|
|
if not any(t.name.startswith("hhstream-client") and t.is_alive()
|
|
for t in threading.enumerate()):
|
|
break
|
|
time.sleep(0.05)
|
|
else:
|
|
pytest.fail("a client thread outlived stop()")
|
|
conn.close()
|
|
|
|
|
|
def test_stopping_twice_does_not_delete_a_restarts_socket(sock_path, serve):
|
|
"""A second stop() after a restart must not take the new server's socket."""
|
|
first = FrameServer(sock_path, FakeCapture(), 20)
|
|
thread = threading.Thread(target=first.serve_forever, daemon=True)
|
|
thread.start()
|
|
assert first.ready.wait(5)
|
|
first.stop()
|
|
thread.join(5)
|
|
assert not os.path.exists(sock_path)
|
|
|
|
with serve(sock_path, FakeCapture(), fps=20): # the "restart"
|
|
first.stop() # a late, duplicate stop from the old instance
|
|
assert os.path.exists(sock_path), "the restart's socket was removed"
|
|
conn = connect(sock_path)
|
|
assert protocol.read_hello(conn.makefile("rb"))["magic"] == "HHS1"
|
|
conn.close()
|