feat: 采集任务在有效账号之间按负载分摊

This commit is contained in:
2026-11-10 11:34:29 +08:00
parent 8f92e5aa36
commit 9309d25420
7 changed files with 112 additions and 8 deletions
@@ -0,0 +1,21 @@
"""记录号池账号正在执行和累计执行的任务数,用来分摊采集。"""
from alembic import op
import sqlalchemy as sa
revision = "0006_account_task_load"
down_revision = "0005_account_created_at"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.add_column("nqi_account", sa.Column("active_tasks", sa.Integer(), nullable=False, server_default="0"))
op.add_column("nqi_account", sa.Column("task_runs", sa.Integer(), nullable=False, server_default="0"))
op.add_column("nqi_account", sa.Column("last_task_at", sa.DateTime(timezone=True), nullable=True))
def downgrade() -> None:
op.drop_column("nqi_account", "last_task_at")
op.drop_column("nqi_account", "task_runs")
op.drop_column("nqi_account", "active_tasks")
+49
View File
@@ -0,0 +1,49 @@
"""采集任务在有效账号之间分摊。正在执行的少的优先,其次是历史次数少、更久没用过的。"""
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))
+3
View File
@@ -51,6 +51,9 @@ class NqiAccount(Base):
role: Mapped[str] = mapped_column(String(16), default="user")
session_open: Mapped[bool] = mapped_column(Boolean, default=True)
credential_valid: Mapped[bool] = mapped_column(Boolean, default=True)
active_tasks: Mapped[int] = mapped_column(Integer, default=0)
task_runs: Mapped[int] = mapped_column(Integer, default=0)
last_task_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
saved_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
+5
View File
@@ -7,6 +7,7 @@ import logging
import threading
import time
from app.collect.accounts import reset_active_tasks
from app.config import installed
from app.db import session_scope
from app.tasks.runner import refresh_accounts, scan_sources
@@ -20,6 +21,10 @@ def start_background() -> None:
if _started:
return
_started = True
try:
reset_active_tasks()
except Exception as exc:
logger.info("重置账号占用未完成: %s", exc)
threading.Thread(target=_refresh_loop, name="decom-refresh", daemon=True).start()
threading.Thread(target=_collect_loop, name="decom-collect", daemon=True).start()
+10 -8
View File
@@ -8,6 +8,7 @@ from datetime import date, datetime, timedelta, timezone
from sqlalchemy import select
from app.collect.accounts import borrow_account, release_account
from app.collect.io import parse_upload, write_table
from app.collect.remote import fetch_nqi
from app.collect.schedule import next_run_at
@@ -155,16 +156,14 @@ def execute_collection(source_id: int) -> None:
kind = source.kind
config = dict(source.config or {})
source_name = source.name
account = None
if kind == "nqi":
account = session.scalar(
select(NqiAccount).where(NqiAccount.credential_valid.is_(True)).order_by(NqiAccount.saved_at.desc())
)
cookies = list(account.cookies or []) if account is not None else []
else:
cookies = []
account_id = None
cookies: list = []
try:
if kind == "nqi":
borrowed = borrow_account()
if borrowed is None:
raise ValueError("账号池里没有可用凭证")
account_id, cookies = borrowed
if not cookies:
raise ValueError("账号池里没有可用凭证")
if config.get("tables"):
@@ -190,6 +189,9 @@ def execute_collection(source_id: int) -> None:
source = session.get(CollectionSource, source_id)
if source is not None:
source.last_error = str(exc) or "采集失败"
finally:
if account_id is not None:
release_account(account_id)
def _save_nqi_tables(cookies: list, config: dict, source_id: int, source_name: str) -> None:
+22
View File
@@ -194,6 +194,28 @@ def test_pool_add_is_allowed_when_login_is_local(client: TestClient, monkeypatch
assert pool.json()["detail"] == "未连接平台"
def test_collection_borrows_the_less_used_account(client: TestClient):
from app.collect.accounts import borrow_account, release_account
from app.db import session_scope
from app.models import NqiAccount, utcnow
now = utcnow()
with session_scope() as session:
session.add(NqiAccount(login_id="busy", credential_valid=True, cookies=[{"name": "a"}], active_tasks=1, task_runs=4, last_task_at=now))
session.add(NqiAccount(login_id="idle", credential_valid=True, cookies=[{"name": "b"}]))
session.add(NqiAccount(login_id="dead", credential_valid=False, cookies=[{"name": "c"}]))
account_id, cookies = borrow_account()
assert cookies == [{"name": "b"}]
with session_scope() as session:
account = session.get(NqiAccount, account_id)
assert account.login_id == "idle"
assert account.active_tasks == 1
assert account.task_runs == 1
release_account(account_id)
with session_scope() as session:
assert session.get(NqiAccount, account_id).active_tasks == 0
def test_concurrency_bounds():
assert check_concurrency(1) == 1
assert check_concurrency(32) == 32
+2
View File
@@ -3,6 +3,7 @@
from __future__ import annotations
from app.bootstrap import init_db
from app.collect.accounts import reset_active_tasks
from app.config import postgres_conninfo
from app.runtime import start_background
@@ -16,6 +17,7 @@ def main() -> None:
if sys.platform == "win32":
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
ready = init_db()
reset_active_tasks()
start_background()
import time