refactor: 优化代码结构,简化条件判断和异常处理
This commit is contained in:
@@ -42,8 +42,7 @@ class RegisteredComponent:
|
||||
# 预编译命令正则(仅 command 类型)
|
||||
self._compiled_pattern: re.Pattern | None = None
|
||||
if component_type == "command":
|
||||
pattern = metadata.get("command_pattern", "")
|
||||
if pattern:
|
||||
if pattern := metadata.get("command_pattern", ""):
|
||||
try:
|
||||
self._compiled_pattern = re.compile(pattern)
|
||||
except re.error as e:
|
||||
@@ -120,8 +119,7 @@ class ComponentRegistry:
|
||||
comps = self._by_plugin.pop(plugin_id, [])
|
||||
for comp in comps:
|
||||
self._components.pop(comp.full_name, None)
|
||||
type_dict = self._by_type.get(comp.component_type)
|
||||
if type_dict:
|
||||
if type_dict := self._by_type.get(comp.component_type):
|
||||
type_dict.pop(comp.full_name, None)
|
||||
return len(comps)
|
||||
|
||||
@@ -162,9 +160,7 @@ class ComponentRegistry:
|
||||
) -> list[RegisteredComponent]:
|
||||
"""按插件查询。"""
|
||||
comps = self._by_plugin.get(plugin_id, [])
|
||||
if enabled_only:
|
||||
return [c for c in comps if c.enabled]
|
||||
return list(comps)
|
||||
return [c for c in comps if c.enabled] if enabled_only else list(comps)
|
||||
|
||||
def find_command_by_text(self, text: str) -> RegisteredComponent | None:
|
||||
"""通过文本匹配命令正则,返回第一个匹配的 command 组件。"""
|
||||
|
||||
@@ -93,7 +93,7 @@ class RPCServer:
|
||||
self._running = False
|
||||
|
||||
# 取消所有 pending 请求
|
||||
for req_id, future in self._pending_requests.items():
|
||||
for future in self._pending_requests.values():
|
||||
if not future.done():
|
||||
future.set_exception(RPCError(ErrorCode.E_TIMEOUT, "服务器关闭"))
|
||||
self._pending_requests.clear()
|
||||
@@ -162,16 +162,15 @@ class RPCServer:
|
||||
|
||||
# 等待响应
|
||||
timeout_sec = timeout_ms / 1000.0
|
||||
response = await asyncio.wait_for(future, timeout=timeout_sec)
|
||||
return response
|
||||
return await asyncio.wait_for(future, timeout=timeout_sec)
|
||||
except asyncio.TimeoutError:
|
||||
self._pending_requests.pop(request_id, None)
|
||||
raise RPCError(ErrorCode.E_TIMEOUT, f"请求 {method} 超时 ({timeout_ms}ms)")
|
||||
raise RPCError(ErrorCode.E_TIMEOUT, f"请求 {method} 超时 ({timeout_ms}ms)") from None
|
||||
except Exception as e:
|
||||
self._pending_requests.pop(request_id, None)
|
||||
if isinstance(e, RPCError):
|
||||
raise
|
||||
raise RPCError(ErrorCode.E_UNKNOWN, str(e))
|
||||
raise RPCError(ErrorCode.E_UNKNOWN, str(e)) from e
|
||||
|
||||
async def send_event(self, method: str, plugin_id: str = "", payload: dict[str, Any] | None = None) -> None:
|
||||
"""向 Runner 发送单向事件(不等待响应)"""
|
||||
@@ -338,8 +337,7 @@ class RPCServer:
|
||||
|
||||
async def _handle_event(self, envelope: Envelope) -> None:
|
||||
"""处理来自 Runner 的事件"""
|
||||
handler = self._method_handlers.get(envelope.method)
|
||||
if handler:
|
||||
if handler := self._method_handlers.get(envelope.method):
|
||||
try:
|
||||
await handler(envelope)
|
||||
except Exception as e:
|
||||
|
||||
@@ -203,19 +203,15 @@ class PluginSupervisor:
|
||||
|
||||
由主进程业务逻辑调用,通过 RPC 转发给 Runner。
|
||||
"""
|
||||
try:
|
||||
response = await self._rpc_server.send_request(
|
||||
method=method,
|
||||
plugin_id=plugin_id,
|
||||
payload={
|
||||
"component_name": component_name,
|
||||
"args": args or {},
|
||||
},
|
||||
timeout_ms=timeout_ms,
|
||||
)
|
||||
return response
|
||||
except RPCError:
|
||||
raise
|
||||
return await self._rpc_server.send_request(
|
||||
method=method,
|
||||
plugin_id=plugin_id,
|
||||
payload={
|
||||
"component_name": component_name,
|
||||
"args": args or {},
|
||||
},
|
||||
timeout_ms=timeout_ms,
|
||||
)
|
||||
|
||||
async def reload_plugins(self, reason: str = "manual") -> None:
|
||||
"""热重载所有插件(进程级 generation 切换)
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
- modification_log: 消息修改审计
|
||||
"""
|
||||
|
||||
from typing import Any, Callable, Awaitable, Optional
|
||||
from typing import Any, Awaitable, Callable
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
@@ -273,10 +273,9 @@ class WorkflowExecutor:
|
||||
"""
|
||||
for key, expected in filter_cond.items():
|
||||
actual = message.get(key)
|
||||
if isinstance(expected, list):
|
||||
if actual not in expected:
|
||||
return False
|
||||
elif actual != expected:
|
||||
if (isinstance(expected, list) and actual not in expected) or (
|
||||
not isinstance(expected, list) and actual != expected
|
||||
):
|
||||
return False
|
||||
return True
|
||||
|
||||
@@ -376,12 +375,11 @@ class WorkflowExecutor:
|
||||
logger.info(f"[{ctx.trace_id}] 命令匹配: {matched.full_name}")
|
||||
|
||||
try:
|
||||
resp = await invoke_fn(matched.plugin_id, matched.name, {
|
||||
return await invoke_fn(matched.plugin_id, matched.name, {
|
||||
"text": plain_text,
|
||||
"message": message,
|
||||
"trace_id": ctx.trace_id,
|
||||
})
|
||||
return resp
|
||||
except Exception as e:
|
||||
logger.error(f"[{ctx.trace_id}] 命令 {matched.full_name} 执行失败: {e}", exc_info=True)
|
||||
ctx.errors.append(f"command:{matched.full_name}: {e}")
|
||||
@@ -390,8 +388,4 @@ class WorkflowExecutor:
|
||||
|
||||
def _diff_keys(old: dict[str, Any], new: dict[str, Any]) -> list[str]:
|
||||
"""返回 new 中与 old 不同的 key 列表。"""
|
||||
changed = []
|
||||
for k in new:
|
||||
if k not in old or old[k] != new[k]:
|
||||
changed.append(k)
|
||||
return changed
|
||||
return [k for k, v in new.items() if k not in old or old[k] != v]
|
||||
|
||||
Reference in New Issue
Block a user