- kurgan/hw/protocol.py: newline-delimited JSON between the app and the
coming kurgan.hw service. Requests {"op", "args", "id"}; replies {"id",
"ok", "result"|"error": {"code", "message"}}. Operations: hello (protocol
and service versions; required first on every connection), state,
set_profile, set_ram_lighting, and ram_chase, which carries the app's chase
clock so the RAM stays in step with the case fan and GPU chases.
- Strict: a 64 KiB line cap (an oversized line closes the connection),
unknown operations and fields, missing or mistyped arguments, NaN and
Infinity, duplicate keys and deep nesting are all rejected. Profiles and RAM
modes are checked against the same lists the web API uses, on both sides:
the client encodes through the same checks before sending.
- Session: one connection's state machine (hello first, a version mismatch is
answered then closed, operation errors map to invalid/unavailable/internal,
a reply that can't be encoded is an internal error, not a dead connection).
- Tests: 15 new (malformed, oversized and unknown input, version mismatch).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
316 lines
12 KiB
Python
316 lines
12 KiB
Python
"""The hardware service's pipe protocol: newline-delimited JSON between the app and kurgan.hw.
|
|
|
|
request {"op": "state", "args": {}, "id": 7}
|
|
reply {"id": 7, "ok": true, "result": {...}}
|
|
{"id": 7, "ok": false, "error": {"code": "invalid", "message": "..."}}
|
|
|
|
Operations and their arguments:
|
|
|
|
hello {"protocol": 1, "client": "..."} the first request on every connection
|
|
state {} the service's latest snapshot
|
|
set_profile {"profile": "quiet"|"balanced"|"performance"|"full"}
|
|
set_ram_lighting {"mode": "off"|"temperature"|"chase"}
|
|
ram_chase {"phase": n, "rate": n, "power": n|null}
|
|
the app's chase clock, about once a second while the RAM chases, so the
|
|
RAM stays in step with the case fan and GPU chases
|
|
|
|
Each message is one line of UTF-8 JSON, at most MAX_MESSAGE bytes. Rejected: unknown
|
|
operations, unknown, missing or mistyped fields, NaN and Infinity, duplicate keys, and any
|
|
request before a successful hello. A protocol version mismatch is answered and the connection
|
|
closed. A line over MAX_MESSAGE closes the connection, since the stream can't be trusted after it.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import logging
|
|
import math
|
|
from dataclasses import dataclass, field
|
|
from typing import Callable
|
|
|
|
from kurgan.cooling.profiles import PROFILES
|
|
from kurgan.settings import LIGHTING_MODES
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
PIPE_NAME = r"\\.\pipe\kurgan-hw"
|
|
PROTOCOL_VERSION = 1
|
|
MAX_MESSAGE = 64 * 1024
|
|
READ_TIMEOUT = 30.0 # seconds a connection may stay silent (or mid-line) before the service drops it
|
|
|
|
# Error codes
|
|
BAD_REQUEST = "bad_request" # not a well-formed request
|
|
UNKNOWN_OP = "unknown_op"
|
|
INVALID = "invalid" # well-formed, but the arguments are wrong
|
|
HELLO_FIRST = "hello_first"
|
|
VERSION = "version"
|
|
TOO_LARGE = "too_large"
|
|
UNAVAILABLE = "unavailable" # the service can't do that right now
|
|
INTERNAL = "internal"
|
|
|
|
_MAX_ID = 2 ** 53
|
|
_MAX_TEXT = 64
|
|
|
|
|
|
class ProtocolError(Exception):
|
|
def __init__(self, code: str, message: str, request_id: int | str | None = None):
|
|
super().__init__(message)
|
|
self.code = code
|
|
self.request_id = request_id
|
|
|
|
|
|
class RemoteError(Exception):
|
|
"""The service answered with an error."""
|
|
|
|
def __init__(self, code: str, message: str):
|
|
super().__init__(message)
|
|
self.code = code
|
|
|
|
|
|
class Unavailable(OSError):
|
|
"""Raised by the service's operations when they can't run now (answered as UNAVAILABLE)."""
|
|
|
|
|
|
# ----------------------------------------------------------------------------- argument checks
|
|
|
|
def _integer(low: int, high: int):
|
|
def check(name: str, value) -> int:
|
|
if type(value) is not int or not low <= value <= high:
|
|
raise ValueError(f"{name} must be a whole number from {low} to {high}")
|
|
return value
|
|
return check
|
|
|
|
|
|
def _number(low: float, high: float, nullable: bool = False):
|
|
def check(name: str, value) -> float | None:
|
|
if value is None and nullable:
|
|
return None
|
|
if type(value) not in (int, float) or not math.isfinite(value) or not low <= value <= high:
|
|
raise ValueError(f"{name} must be a number from {low:g} to {high:g}" + (" or null" if nullable else ""))
|
|
return float(value)
|
|
return check
|
|
|
|
|
|
def _text(max_length: int = _MAX_TEXT):
|
|
def check(name: str, value) -> str:
|
|
if not isinstance(value, str) or len(value) > max_length:
|
|
raise ValueError(f"{name} must be a string of at most {max_length} characters")
|
|
return value
|
|
return check
|
|
|
|
|
|
def _choice(choices):
|
|
choices = tuple(choices)
|
|
|
|
def check(name: str, value) -> str:
|
|
if value not in choices or not isinstance(value, str):
|
|
raise ValueError(f"{name} must be one of {', '.join(choices)}")
|
|
return value
|
|
return check
|
|
|
|
|
|
# op -> {field: (check, required)}
|
|
OPERATIONS: dict[str, dict[str, tuple[Callable, bool]]] = {
|
|
"hello": {"protocol": (_integer(0, 1_000_000), True), "client": (_text(), False)},
|
|
"state": {},
|
|
"set_profile": {"profile": (_choice(PROFILES), True)},
|
|
"set_ram_lighting": {"mode": (_choice(LIGHTING_MODES["memory"]), True)},
|
|
"ram_chase": {"phase": (_number(-1e12, 1e12), True), "rate": (_number(0, 1000), True),
|
|
"power": (_number(0, 100_000, nullable=True), True)},
|
|
}
|
|
|
|
|
|
def check_args(op: str, args: object) -> dict:
|
|
"""The arguments, normalised, or ValueError."""
|
|
if not isinstance(args, dict):
|
|
raise ValueError("args must be an object")
|
|
schema = OPERATIONS[op]
|
|
unknown = set(args) - set(schema)
|
|
if unknown:
|
|
raise ValueError(f"{op}: unknown field(s): {', '.join(sorted(map(str, unknown)))}")
|
|
out = {}
|
|
for name, (check, required) in schema.items():
|
|
if name in args:
|
|
out[name] = check(name, args[name])
|
|
elif required:
|
|
raise ValueError(f"{op}: {name} is required")
|
|
return out
|
|
|
|
|
|
# ----------------------------------------------------------------------------- encoding
|
|
|
|
def _no_duplicates(pairs):
|
|
out = {}
|
|
for key, value in pairs:
|
|
if key in out:
|
|
raise ValueError(f"duplicate key {key!r}")
|
|
out[key] = value
|
|
return out
|
|
|
|
|
|
def _reject_constant(name: str):
|
|
raise ValueError(f"{name} is not valid JSON")
|
|
|
|
|
|
def _loads(line: bytes):
|
|
if len(line) > MAX_MESSAGE:
|
|
raise ProtocolError(TOO_LARGE, f"message over {MAX_MESSAGE} bytes")
|
|
try:
|
|
return json.loads(line.decode("utf-8"), object_pairs_hook=_no_duplicates, parse_constant=_reject_constant)
|
|
except (UnicodeDecodeError, ValueError, RecursionError) as e:
|
|
raise ProtocolError(BAD_REQUEST, f"not valid JSON: {e}") from None
|
|
|
|
|
|
def encode(message: dict) -> bytes:
|
|
"""One line of JSON, newline included. ValueError if it can't be sent."""
|
|
data = json.dumps(message, separators=(",", ":"), allow_nan=False).encode("utf-8")
|
|
if len(data) > MAX_MESSAGE:
|
|
raise ValueError(f"message over {MAX_MESSAGE} bytes")
|
|
return data + b"\n"
|
|
|
|
|
|
@dataclass
|
|
class Request:
|
|
op: str
|
|
args: dict = field(default_factory=dict)
|
|
id: int | str = 0
|
|
|
|
|
|
def _check_id(value) -> int | str:
|
|
if type(value) is int and -_MAX_ID < value < _MAX_ID:
|
|
return value
|
|
if isinstance(value, str) and len(value) <= _MAX_TEXT:
|
|
return value
|
|
raise ValueError("id must be an integer or a short string")
|
|
|
|
|
|
def decode_request(line: bytes) -> Request:
|
|
data = _loads(line)
|
|
if not isinstance(data, dict):
|
|
raise ProtocolError(BAD_REQUEST, "a request must be a JSON object")
|
|
request_id = None
|
|
if "id" in data:
|
|
try:
|
|
request_id = _check_id(data["id"])
|
|
except ValueError as e:
|
|
raise ProtocolError(BAD_REQUEST, str(e)) from None
|
|
unknown = set(data) - {"op", "args", "id"}
|
|
if unknown:
|
|
raise ProtocolError(BAD_REQUEST, f"unknown field(s): {', '.join(sorted(unknown))}", request_id)
|
|
if request_id is None:
|
|
raise ProtocolError(BAD_REQUEST, "id is required")
|
|
op = data.get("op")
|
|
if not isinstance(op, str):
|
|
raise ProtocolError(BAD_REQUEST, "op is required", request_id)
|
|
if op not in OPERATIONS:
|
|
raise ProtocolError(UNKNOWN_OP, f"unknown operation {op[:_MAX_TEXT]!r}", request_id)
|
|
try:
|
|
args = check_args(op, data.get("args", {}))
|
|
except ValueError as e:
|
|
raise ProtocolError(INVALID, str(e), request_id) from None
|
|
return Request(op, args, request_id)
|
|
|
|
|
|
def encode_request(op: str, args: dict | None, request_id: int | str) -> bytes:
|
|
"""Checked like the service checks it, so a bad call fails here, before anything is sent."""
|
|
if op not in OPERATIONS:
|
|
raise ValueError(f"unknown operation {op!r}")
|
|
return encode({"op": op, "args": check_args(op, args or {}), "id": _check_id(request_id)})
|
|
|
|
|
|
def encode_reply(request_id, result) -> bytes:
|
|
return encode({"id": request_id, "ok": True, "result": result})
|
|
|
|
|
|
def encode_error(request_id, code: str, message: str) -> bytes:
|
|
return encode({"id": request_id, "ok": False, "error": {"code": code, "message": message[:1000]}})
|
|
|
|
|
|
def decode_reply(line: bytes, request_id: int | str):
|
|
"""The result of the reply to `request_id`; RemoteError for an error reply, ProtocolError
|
|
(BAD_REQUEST) for anything that isn't a well-formed reply to that request."""
|
|
data = _loads(line)
|
|
if not isinstance(data, dict) or data.get("id") != request_id or type(data.get("ok")) is not bool:
|
|
raise ProtocolError(BAD_REQUEST, "not a reply to this request")
|
|
if data["ok"]:
|
|
if set(data) != {"id", "ok", "result"}:
|
|
raise ProtocolError(BAD_REQUEST, "malformed reply")
|
|
return data["result"]
|
|
error = data.get("error")
|
|
if (set(data) != {"id", "ok", "error"} or not isinstance(error, dict) or set(error) != {"code", "message"}
|
|
or not all(isinstance(v, str) for v in error.values())):
|
|
raise ProtocolError(BAD_REQUEST, "malformed error reply")
|
|
raise RemoteError(error["code"], error["message"])
|
|
|
|
|
|
# ----------------------------------------------------------------------------- framing and sessions
|
|
|
|
class LineBuffer:
|
|
"""Splits a byte stream into lines; ProtocolError(TOO_LARGE) once a line can't fit."""
|
|
|
|
def __init__(self, limit: int = MAX_MESSAGE):
|
|
self.limit = limit
|
|
self._pending = bytearray()
|
|
|
|
def feed(self, data: bytes) -> list[bytes]:
|
|
self._pending += data
|
|
lines = []
|
|
while True:
|
|
end = self._pending.find(b"\n")
|
|
if end < 0:
|
|
break
|
|
line = bytes(self._pending[:end])
|
|
del self._pending[:end + 1]
|
|
if len(line) > self.limit:
|
|
raise ProtocolError(TOO_LARGE, f"message over {self.limit} bytes")
|
|
lines.append(line[:-1] if line.endswith(b"\r") else line)
|
|
if len(self._pending) > self.limit:
|
|
raise ProtocolError(TOO_LARGE, f"message over {self.limit} bytes")
|
|
return lines
|
|
|
|
@property
|
|
def partial(self) -> bool:
|
|
return bool(self._pending)
|
|
|
|
|
|
class Session:
|
|
"""One connection's side of the protocol, in the service.
|
|
|
|
dispatch(op, args) runs an operation: ValueError is answered as INVALID, Unavailable as
|
|
UNAVAILABLE, anything else as INTERNAL (and logged)."""
|
|
|
|
def __init__(self, dispatch: Callable[[str, dict], object], service_version: str):
|
|
self._dispatch = dispatch
|
|
self._version = service_version
|
|
self.greeted = False
|
|
|
|
def handle(self, line: bytes) -> tuple[bytes, bool]:
|
|
"""(reply, close the connection after sending it)."""
|
|
try:
|
|
request = decode_request(line)
|
|
except ProtocolError as e:
|
|
return encode_error(e.request_id, e.code, str(e)), e.code == TOO_LARGE
|
|
if request.op == "hello":
|
|
theirs = request.args["protocol"]
|
|
if theirs != PROTOCOL_VERSION:
|
|
return encode_error(request.id, VERSION, f"the service speaks protocol {PROTOCOL_VERSION}, "
|
|
f"the client {theirs}"), True
|
|
self.greeted = True
|
|
return encode_reply(request.id, {"protocol": PROTOCOL_VERSION, "service": self._version}), False
|
|
if not self.greeted:
|
|
return encode_error(request.id, HELLO_FIRST, "send hello first"), False
|
|
try:
|
|
result = self._dispatch(request.op, request.args)
|
|
except Unavailable as e:
|
|
return encode_error(request.id, UNAVAILABLE, str(e)), False
|
|
except ValueError as e:
|
|
return encode_error(request.id, INVALID, str(e)), False
|
|
except Exception:
|
|
log.exception("%s failed", request.op)
|
|
return encode_error(request.id, INTERNAL, f"{request.op} failed; see the service log"), False
|
|
try:
|
|
return encode_reply(request.id, result), False
|
|
except (TypeError, ValueError):
|
|
log.exception("%s: the reply can't be encoded", request.op)
|
|
return encode_error(request.id, INTERNAL, f"{request.op}: the reply can't be sent; see the service log"), False
|