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
This commit is contained in:
HermenixandClaude Opus 5 committed 2026-10-06 16:20:00 +00:00
1 parent a9299682d2
commit bd3ca2e644
2 files changed
+157 -23

No files matched your search

+80 -21
View File
@@ -17,12 +17,16 @@ 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.
@@ -53,13 +57,27 @@ def parse_stream(arg: str) -> tuple[str, str]:
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__)
parser.add_argument("--log-level", default="info",
choices=["debug", "info", "warning", "error"])
_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,
@@ -76,11 +94,36 @@ def build_parser() -> argparse.ArgumentParser:
"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
@@ -97,42 +140,58 @@ def cmd_serve(args: argparse.Namespace) -> int:
registry = make_registry(args.stream, capture_base, args.fps)
server = LiveServer(registry, host=args.bind, port=args.port)
print(f"landing page: http://{server.address}:{args.port}/", file=sys.stderr)
if not args.stream:
print("no --stream given; only the landing page will answer", file=sys.stderr)
server.start() # raises OSError loudly if the port is taken
for phrase in registry.phrases():
print(server.url_for(phrase))
sys.stdout.flush()
# 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:
import time
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)")
while True:
time.sleep(3600)
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:
parser = build_parser()
args = parser.parse_args(argv)
args = parse_args(argv)
logging.basicConfig(
level=getattr(logging, (args.log_level or "info").upper()),
level=getattr(logging, (getattr(args, "log_level", None) or "info").upper()),
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
command = args.command or "serve"
if command == "phrase":
if args.command == "phrase":
for _ in range(args.count):
print(phrase_mod.generate())
return 0
if command == "serve":
return cmd_serve(args)
parser.error(f"unknown command {command!r}") # pragma: no cover
return 2
return cmd_serve(args)
if __name__ == "__main__":