初始化提交

This commit is contained in:
2026-04-07 14:11:45 +08:00
parent 46342134b6
commit c412e4de5f
69 changed files with 19321 additions and 1 deletions
+17
View File
@@ -0,0 +1,17 @@
# ///
# __init__.py
# 描述:工具模块
# 作者:AI Generated
# 创建日期:2026-04-05
# ///
from utils.common import require_api_key, require_external_key
from utils.helpers import check_node_health, build_success_response, build_error_response
__all__ = [
"require_api_key",
"require_external_key",
"check_node_health",
"build_success_response",
"build_error_response",
]
+50
View File
@@ -0,0 +1,50 @@
# ///
# common.py
# 描述:公共工具函数和依赖注入
# 作者:AI Generated
# 创建日期:2026-04-05
# ///
from typing import Optional
from fastapi import Header, HTTPException, Depends
from config import get_settings
def require_api_key(x_api_key: Optional[str] = Header(None, alias="X-API-Key")):
"""
API Key 验证依赖
用于验证 X-API-Key Header 是否有效
Raises:
HTTPException: 401 - API Key 无效或缺失
Returns:
str: 有效的 API Key
"""
if not x_api_key:
raise HTTPException(status_code=401, detail="API Key required")
settings = get_settings()
if x_api_key != settings.external_api_key:
raise HTTPException(status_code=401, detail="Invalid API Key")
return x_api_key
def require_external_key(x_externalkey: Optional[str] = Header(None, alias="X-ExternalKey")):
"""
外部 API Key 验证依赖
用于验证 X-ExternalKey Header 是否有效
Raises:
HTTPException: 401 - External API Key 无效或缺失
Returns:
str: 有效的 External API Key
"""
if not x_externalkey:
raise HTTPException(status_code=401, detail="External API Key required")
settings = get_settings()
if x_externalkey != settings.external_api_key:
raise HTTPException(status_code=401, detail="Invalid External API Key")
return x_externalkey
+77
View File
@@ -0,0 +1,77 @@
# ///
# 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")