client.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. """HTTP client for the agent routes of the config plane (contract.md §7.1, §7.2).
  2. Plain HTTP (D9), stdlib only: it runs inside ``load_hermes_dotenv`` before most of Hermes is
  3. imported. Every request re-resolves the bearer (contract §10.2).
  4. """
  5. from __future__ import annotations
  6. import json
  7. import os
  8. import urllib.error
  9. import urllib.parse
  10. import urllib.request
  11. from dataclasses import dataclass
  12. from pathlib import Path
  13. from typing import Any, Dict, Optional
  14. from .credentials import plane_token
  15. from .destination import checked_url, display_url, open_credentialed
  16. DEFAULT_URL = "https://config-config.nousresearch.com"
  17. URL_ENV = "HERMES_CONFIG_REMOTE_URL"
  18. INSTANCE_ENV = "HERMES_CONFIG_INSTANCE_ID"
  19. _HTTP_TIMEOUT_S = 15.0
  20. @dataclass(frozen=True)
  21. class Response:
  22. status: int
  23. body: dict[str, Any]
  24. etag: Optional[str]
  25. retry_after: Optional[float]
  26. @property
  27. def error(self) -> str:
  28. return str(self.body.get("error") or f"http_{self.status}")
  29. @property
  30. def message(self) -> str:
  31. return str(self.body.get("message") or f"HTTP {self.status}")
  32. class TransportError(RuntimeError):
  33. """The request never produced an HTTP response (DNS, connect, TLS, timeout)."""
  34. def base_url() -> str:
  35. """The configured plane origin (+ path prefix), as configured: :func:`request` checks it
  36. against the credential destination policy before anything is sent. Messages use :func:`shown_url`."""
  37. return (os.environ.get(URL_ENV, "").strip() or DEFAULT_URL).rstrip("/")
  38. def shown_url() -> str:
  39. """:func:`base_url` without any user info, for messages, ``describe()`` and provenance."""
  40. return display_url(base_url())
  41. def instance_id() -> str:
  42. return os.environ.get(INSTANCE_ENV, "").strip()
  43. def _parse_body(raw: bytes) -> dict[str, Any]:
  44. if not raw:
  45. return {}
  46. try:
  47. data = json.loads(raw.decode("utf-8"))
  48. except ValueError:
  49. return {}
  50. return data if isinstance(data, dict) else {}
  51. def _retry_after(value: Optional[str]) -> Optional[float]:
  52. try:
  53. return float(value) if value else None
  54. except ValueError:
  55. return None
  56. def bearer(home: Path) -> str:
  57. """``home``'s plane bearer, resolved only once the plane destination passed the policy."""
  58. checked_url(base_url(), env_name=URL_ENV)
  59. return plane_token(home)
  60. def request(method: str, home: Path, profile: str, *, etag: Optional[str] = None,
  61. body: Optional[dict[str, Any]] = None, token: Optional[str] = None) -> Response:
  62. """One call to ``/v1/config/self?profile=<profile>`` as ``home``'s agent, with ``token`` (a
  63. :func:`bearer` the caller resolved) or a bearer resolved here.
  64. The destination is checked before the bearer is resolved, and the request never follows a
  65. redirect (:mod:`.destination`): raises its :class:`CredentialDestinationError` instead."""
  66. plane = checked_url(base_url(), env_name=URL_ENV)
  67. url = f"{plane}/v1/config/self?{urllib.parse.urlencode({'profile': profile})}"
  68. headers = {
  69. "Authorization": f"Bearer {token or plane_token(home)}",
  70. "X-Hermes-Instance-Id": instance_id(),
  71. "Accept": "application/json",
  72. }
  73. data = None
  74. if body is not None:
  75. data = json.dumps(body, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
  76. headers["Content-Type"] = "application/json"
  77. if etag:
  78. headers["If-None-Match"] = etag
  79. req = urllib.request.Request(url, data=data, method=method, headers=headers)
  80. try:
  81. with open_credentialed(req, timeout=_HTTP_TIMEOUT_S) as resp:
  82. return Response(resp.status, _parse_body(resp.read()), resp.headers.get("ETag"),
  83. _retry_after(resp.headers.get("Retry-After")))
  84. except urllib.error.HTTPError as exc: # every non-2xx, including 304
  85. with exc:
  86. raw = exc.read() if exc.fp is not None else b""
  87. return Response(exc.code, _parse_body(raw), exc.headers.get("ETag") if exc.headers else None,
  88. _retry_after(exc.headers.get("Retry-After") if exc.headers else None))
  89. except (urllib.error.URLError, OSError, TimeoutError) as exc:
  90. raise TransportError(f"{method} {url}: {getattr(exc, 'reason', exc)}") from exc