Three layers, because the stream has three and each one can be wrong on its own. `tests/live/test_live_control.py` (20 tests) runs `Control` against a fake capture: the four ops, `attach` idempotent on the phrase, the same phrase aimed at another output refused, a malformed phrase refused *without the value in the message*, and `fps` defaulting to the daemon's when the broker sends none. `tests/sessions/unit/test_stream_verbs.py` (24 tests) runs the broker against a fake daemon, and its subjects are the decisions rather than the plumbing: no container output is a refusal and never a fallback to the main output; a re-`enable` returns the same phrase and a different one is exit 8; a down daemon turns `attached` false rather than failing a read; the sweep touches a watched session and leaves an unwatched one alone; teardown detaches before the container is destroyed. `tests/unit/test_mcp_*` grow the two tools, the two resources and the three `session_start` arguments, with the read-only half asserted *absent* as a tool by name -- re-adding one should be a failure, not a silent widening. `checks/vm-stream.nix` is the new guest check, and it exists for the two things none of the above can say: 1. **That `grim` captures a real compositor from inside a unit.** It reads actual JPEGs off `/<phrase>/stream.mjpg` with `checks/lib/mjpeg_read.py`, a hand-rolled multipart reader that shares no code with the server -- a parser that did could not tell you the boundary was wrong. It framed on SOI/EOI rather than `Content-Length` for the same reason. This is what caught the unit's missing `XDG_RUNTIME_DIR`: `frames: [25827, 25827, 25827]` now, ten capture failures and a stream that gave up before. 2. **That a connected viewer moves the idle clock.** That needs the broker's real sweep, on a real timer, with a client genuinely still there a minute later -- hence `--hold`, and hence a check that spends ~90 seconds twice. The negative control runs first, because if the sweep touched an unwatched stream the positive case would pass for the wrong reason. Measured in the guest: with nobody watching `580s -> 502s` remaining, with a viewer `499s -> 596s`. It also asserts the phrase is in neither the audit log nor a 404 body, that the old URL stops serving after `disable`, that `disable` then `enable` rotates it, that `kill` takes the stream down and leaves the daemon up, and that `start --stream` yields an id and a URL that serves frames. No clock is injected anywhere in this check. An injected one would prove the arithmetic, which the unit tests already do, and not the daemon. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011ZeH65zd6pFTgBSu52W9PE
149 lines
5.2 KiB
Python
Executable File
149 lines
5.2 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""``hhs-mjpeg-read`` -- read a real MJPEG stream, and optionally keep watching.
|
|
|
|
What `checks/vm-stream.nix` uses as the *person with a phone*. Two jobs, and the
|
|
second is the one that matters:
|
|
|
|
1. Read N frames off ``multipart/x-mixed-replace`` and report their sizes, so
|
|
"the stream works" is a statement about bytes a client actually received
|
|
rather than about a 200.
|
|
2. **Hold the connection open** for a while afterwards. The broker counts
|
|
connected viewers and treats one as activity, so proving that needs a viewer
|
|
that is still there a minute later -- a client that read three frames and
|
|
exited would make the sweep correct and untested.
|
|
|
|
Standard library only, and a hand-rolled multipart reader rather than anything
|
|
that understands HTTP for us: the framing is this repository's own
|
|
(`hhstream_live.server`), and a parser that shared code with it could not tell
|
|
you the boundary was wrong.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import json
|
|
import socket
|
|
import sys
|
|
import time
|
|
import urllib.parse
|
|
|
|
SOI = b"\xff\xd8"
|
|
EOI = b"\xff\xd9"
|
|
|
|
|
|
def connect(url: str, timeout: float) -> socket.socket:
|
|
parsed = urllib.parse.urlsplit(url)
|
|
host = parsed.hostname or "127.0.0.1"
|
|
port = parsed.port or 80
|
|
path = parsed.path or "/"
|
|
sock = socket.create_connection((host, port), timeout=timeout)
|
|
request = (
|
|
f"GET {path} HTTP/1.1\r\n"
|
|
f"Host: {host}:{port}\r\n"
|
|
"Accept: */*\r\n"
|
|
"Connection: close\r\n\r\n"
|
|
)
|
|
sock.sendall(request.encode("ascii"))
|
|
return sock
|
|
|
|
|
|
def read_headers(sock: socket.socket) -> tuple[int, dict[str, str], bytes]:
|
|
buffer = b""
|
|
while b"\r\n\r\n" not in buffer:
|
|
chunk = sock.recv(4096)
|
|
if not chunk:
|
|
raise SystemExit("the server closed the connection before any headers")
|
|
buffer += chunk
|
|
head, rest = buffer.split(b"\r\n\r\n", 1)
|
|
lines = head.decode("latin-1").split("\r\n")
|
|
status = int(lines[0].split()[1])
|
|
headers = {}
|
|
for line in lines[1:]:
|
|
if ":" in line:
|
|
name, _, value = line.partition(":")
|
|
headers[name.strip().lower()] = value.strip()
|
|
return status, headers, rest
|
|
|
|
|
|
def frames(sock: socket.socket, rest: bytes, wanted: int, deadline: float) -> list[int]:
|
|
"""Sizes of the JPEGs read off the multipart body, by SOI/EOI.
|
|
|
|
Framed on the markers rather than on ``Content-Length``: a stream that sent
|
|
the right lengths and the wrong bytes would pass a length-based reader, and
|
|
what the check is about is whether a browser would paint this.
|
|
"""
|
|
|
|
sizes: list[int] = []
|
|
buffer = rest
|
|
while len(sizes) < wanted:
|
|
if time.monotonic() > deadline:
|
|
raise SystemExit(
|
|
f"only {len(sizes)} of {wanted} frames arrived before the deadline"
|
|
)
|
|
start = buffer.find(SOI)
|
|
end = buffer.find(EOI, start + 2) if start != -1 else -1
|
|
if start != -1 and end != -1:
|
|
sizes.append(end + 2 - start)
|
|
buffer = buffer[end + 2 :]
|
|
continue
|
|
try:
|
|
chunk = sock.recv(65536)
|
|
except TimeoutError:
|
|
raise SystemExit("the stream went quiet") from None
|
|
if not chunk:
|
|
raise SystemExit("the stream ended before enough frames arrived")
|
|
buffer += chunk
|
|
return sizes
|
|
|
|
|
|
def main(argv: list[str] | None = None) -> int:
|
|
parser = argparse.ArgumentParser(prog="hhs-mjpeg-read", description=__doc__)
|
|
parser.add_argument("url", help="the stream.mjpg URL")
|
|
parser.add_argument("--frames", type=int, default=2, help="how many to read")
|
|
parser.add_argument(
|
|
"--hold",
|
|
type=float,
|
|
default=0.0,
|
|
metavar="SECONDS",
|
|
help="keep the connection open this long after reading, so the broker "
|
|
"counts a viewer for that whole time",
|
|
)
|
|
parser.add_argument("--timeout", type=float, default=30.0)
|
|
args = parser.parse_args(argv)
|
|
|
|
sock = connect(args.url, args.timeout)
|
|
sock.settimeout(args.timeout)
|
|
try:
|
|
status, headers, rest = read_headers(sock)
|
|
content_type = headers.get("content-type", "")
|
|
if status != 200:
|
|
print(json.dumps({"status": status}), flush=True)
|
|
raise SystemExit(f"the stream answered {status}, not 200")
|
|
if "multipart/x-mixed-replace" not in content_type:
|
|
raise SystemExit(f"content-type is {content_type!r}, not multipart")
|
|
sizes = frames(sock, rest, args.frames, time.monotonic() + args.timeout)
|
|
print(
|
|
json.dumps(
|
|
{"status": status, "content_type": content_type, "frames": sizes}
|
|
),
|
|
flush=True,
|
|
)
|
|
if args.hold > 0:
|
|
# Still connected, and still reading: a viewer that stopped reading
|
|
# would have its socket buffer fill and the server would see it go.
|
|
deadline = time.monotonic() + args.hold
|
|
while time.monotonic() < deadline:
|
|
try:
|
|
if not sock.recv(65536):
|
|
break
|
|
except TimeoutError:
|
|
continue
|
|
print(json.dumps({"held_for_s": args.hold}), flush=True)
|
|
finally:
|
|
sock.close()
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|