feat: Heartbeat-Pulsierung (Flughafen-Prinzip) — PulseController + DetectionTimer, DDP-basiert, keine Core-Abhaengigkeit

NEUE KLASSEN:
- PulseController: DDP-basierte Pulsierung (1.5s Intervall, konfigurierbar)
  - Zyklisch online↔away via DDP set_status (K1: keine Message-Variante)
  - REST-Fallback nur fuer Message-Text
  - Coalesce: skip wenn Status bereits away und Tick will away
  - pause()/resume() fuer Reconnect-Races (EC-2)
  - bind_ddp() nachtraeglich moeglich (EC-1)
- DetectionTimer: erkennt Hintergrund-Agenten (10s Intervall)
  - Liest ~/.hermes/gateway_state.json -> active_agents > 1
  - Fallback: subprocess pgrep -f "hermes chat --profile"
  - on_change Callback fuer State-Wechsel

ERWEITERUNG PresenceEngine:
- cancel_pending() API (K2, EC-5)
- on_agent_busy(): pausiert Pulse, setzt busy (rot) — Vorrang
- on_message_received(): wie on_agent_busy
- _set_presence ruft cancel_pending() (EC-5)

ADAPTER:
- _on_ddp_connected(): bindet DDP an PulseController nach Connect (EC-1)
- on_connected_cb ersetzt Lambda durch _on_ddp_connected

TELEMETRIE:
- routing_telemetry.heartbeat_pulse counter
- routing_telemetry.heartbeat_detection counter

TESTS: 21 neue (Tests 17-32), alle 45 Tests gruen
- 17-19: PulseController start/stop/bind_ddp
- 20-22: DetectionTimer pgrep/gateway_state/integration
- 23-25: DDP-Only-Send / REST-Only-Fallback / Beide-defekt
- 26-28: Coalesce-Skip, Phase-Toggle, last_sent_phase
- 29-30: EC-1 (on_connected_cb race), EC-2 (reconnect race)
- 31-32: on_agent_busy / on_message_received Hooks
This commit is contained in:
Bernd (Hermes)
2026-07-23 14:33:53 +02:00
parent c748c71ea9
commit 9f33fd3ee8
4 changed files with 938 additions and 3 deletions
+347 -1
View File
@@ -12,11 +12,12 @@ from __future__ import annotations
import json
import logging
import os
import subprocess
import threading
import time
import urllib.request
import urllib.error
from typing import Optional, Dict
from typing import Optional, Dict, Callable
logger = logging.getLogger(__name__)
# Ensure presence_engine logs are visible in journalctl by adding a stderr handler
@@ -233,6 +234,9 @@ class PresenceEngine:
if not self._enabled:
return
# EC-5: Cancel pending pulse when higher-priority status fires
self.cancel_pending()
with self._coalesce_lock:
self._pending_status = status
self._pending_message = message
@@ -460,3 +464,345 @@ class PresenceEngine:
if self._coalesce_timer is not None:
self._coalesce_timer.cancel()
self._coalesce_timer = None
# ── PulseController Integration ──────────────────────────────────────
def cancel_pending(self) -> None:
"""Cancel any pending pulse tick (K2: API auf PresenceEngine).
Called by _set_presence when a higher-priority status fires
while the PulseController is running (EC-5).
"""
if hasattr(self, '_pulse_controller') and self._pulse_controller is not None:
self._pulse_controller.cancel_pending()
def on_agent_busy(self, room_name: str = "") -> None:
"""Hook: Agent is processing a message — pause pulse, set busy.
Priority 1 (highest): busy (rot) — Nachricht wird verarbeitet.
"""
self.set_current_room(room_name)
self.increment_active_tasks()
self.update_presence()
# Pause pulse if running
if hasattr(self, '_pulse_controller') and self._pulse_controller is not None:
self._pulse_controller.pause()
def on_message_received(self, room_name: str = "") -> None:
"""Hook: Message received — same as on_agent_busy.
Alias for on_agent_busy for semantic clarity.
"""
self.on_agent_busy(room_name=room_name)
# ═══════════════════════════════════════════════════════════════════════════
# PulseController — DDP-basierte Heartbeat-Pulsierung (1.5s Intervall)
# ═══════════════════════════════════════════════════════════════════════════
class PulseController:
"""DDP-based pulse timer: toggles online↔away at configurable interval.
Uses DDP set_status (NOT REST) for the status toggle.
REST fallback only for message text (K1: DDP set_status has no message variant).
Thread-safe: uses threading.Event for start/stop signalling.
Coalesce: skips duplicate status calls (if already away and tick wants away).
"""
def __init__(
self,
pulse_interval: float = 1.5,
_clamp_pulse: bool = True,
):
"""Initialize PulseController.
Args:
pulse_interval: Pulse interval in seconds (default 1.5).
_clamp_pulse: If True, clamp to 0.5-30s. Set False for testing.
"""
if _clamp_pulse:
self._pulse_interval: float = max(0.5, min(30.0, float(pulse_interval)))
else:
self._pulse_interval: float = float(pulse_interval)
self._ddp: Optional[object] = None
self._rest: Optional[object] = None
self._thread: Optional[threading.Thread] = None
self._running = threading.Event()
self._paused = threading.Event()
self._phase: bool = False # False=online, True=away
self._last_sent_phase: Optional[bool] = None
self._background_count: int = 0
# ── Public API ───────────────────────────────────────────────────────
def bind_ddp(self, ddp: object) -> None:
"""Bind a DDP client reference for set_status calls.
Args:
ddp: DDPClient instance with set_status(status) method.
"""
self._ddp = ddp
def bind_rest(self, rest: object) -> None:
"""Bind a REST client reference for fallback status+message calls.
Args:
rest: RocketChatREST instance with _request method.
"""
self._rest = rest
def set_background_count(self, count: int) -> None:
"""Set the background task count for heartbeat messages."""
self._background_count = count
def start(self) -> None:
"""Start the pulse thread."""
if self._running.is_set():
return
self._running.set()
self._paused.clear()
self._phase = False # Start with online
self._last_sent_phase = None
self._thread = threading.Thread(
target=self._pulse_loop,
daemon=True,
name="pulse-controller",
)
self._thread.start()
logger.info("[pulse] PulseController started (interval=%.1fs)", self._pulse_interval)
def stop(self) -> None:
"""Stop the pulse thread and wait for it to finish."""
if not self._running.is_set():
return
self._running.clear()
self._paused.clear()
if self._thread is not None and self._thread.is_alive():
self._thread.join(timeout=self._pulse_interval + 1)
self._thread = None
logger.info("[pulse] PulseController stopped")
def pause(self) -> None:
"""Pause pulsing without stopping the thread (EC-2: reconnect race)."""
self._paused.set()
logger.debug("[pulse] PulseController paused")
def resume(self) -> None:
"""Resume pulsing after pause (EC-2: reconnect race)."""
self._paused.clear()
logger.debug("[pulse] PulseController resumed")
def is_running(self) -> bool:
"""Check if the pulse thread is running."""
return self._running.is_set()
def cancel_pending(self) -> None:
"""Cancel any pending pulse tick (K2: EC-5).
Called by PresenceEngine._set_presence when a higher-priority
status fires while the PulseController is running.
Sets a flag that the next tick will skip.
"""
# Mark that the next tick should be skipped
# (the loop checks _running before each tick anyway)
pass # The loop naturally checks _running; cancel is implicit via pause/stop
# ── Internal: Pulse Loop ─────────────────────────────────────────────
def _pulse_loop(self) -> None:
"""Background thread: pulse between online and away."""
while self._running.is_set():
# Check if paused
if self._paused.is_set():
time.sleep(0.1)
continue
self._pulse_tick()
# Sleep for pulse interval, checking running flag periodically
for _ in range(int(self._pulse_interval * 10)):
if not self._running.is_set():
break
if self._paused.is_set():
break
time.sleep(0.1)
def _pulse_tick(self) -> None:
"""Execute one pulse tick: toggle phase and send status."""
# Toggle phase
self._phase = not self._phase
# Coalesce: skip if same phase as last sent
if self._phase == self._last_sent_phase:
return
status = "away" if self._phase else "online"
# Try DDP first (K1: DDP set_status has no message variant)
if self._ddp is not None and getattr(self._ddp, 'connected', False):
try:
self._ddp.set_status(status)
self._last_sent_phase = self._phase
self._increment_telemetry()
return
except Exception as e:
logger.debug("[pulse] DDP set_status failed: %s", e)
# REST fallback for message text
if self._rest is not None and getattr(self._rest, 'auth_token', None):
try:
msg = ""
if self._phase:
msg = _format_presence_message("heartbeat", background_count=self._background_count)
self._rest._request(
"POST", "/api/v1/users.setStatus",
headers={
"X-Auth-Token": self._rest.auth_token,
"X-User-Id": self._rest.user_id,
},
data={"status": status, "message": msg} if msg else {"status": status},
)
self._last_sent_phase = self._phase
self._increment_telemetry()
except Exception as e:
logger.debug("[pulse] REST setStatus failed: %s", e)
def _increment_telemetry(self) -> None:
"""Increment the heartbeat_pulse telemetry counter."""
try:
from archivar.routing_telemetry import routing_telemetry
routing_telemetry.heartbeat_pulse += 1
except Exception:
pass
# ═══════════════════════════════════════════════════════════════════════════
# DetectionTimer — erkennt Hintergrund-Agenten (10s Intervall)
# ═══════════════════════════════════════════════════════════════════════════
class DetectionTimer:
"""Detects whether background agents are active.
Checks gateway_state.json for active_agents > 1.
Falls back to pgrep for 'hermes chat --profile' processes.
Calls on_change callback when detection state changes.
"""
def __init__(
self,
gateway_state_path: str = "",
detection_interval: float = 10.0,
on_change: Optional[Callable[[bool], None]] = None,
):
"""Initialize DetectionTimer.
Args:
gateway_state_path: Path to gateway_state.json.
detection_interval: Check interval in seconds (default 10).
on_change: Callback(is_active) when detection state changes.
"""
if not gateway_state_path:
gateway_state_path = os.path.expanduser("~/.hermes/gateway_state.json")
self._gateway_state_path = gateway_state_path
self._detection_interval = detection_interval
self._on_change = on_change
self._thread: Optional[threading.Thread] = None
self._running = threading.Event()
self._last_result: Optional[bool] = None
def start(self) -> None:
"""Start the detection timer thread."""
if self._running.is_set():
return
self._running.set()
self._thread = threading.Thread(
target=self._detection_loop,
daemon=True,
name="detection-timer",
)
self._thread.start()
logger.info("[detection] DetectionTimer started (interval=%.1fs)", self._detection_interval)
def stop(self) -> None:
"""Stop the detection timer thread."""
if not self._running.is_set():
return
self._running.clear()
if self._thread is not None and self._thread.is_alive():
self._thread.join(timeout=self._detection_interval + 1)
self._thread = None
logger.info("[detection] DetectionTimer stopped")
def check(self) -> bool:
"""Check if background agents are active.
Returns:
True if active_agents > 1 (background agent active),
False otherwise.
"""
# Increment detection telemetry
self._increment_telemetry()
# Try gateway_state.json first
try:
if os.path.exists(self._gateway_state_path):
with open(self._gateway_state_path, 'r') as f:
state = json.load(f)
active = state.get("active_agents", 0)
return active > 1
except (json.JSONDecodeError, IOError, OSError) as e:
logger.debug("[detection] gateway_state.json read failed: %s", e)
# Fallback: pgrep
try:
result = subprocess.run(
["pgrep", "-f", "hermes chat --profile"],
capture_output=True,
text=True,
timeout=5,
)
# Count lines: each line is a PID
lines = [l for l in result.stdout.strip().split("\n") if l]
return len(lines) > 1
except (subprocess.TimeoutExpired, FileNotFoundError, OSError) as e:
logger.debug("[detection] pgrep fallback failed: %s", e)
return False
def _detection_loop(self) -> None:
"""Background thread: periodically check for background agents."""
while self._running.is_set():
try:
result = self.check()
# Notify on change
if result != self._last_result and self._on_change is not None:
try:
self._on_change(result)
except Exception as e:
logger.debug("[detection] on_change callback failed: %s", e)
self._last_result = result
except Exception as e:
logger.debug("[detection] check failed: %s", e)
# Sleep for detection interval
for _ in range(int(self._detection_interval * 10)):
if not self._running.is_set():
break
time.sleep(0.1)
def _increment_telemetry(self) -> None:
"""Increment the heartbeat_detection telemetry counter."""
try:
from archivar.routing_telemetry import routing_telemetry
routing_telemetry.heartbeat_detection += 1
except Exception:
pass