| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462 |
- """grpc.aio client over Unix domain sockets.
- Observe and control are separate sockets. This client never opens a serial
- port. SET_ALL confirmation from the daemon must remain UNCONFIRMED on the
- current Prod2U UART contract.
- """
- from __future__ import annotations
- import asyncio
- from collections.abc import AsyncIterator, Callable
- from datetime import timedelta
- from typing import Any, Optional
- from hth_sdk.constants import (
- API_VERSION,
- DEFAULT_CONTROL_SOCKET,
- DEFAULT_OBSERVE_SOCKET,
- )
- from hth_sdk.exceptions import (
- ActionRejected,
- ApiVersionMismatch,
- DataGap,
- DeviceEpochChanged,
- LeaseError,
- LeaseExpired,
- LeaseMismatch,
- NotConnected,
- TransportError,
- )
- from hth_sdk.lease import ControlLease
- from hth_sdk.proto_codec import (
- action_result_from_proto,
- batch_to_proto,
- capabilities_from_proto,
- device_info_from_proto,
- snapshot_from_proto,
- )
- from hth_sdk.stubs import load_stubs
- from hth_sdk.types import (
- ActionBatch,
- ActionResult,
- Capabilities,
- DeviceInfo,
- Snapshot,
- TelemetryEvent,
- )
- EpochCallback = Callable[[int, int, Snapshot], None]
- GapCallback = Callable[[Snapshot], None]
- def unix_target(path: str) -> str:
- if path.startswith("unix:"):
- return path
- if path.startswith("@"):
- return f"unix://{path}"
- if not path.startswith("/"):
- raise TransportError(f"socket path must be absolute or unix://, got {path!r}")
- return f"unix://{path}"
- class HthClient:
- def __init__(
- self,
- *,
- observe_channel=None,
- control_channel=None,
- observe_stub=None,
- control_stub=None,
- pb2=None,
- check_api_version: bool = True,
- on_device_epoch_changed: Optional[EpochCallback] = None,
- on_data_gap: Optional[GapCallback] = None,
- raise_on_epoch_change: bool = False,
- raise_on_data_gap: bool = False,
- ) -> None:
- self._observe_channel = observe_channel
- self._control_channel = control_channel
- self._observe = observe_stub
- self._control = control_stub
- self._pb2 = pb2
- self._check_api_version = check_api_version
- self._seen_api_version: Optional[str] = None
- self.on_device_epoch_changed = on_device_epoch_changed
- self.on_data_gap = on_data_gap
- self.raise_on_epoch_change = raise_on_epoch_change
- self.raise_on_data_gap = raise_on_data_gap
- self._last_epoch: dict[str, int] = {}
- self._timing: Optional[object] = None
- self._rpc_deadline_s: Optional[float] = None
- @property
- def has_observe(self) -> bool:
- return self._observe is not None
- @property
- def has_control(self) -> bool:
- return self._control is not None
- async def close(self) -> None:
- for ch in (self._observe_channel, self._control_channel):
- if ch is None:
- continue
- await ch.close()
- self._observe_channel = None
- self._control_channel = None
- async def __aenter__(self) -> "HthClient":
- return self
- async def __aexit__(self, *exc: object) -> None:
- await self.close()
- def _need_observe(self):
- if self._observe is None:
- raise NotConnected("observe socket is not connected")
- return self._observe
- def _need_control(self):
- if self._control is None:
- raise NotConnected("control socket is not connected")
- return self._control
- def _need_pb2(self):
- if self._pb2 is None:
- self._pb2, _ = load_stubs()
- return self._pb2
- def _maybe_check_api(self, api_version: str) -> None:
- self._seen_api_version = api_version
- if self._check_api_version and api_version and api_version != API_VERSION:
- raise ApiVersionMismatch(api_version, API_VERSION)
- async def list_devices(self) -> list[DeviceInfo]:
- pb2 = self._need_pb2()
- try:
- resp = await self._need_observe().ListDevices(pb2.ListDevicesRequest())
- except Exception as exc:
- raise TransportError(str(exc)) from exc
- return [device_info_from_proto(pb2, d) for d in resp.devices]
- async def get_capabilities(self, device_id: str) -> Capabilities:
- pb2 = self._need_pb2()
- try:
- resp = await self._need_observe().GetCapabilities(
- pb2.GetCapabilitiesRequest(device_id=device_id)
- )
- except Exception as exc:
- raise TransportError(str(exc)) from exc
- caps = capabilities_from_proto(pb2, resp.capabilities)
- self._maybe_check_api(caps.api_version)
- if caps.timing is not None and caps.timing.recommended_rpc_deadline_ms > 0:
- self._timing = caps.timing
- self._rpc_deadline_s = caps.timing.recommended_rpc_deadline_ms / 1000.0
- return caps
- async def get_snapshot(self, device_id: str) -> Snapshot:
- pb2 = self._need_pb2()
- try:
- resp = await self._need_observe().GetSnapshot(pb2.GetSnapshotRequest(device_id=device_id))
- except Exception as exc:
- raise TransportError(str(exc)) from exc
- snap = snapshot_from_proto(pb2, resp.snapshot)
- self._note_epoch(snap)
- return snap
- async def get_faults(self, device_id: str, include_inactive: bool = False):
- pb2 = self._need_pb2()
- try:
- resp = await self._need_observe().GetFaults(
- pb2.GetFaultsRequest(device_id=device_id, include_inactive=include_inactive)
- )
- except Exception as exc:
- raise TransportError(str(exc)) from exc
- from hth_sdk.proto_codec import _fault_from_proto
- return [ _fault_from_proto(pb2, f) for f in resp.faults ]
- async def subscribe_telemetry(
- self,
- device_id: str,
- resume_after_event_id: int = 0,
- ) -> AsyncIterator[TelemetryEvent]:
- pb2 = self._need_pb2()
- call = self._need_observe().SubscribeTelemetry(
- pb2.SubscribeTelemetryRequest(
- device_id=device_id, resume_after_event_id=resume_after_event_id
- )
- )
- last_epoch: Optional[int] = self._last_epoch.get(device_id)
- try:
- async for msg in call:
- snap = snapshot_from_proto(pb2, msg)
- event = self._wrap_telemetry(snap, last_epoch)
- last_epoch = snap.device_epoch
- yield event
- except (DeviceEpochChanged, DataGap):
- raise
- except asyncio.CancelledError:
- raise
- except Exception as exc:
- raise TransportError(str(exc)) from exc
- def _wrap_telemetry(self, snap: Snapshot, last_epoch: Optional[int]) -> TelemetryEvent:
- epoch_changed = last_epoch is not None and snap.device_epoch != last_epoch
- data_gap = bool(snap.data_gap)
- if epoch_changed and self.on_device_epoch_changed:
- self.on_device_epoch_changed(last_epoch or 0, snap.device_epoch, snap)
- if data_gap and self.on_data_gap:
- self.on_data_gap(snap)
- if epoch_changed and self.raise_on_epoch_change:
- raise DeviceEpochChanged(last_epoch or 0, snap.device_epoch, snap.device_id)
- if data_gap and self.raise_on_data_gap:
- raise DataGap(dropped_count=snap.dropped_telemetry_count)
- self._note_epoch(snap)
- return TelemetryEvent(
- snapshot=snap,
- epoch_changed=epoch_changed,
- previous_epoch=last_epoch,
- data_gap=data_gap,
- dropped_count=snap.dropped_telemetry_count,
- )
- async def subscribe_events(
- self,
- device_id: str,
- resume_after_event_id: int = 0,
- ) -> AsyncIterator[Any]:
- """Yield ObserveService events. Non-zero event_id is strictly increasing.
- A structured delivery_gap on a real event is a transport gap, not a
- device event with its own id. SDK raises DataGap when raise_on_data_gap.
- """
- pb2 = self._need_pb2()
- call = self._need_observe().SubscribeEvents(
- pb2.SubscribeEventsRequest(
- device_id=device_id, resume_after_event_id=resume_after_event_id
- )
- )
- last_id = 0
- try:
- async for ev in call:
- eid = int(ev.event_id)
- if eid == 0:
- raise DataGap(dropped_count=int(getattr(ev, "dropped_count", 0) or 0))
- if last_id and eid <= last_id:
- raise DataGap(
- dropped_count=0,
- resume_after_event_id=last_id,
- )
- gap = getattr(ev, "delivery_gap", None)
- if gap is not None and int(getattr(gap, "dropped_count", 0) or 0) > 0:
- if self.on_data_gap:
- self.on_data_gap(ev)
- if self.raise_on_data_gap:
- raise DataGap(
- dropped_count=int(gap.dropped_count),
- resume_after_event_id=int(gap.requested_resume_after_event_id),
- last_contiguous_event_id=int(gap.last_contiguous_event_id),
- oldest_available_event_id=int(gap.oldest_available_event_id),
- )
- last_id = eid
- yield ev
- except DataGap:
- raise
- except asyncio.CancelledError:
- raise
- except Exception as exc:
- raise TransportError(str(exc)) from exc
- def _note_epoch(self, snap: Snapshot) -> None:
- self._last_epoch[snap.device_id] = snap.device_epoch
- async def acquire_lease(
- self,
- device_id: str,
- holder: str,
- ttl: timedelta,
- *,
- auto_renew: bool = True,
- ) -> ControlLease:
- pb2 = self._need_pb2()
- req = pb2.AcquireControlLeaseRequest(device_id=device_id, holder=holder)
- req.ttl.FromTimedelta(ttl)
- try:
- resp = await self._need_control().AcquireControlLease(req)
- except Exception as exc:
- raise LeaseError(str(exc)) from exc
- lease = ControlLease(
- client=self,
- device_id=resp.lease.device_id or device_id,
- lease_id=resp.lease.lease_id,
- lease_epoch=int(resp.lease.lease_epoch),
- holder=resp.lease.holder or holder,
- ttl=ttl,
- auto_renew=auto_renew,
- )
- return lease
- async def renew_lease(self, device_id: str, lease_id: str, lease_epoch: int, ttl: timedelta):
- pb2 = self._need_pb2()
- req = pb2.RenewControlLeaseRequest(
- device_id=device_id, lease_id=lease_id, lease_epoch=lease_epoch
- )
- req.ttl.FromTimedelta(ttl)
- try:
- resp = await self._need_control().RenewControlLease(req)
- except Exception as exc:
- raise LeaseExpired(str(exc)) from exc
- return resp.lease
- async def release_lease(self, device_id: str, lease_id: str, lease_epoch: int) -> None:
- pb2 = self._need_pb2()
- req = pb2.ReleaseControlLeaseRequest(
- device_id=device_id, lease_id=lease_id, lease_epoch=lease_epoch
- )
- try:
- await self._need_control().ReleaseControlLease(req)
- except Exception as exc:
- text = str(exc).upper()
- if "EXPIRED" in text or "MISSING" in text or "NOT_FOUND" in text:
- return
- raise LeaseError(str(exc)) from exc
- async def validate(self, batch: ActionBatch) -> ActionResult:
- return await self._action("ValidateAction", batch)
- async def apply(self, batch: ActionBatch) -> ActionResult:
- result = await self._action("ApplyAction", batch)
- # Honesty: current UART has no ACK. Do not upgrade confirmation.
- if result.confirmation == "CONFIRMED":
- from hth_sdk.exceptions import ConfirmationNotProven
- raise ConfirmationNotProven(
- "daemon returned CONFIRMED; current Prod2U UART has no ACK. "
- "Treat this as a daemon bug, not hardware proof."
- )
- return result
- def action_builder(self, device_id: str, capabilities: Capabilities, client_id: str = "hth-sdk"):
- from hth_sdk.batch import ActionBatchBuilder
- return ActionBatchBuilder(
- device_id, client_id=client_id, capabilities=capabilities
- )
- async def resume_from_safe(
- self,
- device_id: str,
- lease_id: str,
- lease_epoch: int,
- batch: ActionBatch,
- *,
- timeout: Optional[float] = None,
- ) -> ActionResult:
- pb2 = self._need_pb2()
- req = pb2.ResumeFromSafeRequest(
- device_id=device_id, lease_id=lease_id, lease_epoch=lease_epoch, batch=batch_to_proto(pb2, batch)
- )
- try:
- resp = await self._need_control().ResumeFromSafe(req, timeout=self._deadline(timeout))
- except Exception as exc:
- raise TransportError(str(exc)) from exc
- return action_result_from_proto(pb2, resp)
- def _deadline(self, timeout: Optional[float]) -> float:
- if timeout is not None:
- return timeout
- if self._rpc_deadline_s is not None and self._rpc_deadline_s > 0:
- return self._rpc_deadline_s
- raise TransportError(
- "RPC deadline unknown; call get_capabilities() first or pass an explicit timeout "
- "(do not assume 2s — temperature transactions can exceed 5s)"
- )
- async def enter_safe_mode(self, device_id: str, lease_id: str, lease_epoch: int, reason: str) -> ActionResult:
- pb2 = self._need_pb2()
- req = pb2.EnterSafeModeRequest(
- device_id=device_id, lease_id=lease_id, lease_epoch=lease_epoch, reason=reason
- )
- try:
- resp = await self._need_control().EnterSafeMode(req, timeout=self._deadline(None))
- except Exception as exc:
- raise TransportError(str(exc)) from exc
- return action_result_from_proto(pb2, resp)
- async def _action(self, method: str, batch: ActionBatch) -> ActionResult:
- pb2 = self._need_pb2()
- stub = self._need_control()
- msg = batch_to_proto(pb2, batch)
- if method == "ValidateAction":
- req = pb2.ValidateActionRequest(batch=msg)
- rpc = stub.ValidateAction
- else:
- req = pb2.ApplyActionRequest(batch=msg)
- rpc = stub.ApplyAction
- try:
- resp = await rpc(req, timeout=self._deadline(None))
- except Exception as exc:
- text = str(exc)
- if "LEASE" in text.upper() and "EXPIRED" in text.upper():
- raise LeaseExpired(text) from exc
- if "LEASE" in text.upper() and "MISMATCH" in text.upper():
- raise LeaseMismatch(text) from exc
- raise TransportError(text) from exc
- result = action_result_from_proto(pb2, resp)
- if not result.accepted:
- raise ActionRejected(result.reject_reason, result.message, result.command_id)
- return result
- async def connect(
- *,
- observe: str = DEFAULT_OBSERVE_SOCKET,
- control: Optional[str] = None,
- role: str = "observe",
- check_api_version: bool = True,
- **kwargs,
- ) -> HthClient:
- """Connect to hthd Unix sockets.
- role:
- - observe: only observe.sock
- - control: observe.sock + control.sock (control defaults to DEFAULT_CONTROL_SOCKET)
- """
- try:
- import grpc
- except ImportError as exc:
- raise TransportError("grpcio is not installed") from exc
- pb2, pb2_grpc = load_stubs()
- observe_target = unix_target(observe)
- observe_channel = grpc.aio.insecure_channel(observe_target)
- observe_stub = pb2_grpc.ObserveServiceStub(observe_channel)
- control_channel = None
- control_stub = None
- if role in ("control", "both"):
- control_path = control or DEFAULT_CONTROL_SOCKET
- control_channel = grpc.aio.insecure_channel(unix_target(control_path))
- control_stub = pb2_grpc.ControlServiceStub(control_channel)
- return HthClient(
- observe_channel=observe_channel,
- control_channel=control_channel,
- observe_stub=observe_stub,
- control_stub=control_stub,
- pb2=pb2,
- check_api_version=check_api_version,
- **kwargs,
- )
- async def connect_observe(path: str = DEFAULT_OBSERVE_SOCKET, **kwargs) -> HthClient:
- return await connect(observe=path, role="observe", **kwargs)
- async def connect_control(
- observe: str = DEFAULT_OBSERVE_SOCKET,
- control: str = DEFAULT_CONTROL_SOCKET,
- **kwargs,
- ) -> HthClient:
- return await connect(observe=observe, control=control, role="control", **kwargs)
|