feat(P1-2-O2): Phase 2 — PulseController async-await via run_coroutine_threadsafe

This commit is contained in:
Bernd (Hermes)
2026-07-24 05:48:48 +02:00
parent 42cb259bce
commit b6a9c9d8c3
2 changed files with 127 additions and 3 deletions
+35
View File
@@ -1446,6 +1446,24 @@ class RocketChatAdapter(BasePlatformAdapter):
self._rooms = self.rest.get_rooms() self._rooms = self.rest.get_rooms()
logger.info("[rocketchat] REST get_rooms returned %d rooms", len(self._rooms)) logger.info("[rocketchat] REST get_rooms returned %d rooms", len(self._rooms))
# P1-2 O-2: Bind asyncio loop to DDPClient and PulseController
try:
loop = asyncio.get_running_loop()
self.ddp.bind_loop(loop)
if hasattr(self, '_presence_engine') and self._presence_engine is not None:
self._presence_engine._pulse_controller.bind_loop(loop)
logger.info(
"[rocketchat] P1-2 O-2: PresenceEngine async-bound: yes "
"(loop=%s)",
id(loop),
)
except RuntimeError:
# No running event loop (e.g., in tests) — graceful degradation
logger.info(
"[rocketchat] P1-2 O-2: PresenceEngine async-bound: no "
"(no running event loop)"
)
# A1b: Subscribe to stream-notify-room for rooms-changed events # A1b: Subscribe to stream-notify-room for rooms-changed events
if self.ddp.connected: if self.ddp.connected:
room_events_sub = self.ddp.subscribe_room_events() room_events_sub = self.ddp.subscribe_room_events()
@@ -1677,6 +1695,23 @@ class RocketChatAdapter(BasePlatformAdapter):
logger.error("[rocketchat] _reconnect_ddp: DDP connect/login failed") logger.error("[rocketchat] _reconnect_ddp: DDP connect/login failed")
return False return False
# P1-2 O-2: Re-bind asyncio loop to new DDPClient and PulseController
try:
loop = asyncio.get_running_loop()
self.ddp.bind_loop(loop)
if hasattr(self, '_presence_engine') and self._presence_engine is not None:
self._presence_engine._pulse_controller.bind_loop(loop)
logger.info(
"[rocketchat] P1-2 O-2: PresenceEngine async-bound: yes "
"(reconnect, loop=%s)",
id(loop),
)
except RuntimeError:
logger.info(
"[rocketchat] P1-2 O-2: PresenceEngine async-bound: no "
"(reconnect, no running event loop)"
)
# A1b: Re-subscribe to stream-notify-room for rooms-changed events (P0-3) # A1b: Re-subscribe to stream-notify-room for rooms-changed events (P0-3)
if self.ddp.connected: if self.ddp.connected:
room_events_sub = self.ddp.subscribe_room_events() room_events_sub = self.ddp.subscribe_room_events()
+92 -3
View File
@@ -9,6 +9,7 @@ Zero external dependencies — stdlib only.
from __future__ import annotations from __future__ import annotations
import asyncio
import json import json
import logging import logging
import os import os
@@ -501,6 +502,9 @@ class PulseController:
self._last_sent_phase: Optional[bool] = None self._last_sent_phase: Optional[bool] = None
self._background_count: int = 0 self._background_count: int = 0
self._cancel_pending: bool = False # P0-2: skip next tick flag self._cancel_pending: bool = False # P0-2: skip next tick flag
# P1-2 O-2: Async-await bridge
self._loop: Optional[asyncio.AbstractEventLoop] = None
self._await_timeout: float = 2.0
# ── Public API ─────────────────────────────────────────────────────── # ── Public API ───────────────────────────────────────────────────────
@@ -520,6 +524,18 @@ class PulseController:
""" """
self._rest = rest self._rest = rest
def bind_loop(self, loop: asyncio.AbstractEventLoop) -> None:
"""P1-2 O-2: Bind the asyncio event loop for async-await bridge.
When a loop is bound, _pulse_tick delegates to _pulse_tick_async
via run_coroutine_threadsafe. Without a loop, the legacy sync
path is used (graceful degradation).
Args:
loop: The running asyncio event loop.
"""
self._loop = loop
def set_background_count(self, count: int) -> None: def set_background_count(self, count: int) -> None:
"""Set the background task count for heartbeat messages.""" """Set the background task count for heartbeat messages."""
self._background_count = count self._background_count = count
@@ -629,13 +645,19 @@ class PulseController:
time.sleep(0.1) time.sleep(0.1)
def _pulse_tick(self) -> None: def _pulse_tick(self) -> None:
"""Execute one pulse tick: toggle phase and send status.""" """Execute one pulse tick: toggle phase and send status.
P1-2 O-2: When an asyncio loop is bound, delegates to
_pulse_tick_async via run_coroutine_threadsafe. Otherwise
uses the legacy sync path (graceful degradation).
"""
logger.debug( logger.debug(
"[pulse] _pulse_tick fired, phase=%s, ddp=%s, paused=%s, cancel_pending=%s", "[pulse] _pulse_tick fired, phase=%s, ddp=%s, paused=%s, cancel_pending=%s, loop=%s",
self._phase, self._phase,
self._ddp is not None, self._ddp is not None,
self._paused.is_set(), self._paused.is_set(),
self._cancel_pending, self._cancel_pending,
self._loop is not None,
) )
# P0-2: Check cancel_pending flag (set by PresenceEngine._set_presence) # P0-2: Check cancel_pending flag (set by PresenceEngine._set_presence)
@@ -655,8 +677,25 @@ class PulseController:
) )
return return
# P1-2 O-2: Delegate to async path if loop is bound and running
if self._loop is not None and self._loop.is_running():
try:
future = asyncio.run_coroutine_threadsafe(
self._pulse_tick_async(),
self._loop,
)
future.result(timeout=self._pulse_interval)
return
except Exception as e:
logger.info(
"[pulse] _pulse_tick async path failed: %s — falling back to sync",
e,
)
# Fall through to legacy sync path below
# ── Legacy sync path (no loop bound, or async path failed) ──────
status = "away" if self._phase else "online" status = "away" if self._phase else "online"
logger.debug("[pulse] _pulse_tick sending: status=%s", status) logger.debug("[pulse] _pulse_tick sending (sync): status=%s", status)
# Try DDP first (K1: DDP set_status has no message variant) # Try DDP first (K1: DDP set_status has no message variant)
if self._ddp is not None and getattr(self._ddp, 'connected', False): if self._ddp is not None and getattr(self._ddp, 'connected', False):
@@ -695,6 +734,56 @@ class PulseController:
self._rest is not None, self._rest is not None,
) )
async def _pulse_tick_async(self) -> None:
"""P1-2 O-2: Async pulse tick using await set_status_async.
Runs on the asyncio event loop (dispatched via
run_coroutine_threadsafe from the pulse thread).
Uses DDPClient.set_status_async for true await-semantics
with timeout and error handling.
"""
status = "away" if self._phase else "online"
logger.debug("[pulse] _pulse_tick_async sending: status=%s", status)
# Try DDP with await-semantics
if self._ddp is not None and getattr(self._ddp, 'connected', False):
try:
await self._ddp.set_status_async(status, timeout=self._await_timeout)
self._last_sent_phase = self._phase
self._increment_telemetry()
logger.debug("[pulse] _pulse_tick_async DDP set_status_async OK: %s", status)
return
except Exception as e:
logger.info(
"[pulse] _pulse_tick_async DDP set_status_async failed: %s — "
"falling back to REST",
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()
logger.debug("[pulse] _pulse_tick_async REST setStatus OK: %s", status)
except Exception as e:
logger.info("[pulse] _pulse_tick_async REST setStatus failed: %s", e)
else:
logger.debug(
"[pulse] _pulse_tick_async skip: no DDP and no REST available",
)
def _increment_telemetry(self) -> None: def _increment_telemetry(self) -> None:
"""Increment the heartbeat_pulse telemetry counter. """Increment the heartbeat_pulse telemetry counter.