client.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  1. """grpc.aio client over Unix domain sockets.
  2. Observe and control are separate sockets. This client never opens a serial
  3. port. SET_ALL confirmation from the daemon must remain UNCONFIRMED on the
  4. current Prod2U UART contract.
  5. """
  6. from __future__ import annotations
  7. import asyncio
  8. from collections.abc import AsyncIterator, Callable
  9. from datetime import timedelta
  10. from typing import Any, Optional
  11. from hth_sdk.constants import (
  12. API_VERSION,
  13. DEFAULT_CONTROL_SOCKET,
  14. DEFAULT_OBSERVE_SOCKET,
  15. )
  16. from hth_sdk.exceptions import (
  17. ActionRejected,
  18. ApiVersionMismatch,
  19. DataGap,
  20. DeviceEpochChanged,
  21. LeaseError,
  22. LeaseExpired,
  23. LeaseMismatch,
  24. NotConnected,
  25. TransportError,
  26. )
  27. from hth_sdk.lease import ControlLease
  28. from hth_sdk.proto_codec import (
  29. action_result_from_proto,
  30. batch_to_proto,
  31. capabilities_from_proto,
  32. device_info_from_proto,
  33. snapshot_from_proto,
  34. )
  35. from hth_sdk.stubs import load_stubs
  36. from hth_sdk.types import (
  37. ActionBatch,
  38. ActionResult,
  39. Capabilities,
  40. DeviceInfo,
  41. Snapshot,
  42. TelemetryEvent,
  43. )
  44. EpochCallback = Callable[[int, int, Snapshot], None]
  45. GapCallback = Callable[[Snapshot], None]
  46. def unix_target(path: str) -> str:
  47. if path.startswith("unix:"):
  48. return path
  49. if path.startswith("@"):
  50. return f"unix://{path}"
  51. if not path.startswith("/"):
  52. raise TransportError(f"socket path must be absolute or unix://, got {path!r}")
  53. return f"unix://{path}"
  54. class HthClient:
  55. def __init__(
  56. self,
  57. *,
  58. observe_channel=None,
  59. control_channel=None,
  60. observe_stub=None,
  61. control_stub=None,
  62. pb2=None,
  63. check_api_version: bool = True,
  64. on_device_epoch_changed: Optional[EpochCallback] = None,
  65. on_data_gap: Optional[GapCallback] = None,
  66. raise_on_epoch_change: bool = False,
  67. raise_on_data_gap: bool = False,
  68. ) -> None:
  69. self._observe_channel = observe_channel
  70. self._control_channel = control_channel
  71. self._observe = observe_stub
  72. self._control = control_stub
  73. self._pb2 = pb2
  74. self._check_api_version = check_api_version
  75. self._seen_api_version: Optional[str] = None
  76. self.on_device_epoch_changed = on_device_epoch_changed
  77. self.on_data_gap = on_data_gap
  78. self.raise_on_epoch_change = raise_on_epoch_change
  79. self.raise_on_data_gap = raise_on_data_gap
  80. self._last_epoch: dict[str, int] = {}
  81. self._timing: Optional[object] = None
  82. self._rpc_deadline_s: Optional[float] = None
  83. @property
  84. def has_observe(self) -> bool:
  85. return self._observe is not None
  86. @property
  87. def has_control(self) -> bool:
  88. return self._control is not None
  89. async def close(self) -> None:
  90. for ch in (self._observe_channel, self._control_channel):
  91. if ch is None:
  92. continue
  93. await ch.close()
  94. self._observe_channel = None
  95. self._control_channel = None
  96. async def __aenter__(self) -> "HthClient":
  97. return self
  98. async def __aexit__(self, *exc: object) -> None:
  99. await self.close()
  100. def _need_observe(self):
  101. if self._observe is None:
  102. raise NotConnected("observe socket is not connected")
  103. return self._observe
  104. def _need_control(self):
  105. if self._control is None:
  106. raise NotConnected("control socket is not connected")
  107. return self._control
  108. def _need_pb2(self):
  109. if self._pb2 is None:
  110. self._pb2, _ = load_stubs()
  111. return self._pb2
  112. def _maybe_check_api(self, api_version: str) -> None:
  113. self._seen_api_version = api_version
  114. if self._check_api_version and api_version and api_version != API_VERSION:
  115. raise ApiVersionMismatch(api_version, API_VERSION)
  116. async def list_devices(self) -> list[DeviceInfo]:
  117. pb2 = self._need_pb2()
  118. try:
  119. resp = await self._need_observe().ListDevices(pb2.ListDevicesRequest())
  120. except Exception as exc:
  121. raise TransportError(str(exc)) from exc
  122. return [device_info_from_proto(pb2, d) for d in resp.devices]
  123. async def get_capabilities(self, device_id: str) -> Capabilities:
  124. pb2 = self._need_pb2()
  125. try:
  126. resp = await self._need_observe().GetCapabilities(
  127. pb2.GetCapabilitiesRequest(device_id=device_id)
  128. )
  129. except Exception as exc:
  130. raise TransportError(str(exc)) from exc
  131. caps = capabilities_from_proto(pb2, resp.capabilities)
  132. self._maybe_check_api(caps.api_version)
  133. if caps.timing is not None and caps.timing.recommended_rpc_deadline_ms > 0:
  134. self._timing = caps.timing
  135. self._rpc_deadline_s = caps.timing.recommended_rpc_deadline_ms / 1000.0
  136. return caps
  137. async def get_snapshot(self, device_id: str) -> Snapshot:
  138. pb2 = self._need_pb2()
  139. try:
  140. resp = await self._need_observe().GetSnapshot(pb2.GetSnapshotRequest(device_id=device_id))
  141. except Exception as exc:
  142. raise TransportError(str(exc)) from exc
  143. snap = snapshot_from_proto(pb2, resp.snapshot)
  144. self._note_epoch(snap)
  145. return snap
  146. async def get_faults(self, device_id: str, include_inactive: bool = False):
  147. pb2 = self._need_pb2()
  148. try:
  149. resp = await self._need_observe().GetFaults(
  150. pb2.GetFaultsRequest(device_id=device_id, include_inactive=include_inactive)
  151. )
  152. except Exception as exc:
  153. raise TransportError(str(exc)) from exc
  154. from hth_sdk.proto_codec import _fault_from_proto
  155. return [ _fault_from_proto(pb2, f) for f in resp.faults ]
  156. async def subscribe_telemetry(
  157. self,
  158. device_id: str,
  159. resume_after_event_id: int = 0,
  160. ) -> AsyncIterator[TelemetryEvent]:
  161. pb2 = self._need_pb2()
  162. call = self._need_observe().SubscribeTelemetry(
  163. pb2.SubscribeTelemetryRequest(
  164. device_id=device_id, resume_after_event_id=resume_after_event_id
  165. )
  166. )
  167. last_epoch: Optional[int] = self._last_epoch.get(device_id)
  168. try:
  169. async for msg in call:
  170. snap = snapshot_from_proto(pb2, msg)
  171. event = self._wrap_telemetry(snap, last_epoch)
  172. last_epoch = snap.device_epoch
  173. yield event
  174. except (DeviceEpochChanged, DataGap):
  175. raise
  176. except asyncio.CancelledError:
  177. raise
  178. except Exception as exc:
  179. raise TransportError(str(exc)) from exc
  180. def _wrap_telemetry(self, snap: Snapshot, last_epoch: Optional[int]) -> TelemetryEvent:
  181. epoch_changed = last_epoch is not None and snap.device_epoch != last_epoch
  182. data_gap = bool(snap.data_gap)
  183. if epoch_changed and self.on_device_epoch_changed:
  184. self.on_device_epoch_changed(last_epoch or 0, snap.device_epoch, snap)
  185. if data_gap and self.on_data_gap:
  186. self.on_data_gap(snap)
  187. if epoch_changed and self.raise_on_epoch_change:
  188. raise DeviceEpochChanged(last_epoch or 0, snap.device_epoch, snap.device_id)
  189. if data_gap and self.raise_on_data_gap:
  190. raise DataGap(dropped_count=snap.dropped_telemetry_count)
  191. self._note_epoch(snap)
  192. return TelemetryEvent(
  193. snapshot=snap,
  194. epoch_changed=epoch_changed,
  195. previous_epoch=last_epoch,
  196. data_gap=data_gap,
  197. dropped_count=snap.dropped_telemetry_count,
  198. )
  199. async def subscribe_events(
  200. self,
  201. device_id: str,
  202. resume_after_event_id: int = 0,
  203. ) -> AsyncIterator[Any]:
  204. """Yield ObserveService events. Non-zero event_id is strictly increasing.
  205. A structured delivery_gap on a real event is a transport gap, not a
  206. device event with its own id. SDK raises DataGap when raise_on_data_gap.
  207. """
  208. pb2 = self._need_pb2()
  209. call = self._need_observe().SubscribeEvents(
  210. pb2.SubscribeEventsRequest(
  211. device_id=device_id, resume_after_event_id=resume_after_event_id
  212. )
  213. )
  214. last_id = 0
  215. try:
  216. async for ev in call:
  217. eid = int(ev.event_id)
  218. if eid == 0:
  219. raise DataGap(dropped_count=int(getattr(ev, "dropped_count", 0) or 0))
  220. if last_id and eid <= last_id:
  221. raise DataGap(
  222. dropped_count=0,
  223. resume_after_event_id=last_id,
  224. )
  225. gap = getattr(ev, "delivery_gap", None)
  226. if gap is not None and int(getattr(gap, "dropped_count", 0) or 0) > 0:
  227. if self.on_data_gap:
  228. self.on_data_gap(ev)
  229. if self.raise_on_data_gap:
  230. raise DataGap(
  231. dropped_count=int(gap.dropped_count),
  232. resume_after_event_id=int(gap.requested_resume_after_event_id),
  233. last_contiguous_event_id=int(gap.last_contiguous_event_id),
  234. oldest_available_event_id=int(gap.oldest_available_event_id),
  235. )
  236. last_id = eid
  237. yield ev
  238. except DataGap:
  239. raise
  240. except asyncio.CancelledError:
  241. raise
  242. except Exception as exc:
  243. raise TransportError(str(exc)) from exc
  244. def _note_epoch(self, snap: Snapshot) -> None:
  245. self._last_epoch[snap.device_id] = snap.device_epoch
  246. async def acquire_lease(
  247. self,
  248. device_id: str,
  249. holder: str,
  250. ttl: timedelta,
  251. *,
  252. auto_renew: bool = True,
  253. ) -> ControlLease:
  254. pb2 = self._need_pb2()
  255. req = pb2.AcquireControlLeaseRequest(device_id=device_id, holder=holder)
  256. req.ttl.FromTimedelta(ttl)
  257. try:
  258. resp = await self._need_control().AcquireControlLease(req)
  259. except Exception as exc:
  260. raise LeaseError(str(exc)) from exc
  261. lease = ControlLease(
  262. client=self,
  263. device_id=resp.lease.device_id or device_id,
  264. lease_id=resp.lease.lease_id,
  265. lease_epoch=int(resp.lease.lease_epoch),
  266. holder=resp.lease.holder or holder,
  267. ttl=ttl,
  268. auto_renew=auto_renew,
  269. )
  270. return lease
  271. async def renew_lease(self, device_id: str, lease_id: str, lease_epoch: int, ttl: timedelta):
  272. pb2 = self._need_pb2()
  273. req = pb2.RenewControlLeaseRequest(
  274. device_id=device_id, lease_id=lease_id, lease_epoch=lease_epoch
  275. )
  276. req.ttl.FromTimedelta(ttl)
  277. try:
  278. resp = await self._need_control().RenewControlLease(req)
  279. except Exception as exc:
  280. raise LeaseExpired(str(exc)) from exc
  281. return resp.lease
  282. async def release_lease(self, device_id: str, lease_id: str, lease_epoch: int) -> None:
  283. pb2 = self._need_pb2()
  284. req = pb2.ReleaseControlLeaseRequest(
  285. device_id=device_id, lease_id=lease_id, lease_epoch=lease_epoch
  286. )
  287. try:
  288. await self._need_control().ReleaseControlLease(req)
  289. except Exception as exc:
  290. text = str(exc).upper()
  291. if "EXPIRED" in text or "MISSING" in text or "NOT_FOUND" in text:
  292. return
  293. raise LeaseError(str(exc)) from exc
  294. async def validate(self, batch: ActionBatch) -> ActionResult:
  295. return await self._action("ValidateAction", batch)
  296. async def apply(self, batch: ActionBatch) -> ActionResult:
  297. result = await self._action("ApplyAction", batch)
  298. # Honesty: current UART has no ACK. Do not upgrade confirmation.
  299. if result.confirmation == "CONFIRMED":
  300. from hth_sdk.exceptions import ConfirmationNotProven
  301. raise ConfirmationNotProven(
  302. "daemon returned CONFIRMED; current Prod2U UART has no ACK. "
  303. "Treat this as a daemon bug, not hardware proof."
  304. )
  305. return result
  306. def action_builder(self, device_id: str, capabilities: Capabilities, client_id: str = "hth-sdk"):
  307. from hth_sdk.batch import ActionBatchBuilder
  308. return ActionBatchBuilder(
  309. device_id, client_id=client_id, capabilities=capabilities
  310. )
  311. async def resume_from_safe(
  312. self,
  313. device_id: str,
  314. lease_id: str,
  315. lease_epoch: int,
  316. batch: ActionBatch,
  317. *,
  318. timeout: Optional[float] = None,
  319. ) -> ActionResult:
  320. pb2 = self._need_pb2()
  321. req = pb2.ResumeFromSafeRequest(
  322. device_id=device_id, lease_id=lease_id, lease_epoch=lease_epoch, batch=batch_to_proto(pb2, batch)
  323. )
  324. try:
  325. resp = await self._need_control().ResumeFromSafe(req, timeout=self._deadline(timeout))
  326. except Exception as exc:
  327. raise TransportError(str(exc)) from exc
  328. return action_result_from_proto(pb2, resp)
  329. def _deadline(self, timeout: Optional[float]) -> float:
  330. if timeout is not None:
  331. return timeout
  332. if self._rpc_deadline_s is not None and self._rpc_deadline_s > 0:
  333. return self._rpc_deadline_s
  334. raise TransportError(
  335. "RPC deadline unknown; call get_capabilities() first or pass an explicit timeout "
  336. "(do not assume 2s — temperature transactions can exceed 5s)"
  337. )
  338. async def enter_safe_mode(self, device_id: str, lease_id: str, lease_epoch: int, reason: str) -> ActionResult:
  339. pb2 = self._need_pb2()
  340. req = pb2.EnterSafeModeRequest(
  341. device_id=device_id, lease_id=lease_id, lease_epoch=lease_epoch, reason=reason
  342. )
  343. try:
  344. resp = await self._need_control().EnterSafeMode(req, timeout=self._deadline(None))
  345. except Exception as exc:
  346. raise TransportError(str(exc)) from exc
  347. return action_result_from_proto(pb2, resp)
  348. async def _action(self, method: str, batch: ActionBatch) -> ActionResult:
  349. pb2 = self._need_pb2()
  350. stub = self._need_control()
  351. msg = batch_to_proto(pb2, batch)
  352. if method == "ValidateAction":
  353. req = pb2.ValidateActionRequest(batch=msg)
  354. rpc = stub.ValidateAction
  355. else:
  356. req = pb2.ApplyActionRequest(batch=msg)
  357. rpc = stub.ApplyAction
  358. try:
  359. resp = await rpc(req, timeout=self._deadline(None))
  360. except Exception as exc:
  361. text = str(exc)
  362. if "LEASE" in text.upper() and "EXPIRED" in text.upper():
  363. raise LeaseExpired(text) from exc
  364. if "LEASE" in text.upper() and "MISMATCH" in text.upper():
  365. raise LeaseMismatch(text) from exc
  366. raise TransportError(text) from exc
  367. result = action_result_from_proto(pb2, resp)
  368. if not result.accepted:
  369. raise ActionRejected(result.reject_reason, result.message, result.command_id)
  370. return result
  371. async def connect(
  372. *,
  373. observe: str = DEFAULT_OBSERVE_SOCKET,
  374. control: Optional[str] = None,
  375. role: str = "observe",
  376. check_api_version: bool = True,
  377. **kwargs,
  378. ) -> HthClient:
  379. """Connect to hthd Unix sockets.
  380. role:
  381. - observe: only observe.sock
  382. - control: observe.sock + control.sock (control defaults to DEFAULT_CONTROL_SOCKET)
  383. """
  384. try:
  385. import grpc
  386. except ImportError as exc:
  387. raise TransportError("grpcio is not installed") from exc
  388. pb2, pb2_grpc = load_stubs()
  389. observe_target = unix_target(observe)
  390. observe_channel = grpc.aio.insecure_channel(observe_target)
  391. observe_stub = pb2_grpc.ObserveServiceStub(observe_channel)
  392. control_channel = None
  393. control_stub = None
  394. if role in ("control", "both"):
  395. control_path = control or DEFAULT_CONTROL_SOCKET
  396. control_channel = grpc.aio.insecure_channel(unix_target(control_path))
  397. control_stub = pb2_grpc.ControlServiceStub(control_channel)
  398. return HthClient(
  399. observe_channel=observe_channel,
  400. control_channel=control_channel,
  401. observe_stub=observe_stub,
  402. control_stub=control_stub,
  403. pb2=pb2,
  404. check_api_version=check_api_version,
  405. **kwargs,
  406. )
  407. async def connect_observe(path: str = DEFAULT_OBSERVE_SOCKET, **kwargs) -> HthClient:
  408. return await connect(observe=path, role="observe", **kwargs)
  409. async def connect_control(
  410. observe: str = DEFAULT_OBSERVE_SOCKET,
  411. control: str = DEFAULT_CONTROL_SOCKET,
  412. **kwargs,
  413. ) -> HthClient:
  414. return await connect(observe=observe, control=control, role="control", **kwargs)