feat(P1-2-O2): Phase 1 — DDPClient Future-Store + result-Handler (no behavior change)

This commit is contained in:
Bernd (Hermes)
2026-07-24 05:46:24 +02:00
parent 9098a760dc
commit 42cb259bce
+196
View File
@@ -9,6 +9,7 @@ Zero external dependencies — stdlib only.
""" """
import asyncio import asyncio
import concurrent.futures
import contextvars import contextvars
import json import json
import logging import logging
@@ -270,6 +271,24 @@ class RocketChatREST:
return bool(r and r.get("success")) return bool(r and r.get("success"))
class DDPTimeout(Exception):
"""Raised when a DDP method call times out waiting for a result message."""
pass
class DDPServerError(Exception):
"""Raised when the DDP server returns an error for a method call."""
def __init__(self, error_data: dict):
self.error_data = error_data
super().__init__(f"DDP server error: {error_data}")
class DDPNotConnected(Exception):
"""Raised when a DDP method is called but the client is not connected."""
pass
class DDPClient: class DDPClient:
PING_INTERVAL = 8.0 PING_INTERVAL = 8.0
@@ -290,6 +309,11 @@ class DDPClient:
self._session: Optional[str] = None self._session: Optional[str] = None
self._reconnect_attempt = 0 self._reconnect_attempt = 0
self._last_rx_time = 0.0 self._last_rx_time = 0.0
# P1-2 O-2: Future-Store für await-Semantik
self._pending_results: Dict[str, concurrent.futures.Future] = {}
self._loop: Optional[asyncio.AbstractEventLoop] = None
self._result_lock = threading.Lock()
self._msg_seq: int = 0
def _create_socket(self) -> socket.socket: def _create_socket(self) -> socket.socket:
ctx = ssl.create_default_context() ctx = ssl.create_default_context()
@@ -347,6 +371,7 @@ class DDPClient:
import select import select
self.sock.settimeout(1.0) self.sock.settimeout(1.0)
last_ping = time.time() last_ping = time.time()
last_sweep = time.time()
while self._running: while self._running:
try: try:
if time.time() - last_ping >= self.PING_INTERVAL: if time.time() - last_ping >= self.PING_INTERVAL:
@@ -355,6 +380,10 @@ class DDPClient:
last_ping = time.time() last_ping = time.time()
except Exception: except Exception:
break break
# P1-2 O-2: Periodic sweep of stale pending results (every 5s)
if time.time() - last_sweep >= 5.0:
self._sweep_pending_results()
last_sweep = time.time()
readable, _, _ = select.select([self.sock], [], [], 1.0) readable, _, _ = select.select([self.sock], [], [], 1.0)
if not readable: if not readable:
continue continue
@@ -396,6 +425,15 @@ class DDPClient:
self._on_connected() self._on_connected()
elif msg_type == "ping": elif msg_type == "ping":
self._send_json({"msg": "pong"}) self._send_json({"msg": "pong"})
# P1-2 O-2: Handle DDP result messages (resolve pending Futures)
elif msg_type == "result":
self._handle_result_message(data)
# P1-2 O-2: Handle DDP updated messages (log only, result follows)
elif msg_type == "updated":
logger.debug(
"DDP: updated message received (id=%s)",
data.get("id", "?"),
)
elif msg_type in ("changed", "added") and data.get("collection") == "stream-room-messages": elif msg_type in ("changed", "added") and data.get("collection") == "stream-room-messages":
fields = data.get("fields", {}) fields = data.get("fields", {})
args = fields.get("args", []) args = fields.get("args", [])
@@ -541,13 +579,171 @@ class DDPClient:
room_id[:12], event["name"], event["type"]) room_id[:12], event["name"], event["type"])
self._on_room_event(event) self._on_room_event(event)
def _handle_result_message(self, data: dict) -> None:
"""P1-2 O-2: Resolve pending Futures when a DDP result message arrives.
Called from the reader thread (PURE SYNC — no asyncio calls here).
Looks up the msg_id in _pending_results and resolves the Future
with the result or error.
Args:
data: The parsed DDP JSON message with msg='result'.
"""
msg_id = data.get("id", "")
if not msg_id:
return
with self._result_lock:
future = self._pending_results.pop(msg_id, None)
if future is None:
# No pending future for this msg_id — likely a result for
# a fire-and-forget call (legacy set_status) or already timed out
return
if future.done():
# Already resolved (e.g., by timeout sweep)
return
if "error" in data:
future.set_exception(DDPServerError(data["error"]))
else:
future.set_result(data.get("result", True))
def set_status(self, status: str) -> bool: def set_status(self, status: str) -> bool:
"""Set the user presence status via DDP (fire-and-forget, no await).
.. deprecated::
Use :meth:`set_status_async` for await-semantics with timeout
and error handling. This method remains for legacy callers
(on_connected callback, idle timer) that don't need the result.
Returns:
True if the frame was sent, False if not connected.
"""
if not self.connected: if not self.connected:
return False return False
method = "UserPresence:setDefaultStatus" method = "UserPresence:setDefaultStatus"
self._send_json({"msg": "method", "method": method, "params": [status], "id": f"st{int(time.time()*1000)}"}) self._send_json({"msg": "method", "method": method, "params": [status], "id": f"st{int(time.time()*1000)}"})
return True return True
def bind_loop(self, loop: asyncio.AbstractEventLoop) -> None:
"""Bind the asyncio event loop for async operations.
Called by the adapter after the event loop is running.
The loop reference is used by set_status_async to bridge
between the DDP reader thread and the asyncio world.
Args:
loop: The running asyncio event loop.
"""
self._loop = loop
async def set_status_async(self, status: str, timeout: float = 2.0) -> bool:
"""Set the user presence status via DDP with await-semantics.
Sends a DDP method call and waits for the corresponding result
message from the server. Uses a Future registered in
_pending_results that the reader thread resolves when the
result message arrives.
Args:
status: Rocket.Chat status ('online', 'away', 'busy').
timeout: Maximum seconds to wait for the result (default 2.0).
Returns:
True if the server confirmed the status change.
Raises:
DDPNotConnected: If the DDP client is not connected.
DDPTimeout: If no result message arrives within timeout.
DDPServerError: If the server returns an error for the call.
"""
if not self.connected:
raise DDPNotConnected("DDP client is not connected")
# Generate unique msg_id with sequence counter to prevent collisions
with self._result_lock:
self._msg_seq += 1
msg_id = f"st{int(time.time() * 1000)}_{self._msg_seq}"
# Create Future and register it
future: concurrent.futures.Future = concurrent.futures.Future()
with self._result_lock:
self._pending_results[msg_id] = future
try:
# Send the DDP method call
method = "UserPresence:setDefaultStatus"
self._send_json({
"msg": "method",
"method": method,
"params": [status],
"id": msg_id,
})
# Await the future — bridge concurrent.Future to asyncio with timeout
result = await asyncio.wait_for(
asyncio.wrap_future(future),
timeout=timeout,
)
# If we get here, the reader thread resolved the future
if result is False:
raise DDPServerError({"error": "server returned false"})
return True
except asyncio.TimeoutError:
# Clean up the pending future
with self._result_lock:
self._pending_results.pop(msg_id, None)
raise DDPTimeout(
f"setDefaultStatus('{status}') timed out after {timeout}s"
)
except (DDPTimeout, DDPServerError, DDPNotConnected):
# Re-raise our own exceptions without wrapping
with self._result_lock:
self._pending_results.pop(msg_id, None)
raise
except Exception:
# Clean up on any other exception
with self._result_lock:
self._pending_results.pop(msg_id, None)
raise
def _sweep_pending_results(self) -> None:
"""Sweep through _pending_results and cancel Futures older than 2s.
Called periodically from the reader loop to prevent memory leaks
from method calls whose result messages never arrive.
"""
now = time.time()
stale_ids = []
with self._result_lock:
for msg_id, future in list(self._pending_results.items()):
# msg_id format: st<TIMESTAMP_MS>_<SEQ>
# Extract timestamp from msg_id
try:
ts_part = msg_id[2:].split("_")[0] # strip 'st' prefix
ts_ms = int(ts_part)
ts_s = ts_ms / 1000.0
if now - ts_s > 2.0:
stale_ids.append(msg_id)
except (ValueError, IndexError):
# Malformed msg_id — clean it up
stale_ids.append(msg_id)
for msg_id in stale_ids:
future = self._pending_results.pop(msg_id, None)
if future is not None and not future.done():
future.cancel()
if stale_ids:
logger.debug(
"DDP: Swept %d stale pending results (age > 2s)",
len(stale_ids),
)
def disconnect(self): def disconnect(self):
self._running = False self._running = False
if self.sock: if self.sock: