refactor: 优化异步调用和权限系统架构

- 移除bot.py中不必要的asyncio.to_thread包装
- 将权限API的is_master方法改为异步调用
- 删除不再使用的SQLAlchemyTransaction类
This commit is contained in:
雅诺狐
2025-10-06 21:02:38 +08:00
parent d2c4726ad1
commit e83e0d9ff2
4 changed files with 5 additions and 34 deletions

2
bot.py
View File

@@ -289,7 +289,7 @@ class DatabaseManager:
start_time = time.time()
# 使用线程执行器运行潜在的阻塞操作
await asyncio.to_thread(initialize_sql_database, global_config.database)
await initialize_sql_database( global_config.database)
elapsed_time = time.time() - start_time
logger.info(
f"数据库连接初始化成功,使用 {global_config.database.database_type} 数据库,耗时: {elapsed_time:.2f}"

View File

@@ -48,35 +48,6 @@ class DatabaseProxy:
return result
class SQLAlchemyTransaction:
"""SQLAlchemy 异步事务上下文管理器 (兼容旧代码示例,推荐直接使用 get_db_session)。"""
def __init__(self):
self._ctx = None
self.session = None
async def __aenter__(self):
# get_db_session 是一个 async contextmanager
self._ctx = get_db_session()
self.session = await self._ctx.__aenter__()
return self.session
async def __aexit__(self, exc_type, exc_val, exc_tb):
try:
if self.session:
if exc_type is None:
try:
await self.session.commit()
except Exception:
await self.session.rollback()
raise
else:
await self.session.rollback()
finally:
if self._ctx:
await self._ctx.__aexit__(exc_type, exc_val, exc_tb)
# 创建全局数据库代理实例
db = DatabaseProxy()

View File

@@ -36,7 +36,7 @@ class IPermissionManager(ABC):
async def check_permission(self, user: UserInfo, permission_node: str) -> bool: ...
@abstractmethod
def is_master(self, user: UserInfo) -> bool: ... # 同步快速判断
async def is_master(self, user: UserInfo) -> bool: ... # 同步快速判断
@abstractmethod
async def register_permission_node(self, node: PermissionNode) -> bool: ...
@@ -82,9 +82,9 @@ class PermissionAPI:
self._ensure_manager()
return await self._permission_manager.check_permission(UserInfo(platform, user_id), permission_node)
def is_master(self, platform: str, user_id: str) -> bool:
async def is_master(self, platform: str, user_id: str) -> bool:
self._ensure_manager()
return self._permission_manager.is_master(UserInfo(platform, user_id))
return await self._permission_manager.is_master(UserInfo(platform, user_id))
async def register_permission_node(
self,

View File

@@ -231,7 +231,7 @@ class PermissionCommand(PlusCommand):
target_user_id = chat_stream.user_info.user_id
# 检查是否为Master用户
is_master = permission_api.is_master(chat_stream.platform, target_user_id)
is_master = await permission_api.is_master(chat_stream.platform, target_user_id)
# 获取用户权限
permissions = await permission_api.get_user_permissions(chat_stream.platform, target_user_id)