protocol.py 3.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. """Wire protocol for gateway ↔ node RPC (JSON envelopes).
  2. Request: {"type": <str>, "id": <str>, "token": <str>, "payload": <dict>}
  3. Response: {"type": "response", "id": <req-id>, "payload": <dict>}
  4. Error: {"type": "error", "id": <req-id>, "error": <str>}
  5. Requests carry the shared bearer token (``hermes meet node approve`` on the gateway, read off
  6. disk on the server); mismatched tokens are rejected before dispatch.
  7. """
  8. from __future__ import annotations
  9. import json
  10. import uuid
  11. from typing import Any, Dict, Tuple
  12. VALID_REQUEST_TYPES = frozenset({"start_bot", "stop", "status", "transcript", "say", "ping"})
  13. def _nonempty_str(value: Any) -> bool:
  14. return isinstance(value, str) and bool(value)
  15. def make_request(type: str, token: str, payload: dict[str, Any], req_id: str | None = None) -> dict[str, Any]:
  16. """Construct a request envelope; ``req_id`` defaults to a uuid4 hex."""
  17. if not _nonempty_str(type):
  18. raise ValueError("type must be a non-empty string")
  19. if type not in VALID_REQUEST_TYPES:
  20. raise ValueError(f"unknown request type: {type!r}")
  21. if not isinstance(token, str):
  22. raise ValueError("token must be a string")
  23. if not isinstance(payload, dict):
  24. raise ValueError("payload must be a dict")
  25. return {"type": type, "id": req_id or uuid.uuid4().hex, "token": token, "payload": payload}
  26. def make_response(req_id: str, payload: dict[str, Any]) -> dict[str, Any]:
  27. """Build a success envelope; clients correlate replies by ``id``, not type."""
  28. if not isinstance(payload, dict):
  29. raise ValueError("payload must be a dict")
  30. return {"type": "response", "id": req_id, "payload": payload}
  31. def make_error(req_id: str, error: str) -> dict[str, Any]:
  32. return {"type": "error", "id": req_id, "error": str(error)}
  33. def encode(msg: dict[str, Any]) -> str:
  34. """Serialize a message envelope to a JSON string."""
  35. return json.dumps(msg, separators=(",", ":"), ensure_ascii=False)
  36. def decode(raw) -> dict[str, Any]:
  37. """Parse a JSON envelope (object with string ``type`` + ``id``) from str/bytes; ValueError otherwise.
  38. Token match and payload shape are checked server-side in :func:`validate_request`."""
  39. if isinstance(raw, (bytes, bytearray)):
  40. raw = raw.decode("utf-8")
  41. try:
  42. obj = json.loads(raw)
  43. except (TypeError, json.JSONDecodeError) as exc:
  44. raise ValueError(f"malformed JSON: {exc}") from exc
  45. if not isinstance(obj, dict):
  46. raise ValueError("envelope must be a JSON object")
  47. for key in ("type", "id"):
  48. if not isinstance(obj.get(key), str):
  49. raise ValueError(f"envelope missing string '{key}'")
  50. return obj
  51. def validate_request(msg: dict[str, Any], expected_token: str) -> tuple[bool, str]:
  52. """Return ``(True, "")`` or ``(False, <reason>)``; reasons are safe to send back to the client."""
  53. if not isinstance(msg, dict):
  54. return False, "envelope must be a dict"
  55. t, token = msg.get("type"), msg.get("token")
  56. checks = ( # ordered, lazily evaluated: first failing check wins
  57. (lambda: _nonempty_str(t), "missing or non-string 'type'"),
  58. (lambda: t in VALID_REQUEST_TYPES, f"unknown request type: {t!r}"),
  59. (lambda: _nonempty_str(msg.get("id")), "missing or non-string 'id'"),
  60. (lambda: _nonempty_str(token), "missing token"),
  61. (lambda: token == expected_token, "token mismatch"),
  62. (lambda: isinstance(msg.get("payload"), dict), "payload must be a dict"))
  63. return next(((False, reason) for ok, reason in checks if not ok()), (True, ""))