Files
hyprland-headless-stream-pl…/src/hhstream_live/__main__.py
T
HermenixandClaude Opus 5 bd3ca2e644 fix(live): hhstream-live with no subcommand serves, and SIGTERM stops it
`cmd_serve` read `args.capture_command`, which only exists on the `serve`
subparser, so a bare `hhstream-live` died with an `AttributeError`. The word
`serve` is now inserted before parsing rather than defaulted afterwards: the
top-level parser would otherwise reject `hhstream-live --port 9999` for an
unknown option before anything could be filled in. `--help` is left alone so
it still shows the program's own help. `--log-level` gained a copy on each
subparser, defaulting to `SUPPRESS` so that naming the subcommand does not
reset it.

SIGTERM had no handler, so the default action killed the process and
`server.stop()` never ran -- the exit status was a signal, not a 0. The
handler is installed before the listener is bound, so a supervisor's first
signal is never the fatal one.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01URhyHGQnmKH9zBXxoznfQY
2026-10-06 16:20:00 +00:00

199 lines
8.2 KiB
Python

"""``hhstream-live`` -- run the session-stream web app.
Stage 1 runs it **standalone**: the streams are named on the command line as
``--stream <phrase>=<output>``, which is enough to watch a real container and to
drive the unit tests. Stage 2 adds the broker's control socket
(``/run/hhstream/live.sock``), at which point ``--stream`` becomes the way a
human debugs it rather than the way the broker configures it.
hhstream-live serve --stream four-words-and-a-tail=hh-demo
hhstream-live phrase
The capture command is one list of words; the output is aimed by inserting
``-o <output>`` before the trailing ``-``, which is grim's "write to stdout".
"""
from __future__ import annotations
import argparse
import logging
import signal
import sys
import threading
from . import phrase as phrase_mod
from .publisher import DEFAULT_FPS, FPS_CAP, StreamRegistry, StreamSpec
from .server import DEFAULT_HOST, DEFAULT_PORT, LiveServer
log = logging.getLogger("hhstream.live")
#: The session's own capture command, JPEG for the same reason the host config
#: spells it out: a 1280x720 JPEG q80 is ~46 ms and the point is a video, not a
#: slideshow. `-c` asks grim to include the cursor.
DEFAULT_CAPTURE = ["grim", "-c", "-t", "jpeg", "-q", "80", "-"]
def capture_argv(base: list[str], output: str) -> list[str]:
"""Aim the base capture command at one output.
``grim`` writes to stdout when its last argument is ``-``; the output
selector goes just before it so the shape holds for any tool that keeps that
convention, and a base without a trailing ``-`` simply gets ``-o`` appended.
"""
base = list(base)
if base and base[-1] == "-":
return base[:-1] + ["-o", output, "-"]
return base + ["-o", output]
def parse_stream(arg: str) -> tuple[str, str]:
"""``<phrase>=<output>`` -> the pair, each side checked non-empty."""
phrase, sep, output = arg.partition("=")
if not sep or not phrase.strip() or not output.strip():
raise argparse.ArgumentTypeError(f"expected PHRASE=OUTPUT, got {arg!r}")
try:
return phrase_mod.validate(phrase), output.strip()
except ValueError as exc:
raise argparse.ArgumentTypeError(str(exc)) from exc
def _add_log_level(parser: argparse.ArgumentParser, default: str) -> None:
"""Put `--log-level` on a parser.
It is a global option, but it has to exist on the subparsers too: with no
subcommand the whole line is parsed as `serve ...`, and `serve` is then the
parser that sees it. `SUPPRESS` as the subparser default is what stops
`hhstream-live --log-level debug serve` from being reset to `info` -- a
subparser argument that defaults to `SUPPRESS` and is not supplied leaves
the namespace alone.
"""
parser.add_argument("--log-level", default=default,
choices=["debug", "info", "warning", "error"])
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(prog="hhstream-live", description=__doc__)
_add_log_level(parser, "info")
subs = parser.add_subparsers(dest="command")
serve = subs.add_parser("serve", help="run the web app (default)")
_add_log_level(serve, argparse.SUPPRESS)
serve.add_argument("--port", type=int, default=DEFAULT_PORT,
help=f"the one port every stream shares (default {DEFAULT_PORT})")
serve.add_argument("--bind", default=DEFAULT_HOST,
help=f"address to bind (default {DEFAULT_HOST}, loopback)")
serve.add_argument("--fps", type=int, default=DEFAULT_FPS,
help=f"capture rate for streams that do not set one "
f"(default {DEFAULT_FPS}, cap {FPS_CAP})")
serve.add_argument("--stream", action="append", default=[], type=parse_stream,
metavar="PHRASE=OUTPUT",
help="enable a stream on this output; repeatable")
serve.add_argument("--capture-command", action="append", default=None,
metavar="WORD",
help="capture argv word; repeat (a repeated flag is the "
"only shape that survives words starting with '-')")
gen = subs.add_parser("phrase", help="print a fresh phrase and exit")
_add_log_level(gen, argparse.SUPPRESS)
gen.add_argument("--count", type=int, default=1)
return parser
#: The subcommands, named here because the default one is chosen before the
#: parser runs. See `parse_args`.
COMMANDS = ("serve", "phrase")
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
"""Parse the command line, defaulting to `serve`.
`serve` is the default, and its options live on its own subparser, so the
word has to be *inserted* rather than filled in afterwards: a namespace from
the top-level parser has no `capture_command`, no `port` and no `stream`, and
`cmd_serve` would die on the first attribute it read. Inserting it has to
happen before parsing, too -- `hhstream-live --port 9999` would otherwise be
rejected for an unknown `--port` before anything could be defaulted.
`--help` is left alone so that a bare `hhstream-live --help` still shows the
program's own help rather than `serve`'s.
"""
raw = list(sys.argv[1:] if argv is None else argv)
if not any(word in COMMANDS or word in ("-h", "--help") for word in raw):
raw = ["serve", *raw]
return build_parser().parse_args(raw)
def make_registry(streams: list[tuple[str, str]], capture_base: list[str],
fps: int) -> StreamRegistry:
from hhstream.capture import CommandCapture
registry = StreamRegistry()
for phrase, output in streams:
spec = StreamSpec(phrase=phrase, output=output, fps=fps, label=output)
registry.add(spec, CommandCapture(capture_argv(capture_base, output)))
return registry
def cmd_serve(args: argparse.Namespace) -> int:
capture_base = args.capture_command or DEFAULT_CAPTURE
registry = make_registry(args.stream, capture_base, args.fps)
server = LiveServer(registry, host=args.bind, port=args.port)
# A service is stopped with SIGTERM, not with Ctrl-C: without a handler the
# default action kills the process outright and `server.stop` never runs, so
# the listener and the capture threads go down with no ordering at all.
# Installed *before* the listener exists, so there is no window in which a
# supervisor's very first signal is the fatal one.
stopping = threading.Event()
previous = None
def _request_stop(signum, frame) -> None: # noqa: ARG001 - handler signature
stopping.set()
try:
previous = signal.signal(signal.SIGTERM, _request_stop)
except ValueError:
# Not the main thread: an embedder's problem to solve, not ours.
log.debug("SIGTERM handler not installed (not the main thread)")
try:
server.start() # raises OSError loudly if the port is taken
# Printed after `start`, because a requested port of 0 only has an answer
# once it is bound. `describe_bind` names the real bind, so `0.0.0.0` is
# not reported as loopback just because that is the address you click.
print(server.describe_bind(), file=sys.stderr)
print(f"landing page: http://{server.address}:{server.port}/", file=sys.stderr)
if not args.stream:
print("no --stream given; only the landing page will answer",
file=sys.stderr)
for phrase in registry.phrases():
print(server.url_for(phrase))
sys.stdout.flush()
stopping.wait()
print("stopping", file=sys.stderr)
except KeyboardInterrupt:
print("stopping", file=sys.stderr)
finally:
if previous is not None:
signal.signal(signal.SIGTERM, previous)
server.stop()
return 0
def main(argv: list[str] | None = None) -> int:
args = parse_args(argv)
logging.basicConfig(
level=getattr(logging, (getattr(args, "log_level", None) or "info").upper()),
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
if args.command == "phrase":
for _ in range(args.count):
print(phrase_mod.generate())
return 0
return cmd_serve(args)
if __name__ == "__main__":
sys.exit(main())