Files
hyprland-headless-stream-pl…/src/hhstreamd/server.py
T
HermenixandClaude Opus 5 7d8ca6191b feat(sessions)!: the four stream verbs, schema 4, and the viewer sweep
The broker half of sessions-v4: `stream.enable`, `stream.disable`,
`stream.list`, `stream.status`, `start`'s three new arguments, and the one rule
that is genuinely new rather than additive -- a connected viewer is activity.

The decisions worth reading the diff for:

**A stream never falls back to the main output.** `_stream_output` refuses when
a session has no container, and the refusal is stronger than the pointer's for a
reason the hint states: the main output carries *every other session*, so a
fallback would put somebody else's desktop on a phone behind a phrase that was
issued for this one.

**The phrase lives in the record, so re-enabling returns the same URL.** A
different `--phrase` on an already-enabled session is `stream_busy` (exit 8),
not a silent rotation: rotating under a caller who is holding the old URL is the
one outcome neither answer can be mistaken for. `disable` then `enable` is how
it rotates, which is explicit.

**`_checked_phrase` raises the shape and never the value**, with `from None`, for
`control._phrase_of`'s reason: `phrase.validate` names what it rejected, and
this value is a password on its way into an error reply and a log.

**`fps` is only sent when a caller named one** (`_checked_fps` returns `None`
otherwise), which is what makes the daemon's own default authoritative instead
of decorative. The broker holds the daemon to the frozen cap before sending, so
a nonsense rate is exit 2 from the verb rather than a surprise from the socket.

**`attached` is its own field and is not folded into `enabled`.** A record can
say the operator asked for a stream while the daemon is down, and those are two
different facts; `url` and `viewers` are *absent* rather than stale when it is
false, because a URL that no longer serves anything is worse than no URL.
`stream.list` also reports `available`, so "no streams" is distinguishable from
"no daemon" without parsing an error.

**The viewer sweep** (`_sweep_streams`, every `STREAM_SWEEP_S = 60`s) asks the
daemon for viewer counts and stamps `touch` on every session somebody is
watching. It is the only thing in this daemon that treats an observation as an
intention, and it exists for one failure: an operator watching a long job on his
phone and losing the session at three hours *because* watching was all he was
doing. It cannot hold a session open by itself -- an enabled stream with no
viewer runs no `grim` and stamps nothing -- which is why it is safe to run
unconditionally.

**Teardown detaches before it destroys the container.** The other order makes
every capture fail against a removed output, which is a stream that gives up
ten frames later and a log that blames `grim`.

`start` takes `stream`, `stream_phrase` and `stream_fps` and reports a stream it
could not open in `stream_error` beside a session that *did* start, because the
exit code is 0 and a caller who asked for a stream must not read that as one.

Registry schema 3 -> 4: the record gains `stream`, older records migrate to
`null` rather than being refused, and the viewer count is deliberately not
stored -- a viewer count on disk is a number that is wrong the moment it is
written.

No new exit numbers: `stream_busy` -> 8, `stream_budget` -> 6,
`stream_unavailable` -> 10. The last one is 10 for `driver_refused`'s reason --
the session keeps running, and a caller that read an unreachable stream as a
dead session would kill an application over a web page.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011ZeH65zd6pFTgBSu52W9PE
2026-10-11 22:47:43 +00:00

479 lines
18 KiB
Python

"""The control socket (DESIGN.md §3.4).
An asyncio unix ``SOCK_STREAM`` server speaking newline-delimited JSON: one
request object, one response object, connection closed. Chosen over HTTP
(framing and a server for no benefit on a local socket), D-Bus (no stdlib
client) and a bespoke binary protocol (unreadable at 3am). It is debuggable
with ``socat - UNIX-CONNECT:/run/hhstream/control.sock`` and costs nothing.
This module is framing and dispatch only. Every decision lives in
:mod:`hhstreamd.manager`.
"""
from __future__ import annotations
import asyncio
import contextlib
import logging
import os
import socket
import struct
from pathlib import Path
from typing import Any, Awaitable, Callable
from . import protocol
from .manager import ManagerError, SessionManager
from .policy import PolicyError
log = logging.getLogger("hhstreamd.server")
#: A request that has not produced a reply in this long is abandoned and the
#: caller told so, rather than holding the connection open indefinitely.
DEFAULT_REQUEST_TIMEOUT_S = 5.0
#: A `kill` may legitimately take `grace` seconds, so it gets its own budget.
KILL_TIMEOUT_MARGIN_S = 5.0
#: `request_id` idempotency lives in `protocol` (which verbs mutate, how many
#: replies are kept, what a replay looks like) because the CLI has to agree
#: with it and the CLI imports that module and not this one.
class ControlServer:
def __init__(
self,
manager: SessionManager,
socket_path: Path | str,
*,
request_timeout_s: float = DEFAULT_REQUEST_TIMEOUT_S,
socket_mode: int = 0o660,
) -> None:
self.manager = manager
self.socket_path = Path(socket_path)
self.request_timeout_s = request_timeout_s
self.socket_mode = socket_mode
self._server: asyncio.AbstractServer | None = None
self._dedup = protocol.IdempotencyCache()
self._ops: dict[str, Callable[[dict[str, Any], dict[str, Any]], Awaitable[dict[str, Any]]]] = {
"ping": self._op_ping,
"start": self._op_start,
"list": self._op_list,
"status": self._op_status,
"touch": self._op_touch,
"kill": self._op_kill,
"gc": self._op_gc,
"adopt": self._op_adopt,
"logs": self._op_logs,
"container.list": self._op_container_list,
"container.reconcile": self._op_container_reconcile,
"pointer.acquire": self._op_pointer_acquire,
"pointer.move": self._op_pointer_move,
"pointer.button": self._op_pointer_button,
"pointer.click": self._op_pointer_click,
"pointer.scroll": self._op_pointer_scroll,
"pointer.release": self._op_pointer_release,
"pointer.state": self._op_pointer_state,
"keyboard.key": self._op_keyboard_key,
"keyboard.type": self._op_keyboard_type,
"stream.enable": self._op_stream_enable,
"stream.disable": self._op_stream_disable,
"stream.list": self._op_stream_list,
"stream.status": self._op_stream_status,
}
# ------------------------------------------------------------------
# lifecycle
# ------------------------------------------------------------------
async def start(self) -> None:
self._prepare_socket_path()
self._server = await asyncio.start_unix_server(
self._handle,
path=str(self.socket_path),
# The stream limit is the frame limit: a peer cannot grow the
# daemon's read buffer past one message.
limit=protocol.MAX_LINE_BYTES,
)
with contextlib.suppress(OSError):
os.chmod(self.socket_path, self.socket_mode)
log.info("listening on %s", self.socket_path)
async def stop(self) -> None:
if self._server is not None:
self._server.close()
with contextlib.suppress(Exception):
await self._server.wait_closed()
self._server = None
with contextlib.suppress(FileNotFoundError, OSError):
self.socket_path.unlink()
def _prepare_socket_path(self) -> None:
"""Create the parent directory and clear a stale socket.
A socket file left by a crashed daemon is unlinked only after proving
nobody is listening on it: connecting and being refused is the proof.
Unlinking a *live* socket would silently steal another daemon's clients.
"""
self.socket_path.parent.mkdir(parents=True, exist_ok=True, mode=0o750)
if not self.socket_path.exists():
return
probe = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
try:
probe.settimeout(0.5)
probe.connect(str(self.socket_path))
except (ConnectionRefusedError, FileNotFoundError):
log.warning("removing stale socket %s", self.socket_path)
with contextlib.suppress(OSError):
self.socket_path.unlink()
except OSError as exc:
raise OSError(
f"{self.socket_path} exists and could not be probed: {exc}"
) from exc
else:
raise OSError(f"another daemon is already listening on {self.socket_path}")
finally:
probe.close()
# ------------------------------------------------------------------
# connection handling
# ------------------------------------------------------------------
async def _handle(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
caller = _peer_credentials(writer)
try:
try:
line = await reader.readuntil(b"\n")
except asyncio.IncompleteReadError as exc:
if not exc.partial:
return # a peer that connected and went away; not an error
line = exc.partial
except asyncio.LimitOverrunError:
await self._send(
writer,
protocol.error("message_too_large", "request exceeds the frame limit"),
)
return
if len(line) > protocol.MAX_LINE_BYTES:
await self._send(
writer,
protocol.error("message_too_large", "request exceeds the frame limit"),
)
return
response = await self._dispatch(line, caller)
await self._send(writer, response)
except (ConnectionResetError, BrokenPipeError):
pass
except Exception:
log.exception("unhandled error serving a request")
with contextlib.suppress(Exception):
await self._send(
writer, protocol.error("refused", "internal error; see the daemon log")
)
finally:
with contextlib.suppress(Exception):
writer.close()
await writer.wait_closed()
async def _send(self, writer: asyncio.StreamWriter, message: dict[str, Any]) -> None:
writer.write(protocol.encode(message))
await writer.drain()
async def _dispatch(self, line: bytes, caller: dict[str, Any]) -> dict[str, Any]:
started = self.manager.clock.boottime()
try:
request = protocol.decode_request(line)
except protocol.ProtocolError as exc:
self.manager.audit.emit(
"request_rejected", error=exc.error, reason=exc.reason, caller=caller
)
return protocol.error(exc.error, exc.reason)
op = request["op"]
request_id = request.get("request_id")
handler = self._ops.get(op)
if handler is None:
return protocol.error(
"unknown_op", f"unknown op {op!r}", hint=f"known: {', '.join(sorted(self._ops))}"
)
cached = self._dedup.lookup(op, request_id)
if cached is not None:
return cached
timeout = self.request_timeout_s
if op == "kill":
# A kill is allowed to take its grace period plus the SIGKILL step.
grace = request.get("grace_s")
grace = self.manager.config.policy.grace_s if grace is None else float(grace or 0)
timeout = max(timeout, grace + KILL_TIMEOUT_MARGIN_S)
elif op == "start":
wait_ready = request.get("wait_ready_s")
wait_ready = (
self.manager.config.policy.wait_ready_s if wait_ready is None else float(wait_ready or 0)
)
timeout = max(timeout, wait_ready + 1.0)
try:
response = await asyncio.wait_for(handler(request, caller), timeout=timeout)
except TimeoutError:
response = protocol.error("timeout", f"{op} did not complete within {timeout:g}s")
except ManagerError as exc:
response = protocol.error(exc.error, exc.reason, hint=exc.hint, **exc.fields)
except PolicyError as exc:
response = protocol.error(exc.error, exc.reason, hint=exc.hint)
except (TypeError, ValueError) as exc:
response = protocol.error("invalid_argument", str(exc))
except Exception as exc:
log.exception("op %s failed", op)
response = protocol.error("refused", f"internal error: {type(exc).__name__}")
elapsed_ms = round((self.manager.clock.boottime() - started) * 1000, 3)
response.setdefault("elapsed_ms", elapsed_ms)
if isinstance(request_id, str):
response["request_id"] = request_id
self._dedup.remember(op, request_id, response)
self.manager.audit.emit(
"request",
verb=op,
session=request.get("id") or response.get("id"),
caller=caller,
ok=bool(response.get("ok")),
error=response.get("error"),
duration_ms=elapsed_ms,
request_id=request_id if isinstance(request_id, str) else None,
)
return response
# ------------------------------------------------------------------
# ops
# ------------------------------------------------------------------
async def _op_ping(self, request: dict[str, Any], caller: dict[str, Any]) -> dict[str, Any]:
from . import __version__
return protocol.ok(
version=__version__,
pid=os.getpid(),
boottime=self.manager.now(),
live=len(self.manager.registry.live()),
)
async def _op_start(self, request: dict[str, Any], caller: dict[str, Any]) -> dict[str, Any]:
record = await self.manager.start(
request.get("app"),
request.get("argv"),
idle_timeout_s=request.get("idle_timeout_s"),
wait_ready_s=request.get("wait_ready_s"),
home=request.get("home"),
ephemeral_home=bool(request.get("ephemeral_home", False)),
stream=bool(request.get("stream", False)),
stream_phrase=request.get("stream_phrase"),
stream_fps=request.get("stream_fps"),
)
return protocol.ok(id=record["id"], state=record["state"], session=record)
async def _op_list(self, request: dict[str, Any], caller: dict[str, Any]) -> dict[str, Any]:
return protocol.ok(**self.manager.list(include_tombstones=bool(request.get("all", False))))
async def _op_status(self, request: dict[str, Any], caller: dict[str, Any]) -> dict[str, Any]:
record = self.manager.status(request.get("id"), events=int(request.get("events", 20)))
return protocol.ok(id=record["id"], state=record["state"], session=record)
async def _op_touch(self, request: dict[str, Any], caller: dict[str, Any]) -> dict[str, Any]:
record = self.manager.touch(request.get("id"))
return protocol.ok(id=record["id"], state=record["state"], session=record)
async def _op_kill(self, request: dict[str, Any], caller: dict[str, Any]) -> dict[str, Any]:
record = await self.manager.kill(
request.get("id"),
grace_s=request.get("grace_s"),
sig=request.get("signal", "TERM"),
)
return protocol.ok(id=record["id"], state=record["state"], session=record)
async def _op_gc(self, request: dict[str, Any], caller: dict[str, Any]) -> dict[str, Any]:
return protocol.ok(**await self.manager.gc())
async def _op_adopt(self, request: dict[str, Any], caller: dict[str, Any]) -> dict[str, Any]:
record = await self.manager.adopt(
request.get("pid"),
app=request.get("app"),
idle_timeout_s=request.get("idle_timeout_s"),
)
return protocol.ok(id=record["id"], state=record["state"], session=record)
async def _op_stream_enable(
self, request: dict[str, Any], caller: dict[str, Any]
) -> dict[str, Any]:
return protocol.ok(
**await self.manager.stream_enable(
request.get("id"),
phrase=request.get("phrase"),
fps=request.get("fps"),
)
)
async def _op_stream_disable(
self, request: dict[str, Any], caller: dict[str, Any]
) -> dict[str, Any]:
return protocol.ok(**await self.manager.stream_disable(request.get("id")))
async def _op_stream_list(
self, request: dict[str, Any], caller: dict[str, Any]
) -> dict[str, Any]:
return protocol.ok(**self.manager.stream_list())
async def _op_stream_status(
self, request: dict[str, Any], caller: dict[str, Any]
) -> dict[str, Any]:
return protocol.ok(**self.manager.stream_status(request.get("id")))
async def _op_container_list(
self, request: dict[str, Any], caller: dict[str, Any]
) -> dict[str, Any]:
return protocol.ok(**self.manager.container_list())
async def _op_container_reconcile(
self, request: dict[str, Any], caller: dict[str, Any]
) -> dict[str, Any]:
return protocol.ok(**await self.manager.container_reconcile(request.get("id")))
async def _op_pointer_acquire(
self, request: dict[str, Any], caller: dict[str, Any]
) -> dict[str, Any]:
return protocol.ok(
**await self.manager.pointer_acquire(
request.get("id"),
ttl_s=request.get("ttl_s"),
# Restoring is the default: the bookmark exists so a gesture
# can be picked up where it was left, and a caller that wants
# the centre of the output says so.
restore=bool(request.get("restore", True)),
)
)
async def _op_pointer_move(
self, request: dict[str, Any], caller: dict[str, Any]
) -> dict[str, Any]:
return protocol.ok(
**await self.manager.pointer_move(
request.get("id"),
request.get("lease_id"),
x=request.get("x"),
y=request.get("y"),
dx=request.get("dx"),
dy=request.get("dy"),
)
)
async def _op_pointer_button(
self, request: dict[str, Any], caller: dict[str, Any]
) -> dict[str, Any]:
return protocol.ok(
**await self.manager.pointer_button(
request.get("id"),
request.get("lease_id"),
request.get("button"),
request.get("state"),
)
)
async def _op_pointer_click(
self, request: dict[str, Any], caller: dict[str, Any]
) -> dict[str, Any]:
return protocol.ok(
**await self.manager.pointer_click(
request.get("id"),
request.get("lease_id"),
request.get("button", "left"),
request.get("count", 1),
)
)
async def _op_pointer_scroll(
self, request: dict[str, Any], caller: dict[str, Any]
) -> dict[str, Any]:
return protocol.ok(
**await self.manager.pointer_scroll(
request.get("id"),
request.get("lease_id"),
request.get("axis", "vertical"),
request.get("amount", 3),
)
)
async def _op_pointer_release(
self, request: dict[str, Any], caller: dict[str, Any]
) -> dict[str, Any]:
return protocol.ok(
**await self.manager.pointer_release(request.get("id"), request.get("lease_id"))
)
async def _op_pointer_state(
self, request: dict[str, Any], caller: dict[str, Any]
) -> dict[str, Any]:
return protocol.ok(**self.manager.pointer_state())
async def _op_keyboard_key(
self, request: dict[str, Any], caller: dict[str, Any]
) -> dict[str, Any]:
return protocol.ok(
**await self.manager.keyboard_key(
request.get("id"),
request.get("lease_id"),
request.get("key"),
request.get("state"),
)
)
async def _op_keyboard_type(
self, request: dict[str, Any], caller: dict[str, Any]
) -> dict[str, Any]:
# `text` is passed through untouched -- no default, no strip, no
# escape handling. A newline in the argument is a newline on the wire;
# the shell did the quoting and inventing an escape language here
# would mean `\n` could never be typed literally.
return protocol.ok(
**await self.manager.keyboard_type(
request.get("id"),
request.get("lease_id"),
request.get("text"),
)
)
async def _op_logs(self, request: dict[str, Any], caller: dict[str, Any]) -> dict[str, Any]:
return protocol.ok(
**self.manager.logs(
request.get("id"),
lines=int(request.get("lines", 100)),
offset=request.get("offset"),
)
)
def _peer_credentials(writer: asyncio.StreamWriter) -> dict[str, Any]:
"""``SO_PEERCRED`` of the connecting process, for the audit log.
M0 records who asked but does **not** authorise on it: the uid/gid
allowlist is §8 item 2, which the brief holds out of this milestone. The
socket's own mode and its directory are the access control here.
"""
sock = writer.get_extra_info("socket")
if sock is None:
return {}
try:
raw = sock.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, struct.calcsize("3i"))
pid, uid, gid = struct.unpack("3i", raw)
except OSError:
return {}
caller: dict[str, Any] = {"pid": pid, "uid": uid, "gid": gid}
try:
with open(f"/proc/{pid}/comm", encoding="utf-8") as fh:
caller["comm"] = fh.read().strip()
except OSError:
pass
return caller