Coverage for src/anpr2mqtt/heartbeat.py: 100%

33 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-23 13:55 +0000

1"""Liveness heartbeat: the main loop touches a file, and the healthcheck checks how recently. 

2 

3Checking a local file means the container healthcheck needs no MQTT credentials or extra system 

4packages, and fails if the main loop stalls or the broker connection is lost, not only on a crash. 

5""" 

6 

7import os 

8import tempfile 

9import time 

10from pathlib import Path 

11 

12import structlog 

13 

14log = structlog.get_logger() 

15 

16HEARTBEAT_ENV = "ANPR2MQTT_HEARTBEAT_FILE" 

17HEARTBEAT_INTERVAL = 10 # seconds between touches of the heartbeat file 

18DEFAULT_MAX_AGE = 60 # seconds, several missed beats before the healthcheck fails 

19 

20 

21def heartbeat_path() -> Path: 

22 return Path(os.environ.get(HEARTBEAT_ENV) or Path(tempfile.gettempdir()) / "anpr2mqtt.heartbeat") 

23 

24 

25class Heartbeat: 

26 """Touches the heartbeat file at most once per interval, so it can be called on every loop pass""" 

27 

28 def __init__(self, path: Path | None = None, interval: float = HEARTBEAT_INTERVAL) -> None: 

29 self.path: Path = path or heartbeat_path() 

30 self.interval: float = interval 

31 self.last_beat: float | None = None 

32 

33 def beat(self) -> None: 

34 now: float = time.monotonic() 

35 if self.last_beat is not None and now - self.last_beat < self.interval: 

36 return 

37 try: 

38 self.path.touch() 

39 self.last_beat = now 

40 except OSError as e: 

41 log.warning("Unable to write heartbeat file %s: %s", self.path, e) 

42 

43 def clear(self) -> None: 

44 self.path.unlink(missing_ok=True) 

45 self.last_beat = None 

46 

47 

48def heartbeat_age(path: Path | None = None) -> float | None: 

49 """Seconds since the last heartbeat, or None if there has never been one""" 

50 try: 

51 return time.time() - (path or heartbeat_path()).stat().st_mtime 

52 except FileNotFoundError: 

53 return None