The failure cap read `consecutive_failures >= FAILURE_LIMIT and captured == 0`, so it could only ever fire on a cold start. An output removed while someone was watching -- grim answering "unknown output" to every grab from then on -- kept the loop retrying twice a second for as long as the viewer held the page open. That is the busy loop the cap exists to stop, so the count is now of failures in a row and nothing else. Giving up stays sticky: a removed output does not come back, and re-enabling the session is how it returns. While here, the capture thread is named for its output and the give-up is logged by output. The phrase is the stream's only credential, and faulthandler, `threading.excepthook` and any sampling profiler all print thread names. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01URhyHGQnmKH9zBXxoznfQY
93 lines
3.2 KiB
Python
93 lines
3.2 KiB
Python
"""Shared doubles for the session-stream web app suite.
|
|
|
|
Kept out of `conftest.py` on purpose: the rest of the suite imports its doubles
|
|
from a plain module (`tests/unit/helpers.py`), and `import conftest` by name is
|
|
fragile across directories.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import pathlib
|
|
import sys
|
|
import threading
|
|
import time
|
|
|
|
_HERE = pathlib.Path(__file__).resolve().parent
|
|
_SRC = _HERE.parents[1] / "src"
|
|
for _path in (str(_HERE), str(_SRC)):
|
|
if _path not in sys.path:
|
|
sys.path.insert(0, _path)
|
|
|
|
from fake_jpeg import jpeg_bytes # noqa: E402
|
|
|
|
#: The one phrase the suite enables. Shape matters, not the words.
|
|
PHRASE = "amber-otter-lantern-harbor-7k2qp"
|
|
|
|
|
|
class StubCapture:
|
|
"""A `Capture` under the test's control: counts grabs, can be told to fail.
|
|
|
|
`fail_first` is a capture that is broken from the start (a cold start that
|
|
never works); `fail_after` is one that works and then stops -- the output
|
|
was removed while someone was watching, which is grim's "unknown output" on
|
|
every grab from then on.
|
|
"""
|
|
|
|
def __init__(self, frames=None, fail_first: int = 0, delay: float = 0.0,
|
|
fail_after: int | None = None):
|
|
self.frames = list(frames) if frames else [jpeg_bytes(i) for i in range(1, 50)]
|
|
self.fail_first = fail_first
|
|
self.fail_after = fail_after
|
|
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_first:
|
|
raise RuntimeError(f"stub capture failing on purpose (call {call})")
|
|
if self.fail_after is not None and call > self.fail_after:
|
|
raise RuntimeError(f"stub capture: unknown output (call {call})")
|
|
return self.frames[(call - 1 - self.fail_first) % len(self.frames)]
|
|
|
|
|
|
def read_parts(resp, count: int, timeout: float = 10.0) -> list[bytes]:
|
|
"""Read up to `count` JPEG parts out of a multipart MJPEG response."""
|
|
from hhstream_live.server import BOUNDARY
|
|
|
|
boundary = ("--" + BOUNDARY).encode("ascii")
|
|
parts: list[bytes] = []
|
|
buf = b""
|
|
deadline = time.monotonic() + timeout
|
|
while len(parts) < count and time.monotonic() < deadline:
|
|
chunk = resp.read(4096)
|
|
if not chunk:
|
|
break
|
|
buf += chunk
|
|
while True:
|
|
start = buf.find(boundary)
|
|
if start < 0:
|
|
break
|
|
header_end = buf.find(b"\r\n\r\n", start)
|
|
if header_end < 0:
|
|
break
|
|
header = buf[start:header_end].decode("latin-1")
|
|
length = None
|
|
for line in header.splitlines():
|
|
if line.lower().startswith("content-length:"):
|
|
length = int(line.split(":", 1)[1].strip())
|
|
if length is None:
|
|
break
|
|
body_start = header_end + 4
|
|
if len(buf) < body_start + length:
|
|
break
|
|
parts.append(buf[body_start:body_start + length])
|
|
buf = buf[body_start + length + 2:]
|
|
if len(parts) >= count:
|
|
break
|
|
return parts[:count]
|