fix+perf: SQLite连接busy_timeout修复并发锁/静态版本号缓存/删除资产批量清理/安全检查最新记录子查询修正/AI余额与SSL探测并发化/密钥常量时间比较
This commit is contained in:
@@ -299,26 +299,44 @@ def refresh_ai_balance(session: Session, asset_id: int) -> dict:
|
||||
}
|
||||
|
||||
|
||||
def sync_all_ai_balances(session: Session) -> dict:
|
||||
"""遍历所有 AI 账号资产,逐个刷新余额(单个失败不中断整体)"""
|
||||
def sync_all_ai_balances(session: Session, max_workers: int = 5) -> dict:
|
||||
"""并发刷新所有 AI 账号余额(单个失败不中断整体)
|
||||
|
||||
每个账号需调用外部 API(单次最长 30s),串行时总耗时随账号数线性增长;
|
||||
改为线程池并发后显著提速。注意:SQLite Session 不能跨线程共享,
|
||||
每个 worker 使用独立 Session(WAL 模式下多连接读写安全)。
|
||||
"""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
from app.database import assets_engine
|
||||
|
||||
ai_assets = session.exec(
|
||||
select(Asset).where(Asset.asset_type == AssetType.AI_AGENT)
|
||||
).all()
|
||||
asset_ids = [(a.id, a.name) for a in ai_assets]
|
||||
|
||||
def _refresh_one(asset_id: int):
|
||||
with Session(assets_engine) as worker_session:
|
||||
refresh_ai_balance(worker_session, asset_id)
|
||||
|
||||
success = 0
|
||||
failed = 0
|
||||
errors = []
|
||||
for asset in ai_assets:
|
||||
try:
|
||||
refresh_ai_balance(session, asset.id)
|
||||
success += 1
|
||||
except HTTPException as e:
|
||||
failed += 1
|
||||
errors.append(f"{asset.name}: {e.detail}")
|
||||
except Exception as e: # noqa: BLE001
|
||||
failed += 1
|
||||
errors.append(f"{asset.name}: {e}")
|
||||
with ThreadPoolExecutor(max_workers=max_workers) as pool:
|
||||
futures = {pool.submit(_refresh_one, aid): name for aid, name in asset_ids}
|
||||
for future in futures:
|
||||
name = futures[future]
|
||||
try:
|
||||
future.result()
|
||||
success += 1
|
||||
except HTTPException as e:
|
||||
failed += 1
|
||||
errors.append(f"{name}: {e.detail}")
|
||||
except Exception as e: # noqa: BLE001
|
||||
failed += 1
|
||||
errors.append(f"{name}: {e}")
|
||||
return {
|
||||
"total": len(ai_assets),
|
||||
"total": len(asset_ids),
|
||||
"success": success,
|
||||
"failed": failed,
|
||||
"errors": errors,
|
||||
|
||||
Reference in New Issue
Block a user