fix(wecom-ws): EOF raises ConnectionError to trigger reconnect; close() hardened
- recv(): connection EOF now raises instead of returning None — the channel outer loop treats it as disconnect and runs backoff reconnect - close(): best-effort with timeouts, no hang when loop already dead - tests: fake aibot gateway (subscribe/reply/heartbeat), auth-failure path 45 passed
This commit is contained in:
1 parent
2bcdf946f7
commit
e22dc9c1ee
2 files changed
+166
-8
No files matched your search
@@ -31,6 +31,7 @@ log = logging.getLogger("agenthub.wecom.ws")
|
|||||||
|
|
||||||
WS_URL = "wss://openws.work.weixin.qq.com"
|
WS_URL = "wss://openws.work.weixin.qq.com"
|
||||||
HEARTBEAT_S = 30
|
HEARTBEAT_S = 30
|
||||||
|
_EOF = object() # queue sentinel: connection ended
|
||||||
|
|
||||||
|
|
||||||
class AibotWSAdapter:
|
class AibotWSAdapter:
|
||||||
@@ -66,13 +67,21 @@ class AibotWSAdapter:
|
|||||||
fut.result(timeout=self.connect_timeout + 15) # raises on auth failure
|
fut.result(timeout=self.connect_timeout + 15) # raises on auth failure
|
||||||
|
|
||||||
def recv(self, timeout: float = 1.0) -> str | None:
|
def recv(self, timeout: float = 1.0) -> str | None:
|
||||||
|
"""Return a raw frame, None on idle timeout, raise ConnectionError on EOF.
|
||||||
|
|
||||||
|
Raising (rather than returning None) on EOF is what makes the channel's
|
||||||
|
outer loop see an exception and run its reconnect/backoff path.
|
||||||
|
"""
|
||||||
if self._loop is None:
|
if self._loop is None:
|
||||||
return None
|
raise ConnectionError("ws loop not running")
|
||||||
fut = asyncio.run_coroutine_threadsafe(self._queue_get(timeout), self._loop)
|
fut = asyncio.run_coroutine_threadsafe(self._queue_get(timeout), self._loop)
|
||||||
try:
|
try:
|
||||||
return fut.result(timeout=timeout + 2)
|
item = fut.result(timeout=timeout + 2)
|
||||||
except TimeoutError:
|
except TimeoutError:
|
||||||
return None
|
return None
|
||||||
|
if item is _EOF:
|
||||||
|
raise ConnectionError("websocket closed by peer")
|
||||||
|
return item
|
||||||
|
|
||||||
def send(self, raw: str) -> None:
|
def send(self, raw: str) -> None:
|
||||||
if self._loop is None or self._ws is None:
|
if self._loop is None or self._ws is None:
|
||||||
@@ -80,8 +89,13 @@ class AibotWSAdapter:
|
|||||||
asyncio.run_coroutine_threadsafe(self._ws.send(raw), self._loop).result(timeout=10)
|
asyncio.run_coroutine_threadsafe(self._ws.send(raw), self._loop).result(timeout=10)
|
||||||
|
|
||||||
def close(self) -> None:
|
def close(self) -> None:
|
||||||
if self._loop is not None:
|
loop = self._loop
|
||||||
asyncio.run_coroutine_threadsafe(self._shutdown(), self._loop).result(timeout=10)
|
if loop is None or loop.is_closed():
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
asyncio.run_coroutine_threadsafe(self._shutdown(), loop).result(timeout=8)
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
pass # best-effort; the reader thread will die with the process
|
||||||
|
|
||||||
# -- asyncio side ---------------------------------------------------------
|
# -- asyncio side ---------------------------------------------------------
|
||||||
def _run_loop(self) -> None:
|
def _run_loop(self) -> None:
|
||||||
@@ -94,7 +108,8 @@ class AibotWSAdapter:
|
|||||||
try:
|
try:
|
||||||
return await asyncio.wait_for(self._queue.get(), timeout=timeout)
|
return await asyncio.wait_for(self._queue.get(), timeout=timeout)
|
||||||
except asyncio.TimeoutError:
|
except asyncio.TimeoutError:
|
||||||
return None
|
return None # idle: caller treats as "no message"
|
||||||
|
|
||||||
|
|
||||||
async def _connect_and_subscribe(self) -> None:
|
async def _connect_and_subscribe(self) -> None:
|
||||||
import websockets
|
import websockets
|
||||||
@@ -139,7 +154,7 @@ class AibotWSAdapter:
|
|||||||
except Exception as e: # noqa: BLE001
|
except Exception as e: # noqa: BLE001
|
||||||
log.warning("[aibot-ws] reader ended: %s", e)
|
log.warning("[aibot-ws] reader ended: %s", e)
|
||||||
finally:
|
finally:
|
||||||
await self._queue.put(None) # EOF marker -> channel recv returns None, triggers reconnect
|
await self._queue.put(_EOF) # signals recv() to raise -> channel reconnects
|
||||||
|
|
||||||
async def _shutdown(self) -> None:
|
async def _shutdown(self) -> None:
|
||||||
self._stop_ev.set()
|
self._stop_ev.set()
|
||||||
@@ -147,11 +162,14 @@ class AibotWSAdapter:
|
|||||||
self._hb_task.cancel()
|
self._hb_task.cancel()
|
||||||
if self._ws is not None:
|
if self._ws is not None:
|
||||||
try:
|
try:
|
||||||
await self._ws.close()
|
await asyncio.wait_for(self._ws.close(), timeout=3)
|
||||||
except Exception: # noqa: BLE001
|
except Exception: # noqa: BLE001
|
||||||
pass
|
pass
|
||||||
self._ws = None
|
self._ws = None
|
||||||
await self._queue.put(None)
|
try:
|
||||||
|
await asyncio.wait_for(self._queue.put(_EOF), timeout=1)
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
def make_ws_factory(**extra: Any) -> Callable[[dict[str, Any]], AibotWSAdapter]:
|
def make_ws_factory(**extra: Any) -> Callable[[dict[str, Any]], AibotWSAdapter]:
|
||||||
|
|||||||
@@ -0,0 +1,140 @@
|
|||||||
|
"""Tests for the real aibot WebSocket transport (wecom_ws.AibotWSAdapter).
|
||||||
|
|
||||||
|
Spins a local websockets server that mimics the WeCom aibot gateway:
|
||||||
|
- expects aibot_subscribe, replies errcode 0
|
||||||
|
- pushes an aibot_msg_callback
|
||||||
|
- records outbound frames (aibot_respond_msg stream)
|
||||||
|
- answers ping with errcode 0
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))
|
||||||
|
|
||||||
|
websockets = pytest.importorskip("websockets")
|
||||||
|
|
||||||
|
from agenthub.channels.wecom_ws import AibotWSAdapter # noqa: E402
|
||||||
|
|
||||||
|
|
||||||
|
class FakeAibotServer:
|
||||||
|
def __init__(self):
|
||||||
|
self.received: list[dict] = []
|
||||||
|
self.port: int | None = None
|
||||||
|
self._loop: asyncio.AbstractEventLoop | None = None
|
||||||
|
self._thread: threading.Thread | None = None
|
||||||
|
self._ready = threading.Event()
|
||||||
|
self._stop = threading.Event()
|
||||||
|
|
||||||
|
def start(self):
|
||||||
|
self._thread = threading.Thread(target=self._run, daemon=True)
|
||||||
|
self._thread.start()
|
||||||
|
assert self._ready.wait(10), "fake server did not start"
|
||||||
|
|
||||||
|
def _run(self):
|
||||||
|
self._loop = asyncio.new_event_loop()
|
||||||
|
asyncio.set_event_loop(self._loop)
|
||||||
|
self._loop.run_until_complete(self._serve())
|
||||||
|
|
||||||
|
async def _serve(self):
|
||||||
|
async def handler(ws):
|
||||||
|
try:
|
||||||
|
async for raw in ws:
|
||||||
|
msg = json.loads(raw)
|
||||||
|
self.received.append(msg)
|
||||||
|
cmd = msg.get("cmd")
|
||||||
|
if cmd == "aibot_subscribe":
|
||||||
|
await ws.send(json.dumps({"headers": msg["headers"], "errcode": 0, "errmsg": "ok"}))
|
||||||
|
# push a user message right after subscribing
|
||||||
|
await asyncio.sleep(0.1)
|
||||||
|
await ws.send(json.dumps({
|
||||||
|
"cmd": "aibot_msg_callback",
|
||||||
|
"headers": {"req_id": "seed-req"},
|
||||||
|
"body": {"msgid": "m1", "chatid": "chatA", "chattype": "single",
|
||||||
|
"msgtype": "text", "from": {"userid": "userA"},
|
||||||
|
"text": {"content": "hello"}},
|
||||||
|
}))
|
||||||
|
elif cmd == "ping":
|
||||||
|
await ws.send(json.dumps({"headers": msg["headers"], "errcode": 0, "errmsg": "ok"}))
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
async with websockets.serve(handler, "127.0.0.1", 0) as server:
|
||||||
|
self.port = server.sockets[0].getsockname()[1]
|
||||||
|
self._ready.set()
|
||||||
|
await asyncio.get_running_loop().create_future() # run forever
|
||||||
|
|
||||||
|
def stop(self):
|
||||||
|
if self._loop:
|
||||||
|
self._loop.call_soon_threadsafe(self._loop.stop)
|
||||||
|
|
||||||
|
|
||||||
|
def test_adapter_subscribe_receive_and_reply():
|
||||||
|
srv = FakeAibotServer()
|
||||||
|
srv.start()
|
||||||
|
adapter = AibotWSAdapter({"bot_id": "bot1", "secret": "sec1",
|
||||||
|
"ws_url": f"ws://127.0.0.1:{srv.port}"})
|
||||||
|
adapter.connect()
|
||||||
|
|
||||||
|
# first outbound frame must be the subscribe with credentials
|
||||||
|
assert srv.received[0]["cmd"] == "aibot_subscribe"
|
||||||
|
assert srv.received[0]["body"] == {"bot_id": "bot1", "secret": "sec1"}
|
||||||
|
|
||||||
|
# inbound callback should come through recv()
|
||||||
|
raw = adapter.recv(timeout=5)
|
||||||
|
assert raw is not None
|
||||||
|
frame = json.loads(raw)
|
||||||
|
assert frame["cmd"] == "aibot_msg_callback"
|
||||||
|
assert frame["body"]["text"]["content"] == "hello"
|
||||||
|
|
||||||
|
# send a streaming reply; server must see it with the callback's req_id
|
||||||
|
adapter.send(json.dumps({
|
||||||
|
"cmd": "aibot_respond_msg",
|
||||||
|
"headers": {"req_id": "seed-req"},
|
||||||
|
"body": {"msgtype": "stream", "stream": {"id": "s1", "finish": False, "content": "partial"}},
|
||||||
|
}))
|
||||||
|
deadline = time.time() + 5
|
||||||
|
while time.time() < deadline:
|
||||||
|
if any(m.get("cmd") == "aibot_respond_msg" for m in srv.received):
|
||||||
|
break
|
||||||
|
time.sleep(0.05)
|
||||||
|
replies = [m for m in srv.received if m.get("cmd") == "aibot_respond_msg"]
|
||||||
|
assert replies and replies[0]["headers"]["req_id"] == "seed-req"
|
||||||
|
assert replies[0]["body"]["stream"]["content"] == "partial"
|
||||||
|
|
||||||
|
adapter.close()
|
||||||
|
srv.stop()
|
||||||
|
|
||||||
|
|
||||||
|
def test_adapter_auth_failure_raises():
|
||||||
|
class BadServer(FakeAibotServer):
|
||||||
|
async def _serve(self):
|
||||||
|
async def handler(ws):
|
||||||
|
async for raw in ws:
|
||||||
|
msg = json.loads(raw)
|
||||||
|
await ws.send(json.dumps({"headers": msg.get("headers", {}), "errcode": 40001,
|
||||||
|
"errmsg": "invalid secret"}))
|
||||||
|
|
||||||
|
async with websockets.serve(handler, "127.0.0.1", 0) as server:
|
||||||
|
self.port = server.sockets[0].getsockname()[1]
|
||||||
|
self._ready.set()
|
||||||
|
await asyncio.get_running_loop().create_future()
|
||||||
|
|
||||||
|
srv = BadServer()
|
||||||
|
srv.start()
|
||||||
|
adapter = AibotWSAdapter({"bot_id": "b", "secret": "bad", "ws_url": f"ws://127.0.0.1:{srv.port}"})
|
||||||
|
try:
|
||||||
|
adapter.connect()
|
||||||
|
assert False, "connect() should raise on subscribe failure"
|
||||||
|
except PermissionError as e:
|
||||||
|
assert "40001" in str(e) or "subscribe failed" in str(e)
|
||||||
|
finally:
|
||||||
|
srv.stop()
|
||||||
Reference in new issue
Block a user