"""采集任务在有效账号之间分摊。正在执行的少的优先,其次是历史次数少、更久没用过的。""" 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() class AccountUnavailable(Exception): def __init__(self, message: str, *, invalid: bool) -> None: super().__init__(message) self.invalid = invalid def borrow_account(exclude: set[int] | None = None, prefer_city: str = "") -> tuple[int, list] | None: """prefer_city 给出时,先用这个地市的账号,没有再用别的。""" skipped = exclude or set() 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() usable = [row for row in rows if row.id not in skipped and row.cookies] if prefer_city: usable.sort(key=lambda row: not (row.city_name or "").startswith(prefer_city)) account = usable[0] if usable else 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, *, invalid: bool = False) -> 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) if invalid: account.credential_valid = False def has_valid_account() -> bool: with session_scope() as session: return session.scalar(select(NqiAccount.id).where(NqiAccount.credential_valid.is_(True)).limit(1)) is not None def reset_active_tasks() -> None: with session_scope() as session: session.execute(update(NqiAccount).values(active_tasks=0))