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
« 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.
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"""
7import os
8import tempfile
9import time
10from pathlib import Path
12import structlog
14log = structlog.get_logger()
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
21def heartbeat_path() -> Path:
22 return Path(os.environ.get(HEARTBEAT_ENV) or Path(tempfile.gettempdir()) / "anpr2mqtt.heartbeat")
25class Heartbeat:
26 """Touches the heartbeat file at most once per interval, so it can be called on every loop pass"""
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
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)
43 def clear(self) -> None:
44 self.path.unlink(missing_ok=True)
45 self.last_beat = None
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