"""ControlLease async context manager. gRPC keepalive is not a control heartbeat. This object renews the *lease*. It does not feed the FPGA watchdog; hthd does that by repeating continuous targets after startup_complete. """ from __future__ import annotations import asyncio from datetime import timedelta from typing import TYPE_CHECKING, Optional from hth_sdk.exceptions import LeaseError from hth_sdk.types import ActionBatch, ActionResult if TYPE_CHECKING: from hth_sdk.client import HthClient from hth_sdk.mock import MockClient class ControlLease: def __init__( self, *, client: "HthClient | MockClient", device_id: str, lease_id: str, lease_epoch: int, holder: str, ttl: timedelta, auto_renew: bool = True, ) -> None: self._client = client self.device_id = device_id self.lease_id = lease_id self.lease_epoch = lease_epoch self.holder = holder self.ttl = ttl self.auto_renew = auto_renew self._task: Optional[asyncio.Task] = None self._closed = False async def __aenter__(self) -> "ControlLease": if self.auto_renew: self._task = asyncio.create_task(self._renew_loop(), name="hth-lease-renew") return self async def __aexit__(self, *exc: object) -> None: await self.release() async def _renew_loop(self) -> None: # Renew at one-third of TTL so a missed tick still has margin. interval = max(self.ttl.total_seconds() / 3.0, 0.2) try: while not self._closed: await asyncio.sleep(interval) if self._closed: return await self._client.renew_lease( self.device_id, self.lease_id, self.lease_epoch, self.ttl ) except asyncio.CancelledError: return def bind(self, batch: ActionBatch) -> ActionBatch: return batch.with_lease(self.lease_id, self.lease_epoch) async def validate(self, batch: ActionBatch) -> ActionResult: return await self._client.validate(self.bind(batch)) async def apply(self, batch: ActionBatch) -> ActionResult: return await self._client.apply(self.bind(batch)) async def enter_safe_mode(self, reason: str = "client-requested") -> ActionResult: result = await self._client.enter_safe_mode( self.device_id, self.lease_id, self.lease_epoch, reason ) if result.accepted: # Host enterSafe() invalidates the control lease. ResumeFromSafe # requires a newly acquired lease (TestResumeFromSafeStateMachine). await self._abandon_invalidated_lease() return result async def resume_from_safe(self, batch: ActionBatch) -> ActionResult: if self._closed: raise LeaseError( "EnterSafeMode invalidates the control lease; " "acquire a new lease before ResumeFromSafe" ) return await self._client.resume_from_safe( self.device_id, self.lease_id, self.lease_epoch, self.bind(batch) ) async def _abandon_invalidated_lease(self) -> None: self._closed = True if self._task is not None: self._task.cancel() try: await self._task except (asyncio.CancelledError, Exception): pass self._task = None async def release(self) -> None: if self._closed: return self._closed = True if self._task is not None: self._task.cancel() try: await self._task except (asyncio.CancelledError, Exception): pass self._task = None await self._client.release_lease(self.device_id, self.lease_id, self.lease_epoch)