lease.py 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. """ControlLease async context manager.
  2. gRPC keepalive is not a control heartbeat. This object renews the *lease*.
  3. It does not feed the FPGA watchdog; hthd does that by repeating continuous
  4. targets after startup_complete.
  5. """
  6. from __future__ import annotations
  7. import asyncio
  8. from datetime import timedelta
  9. from typing import TYPE_CHECKING, Optional
  10. from hth_sdk.types import ActionBatch, ActionResult
  11. if TYPE_CHECKING:
  12. from hth_sdk.client import HthClient
  13. from hth_sdk.mock import MockClient
  14. class ControlLease:
  15. def __init__(
  16. self,
  17. *,
  18. client: "HthClient | MockClient",
  19. device_id: str,
  20. lease_id: str,
  21. lease_epoch: int,
  22. holder: str,
  23. ttl: timedelta,
  24. auto_renew: bool = True,
  25. ) -> None:
  26. self._client = client
  27. self.device_id = device_id
  28. self.lease_id = lease_id
  29. self.lease_epoch = lease_epoch
  30. self.holder = holder
  31. self.ttl = ttl
  32. self.auto_renew = auto_renew
  33. self._task: Optional[asyncio.Task] = None
  34. self._closed = False
  35. async def __aenter__(self) -> "ControlLease":
  36. if self.auto_renew:
  37. self._task = asyncio.create_task(self._renew_loop(), name="hth-lease-renew")
  38. return self
  39. async def __aexit__(self, *exc: object) -> None:
  40. await self.release()
  41. async def _renew_loop(self) -> None:
  42. # Renew at one-third of TTL so a missed tick still has margin.
  43. interval = max(self.ttl.total_seconds() / 3.0, 0.2)
  44. try:
  45. while not self._closed:
  46. await asyncio.sleep(interval)
  47. if self._closed:
  48. return
  49. await self._client.renew_lease(
  50. self.device_id, self.lease_id, self.lease_epoch, self.ttl
  51. )
  52. except asyncio.CancelledError:
  53. return
  54. def bind(self, batch: ActionBatch) -> ActionBatch:
  55. return batch.with_lease(self.lease_id, self.lease_epoch)
  56. async def validate(self, batch: ActionBatch) -> ActionResult:
  57. return await self._client.validate(self.bind(batch))
  58. async def apply(self, batch: ActionBatch) -> ActionResult:
  59. return await self._client.apply(self.bind(batch))
  60. async def enter_safe_mode(self, reason: str = "client-requested") -> ActionResult:
  61. return await self._client.enter_safe_mode(
  62. self.device_id, self.lease_id, self.lease_epoch, reason
  63. )
  64. async def resume_from_safe(self, batch: ActionBatch) -> ActionResult:
  65. return await self._client.resume_from_safe(
  66. self.device_id, self.lease_id, self.lease_epoch, self.bind(batch)
  67. )
  68. async def release(self) -> None:
  69. if self._closed:
  70. return
  71. self._closed = True
  72. if self._task is not None:
  73. self._task.cancel()
  74. try:
  75. await self._task
  76. except asyncio.CancelledError:
  77. pass
  78. self._task = None
  79. await self._client.release_lease(self.device_id, self.lease_id, self.lease_epoch)