"""采集任务在有效账号之间分摊。正在执行的少的优先,其次是历史次数少、更久没用过的。""" from __future__ import annotations import threading from sqlalchemy import select, update from app.db import session_scope from app.models import NqiAccount, utcnow _lock = threading.Lock() def borrow_account() -> tuple[int, list] | None: with _lock: with session_scope() as session: rows = session.scalars( select(NqiAccount) .where(NqiAccount.credential_valid.is_(True)) .order_by( NqiAccount.active_tasks, NqiAccount.task_runs, NqiAccount.last_task_at.asc().nullsfirst(), NqiAccount.id, ) ).all() account = next((row for row in rows if row.cookies), None) if account is None: return None account.active_tasks += 1 account.task_runs += 1 account.last_task_at = utcnow() session.flush() return account.id, list(account.cookies or []) def release_account(account_id: int) -> None: with _lock: with session_scope() as session: account = session.get(NqiAccount, account_id) if account is None: return account.active_tasks = max(0, account.active_tasks - 1) def reset_active_tasks() -> None: with session_scope() as session: session.execute(update(NqiAccount).values(active_tasks=0))