""" V8.6: PresenceEngine — Rocket.Chat User-Status automatisch setzen. Phase 1: Basis-PresenceEngine mit Status-Modell, Coalesce-Timer, Caching. Phase 2: Heartbeat-Pulsieren (Flughafen-Prinzip) für Background-Tasks. Zero external dependencies — stdlib only. """ from __future__ import annotations import json import logging import os import threading import time import urllib.request import urllib.error from typing import Optional, Dict logger = logging.getLogger(__name__) # ═══════════════════════════════════════════════════════════════════════════ # Pure Function: _format_presence_message # ═══════════════════════════════════════════════════════════════════════════ def _format_presence_message( status: str, room_name: str = "", error: str = "", background_count: int = 0, ) -> str: """Format a presence status message as a pure function. Args: status: One of 'online', 'busy', 'away_onboarding', 'away_move_request', 'away_error', 'heartbeat'. room_name: Room name for busy/move_request messages. error: Error description for away_error. background_count: Number of background tasks for heartbeat. Returns: Formatted message string (empty string for online/idle). """ if status == "online": return "" elif status == "busy": return f"Verarbeitet in {room_name}" if room_name else "Verarbeitet" elif status == "away_onboarding": return "Onboarding läuft" elif status == "away_move_request": return f"Wartet auf Bestätigung in {room_name}" if room_name else "Wartet auf Bestätigung" elif status == "away_error": return f"⚠️ Fehler: {error}" if error else "⚠️ Fehler" elif status == "heartbeat": return f"wartet — {background_count} Aufträge im Hintergrund" else: return "" # ═══════════════════════════════════════════════════════════════════════════ # PresenceEngine # ═══════════════════════════════════════════════════════════════════════════ class PresenceEngine: """Manages Rocket.Chat user presence status with coalescing and heartbeat. Thread-safe: uses threading.Lock for all counter operations. Coalesce-Timer: prevents flickering by delaying status updates by 2s. Heartbeat: pulses online↔away when background_tasks > 0 and agent is idle. """ def __init__( self, rest=None, enabled: bool = True, coalesce_ms: int = 2000, pulse_interval: float = 10, _clamp_pulse: bool = True, ): """Initialize the PresenceEngine. Args: 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. """ self._rest = rest self._enabled = enabled # Coalesce self._coalesce_ms = coalesce_ms self._coalesce_timer: Optional[threading.Timer] = None self._coalesce_lock = threading.Lock() # Pending state self._pending_status: Optional[str] = None self._pending_message: str = "" # Caching self._last_sent_status: Optional[str] = None self._last_sent_message: str = "" # Active tasks counter (threading.Lock, NOT asyncio.Lock) self._active_tasks: int = 0 self._active_tasks_lock = threading.Lock() # Sentinels for special states self._onboarding_active: bool = False self._move_request_pending: Dict[str, str] = {} # room_id → room_name self._error_state: Optional[str] = None # 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) 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 # ── Public API ─────────────────────────────────────────────────────── def is_enabled(self) -> bool: """Check if presence updates are enabled.""" return self._enabled def enable(self) -> None: """Enable presence updates.""" self._enabled = True logger.info("[presence] PresenceEngine enabled") def disable(self) -> None: """Disable presence updates. Stops heartbeat if running.""" self._enabled = False self._stop_heartbeat() logger.info("[presence] PresenceEngine disabled") def increment_active_tasks(self) -> int: """Increment the active tasks counter. Thread-safe. Returns: New counter value. """ with self._active_tasks_lock: self._active_tasks += 1 return self._active_tasks def decrement_active_tasks(self) -> int: """Decrement the active tasks counter. Thread-safe. Returns: New counter value. """ with self._active_tasks_lock: if self._active_tasks > 0: self._active_tasks -= 1 return self._active_tasks def set_onboarding_active(self, active: bool) -> None: """Set the onboarding sentinel.""" self._onboarding_active = active def set_move_request_pending(self, room_id: str, room_name: str) -> None: """Set a move request as pending.""" self._move_request_pending[room_id] = room_name def clear_move_request(self, room_id: str) -> None: """Clear a move request.""" self._move_request_pending.pop(room_id, None) def set_error_state(self, error: Optional[str]) -> None: """Set or clear the error state.""" self._error_state = error def set_current_room(self, room_name: str) -> None: """Set the current room name for busy messages.""" self._current_room_name = room_name def increment_background_tasks(self) -> int: """Increment background tasks counter. Thread-safe. Returns: New counter value. """ with self._background_tasks_lock: self._background_tasks += 1 count = self._background_tasks self._maybe_start_heartbeat() return count def decrement_background_tasks(self) -> int: """Decrement background tasks counter. Thread-safe. Returns: New counter value. """ with self._background_tasks_lock: if self._background_tasks > 0: self._background_tasks -= 1 count = self._background_tasks if count == 0: self._stop_heartbeat() return count # ── Internal: Presence Setting ─────────────────────────────────────── def _set_presence(self, status: str, message: str) -> None: """Schedule a presence update with coalescing. The update is delayed by coalesce_ms to prevent flickering. If called again before the timer fires, the timer is reset. Args: status: Rocket.Chat status ('online', 'away', 'busy'). message: Custom status message. """ if not self._enabled: return with self._coalesce_lock: self._pending_status = status self._pending_message = message # Cancel existing timer if self._coalesce_timer is not None: self._coalesce_timer.cancel() self._coalesce_timer = None # Start new timer delay = self._coalesce_ms / 1000.0 self._coalesce_timer = threading.Timer(delay, self._flush_presence) self._coalesce_timer.daemon = True self._coalesce_timer.start() def _flush_presence(self) -> None: """Flush the pending presence update immediately. Skips the REST call if the (status, message) pair is identical to the last sent one (caching). """ with self._coalesce_lock: status = self._pending_status message = self._pending_message self._pending_status = None self._pending_message = "" self._coalesce_timer = None if status is None: return # Caching: skip if identical to last sent if status == self._last_sent_status and message == self._last_sent_message: return if not self._enabled: return # Send via REST API self._send_rest(status, message) # Update cache self._last_sent_status = status self._last_sent_message = message def _send_rest(self, status: str, message: str) -> None: """Send the presence update via REST API. POST /api/v1/users.setStatus with {"status": "...", "message": "..."} Called in a background thread (via Timer), non-blocking. Args: status: Rocket.Chat status ('online', 'away', 'busy'). message: Custom status message. """ if self._rest is None: return if not self._rest.auth_token: return try: data = {"status": status} if message: data["message"] = message self._rest._request("POST", "/api/v1/users.setStatus", headers={ "X-Auth-Token": self._rest.auth_token, "X-User-Id": self._rest.user_id, }, data=data) logger.debug( "[presence] Status set: status=%s, message=%s", status, message[:50] if message else "", ) except Exception as e: logger.warning("[presence] Failed to set status: %s", e) # ── Heartbeat ──────────────────────────────────────────────────────── def _maybe_start_heartbeat(self) -> None: """Start heartbeat if background_tasks > 0 and agent is idle. P1-5: Hält beide Locks gleichzeitig um Race Condition zu vermeiden. """ 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) # ── Convenience: Determine and set appropriate presence ────────────── def update_presence(self) -> None: """Determine the appropriate presence state and schedule an update. Priority (highest first): 1. Error state → away + error message 2. Onboarding active → away + onboarding message 3. Move request pending → away + move request message 4. Active tasks > 0 → busy + room message 5. Active tasks == 0 → online """ if not self._enabled: return # 1. Error state if self._error_state: msg = _format_presence_message("away_error", error=self._error_state) self._set_presence("away", msg) return # 2. Onboarding active if self._onboarding_active: msg = _format_presence_message("away_onboarding") self._set_presence("away", msg) return # 3. Move request pending if self._move_request_pending: # Use the first pending room name room_name = next(iter(self._move_request_pending.values()), "") msg = _format_presence_message("away_move_request", room_name=room_name) self._set_presence("away", msg) return # 4. Active tasks with self._active_tasks_lock: active = self._active_tasks if active > 0: msg = _format_presence_message("busy", room_name=self._current_room_name) self._set_presence("busy", msg) else: self._set_presence("online", "") def shutdown(self) -> None: """Clean shutdown: stop heartbeat, cancel coalesce timer.""" self._stop_heartbeat() with self._coalesce_lock: if self._coalesce_timer is not None: self._coalesce_timer.cancel() self._coalesce_timer = None