fix: 采集账号失败就换号,都不可用时任务留待再试
This commit is contained in:
@@ -12,7 +12,14 @@ from app.models import NqiAccount, utcnow
|
||||
_lock = threading.Lock()
|
||||
|
||||
|
||||
def borrow_account() -> tuple[int, list] | None:
|
||||
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(
|
||||
@@ -25,7 +32,7 @@ def borrow_account() -> tuple[int, list] | None:
|
||||
NqiAccount.id,
|
||||
)
|
||||
).all()
|
||||
account = next((row for row in rows if row.cookies), None)
|
||||
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
|
||||
@@ -35,13 +42,15 @@ def borrow_account() -> tuple[int, list] | None:
|
||||
return account.id, list(account.cookies or [])
|
||||
|
||||
|
||||
def release_account(account_id: int) -> None:
|
||||
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:
|
||||
|
||||
+75
-35
@@ -8,7 +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.accounts import AccountUnavailable, 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
|
||||
@@ -17,7 +17,7 @@ from app.config import inline_worker_allowed, postgres_conninfo, result_dir
|
||||
from app.db import session_scope
|
||||
from app.models import CellData, CollectionSource, ExportTask, NqiAccount, utcnow
|
||||
from app.nqi.adhoc import export_table, time_window
|
||||
from app.nqi.client import NqiAuthError, NqiClient, NqiError
|
||||
from app.nqi.client import NqiAuthError, NqiClient, NqiError, NqiNetworkError
|
||||
|
||||
logger = logging.getLogger("decom")
|
||||
MIN_CONCURRENCY = 1
|
||||
@@ -156,42 +156,82 @@ def execute_collection(source_id: int) -> None:
|
||||
kind = source.kind
|
||||
config = dict(source.config or {})
|
||||
source_name = source.name
|
||||
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 kind != "nqi":
|
||||
_fail_collection(source_id, "未知的采集来源")
|
||||
return
|
||||
tried: set[int] = set()
|
||||
while True:
|
||||
borrowed = borrow_account(tried)
|
||||
if borrowed is None:
|
||||
_postpone_collection(source_id, "账号暂时都不能用,稍后再试")
|
||||
return
|
||||
account_id, cookies = borrowed
|
||||
tried.add(account_id)
|
||||
held = True
|
||||
try:
|
||||
if config.get("tables"):
|
||||
_save_nqi_tables(cookies, config, source_id, source_name)
|
||||
_use_account(lambda: _save_nqi_tables(cookies, config, source_id, source_name))
|
||||
else:
|
||||
name, content = _use_account(lambda: _fetch_nqi_sync(cookies, config))
|
||||
rows = parse_upload(name, content)
|
||||
with session_scope() as session:
|
||||
source = session.get(CollectionSource, source_id)
|
||||
if source is not None:
|
||||
source.last_error = ""
|
||||
return
|
||||
name, content = _fetch_nqi_sync(cookies, config)
|
||||
else:
|
||||
raise ValueError("未知的采集来源")
|
||||
rows = parse_upload(name, content)
|
||||
with session_scope() as session:
|
||||
source = session.get(CollectionSource, source_id)
|
||||
if source is None:
|
||||
return
|
||||
upsert_rows(session, kind, rows)
|
||||
source.last_error = ""
|
||||
except Exception as exc:
|
||||
logger.info("采集失败: %s", exc)
|
||||
with session_scope() as session:
|
||||
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)
|
||||
if source is None:
|
||||
return
|
||||
upsert_rows(session, kind, rows)
|
||||
with session_scope() as session:
|
||||
source = session.get(CollectionSource, source_id)
|
||||
if source is not None:
|
||||
source.last_error = ""
|
||||
return
|
||||
except AccountUnavailable as exc:
|
||||
logger.info("账号 %s 不能完成本次采集: %s", account_id, exc)
|
||||
release_account(account_id, invalid=exc.invalid)
|
||||
held = False
|
||||
except Exception as exc:
|
||||
logger.info("采集失败: %s", exc)
|
||||
_fail_collection(source_id, str(exc) or "采集失败")
|
||||
return
|
||||
finally:
|
||||
if held:
|
||||
release_account(account_id)
|
||||
|
||||
|
||||
def _use_account(action):
|
||||
try:
|
||||
return action()
|
||||
except AccountUnavailable:
|
||||
raise
|
||||
except NqiAuthError as exc:
|
||||
raise AccountUnavailable("账号池凭证已失效", invalid=True) from exc
|
||||
except NqiNetworkError as exc:
|
||||
raise AccountUnavailable(str(exc) or "连接失败", invalid=False) from exc
|
||||
except NqiError as exc:
|
||||
text = str(exc)
|
||||
if "凭证" in text or "登录" in text or "即席查询" in text:
|
||||
raise AccountUnavailable(text or "账号不能用", invalid=True) from exc
|
||||
raise
|
||||
except ValueError as exc:
|
||||
text = str(exc)
|
||||
if "凭证" in text or "登录" in text:
|
||||
raise AccountUnavailable(text, invalid=True) from exc
|
||||
raise
|
||||
|
||||
|
||||
def _postpone_collection(source_id: int, message: str) -> None:
|
||||
with session_scope() as session:
|
||||
source = session.get(CollectionSource, source_id)
|
||||
if source is None:
|
||||
return
|
||||
source.last_error = message
|
||||
source.next_run_at = utcnow() + timedelta(seconds=60)
|
||||
|
||||
|
||||
def _fail_collection(source_id: int, message: str) -> None:
|
||||
with session_scope() as session:
|
||||
source = session.get(CollectionSource, source_id)
|
||||
if source is not None:
|
||||
source.last_error = message
|
||||
|
||||
|
||||
def _save_nqi_tables(cookies: list, config: dict, source_id: int, source_name: str) -> None:
|
||||
|
||||
@@ -216,6 +216,37 @@ def test_collection_borrows_the_less_used_account(client: TestClient):
|
||||
assert session.get(NqiAccount, account_id).active_tasks == 0
|
||||
|
||||
|
||||
def test_borrow_skips_an_account_that_just_failed(client: TestClient):
|
||||
from app.collect.accounts import borrow_account, release_account
|
||||
from app.db import session_scope
|
||||
from app.models import NqiAccount
|
||||
|
||||
with session_scope() as session:
|
||||
session.add(NqiAccount(login_id="first", credential_valid=True, cookies=[{"name": "a"}]))
|
||||
session.add(NqiAccount(login_id="second", credential_valid=True, cookies=[{"name": "b"}]))
|
||||
first_id, _cookies = borrow_account()
|
||||
release_account(first_id, invalid=True)
|
||||
second_id, cookies = borrow_account({first_id})
|
||||
assert cookies == [{"name": "b"}]
|
||||
with session_scope() as session:
|
||||
assert session.get(NqiAccount, first_id).credential_valid is False
|
||||
assert session.get(NqiAccount, second_id).login_id == "second"
|
||||
release_account(second_id)
|
||||
|
||||
|
||||
def test_auth_failure_switches_account():
|
||||
from app.collect.accounts import AccountUnavailable
|
||||
from app.nqi.client import NqiAuthError
|
||||
from app.tasks.runner import _use_account
|
||||
|
||||
def fail():
|
||||
raise NqiAuthError("登录已失效")
|
||||
|
||||
with pytest.raises(AccountUnavailable) as caught:
|
||||
_use_account(fail)
|
||||
assert caught.value.invalid is True
|
||||
|
||||
|
||||
def test_concurrency_bounds():
|
||||
assert check_concurrency(1) == 1
|
||||
assert check_concurrency(32) == 32
|
||||
|
||||
Reference in New Issue
Block a user