fix: P0 Heartbeat Live-Verdrahtung — PulseController+DetectionTimer instanziierung, cancel_pending, ::setstatus Routing, pulse_interval Bereinigung

P0-1: PresenceEngine.__init__ instanziiert PulseController + DetectionTimer
       mit on_change-Callback. DetectionTimer startet automatisch bei enabled=True.
P0-2: PulseController.cancel_pending() implementiert — setzt _cancel_pending
       Flag, _pulse_tick prüft und skipped den nächsten Tick.
P0-3: ::setstatus on/off steuert PulseController — bind_rest/bind_ddp bei on,
       stop() bei off. Adapter.__init__ verdrahtet REST+DDP sofort.
P0-4: Alter Heartbeat-Code (10s, _start_heartbeat/_stop_heartbeat/_heartbeat_loop)
       entfernt. Nur PulseController (1.5s) als einziger Puls-Mechanismus.
       pulse_interval Default von 10s auf 1.5s, Clamping von 5-30 auf 0.5-30.
P0-5: 5 neue Live-Tests (TestP0LiveVerdrahtung) verifizieren PulseController
       + DetectionTimer nach __init__. 50/50 Tests grün.
This commit is contained in:
Bernd (Hermes)
2026-07-23 14:48:24 +02:00
parent 9f33fd3ee8
commit a07ca22ca8
3 changed files with 246 additions and 200 deletions
+56 -117
View File
@@ -84,7 +84,7 @@ class PresenceEngine:
rest=None,
enabled: bool = True,
coalesce_ms: int = 2000,
pulse_interval: float = 10,
pulse_interval: float = 1.5,
_clamp_pulse: bool = True,
):
"""Initialize the PresenceEngine.
@@ -93,8 +93,8 @@ class PresenceEngine:
rest: RocketChatREST instance for API calls.
enabled: Whether presence updates are enabled.
coalesce_ms: Coalesce delay in milliseconds (default 2000).
pulse_interval: Heartbeat pulse interval in seconds (5-30, default 10).
_clamp_pulse: If True, clamp pulse_interval to 5-30. Set False for testing.
pulse_interval: PulseController interval in seconds (0.5-30, default 1.5).
_clamp_pulse: If True, clamp pulse_interval to 0.5-30. Set False for testing.
"""
self._rest = rest
self._enabled = enabled
@@ -124,16 +124,25 @@ class PresenceEngine:
# Current room name for busy messages
self._current_room_name: str = ""
# Heartbeat
if _clamp_pulse:
self._pulse_interval: float = max(5.0, min(30.0, float(pulse_interval)))
else:
self._pulse_interval: float = float(pulse_interval)
# Background tasks counter (for display + PulseController coordination)
self._background_tasks: int = 0
self._background_tasks_lock = threading.Lock()
self._heartbeat_thread: Optional[threading.Thread] = None
self._heartbeat_running = threading.Event()
self._heartbeat_phase: bool = False # False=online, True=away
# P0-1: PulseController — DDP-basierte Heartbeat-Pulsierung (1.5s)
self._pulse_controller = PulseController(
pulse_interval=pulse_interval,
_clamp_pulse=_clamp_pulse,
)
# P0-1: DetectionTimer — erkennt Hintergrund-Agenten, steuert PulseController
self._detection_timer = DetectionTimer(
detection_interval=10.0,
on_change=self._on_detection_change,
)
# Start detection if enabled
if self._enabled:
self._detection_timer.start()
# ── Public API ───────────────────────────────────────────────────────
@@ -142,14 +151,16 @@ class PresenceEngine:
return self._enabled
def enable(self) -> None:
"""Enable presence updates."""
"""Enable presence updates. Starts DetectionTimer."""
self._enabled = True
self._detection_timer.start()
logger.info("[presence] PresenceEngine enabled")
def disable(self) -> None:
"""Disable presence updates. Stops heartbeat if running."""
"""Disable presence updates. Stops PulseController and DetectionTimer."""
self._enabled = False
self._stop_heartbeat()
self._pulse_controller.stop()
self._detection_timer.stop()
logger.info("[presence] PresenceEngine disabled")
def increment_active_tasks(self) -> int:
@@ -202,7 +213,7 @@ class PresenceEngine:
with self._background_tasks_lock:
self._background_tasks += 1
count = self._background_tasks
self._maybe_start_heartbeat()
self._pulse_controller.set_background_count(count)
return count
def decrement_background_tasks(self) -> int:
@@ -215,8 +226,9 @@ class PresenceEngine:
if self._background_tasks > 0:
self._background_tasks -= 1
count = self._background_tasks
self._pulse_controller.set_background_count(count)
if count == 0:
self._stop_heartbeat()
self._pulse_controller.stop()
return count
# ── Internal: Presence Setting ───────────────────────────────────────
@@ -315,102 +327,24 @@ class PresenceEngine:
except Exception as e:
logger.warning("[presence] Failed to set status: %s", e)
# ── Heartbeat ────────────────────────────────────────────────────────
# ── DetectionTimer Callback ──────────────────────────────────────────
def _maybe_start_heartbeat(self) -> None:
"""Start heartbeat if background_tasks > 0 and agent is idle.
def _on_detection_change(self, is_active: bool) -> None:
"""Callback from DetectionTimer: start/stop PulseController.
P1-5: Hält beide Locks gleichzeitig um Race Condition zu vermeiden.
When background agents are detected (is_active=True), start pulsing.
When no background agents (is_active=False), stop pulsing.
"""
if not self._enabled:
return
# P1-5: Beide Locks gleichzeitig halten für konsistente Snapshot-Reads
with self._active_tasks_lock:
with self._background_tasks_lock:
is_idle = self._active_tasks == 0
has_background = self._background_tasks > 0
if has_background and is_idle and not self._heartbeat_running.is_set():
self._start_heartbeat()
def _start_heartbeat(self) -> None:
"""Start the heartbeat pulse thread."""
if not self._enabled:
return
if self._heartbeat_running.is_set():
return
self._heartbeat_running.set()
self._heartbeat_phase = False # Start with online
self._heartbeat_thread = threading.Thread(
target=self._heartbeat_loop,
daemon=True,
name="presence-heartbeat",
)
self._heartbeat_thread.start()
logger.info("[presence] Heartbeat started (interval=%ds)", self._pulse_interval)
def _stop_heartbeat(self) -> None:
"""Stop the heartbeat pulse thread."""
if not self._heartbeat_running.is_set():
return
self._heartbeat_running.clear()
# Wait for thread to finish (with timeout)
if self._heartbeat_thread is not None and self._heartbeat_thread.is_alive():
self._heartbeat_thread.join(timeout=self._pulse_interval + 1)
self._heartbeat_thread = None
logger.info("[presence] Heartbeat stopped")
def _heartbeat_loop(self) -> None:
"""Background thread: pulse between online and away.
P1-5: Hält beide Locks gleichzeitig für konsistente Snapshot-Reads.
"""
while self._heartbeat_running.is_set():
# P1-5: Beide Locks gleichzeitig halten
with self._background_tasks_lock:
with self._active_tasks_lock:
bg_count = self._background_tasks
is_idle = self._active_tasks == 0
if bg_count == 0:
# No more background tasks — stop
self._heartbeat_running.clear()
# Set back to online (bypass coalesce for immediate effect)
self._send_rest("online", "")
self._last_sent_status = "online"
self._last_sent_message = ""
break
if not is_idle:
# Agent is busy — stop pulsing, let busy status take over
self._heartbeat_running.clear()
break
# Toggle phase
self._heartbeat_phase = not self._heartbeat_phase
if self._heartbeat_phase:
# Away phase: show heartbeat message
msg = _format_presence_message("heartbeat", background_count=bg_count)
self._send_rest("away", msg)
self._last_sent_status = "away"
self._last_sent_message = msg
else:
# Online phase: no message
self._send_rest("online", "")
self._last_sent_status = "online"
self._last_sent_message = ""
# Sleep for pulse interval, checking running flag periodically
for _ in range(int(self._pulse_interval * 10)):
if not self._heartbeat_running.is_set():
break
time.sleep(0.1)
if is_active:
if not self._pulse_controller.is_running():
self._pulse_controller.start()
logger.info("[presence] PulseController gestartet (Hintergrund-Agenten erkannt)")
else:
if self._pulse_controller.is_running():
self._pulse_controller.stop()
logger.info("[presence] PulseController gestoppt (keine Hintergrund-Agenten)")
# ── Convenience: Determine and set appropriate presence ──────────────
@@ -458,8 +392,9 @@ class PresenceEngine:
self._set_presence("online", "")
def shutdown(self) -> None:
"""Clean shutdown: stop heartbeat, cancel coalesce timer."""
self._stop_heartbeat()
"""Clean shutdown: stop PulseController, DetectionTimer, cancel coalesce timer."""
self._pulse_controller.stop()
self._detection_timer.stop()
with self._coalesce_lock:
if self._coalesce_timer is not None:
self._coalesce_timer.cancel()
@@ -473,8 +408,7 @@ class 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()
self._pulse_controller.cancel_pending()
def on_agent_busy(self, room_name: str = "") -> None:
"""Hook: Agent is processing a message — pause pulse, set busy.
@@ -485,8 +419,7 @@ class PresenceEngine:
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()
self._pulse_controller.pause()
def on_message_received(self, room_name: str = "") -> None:
"""Hook: Message received — same as on_agent_busy.
@@ -534,6 +467,7 @@ class PulseController:
self._phase: bool = False # False=online, True=away
self._last_sent_phase: Optional[bool] = None
self._background_count: int = 0
self._cancel_pending: bool = False # P0-2: skip next tick flag
# ── Public API ───────────────────────────────────────────────────────
@@ -608,9 +542,8 @@ class PulseController:
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
self._cancel_pending = True
logger.debug("[pulse] cancel_pending: next tick will be skipped")
# ── Internal: Pulse Loop ─────────────────────────────────────────────
@@ -634,6 +567,12 @@ class PulseController:
def _pulse_tick(self) -> None:
"""Execute one pulse tick: toggle phase and send status."""
# P0-2: Check cancel_pending flag (set by PresenceEngine._set_presence)
if self._cancel_pending:
self._cancel_pending = False
logger.debug("[pulse] tick skipped (cancel_pending)")
return
# Toggle phase
self._phase = not self._phase
@@ -714,7 +653,7 @@ class DetectionTimer:
self._on_change = on_change
self._thread: Optional[threading.Thread] = None
self._running = threading.Event()
self._last_result: Optional[bool] = None
self._last_result: Optional[bool] = False # Start with False to avoid spurious first callback
def start(self) -> None:
"""Start the detection timer thread."""