mirror of
https://github.com/fawney19/Aether.git
synced 2026-09-02 09:20:22 +08:00
refactor: 全局适配 ApiFamily/EndpointKind 结构化标识体系
将新的 (ApiFamily, EndpointKind) / `family:kind` 签名体系应用到整个代码库: - API Handlers: 所有 adapter/handler 使用新的签名格式 - Services: provider, model, usage, cache, auth 等服务层适配 - Database: ProviderEndpoint 新增 api_family/endpoint_kind 字段 - Frontend: Provider 管理、Usage 表格等组件适配 - Tests: 更新所有相关测试用例
This commit is contained in:
@@ -4,14 +4,11 @@
|
||||
提供在异步上下文中安全执行同步函数的工具,避免阻塞事件循环。
|
||||
"""
|
||||
|
||||
|
||||
import asyncio
|
||||
from collections.abc import Callable, Coroutine
|
||||
from functools import partial, wraps
|
||||
from typing import Any, TypeVar
|
||||
|
||||
from collections.abc import Callable
|
||||
from collections.abc import Coroutine
|
||||
|
||||
T = TypeVar("T")
|
||||
|
||||
|
||||
@@ -43,4 +40,3 @@ def async_wrap_sync(func: Callable[..., T]) -> Callable[..., Coroutine[Any, Any,
|
||||
return await run_in_executor(func, *args, **kwargs)
|
||||
|
||||
return wrapper
|
||||
|
||||
|
||||
@@ -5,17 +5,17 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
import hashlib
|
||||
from typing import Any
|
||||
|
||||
from fastapi import Depends, Header, HTTPException, status
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from src.core.logger import logger
|
||||
from src.services.auth.service import AuthService
|
||||
|
||||
from ..core.exceptions import ForbiddenException
|
||||
from src.core.logger import logger
|
||||
from ..database import get_db
|
||||
from ..models.database import User, UserRole
|
||||
|
||||
|
||||
@@ -2,13 +2,11 @@
|
||||
|
||||
import functools
|
||||
import json
|
||||
from collections.abc import Callable
|
||||
from typing import Any
|
||||
|
||||
from collections.abc import Callable
|
||||
|
||||
from src.core.logger import logger
|
||||
|
||||
from src.clients.redis_client import get_redis_client_sync
|
||||
from src.core.logger import logger
|
||||
|
||||
|
||||
def _is_adapter_instance(obj: Any) -> bool:
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
提供统一的HTTP请求信息提取功能
|
||||
"""
|
||||
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import Request
|
||||
|
||||
@@ -9,13 +9,12 @@
|
||||
- 多实例部署:设置 SINGLE_INSTANCE_MODE=false 禁用启动清理
|
||||
"""
|
||||
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
import os
|
||||
import pathlib
|
||||
import uuid
|
||||
from typing import Any
|
||||
|
||||
from src.core.logger import logger
|
||||
|
||||
@@ -77,9 +76,7 @@ class StartupTaskCoordinator:
|
||||
return 0
|
||||
"""
|
||||
result = await self.redis.eval(
|
||||
script, 2,
|
||||
self._redis_key(name), self._redis_key(name),
|
||||
token, ttl
|
||||
script, 2, self._redis_key(name), self._redis_key(name), token, ttl
|
||||
)
|
||||
if result == 1:
|
||||
self._tokens[name] = token
|
||||
@@ -88,9 +85,7 @@ class StartupTaskCoordinator:
|
||||
return False
|
||||
else:
|
||||
# 多实例模式:直接使用 NX 选项竞争锁
|
||||
acquired = await self.redis.set(
|
||||
self._redis_key(name), token, nx=True, ex=ttl
|
||||
)
|
||||
acquired = await self.redis.set(self._redis_key(name), token, nx=True, ex=ttl)
|
||||
if acquired:
|
||||
self._tokens[name] = token
|
||||
logger.info(f"任务 {name} 通过 Redis 锁独占执行")
|
||||
@@ -143,7 +138,9 @@ class StartupTaskCoordinator:
|
||||
return False
|
||||
|
||||
|
||||
async def ensure_singleton_task(name: str, redis_client: Any | None = None, ttl: int | None = None) -> Any:
|
||||
async def ensure_singleton_task(
|
||||
name: str, redis_client: Any | None = None, ttl: int | None = None
|
||||
) -> Any:
|
||||
"""便捷协程,返回 (coordinator, acquired)"""
|
||||
|
||||
coordinator = StartupTaskCoordinator(redis_client)
|
||||
|
||||
@@ -7,14 +7,12 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from collections.abc import Callable
|
||||
from functools import wraps
|
||||
from typing import Any, TypeVar
|
||||
|
||||
from collections.abc import Callable
|
||||
|
||||
from src.core.logger import logger
|
||||
|
||||
|
||||
T = TypeVar("T")
|
||||
|
||||
|
||||
|
||||
@@ -8,19 +8,16 @@ from __future__ import annotations
|
||||
|
||||
import functools
|
||||
import inspect
|
||||
from collections.abc import Callable, Generator
|
||||
from contextlib import contextmanager
|
||||
from typing import Any
|
||||
|
||||
from collections.abc import Callable
|
||||
from collections.abc import Generator
|
||||
|
||||
from sqlalchemy.exc import DatabaseError, IntegrityError
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from src.core.logger import logger
|
||||
|
||||
|
||||
|
||||
class TransactionError(Exception):
|
||||
"""事务处理异常"""
|
||||
|
||||
@@ -65,6 +62,7 @@ def transactional(commit: bool = True, rollback_on_error: bool = True) -> Any:
|
||||
def decorator(func: Callable) -> Callable:
|
||||
# 检查是否是异步函数
|
||||
if inspect.iscoroutinefunction(func):
|
||||
|
||||
@functools.wraps(func)
|
||||
async def async_wrapper(*args: Any, **kwargs: Any) -> Any:
|
||||
db_session = _find_db_session(args, kwargs)
|
||||
@@ -107,6 +105,7 @@ def transactional(commit: bool = True, rollback_on_error: bool = True) -> Any:
|
||||
|
||||
return async_wrapper
|
||||
else:
|
||||
|
||||
@functools.wraps(func)
|
||||
def sync_wrapper(*args: Any, **kwargs: Any) -> Any:
|
||||
db_session = _find_db_session(args, kwargs)
|
||||
@@ -138,9 +137,7 @@ def transactional(commit: bool = True, rollback_on_error: bool = True) -> Any:
|
||||
db_session.rollback()
|
||||
except Exception:
|
||||
pass
|
||||
logger.error(
|
||||
f"事务回滚: {transaction_id} - {type(e).__name__}: {str(e)}"
|
||||
)
|
||||
logger.error(f"事务回滚: {transaction_id} - {type(e).__name__}: {str(e)}")
|
||||
else:
|
||||
logger.error(
|
||||
f"事务异常(未回滚): {transaction_id} - {type(e).__name__}: {str(e)}"
|
||||
@@ -222,7 +219,9 @@ def retry_on_database_error(max_retries: int = 3, delay: float = 0.1) -> Any:
|
||||
if attempt < max_retries - 1:
|
||||
# 随机化延迟,避免多个请求同时重试
|
||||
actual_delay = delay * (2**attempt) + random.uniform(0, 0.1)
|
||||
logger.warning(f"数据库操作失败,{actual_delay:.2f}秒后重试 (尝试 {attempt + 1}/{max_retries}): {str(e)}")
|
||||
logger.warning(
|
||||
f"数据库操作失败,{actual_delay:.2f}秒后重试 (尝试 {attempt + 1}/{max_retries}): {str(e)}"
|
||||
)
|
||||
time.sleep(actual_delay)
|
||||
continue
|
||||
else:
|
||||
|
||||
Reference in New Issue
Block a user