import asyncio from collections.abc import Awaitable, Callable from contextlib import suppress from pathlib import Path from messenger.shared.application.ports import Logger class Heartbeat: __slots__ = ("_interval", "_logger", "_path", "_probe", "_task") def __init__( self, path: Path | None, probe: Callable[[], Awaitable[bool]], interval: float, logger: Logger, ) -> None: self._path = path self._probe = probe self._interval = interval self._logger = logger self._task: asyncio.Task[None] | None = None def start(self) -> None: if self._path is not None: self._task = asyncio.create_task(self._run(self._path)) async def stop(self) -> None: if self._task is None: return self._task.cancel() with suppress(asyncio.CancelledError): await self._task self._task = None async def _run(self, path: Path) -> None: while True: try: if await self._probe(): await asyncio.to_thread(path.touch) except Exception as error: self._logger.warning("heartbeat.failed", error=type(error).__name__) await asyncio.sleep(self._interval)