Merge pull request #16 from EvoScientist/channel-fix

fix(channels): critical async, cleanup, and performance bugs
This commit is contained in:
Xi Zhang
2026-02-20 12:20:02 +00:00
committed by GitHub
7 changed files with 141 additions and 55 deletions
+26 -5
View File
@@ -8,7 +8,7 @@ from abc import ABC, abstractmethod
import asyncio
import logging
import re
from collections import defaultdict
from collections import OrderedDict
from collections.abc import Awaitable, Callable as CallableABC
from dataclasses import dataclass, field
from datetime import datetime
@@ -302,8 +302,10 @@ class Channel(ChannelPlugin, ABC):
from .retry import RetryConfig, DEFAULT_RETRY, RETRY_PRESETS
self._retry_config: RetryConfig = RETRY_PRESETS.get(self.name, DEFAULT_RETRY)
# Per-chat send locks to prevent message reordering
self._send_locks: dict[str, asyncio.Lock] = defaultdict(asyncio.Lock)
# Per-chat send locks to prevent message reordering.
# Uses an OrderedDict as a bounded LRU cache to avoid unbounded growth.
self._send_locks: OrderedDict[str, asyncio.Lock] = OrderedDict()
self._send_locks_max: int = 1024
# Build inbound middleware pipeline
self._inbound_middlewares = self._build_inbound_middlewares()
@@ -415,6 +417,25 @@ class Channel(ChannelPlugin, ABC):
except asyncio.TimeoutError:
continue
def _acquire_send_lock(self, chat_id: str) -> asyncio.Lock:
"""Get or create a per-chat send lock with LRU eviction.
Moves the accessed entry to the end (most-recently-used).
When the cache exceeds ``_send_locks_max``, the least-recently-used
entry is evicted — but only if its lock is not currently held.
"""
if chat_id in self._send_locks:
self._send_locks.move_to_end(chat_id)
else:
self._send_locks[chat_id] = asyncio.Lock()
# Evict oldest unlocked entries when over capacity
while len(self._send_locks) > self._send_locks_max:
oldest_key, oldest_lock = next(iter(self._send_locks.items()))
if oldest_lock.locked():
break # don't evict a lock that's in use
del self._send_locks[oldest_key]
return self._send_locks[chat_id]
async def send(self, message: OutboundMessage) -> bool:
"""Send a message. Handles chunking, retry, and error logging.
@@ -436,7 +457,7 @@ class Channel(ChannelPlugin, ABC):
try:
chat_id = self._resolve_chat_id(message)
limit = self._get_chunk_limit()
async with self._send_locks[chat_id]:
async with self._acquire_send_lock(chat_id):
pairs = self._prepare_chunks(message.content, limit)
had_error = False
for i, (formatted, raw) in enumerate(pairs):
@@ -844,7 +865,7 @@ class Channel(ChannelPlugin, ABC):
Convenience method for subclass ``_on_message`` handlers.
"""
msg = self._build_inbound(raw)
msg = await self._build_inbound_async(raw)
if msg is None:
return
if raw.message_id:
+1 -1
View File
@@ -347,7 +347,7 @@ class DingTalkChannel(Channel, WebSocketMixin, TokenMixin):
pass
self._ws_task = None
await self._stop_ws()
if self._http_client:
if hasattr(self, "_http_client") and self._http_client:
await self._http_client.aclose()
self._http_client = None
self._access_token = None
+1 -1
View File
@@ -28,7 +28,7 @@ def create_from_config(config) -> EmailChannel:
smtp_port=config.email_smtp_port,
smtp_username=config.email_smtp_username,
smtp_password=config.email_smtp_password,
smtp_use_tls=config.email_smtp_use_tls,
smtp_starttls=config.email_smtp_use_tls,
from_address=config.email_from_address,
poll_interval=config.email_poll_interval,
mark_seen=config.email_mark_seen,
+49 -35
View File
@@ -1,6 +1,7 @@
"""Email channel implementation using IMAP + SMTP."""
import asyncio
import contextlib
import email as email_lib
import email.utils
import html
@@ -55,7 +56,7 @@ class EmailConfig(BaseChannelConfig):
smtp_port: int = 587
smtp_username: str = ""
smtp_password: str = ""
smtp_use_tls: bool = True
smtp_starttls: bool = True # True=STARTTLS (port 587), False=implicit SSL (port 465)
from_address: str = ""
poll_interval: int = 30
mark_seen: bool = True
@@ -80,7 +81,7 @@ class EmailChannel(Channel, PollingMixin):
cfg = self.config
if not cfg.imap_host or not cfg.imap_username:
raise ChannelError("Email imap_host and imap_username are required")
loop = asyncio.get_event_loop()
loop = asyncio.get_running_loop()
await loop.run_in_executor(None, self._connect_imap)
self._running = True
logger.info(f"Email channel started (IMAP: {cfg.imap_host}, poll {cfg.poll_interval}s)")
@@ -119,7 +120,7 @@ class EmailChannel(Channel, PollingMixin):
self._connect_imap()
async def _poll_once(self) -> None:
loop = asyncio.get_event_loop()
loop = asyncio.get_running_loop()
messages = await loop.run_in_executor(None, self._fetch_unseen)
for m in messages:
await self._process_email(m)
@@ -237,8 +238,39 @@ class EmailChannel(Channel, PollingMixin):
def _is_ready(self) -> bool:
return bool(self.config.smtp_host)
@contextlib.contextmanager
def _smtp_connect(self):
"""Open an SMTP connection as a context manager.
Ensures the connection is closed even if login or send raises.
Uses STARTTLS (port 587) when smtp_starttls=True, otherwise
implicit SSL (port 465).
"""
cfg = self.config
srv = None
try:
if cfg.smtp_starttls:
srv = smtplib.SMTP(cfg.smtp_host, cfg.smtp_port, timeout=30)
srv.starttls()
else:
srv = smtplib.SMTP_SSL(
cfg.smtp_host, cfg.smtp_port,
context=ssl.create_default_context(), timeout=30,
)
srv.login(cfg.smtp_username, cfg.smtp_password)
yield srv
finally:
if srv is not None:
try:
srv.quit()
except Exception:
try:
srv.close()
except Exception:
pass
async def _send_chunk(self, chat_id, formatted_text, raw_text, reply_to, metadata):
loop = asyncio.get_event_loop()
loop = asyncio.get_running_loop()
try:
await loop.run_in_executor(
None, self._smtp_send_html, chat_id, formatted_text, raw_text, metadata or {},
@@ -268,17 +300,11 @@ class EmailChannel(Channel, PollingMixin):
msg["References"] = f"{meta.get('references', '')} {orig_id}".strip()
msg.set_content(content)
try:
if cfg.smtp_use_tls:
srv = smtplib.SMTP(cfg.smtp_host, cfg.smtp_port, timeout=30)
srv.starttls()
else:
srv = smtplib.SMTP_SSL(cfg.smtp_host, cfg.smtp_port, context=ssl.create_default_context(), timeout=30)
srv.login(cfg.smtp_username, cfg.smtp_password)
srv.sendmail(from_addr, [to], msg.as_string())
srv.quit()
with self._smtp_connect() as srv:
srv.sendmail(from_addr, [to], msg.as_string())
except Exception as e:
logger.error(f"SMTP send failed: from={from_addr} to={to} error={e}")
raise RuntimeError(f"SMTP: {e}")
logger.error(f"SMTP send failed: from={from_addr} to={to}")
raise RuntimeError("SMTP send failed") from e
def _smtp_send_html(self, to: str, html_content: str, plain_content: str, meta: dict) -> None:
"""Send an email with both HTML and plain-text parts."""
@@ -297,17 +323,11 @@ class EmailChannel(Channel, PollingMixin):
msg.attach(MIMEText(plain_content, "plain", "utf-8"))
msg.attach(MIMEText(html_content, "html", "utf-8"))
try:
if cfg.smtp_use_tls:
srv = smtplib.SMTP(cfg.smtp_host, cfg.smtp_port, timeout=30)
srv.starttls()
else:
srv = smtplib.SMTP_SSL(cfg.smtp_host, cfg.smtp_port, context=ssl.create_default_context(), timeout=30)
srv.login(cfg.smtp_username, cfg.smtp_password)
srv.sendmail(from_addr, [to], msg.as_string())
srv.quit()
with self._smtp_connect() as srv:
srv.sendmail(from_addr, [to], msg.as_string())
except Exception as e:
logger.error(f"SMTP HTML send failed: from={from_addr} to={to} error={e}")
raise RuntimeError(f"SMTP HTML: {e}")
logger.error(f"SMTP HTML send failed: from={from_addr} to={to}")
raise RuntimeError("SMTP HTML send failed") from e
# ── Media send (email attachment) ─────────────────────────────
@@ -319,7 +339,7 @@ class EmailChannel(Channel, PollingMixin):
metadata: dict | None = None,
) -> bool:
"""Send a file as an email attachment via SMTP."""
loop = asyncio.get_event_loop()
loop = asyncio.get_running_loop()
await loop.run_in_executor(
None, self._smtp_send_attachment, recipient, file_path, caption, metadata or {},
)
@@ -353,14 +373,8 @@ class EmailChannel(Channel, PollingMixin):
msg.attach(part)
try:
if cfg.smtp_use_tls:
srv = smtplib.SMTP(cfg.smtp_host, cfg.smtp_port, timeout=30)
srv.starttls()
else:
srv = smtplib.SMTP_SSL(cfg.smtp_host, cfg.smtp_port, context=ssl.create_default_context(), timeout=30)
srv.login(cfg.smtp_username, cfg.smtp_password)
srv.sendmail(from_addr, [to], msg.as_string())
srv.quit()
with self._smtp_connect() as srv:
srv.sendmail(from_addr, [to], msg.as_string())
except Exception as e:
logger.error(f"SMTP attachment send failed: from={from_addr} to={to} error={e}")
raise RuntimeError(f"SMTP attachment: {e}")
logger.error(f"SMTP attachment send failed: from={from_addr} to={to}")
raise RuntimeError("SMTP attachment send failed") from e
+12 -3
View File
@@ -57,6 +57,7 @@ async def validate_email_smtp(
loop = asyncio.get_event_loop()
def _check():
server = None
try:
if use_tls:
server = smtplib.SMTP(host, port, timeout=10)
@@ -65,11 +66,19 @@ async def validate_email_smtp(
ctx = ssl.create_default_context()
server = smtplib.SMTP_SSL(host, port, context=ctx, timeout=10)
server.login(username, password)
server.quit()
return True, "SMTP credentials valid"
except smtplib.SMTPAuthenticationError as e:
return False, f"SMTP auth failed: {e}"
except smtplib.SMTPAuthenticationError:
return False, "SMTP auth failed"
except Exception as e:
return False, f"SMTP error: {e}"
finally:
if server is not None:
try:
server.quit()
except Exception:
try:
server.close()
except Exception:
pass
return await loop.run_in_executor(None, _check)
+4 -1
View File
@@ -69,6 +69,7 @@ class QQChannel(Channel):
self._processed_ids: deque = deque(maxlen=1000)
self._msg_seq: dict[str, int] = {} # msg_id -> next seq number
self._msg_seq_order: deque = deque(maxlen=500)
self._msg_seq_ids: set[str] = set() # companion set for O(1) lookup
# ── Lifecycle ─────────────────────────────────────────────────
@@ -167,10 +168,12 @@ class QQChannel(Channel):
"""Return the next msg_seq for *msg_id* and increment the counter."""
seq = self._msg_seq.get(msg_id, 1)
self._msg_seq[msg_id] = seq + 1
if msg_id not in set(self._msg_seq_order):
if msg_id not in self._msg_seq_ids:
self._msg_seq_order.append(msg_id)
self._msg_seq_ids.add(msg_id)
if len(self._msg_seq_order) > 500:
oldest = self._msg_seq_order.popleft()
self._msg_seq_ids.discard(oldest)
self._msg_seq.pop(oldest, None)
return seq
+48 -9
View File
@@ -40,9 +40,12 @@ class SignalChannel(Channel):
self._writer: asyncio.StreamWriter | None = None
self._rpc_id = 0
self._daemon_proc = None
# Pending RPC responses: rpc_id -> Future
self._pending_rpcs: dict[int, asyncio.Future] = {}
# Cache message_id → sender for reaction targetAuthor (bounded)
self._msg_senders: dict[str, str] = {}
self._msg_senders_order: deque = deque(maxlen=200)
self._listen_task: asyncio.Task | None = None
async def start(self) -> None:
if not self.config.phone_number:
@@ -51,8 +54,13 @@ class SignalChannel(Channel):
# Try to start signal-cli daemon if not already running
await self._ensure_daemon()
# Connect to JSON RPC socket
await self._connect()
try:
# Connect to JSON RPC socket
await self._connect()
except Exception:
# If connect fails after daemon was started, clean up the daemon
await self._cleanup()
raise
self._running = True
logger.info(f"Signal channel started (phone: {self.config.phone_number})")
@@ -62,9 +70,14 @@ class SignalChannel(Channel):
self._listen_task = asyncio.create_task(self._listen_loop())
async def _cleanup(self) -> None:
if hasattr(self, "_listen_task") and self._listen_task:
if self._listen_task:
self._listen_task.cancel()
self._listen_task = None
# Cancel any pending RPC futures
for fut in self._pending_rpcs.values():
if not fut.done():
fut.cancel()
self._pending_rpcs.clear()
if self._writer:
self._writer.close()
try:
@@ -136,13 +149,25 @@ class SignalChannel(Channel):
raise ChannelError(f"Cannot connect to signal-cli: {e}")
async def _listen_loop(self) -> None:
"""Listen for incoming JSON RPC notifications."""
"""Listen for incoming JSON RPC notifications and responses."""
while self._running and self._reader:
try:
line = await self._reader.readline()
if not line:
break
data = json.loads(line.decode())
# Dispatch RPC response if it has an 'id' matching a pending call
rpc_id = data.get("id")
if rpc_id is not None and rpc_id in self._pending_rpcs:
fut = self._pending_rpcs.pop(rpc_id)
if not fut.done():
if "error" in data:
fut.set_exception(
RuntimeError(f"signal-cli RPC error: {data['error']}")
)
else:
fut.set_result(data.get("result"))
continue
await self._handle_rpc(data)
except asyncio.CancelledError:
break
@@ -156,7 +181,8 @@ class SignalChannel(Channel):
try:
await self._connect()
except Exception:
pass
logger.warning("Signal reconnect failed, exiting listen loop")
break
async def _handle_rpc(self, data: dict) -> None:
"""Handle a JSON RPC message from signal-cli."""
@@ -343,22 +369,35 @@ class SignalChannel(Channel):
def _is_ready(self) -> bool:
return self._writer is not None and not self._writer.is_closing()
async def _rpc_call(self, method: str, params: dict) -> dict | None:
"""Send a JSON RPC call to signal-cli."""
async def _rpc_call(self, method: str, params: dict, timeout: float = 10.0) -> dict | None:
"""Send a JSON RPC call to signal-cli and wait for the response."""
if not self._writer:
return None
self._rpc_id += 1
rpc_id = self._rpc_id
request = {
"jsonrpc": "2.0",
"id": self._rpc_id,
"id": rpc_id,
"method": method,
"params": params,
}
# Register a Future before sending so the listen loop can resolve it
loop = asyncio.get_running_loop()
fut: asyncio.Future = loop.create_future()
self._pending_rpcs[rpc_id] = fut
line = json.dumps(request) + "\n"
self._writer.write(line.encode())
await self._writer.drain()
return None # We don't wait for response in this simple impl
try:
return await asyncio.wait_for(fut, timeout=timeout)
except asyncio.TimeoutError:
self._pending_rpcs.pop(rpc_id, None)
logger.warning(f"Signal RPC '{method}' timed out after {timeout}s")
return None
async def _send_chunk(
self, chat_id, formatted_text, raw_text, reply_to, metadata,