77 lines
1.7 KiB
Python
77 lines
1.7 KiB
Python
# ///
|
|
# helpers.py
|
|
# 描述:业务辅助函数
|
|
# 作者:AI Generated
|
|
# 创建日期:2026-04-05
|
|
# ///
|
|
|
|
from typing import Dict, Any, Optional
|
|
from fastapi import HTTPException
|
|
|
|
from services.node_manager import node_manager
|
|
|
|
|
|
async def check_node_health(node_id: str) -> None:
|
|
"""
|
|
检查节点健康状态
|
|
|
|
如果节点不健康,抛出 503 异常
|
|
|
|
Args:
|
|
node_id: 节点ID
|
|
|
|
Raises:
|
|
HTTPException: 503 - 节点不健康
|
|
"""
|
|
is_healthy, reason = await node_manager.is_node_healthy(node_id)
|
|
if not is_healthy:
|
|
raise HTTPException(
|
|
status_code=503,
|
|
detail=f"Node '{node_id}' is not healthy: {reason}. Message sending failed."
|
|
)
|
|
|
|
|
|
def build_success_response(data: Any = None, message: str = "操作成功") -> Dict[str, Any]:
|
|
"""
|
|
构建成功响应
|
|
|
|
Args:
|
|
data: 响应数据
|
|
message: 响应消息
|
|
|
|
Returns:
|
|
Dict[str, Any]: 成功响应格式
|
|
"""
|
|
response = {"success": True, "message": message}
|
|
if data is not None:
|
|
response["data"] = data
|
|
return response
|
|
|
|
|
|
def build_error_response(error: str, code: int = 400) -> Dict[str, Any]:
|
|
"""
|
|
构建错误响应
|
|
|
|
Args:
|
|
error: 错误信息
|
|
code: HTTP 状态码
|
|
|
|
Returns:
|
|
Dict[str, Any]: 错误响应格式
|
|
"""
|
|
return {"success": False, "error": error}
|
|
|
|
|
|
def parse_node_result(result: Dict[str, Any]) -> tuple[bool, Optional[str]]:
|
|
"""
|
|
解析节点 API 调用结果
|
|
|
|
Args:
|
|
result: 节点返回结果
|
|
|
|
Returns:
|
|
tuple[bool, Optional[str]]: (是否成功, 错误信息)
|
|
"""
|
|
if result.get("success"):
|
|
return True, None
|
|
return False, result.get("error", "Unknown error") |