feat(live): live.sock, both ends
The socket CONTRACT-sessions.md §3.5 freezes, implemented on both sides and by nobody else: `hhstream_live.control` answers it, `hhstreamd.live` asks it. `control.Control` is the four ops and nothing more -- attach, detach, list, viewers -- with the decisions the daemon is allowed to make and no others. It owns the two things only this process knows: how to build a capture for an output (the capture command, from this unit's argv) and what a URL looks like (the bound port). Both are injected as callables by `__main__.control_server`, which is also why `attach` replies with a URL rather than letting the broker assemble one from a port it was told about once. `attach` is idempotent on the phrase and returns the existing stream, so a re-`enable` after a broker restart cannot double the `grim` rate on an output. The same phrase aimed at a *different* output is `invalid_argument`, because that is a mistake and not a request. Two details that are the point rather than polish: * `_phrase_of` holds a caller's phrase to the generated shape and raises a shape-only message, with `from None`. `phrase.validate` names the value it rejected, which is correct for a library and wrong here: this value is a password, and the refusal travels back over a socket and into a log. * `ControlServer.serve_forever` reads `self._sock` into a local before using it. `close()` runs on the main thread while this one is in `accept()`, and the attribute it was reading can be gone by the time it is dereferenced. `hhstreamd.live` is the broker's client: one op at a time behind a lock, a 2-second timeout, `LiveUnavailable` for "could not be reached or did not answer intelligibly" and `LiveRejected` carrying the `kind` the broker maps to an exit code -- the pointer driver's client, verb for verb, because the broker already knows how to hold one of those. `Attachment.parse` refuses a malformed reply rather than defaulting its way past one. `fps` is omitted from an `attach` unless a caller named one, which is what makes `sessions.stream.fps` on the daemon's unit authoritative instead of decorative. And `_safe()` renders a phrase as `<phrase:5 tokens>` for the one log line that mentions a stream at all: the shape, never the words. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011ZeH65zd6pFTgBSu52W9PE
This commit is contained in:
1 parent
0f2810afaa
commit
8c99518a62
3 files changed
+673
-3
No files matched your search
@@ -88,6 +88,13 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
serve.add_argument("--stream", action="append", default=[], type=parse_stream,
|
||||
metavar="PHRASE=OUTPUT",
|
||||
help="enable a stream on this output; repeatable")
|
||||
serve.add_argument(
|
||||
"--control-socket",
|
||||
metavar="PATH",
|
||||
help="serve the broker's control socket here (CONTRACT-sessions.md "
|
||||
"§3.5), so `hhstream session stream enable` can attach a stream. "
|
||||
"Omitted, the app is standalone and only --stream puts anything on it.",
|
||||
)
|
||||
serve.add_argument("--capture-command", action="append", default=None,
|
||||
metavar="WORD",
|
||||
help="capture argv word; repeat (a repeated flag is the "
|
||||
@@ -139,6 +146,7 @@ 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)
|
||||
control = control_server(args, registry, server, capture_base)
|
||||
|
||||
# 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
|
||||
@@ -159,14 +167,25 @@ def cmd_serve(args: argparse.Namespace) -> int:
|
||||
|
||||
try:
|
||||
server.start() # raises OSError loudly if the port is taken
|
||||
if control is not None:
|
||||
# After the listener, because `attach` replies with a URL and the
|
||||
# URL has no answer until the port is bound -- a requested port of
|
||||
# 0 least of all.
|
||||
control.listen()
|
||||
threading.Thread(
|
||||
target=control.serve_forever,
|
||||
name="hhstream-live.control",
|
||||
daemon=True,
|
||||
).start()
|
||||
print(f"control socket: {control.socket_path}", file=sys.stderr)
|
||||
# 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)
|
||||
if not args.stream and control is None:
|
||||
print("no --stream and no --control-socket; only the landing page "
|
||||
"will answer", file=sys.stderr)
|
||||
for phrase in registry.phrases():
|
||||
print(server.url_for(phrase))
|
||||
sys.stdout.flush()
|
||||
@@ -177,10 +196,43 @@ def cmd_serve(args: argparse.Namespace) -> int:
|
||||
finally:
|
||||
if previous is not None:
|
||||
signal.signal(signal.SIGTERM, previous)
|
||||
if control is not None:
|
||||
# Before the HTTP listener: the broker's next `attach` should fail
|
||||
# to connect rather than be accepted by a process on its way out.
|
||||
control.close()
|
||||
server.stop()
|
||||
return 0
|
||||
|
||||
|
||||
def control_server(
|
||||
args: argparse.Namespace,
|
||||
registry: StreamRegistry,
|
||||
server: LiveServer,
|
||||
capture_base: list[str],
|
||||
) -> "ControlServer | None":
|
||||
"""The broker's control socket, or ``None`` for a standalone run.
|
||||
|
||||
The two things only this process knows are injected here and nowhere else:
|
||||
how to build a capture for an output (the capture command, from this unit's
|
||||
argv) and how to name a URL (the bound port). That is the whole reason
|
||||
`attach` replies with a URL instead of letting the broker assemble one.
|
||||
"""
|
||||
|
||||
if not getattr(args, "control_socket", None):
|
||||
return None
|
||||
from .control import Control, ControlServer
|
||||
|
||||
from hhstream.capture import CommandCapture
|
||||
|
||||
control = Control(
|
||||
registry,
|
||||
capture_for=lambda output: CommandCapture(capture_argv(capture_base, output)),
|
||||
url_for=server.url_for,
|
||||
default_fps=args.fps,
|
||||
)
|
||||
return ControlServer(args.control_socket, control)
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
args = parse_args(argv)
|
||||
logging.basicConfig(
|
||||
|
||||
@@ -0,0 +1,317 @@
|
||||
"""``/run/hhstream/live.sock`` — the broker tells this process what to publish.
|
||||
|
||||
The daemon's end of `docs/CONTRACT-sessions.md` §3.5. Four ops (`attach`,
|
||||
`detach`, `list`, `viewers`) over newline-delimited JSON, in the shape the
|
||||
pointer driver's socket already uses, because a second convention for the same
|
||||
job would be a second thing to remember.
|
||||
|
||||
**This process decides nothing about sessions.** It does not know what an idle
|
||||
clock is, which application a session runs, or whether a stream *should* be on.
|
||||
It is told a phrase, an output and a rate, and it publishes. `viewers` is a
|
||||
counter read; what it means is the broker's business
|
||||
(`docs/CONTRACT-sessions.md` §4).
|
||||
|
||||
**It does own the port, the bind address and the capture command**, from its own
|
||||
unit's argv — which is why `attach` replies with the URL rather than letting the
|
||||
broker assemble one. A URL built from a port somebody was told about once is a
|
||||
URL that lies the first time the listener moves.
|
||||
|
||||
**`attach` is idempotent on the phrase.** The same phrase aimed at the same
|
||||
output returns the running stream instead of starting a second capture: the
|
||||
broker re-attaches after a restart, and doubling the ``grim`` rate on one output
|
||||
because of a reconnect would be a self-inflicted load problem. The same phrase
|
||||
aimed somewhere *else* is refused — a phrase is a credential for one view, and
|
||||
silently re-pointing it would show a person a desktop they were not given.
|
||||
|
||||
**The phrase is never logged**, here or in the broker. Every line below names
|
||||
the output and the session.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import socket
|
||||
import threading
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable
|
||||
|
||||
from . import phrase as phrase_mod
|
||||
from .publisher import DEFAULT_FPS, FPS_CAP, StreamRegistry, StreamSpec
|
||||
|
||||
log = logging.getLogger("hhstream.live.control")
|
||||
|
||||
#: Matches ``hhstreamd.protocol.MAX_LINE_BYTES`` and the pointer driver's.
|
||||
MAX_LINE_BYTES = 1 << 20
|
||||
LISTEN_BACKLOG = 8
|
||||
|
||||
#: A rejection the broker maps to exit 2 rather than exit 10 -- the caller's
|
||||
#: mistake, not a failure of this process. Same vocabulary as the driver's.
|
||||
INVALID = "invalid_argument"
|
||||
|
||||
|
||||
class Control:
|
||||
"""The op handler. Holds the registry and the two things only this process knows.
|
||||
|
||||
``capture_for`` turns an output name into a capture object, and ``url_for``
|
||||
turns a phrase into this listener's URL. Both are injected rather than
|
||||
built here so the tests can drive the whole protocol without a compositor
|
||||
and without binding a port.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
registry: StreamRegistry,
|
||||
*,
|
||||
capture_for: Callable[[str], Any],
|
||||
url_for: Callable[[str], str],
|
||||
default_fps: int = DEFAULT_FPS,
|
||||
) -> None:
|
||||
self.registry = registry
|
||||
self.capture_for = capture_for
|
||||
self.url_for = url_for
|
||||
#: The rate an `attach` with no `fps` gets. This process's, from its
|
||||
#: own argv, because it is the one that has to keep up with it -- and
|
||||
#: so an operator's `sessions.stream.fps` reaches every stream rather
|
||||
#: than only the ones somebody named a rate for.
|
||||
self.default_fps = int(default_fps)
|
||||
self._lock = threading.Lock()
|
||||
|
||||
# -- the ops ----------------------------------------------------------
|
||||
|
||||
def handle(self, request: Any) -> dict[str, Any]:
|
||||
if not isinstance(request, dict):
|
||||
return _no(f"request is not an object: {type(request).__name__}", INVALID)
|
||||
op = request.get("op")
|
||||
handler = {
|
||||
"attach": self._attach,
|
||||
"detach": self._detach,
|
||||
"list": self._list,
|
||||
"viewers": self._viewers,
|
||||
}.get(op if isinstance(op, str) else "")
|
||||
if handler is None:
|
||||
return _no(f"unknown op: {op!r}", INVALID)
|
||||
# One op at a time: `attach` reads the registry and then mutates it, and
|
||||
# two brokers (or a broker and a restart sweep) must not interleave
|
||||
# there and start two captures for one phrase.
|
||||
with self._lock:
|
||||
try:
|
||||
return handler(request)
|
||||
except Rejected as refused:
|
||||
return _no(str(refused), refused.kind)
|
||||
except (ValueError, TypeError) as exc:
|
||||
# The registry's own validation (`fps must be a positive int`,
|
||||
# `phrase ... is already enabled`) surfaces here. It is the
|
||||
# caller's mistake, so it is exit 2 and not a daemon failure.
|
||||
return _no(str(exc), INVALID)
|
||||
|
||||
def _attach(self, request: dict[str, Any]) -> dict[str, Any]:
|
||||
phrase = _phrase_of(request)
|
||||
output = _text(request, "output")
|
||||
fps = _fps(request, self.default_fps)
|
||||
session = request.get("session")
|
||||
session = None if session is None else str(session)
|
||||
label = str(request.get("label") or "")
|
||||
|
||||
existing = self.registry.get(phrase)
|
||||
if existing is not None:
|
||||
if existing.spec.output != output:
|
||||
raise Rejected(
|
||||
f"that phrase is already publishing output "
|
||||
f"{existing.spec.output!r}, not {output!r}; disable it first",
|
||||
INVALID,
|
||||
)
|
||||
# Idempotent: the running stream, with whatever rate it was started
|
||||
# at. A new `fps` is deliberately NOT applied here -- changing the
|
||||
# rate under a connected viewer is a `disable`/`enable`, which is
|
||||
# one record write and one obvious act, rather than a silent
|
||||
# re-rate that no log line would explain.
|
||||
log.info("re-attached output %s for %s", output, session or "a standalone stream")
|
||||
return {"ok": True, "stream": self._describe(existing)}
|
||||
|
||||
spec = StreamSpec(
|
||||
phrase=phrase, output=output, fps=fps, session=session, label=label or output
|
||||
)
|
||||
stream = self.registry.add(spec, self.capture_for(output))
|
||||
log.info(
|
||||
"attached output %s for %s at %s fps",
|
||||
output,
|
||||
session or "a standalone stream",
|
||||
fps,
|
||||
)
|
||||
return {"ok": True, "stream": self._describe(stream)}
|
||||
|
||||
def _detach(self, request: dict[str, Any]) -> dict[str, Any]:
|
||||
phrase = _phrase_of(request)
|
||||
stream = self.registry.remove(phrase)
|
||||
if stream is None:
|
||||
# Not an error. `disable` on a session whose daemon restarted since
|
||||
# `enable` is the ordinary case, and the broker has to clear its
|
||||
# record either way.
|
||||
return {"ok": True, "detached": False}
|
||||
log.info(
|
||||
"detached output %s for %s",
|
||||
stream.spec.output,
|
||||
stream.spec.session or "a standalone stream",
|
||||
)
|
||||
return {"ok": True, "detached": True}
|
||||
|
||||
def _list(self, request: dict[str, Any]) -> dict[str, Any]:
|
||||
return {"ok": True, "streams": [self._describe(s) for s in self.registry.all()]}
|
||||
|
||||
def _viewers(self, request: dict[str, Any]) -> dict[str, Any]:
|
||||
return {
|
||||
"ok": True,
|
||||
# `Stream.viewers` is a property, not a method.
|
||||
"viewers": {s.spec.phrase: s.viewers for s in self.registry.all()},
|
||||
}
|
||||
|
||||
def _describe(self, stream: Any) -> dict[str, Any]:
|
||||
public = dict(stream.spec.public())
|
||||
public["url"] = self.url_for(stream.spec.phrase)
|
||||
public["viewers"] = stream.viewers
|
||||
return public
|
||||
|
||||
|
||||
class Rejected(Exception):
|
||||
"""A refusal with a ``kind`` the broker maps to an exit code."""
|
||||
|
||||
def __init__(self, message: str, kind: str | None = None) -> None:
|
||||
super().__init__(message)
|
||||
self.kind = kind
|
||||
|
||||
|
||||
def _no(error: str, kind: str | None = None) -> dict[str, Any]:
|
||||
reply: dict[str, Any] = {"ok": False, "error": error}
|
||||
if kind:
|
||||
reply["kind"] = kind
|
||||
return reply
|
||||
|
||||
|
||||
def _text(request: dict[str, Any], field: str) -> str:
|
||||
value = request.get(field)
|
||||
if not isinstance(value, str) or not value.strip():
|
||||
raise Rejected(f"{field} must be a non-empty string", INVALID)
|
||||
return value.strip()
|
||||
|
||||
|
||||
def _phrase_of(request: dict[str, Any]) -> str:
|
||||
"""The request's phrase, held to the generated shape.
|
||||
|
||||
``phrase.validate`` and not a looser check, for the reason it exists: the
|
||||
phrase is this stream's only credential, so anything that reaches the
|
||||
registry has to be a password rather than ``a-b-c``. The refusal never
|
||||
echoes the phrase back.
|
||||
"""
|
||||
|
||||
value = request.get("phrase")
|
||||
if not isinstance(value, str):
|
||||
raise Rejected("phrase must be a string", INVALID)
|
||||
try:
|
||||
return phrase_mod.validate(value)
|
||||
except ValueError:
|
||||
# Not `{exc}`: the validator names the value it refused, and this
|
||||
# message travels back over the socket into the broker's log. The
|
||||
# shape, never the phrase.
|
||||
raise Rejected(
|
||||
"the phrase given is not of the expected shape: four words of at "
|
||||
"least three letters plus a five-character tail",
|
||||
INVALID,
|
||||
) from None
|
||||
|
||||
|
||||
def _fps(request: dict[str, Any], default: int) -> int:
|
||||
value = request.get("fps")
|
||||
if value is None:
|
||||
return default
|
||||
if isinstance(value, bool) or not isinstance(value, int):
|
||||
raise Rejected(f"fps must be an int, got {type(value).__name__}", INVALID)
|
||||
if value <= 0 or value > FPS_CAP:
|
||||
raise Rejected(f"fps must be between 1 and {FPS_CAP}, got {value}", INVALID)
|
||||
return value
|
||||
|
||||
|
||||
class ControlServer:
|
||||
"""The accept loop for ``live.sock``. One connection at a time.
|
||||
|
||||
The same shape as ``hhstream_pointer.server.PointerServer``: the broker is
|
||||
the only peer, the ops are one small line each, and an async server would
|
||||
buy nothing but a way to interleave two attaches.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
socket_path: Path | str,
|
||||
control: Control,
|
||||
*,
|
||||
socket_mode: int = 0o660,
|
||||
) -> None:
|
||||
self.socket_path = Path(socket_path)
|
||||
self.control = control
|
||||
self.socket_mode = socket_mode
|
||||
self._sock: socket.socket | None = None
|
||||
self.ready = threading.Event()
|
||||
|
||||
def listen(self) -> None:
|
||||
"""Bind and listen. A stale socket file is replaced, not refused:
|
||||
a crashed daemon leaves one behind and the unit must still start."""
|
||||
|
||||
self.socket_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
if self.socket_path.is_socket():
|
||||
self.socket_path.unlink()
|
||||
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
sock.bind(str(self.socket_path))
|
||||
os.chmod(self.socket_path, self.socket_mode)
|
||||
sock.listen(LISTEN_BACKLOG)
|
||||
self._sock = sock
|
||||
self.ready.set()
|
||||
log.info("control socket listening on %s", self.socket_path)
|
||||
|
||||
def serve_forever(self) -> None:
|
||||
assert self._sock is not None, "listen() first"
|
||||
while True:
|
||||
# Read into a local first. `close()` runs on another thread and
|
||||
# sets `_sock` to None, so reading the attribute twice can find a
|
||||
# socket and then find nothing -- measured, as an AttributeError
|
||||
# out of a daemon thread at shutdown rather than the clean return
|
||||
# this loop is supposed to make.
|
||||
sock = self._sock
|
||||
if sock is None:
|
||||
return
|
||||
try:
|
||||
conn, _ = sock.accept()
|
||||
except OSError:
|
||||
# The other way `close()` shows up: the listener was closed
|
||||
# while this thread was blocked in `accept`.
|
||||
return
|
||||
with conn:
|
||||
self._serve_connection(conn)
|
||||
|
||||
def close(self) -> None:
|
||||
sock, self._sock = self._sock, None
|
||||
if sock is not None:
|
||||
sock.close()
|
||||
self.socket_path.unlink(missing_ok=True)
|
||||
self.ready.clear()
|
||||
|
||||
def _serve_connection(self, conn: socket.socket) -> None:
|
||||
with conn.makefile("rwb") as stream:
|
||||
while True:
|
||||
line = stream.readline(MAX_LINE_BYTES + 1)
|
||||
if not line:
|
||||
return
|
||||
if len(line) > MAX_LINE_BYTES:
|
||||
_write(stream, _no("request line too long", INVALID))
|
||||
return
|
||||
try:
|
||||
request = json.loads(line)
|
||||
except json.JSONDecodeError as exc:
|
||||
_write(stream, _no(f"malformed JSON: {exc}", INVALID))
|
||||
continue
|
||||
_write(stream, self.control.handle(request))
|
||||
|
||||
|
||||
def _write(stream, response: dict[str, Any]) -> None:
|
||||
stream.write(json.dumps(response, separators=(",", ":")).encode() + b"\n")
|
||||
stream.flush()
|
||||
@@ -0,0 +1,301 @@
|
||||
"""The broker's end of the stream daemon's socket (CONTRACT-sessions.md §3.5).
|
||||
|
||||
`hhstream-live` is a third executor beside the pointer driver, and this module
|
||||
is the client that talks to it. The split is the driver's, for the driver's
|
||||
reasons: ``grim`` blocks tens to hundreds of milliseconds, so the capture must
|
||||
not run where ``touch`` and ``kill`` are answered, and a LAN-facing HTTP parser
|
||||
must not run in the frame server whose one-socket contract cannot grow one.
|
||||
|
||||
**The broker holds the decision; the daemon holds the capture.** Which session
|
||||
streams, and under which phrase, is the broker's — it is in the session record
|
||||
and it survives a restart. The port, the bind address, the capture command and
|
||||
the URL prefix are the daemon's, from its own unit's argv. So nothing here
|
||||
passes a port and nothing here builds a URL: :attr:`Attachment.url` comes back
|
||||
from the daemon, because a URL assembled from a port the broker was told about
|
||||
once is a URL that lies the first time an operator moves the listener.
|
||||
|
||||
**The phrase is never logged.** It is the stream's only credential, in
|
||||
cleartext in a URL on whatever the bind allows. Every log line here names the
|
||||
output and the session; `_safe` is what keeps a phrase out of the ones that
|
||||
would otherwise carry it.
|
||||
|
||||
Transport, lifetime and failure semantics are :mod:`hhstreamd.driver`'s, down to
|
||||
the held connection and the EOF check before each write. One difference in
|
||||
what a failure *means*: a dropped `release_all` leaves a key down in the
|
||||
compositor, which is why the driver never retries; a dropped `attach` leaves
|
||||
nothing behind but an unattached phrase, so `attach` is **idempotent on the
|
||||
daemon's side** and re-sending it is safe. That is the daemon's guarantee, not
|
||||
this module's, and it is what makes re-enabling after a restart cheap.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import dataclasses
|
||||
import json
|
||||
import logging
|
||||
import select
|
||||
import socket
|
||||
import threading
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
log = logging.getLogger("hhstreamd.live")
|
||||
|
||||
#: The daemon answers from memory for every op here -- it does not capture a
|
||||
#: frame to answer `attach`, and `viewers` is a counter read. This only bounds
|
||||
#: a daemon that has stopped answering at all.
|
||||
DEFAULT_TIMEOUT_S = 2.0
|
||||
|
||||
#: Matches the daemon's own ceiling.
|
||||
MAX_LINE_BYTES = 1 << 20
|
||||
|
||||
|
||||
class LiveUnavailable(Exception):
|
||||
"""The daemon could not be reached, or did not answer intelligibly.
|
||||
|
||||
Distinct from :class:`LiveRejected`: this one means nothing is known about
|
||||
whether the stream is attached, so the caller reports a *degraded* stream
|
||||
rather than an absent one. The session is unaffected either way -- a
|
||||
stream that cannot be reached is a stream, not a dead application -- which
|
||||
is why the manager maps this to exit 10 and never to a session failure.
|
||||
"""
|
||||
|
||||
|
||||
class LiveRejected(Exception):
|
||||
"""The daemon refused. ``kind`` decides the exit code, as the driver's does."""
|
||||
|
||||
def __init__(self, message: str, *, kind: str | None = None) -> None:
|
||||
super().__init__(message)
|
||||
self.kind = kind
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Attachment:
|
||||
"""One stream, as the daemon reports it."""
|
||||
|
||||
phrase: str
|
||||
output: str
|
||||
fps: int
|
||||
session: str | None
|
||||
#: The daemon's own prefix, e.g. ``http://127.0.0.1:9988/<phrase>/``.
|
||||
url: str
|
||||
viewers: int
|
||||
|
||||
@classmethod
|
||||
def parse(cls, data: Any) -> "Attachment":
|
||||
if not isinstance(data, dict):
|
||||
raise ValueError(f"stream is not an object: {type(data).__name__}")
|
||||
try:
|
||||
return cls(
|
||||
phrase=str(data["phrase"]),
|
||||
output=str(data["output"]),
|
||||
fps=int(data["fps"]),
|
||||
session=None if data.get("session") is None else str(data["session"]),
|
||||
url=str(data.get("url") or ""),
|
||||
viewers=int(data.get("viewers") or 0),
|
||||
)
|
||||
except (KeyError, TypeError, ValueError) as exc:
|
||||
raise ValueError(f"malformed stream in the daemon's reply: {exc}") from exc
|
||||
|
||||
|
||||
def _safe(phrase: str) -> str:
|
||||
"""A phrase, for a log line. The shape, never the words.
|
||||
|
||||
``amber-otter-lantern-harbor-7k2qp`` becomes ``<phrase:5 tokens>``. A log
|
||||
is read by whoever can read logs, and this one is a password.
|
||||
"""
|
||||
|
||||
return f"<phrase:{len(phrase.split('-'))} tokens>"
|
||||
|
||||
|
||||
class LiveStreams:
|
||||
"""A client for one stream daemon's socket. Thread-safe; one op at a time."""
|
||||
|
||||
def __init__(self, socket_path: Path | str, *, timeout_s: float = DEFAULT_TIMEOUT_S) -> None:
|
||||
self.socket_path = Path(socket_path)
|
||||
self.timeout_s = float(timeout_s)
|
||||
self._lock = threading.Lock()
|
||||
self._sock: socket.socket | None = None
|
||||
self._stream = None
|
||||
|
||||
# -- the ops ----------------------------------------------------------
|
||||
|
||||
def attach(
|
||||
self,
|
||||
*,
|
||||
phrase: str,
|
||||
output: str,
|
||||
fps: int | None = None,
|
||||
session: str | None = None,
|
||||
label: str = "",
|
||||
) -> Attachment:
|
||||
"""Publish ``output`` under ``phrase``. Idempotent on the phrase.
|
||||
|
||||
The daemon returns the existing stream if the same phrase is already
|
||||
aimed at the same output, rather than starting a second capture: a
|
||||
re-enable after a broker restart must not double the ``grim`` rate on
|
||||
one output. The same phrase aimed somewhere else is a rejection.
|
||||
|
||||
``fps`` is **omitted** when nobody asked for one, and that is the point:
|
||||
the default rate is the daemon's, from its own unit's argv, for the same
|
||||
reason the port is. A broker that sent its own default on every attach
|
||||
would make the operator's ``sessions.stream.fps`` a setting that changed
|
||||
nothing -- which is exactly the failure the keyboard layout's
|
||||
``--xkb-layout`` comment in this tree is about.
|
||||
"""
|
||||
|
||||
request: dict[str, Any] = {
|
||||
"op": "attach",
|
||||
"phrase": phrase,
|
||||
"output": output,
|
||||
"session": session,
|
||||
"label": label,
|
||||
}
|
||||
if fps is not None:
|
||||
request["fps"] = int(fps)
|
||||
reply = self.request(request)
|
||||
attachment = Attachment.parse(reply.get("stream"))
|
||||
log.info(
|
||||
"attached %s to output %s at %s fps (%s)",
|
||||
session or "a standalone stream",
|
||||
output,
|
||||
attachment.fps,
|
||||
_safe(phrase),
|
||||
)
|
||||
return attachment
|
||||
|
||||
def detach(self, phrase: str) -> bool:
|
||||
"""Stop publishing ``phrase``. ``False`` if it was not attached.
|
||||
|
||||
Not an error: ``disable`` on a session whose daemon restarted since
|
||||
``enable`` is the ordinary case, and the caller's job is to clear the
|
||||
record either way.
|
||||
"""
|
||||
|
||||
reply = self.request({"op": "detach", "phrase": phrase})
|
||||
return bool(reply.get("detached"))
|
||||
|
||||
def list(self) -> list[Attachment]:
|
||||
"""Every stream the daemon is publishing, in its own order."""
|
||||
|
||||
reply = self.request({"op": "list"})
|
||||
streams = reply.get("streams")
|
||||
if not isinstance(streams, list):
|
||||
raise LiveUnavailable(
|
||||
f"stream daemon {self.socket_path}: `list` returned "
|
||||
f"{type(streams).__name__}, not a list"
|
||||
)
|
||||
try:
|
||||
return [Attachment.parse(entry) for entry in streams]
|
||||
except ValueError as exc:
|
||||
raise LiveUnavailable(f"stream daemon {self.socket_path}: {exc}") from exc
|
||||
|
||||
def viewers(self) -> dict[str, int]:
|
||||
"""Phrase to connected viewers, for the activity sweep (§4).
|
||||
|
||||
A reading, and nothing more: what it means for the idle clock is the
|
||||
manager's, and this module deliberately has no opinion about it.
|
||||
"""
|
||||
|
||||
reply = self.request({"op": "viewers"})
|
||||
counts = reply.get("viewers")
|
||||
if not isinstance(counts, dict):
|
||||
raise LiveUnavailable(
|
||||
f"stream daemon {self.socket_path}: `viewers` returned "
|
||||
f"{type(counts).__name__}, not an object"
|
||||
)
|
||||
read: dict[str, int] = {}
|
||||
for phrase, count in counts.items():
|
||||
try:
|
||||
read[str(phrase)] = int(count)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise LiveUnavailable(
|
||||
f"stream daemon {self.socket_path}: viewer count for "
|
||||
f"{_safe(str(phrase))} is not a number: {exc}"
|
||||
) from exc
|
||||
return read
|
||||
|
||||
# -- transport --------------------------------------------------------
|
||||
|
||||
def request(self, message: dict[str, Any]) -> dict[str, Any]:
|
||||
"""One request, one reply. Raises rather than returning a guess."""
|
||||
|
||||
with self._lock:
|
||||
try:
|
||||
return self._exchange(message)
|
||||
except (OSError, ValueError) as exc:
|
||||
# The connection is now of unknown state -- a half-written
|
||||
# request, a partial reply -- so it is dropped rather than
|
||||
# reused for the next op.
|
||||
self._disconnect()
|
||||
raise LiveUnavailable(f"stream daemon {self.socket_path}: {exc}") from exc
|
||||
|
||||
def close(self) -> None:
|
||||
with self._lock:
|
||||
self._disconnect()
|
||||
|
||||
def _exchange(self, message: dict[str, Any]) -> dict[str, Any]:
|
||||
stream = self._connect()
|
||||
line = json.dumps(message, separators=(",", ":")).encode("utf-8") + b"\n"
|
||||
stream.write(line)
|
||||
stream.flush()
|
||||
reply_line = stream.readline(MAX_LINE_BYTES + 1)
|
||||
if not reply_line:
|
||||
raise OSError("the daemon closed the connection without answering")
|
||||
if len(reply_line) > MAX_LINE_BYTES:
|
||||
raise ValueError("reply exceeds the frame limit")
|
||||
reply = json.loads(reply_line)
|
||||
if not isinstance(reply, dict):
|
||||
raise ValueError(f"reply is not an object: {type(reply).__name__}")
|
||||
if not reply.get("ok"):
|
||||
kind = reply.get("kind")
|
||||
raise LiveRejected(
|
||||
str(reply.get("error") or "the stream daemon refused the request"),
|
||||
kind=kind if isinstance(kind, str) else None,
|
||||
)
|
||||
return reply
|
||||
|
||||
def _connect(self):
|
||||
if self._stream is not None and not self._stale():
|
||||
return self._stream
|
||||
self._disconnect()
|
||||
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
try:
|
||||
sock.settimeout(self.timeout_s)
|
||||
sock.connect(str(self.socket_path))
|
||||
except OSError:
|
||||
sock.close()
|
||||
raise
|
||||
self._sock = sock
|
||||
self._stream = sock.makefile("rwb")
|
||||
log.debug("connected to the stream daemon at %s", self.socket_path)
|
||||
return self._stream
|
||||
|
||||
def _stale(self) -> bool:
|
||||
"""True if the held connection has died since the last op.
|
||||
|
||||
The daemon never speaks unsolicited, so a readable socket can only be
|
||||
at EOF. One non-blocking ``select``, and it is what makes reconnecting
|
||||
safe: a request is written only to a connection that was alive when it
|
||||
was written.
|
||||
"""
|
||||
|
||||
sock = self._sock
|
||||
if sock is None:
|
||||
return True
|
||||
try:
|
||||
readable, _, _ = select.select([sock], [], [], 0)
|
||||
except (OSError, ValueError):
|
||||
return True
|
||||
return bool(readable)
|
||||
|
||||
def _disconnect(self) -> None:
|
||||
stream, self._stream = self._stream, None
|
||||
sock, self._sock = self._sock, None
|
||||
for closeable in (stream, sock):
|
||||
if closeable is None:
|
||||
continue
|
||||
try:
|
||||
closeable.close()
|
||||
except OSError:
|
||||
pass
|
||||
Reference in new issue
Block a user