Files
DecomEval/backend/app/collect/accounts.py
T

59 lines
1.9 KiB
Python

"""采集任务在有效账号之间分摊。正在执行的少的优先,其次是历史次数少、更久没用过的。"""
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) -> tuple[int, list] | None:
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()
account = next((row for row in rows if row.id not in skipped and 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, *, 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 reset_active_tasks() -> None:
with session_scope() as session:
session.execute(update(NqiAccount).values(active_tasks=0))