修复(登录任务): 取码失败自动换渠道,被跳过账号也落日志
- 登录先用人工设置的默认接口(当前 iframe):等码超时/发信失败后, 同一账号自动切到另一条通道(iframe <-> wgapi)再试一轮,每个账号 最多切一次;DOUYU_LOGIN_EMAIL_FALLBACK_API=off 可关闭 - 步骤 4/5 日志写明当前取码通道,切渠道时单独告警,页面可直接看到 - 配额/账号上限挡下的账号不再「凭空消失」:落一行 skipped 任务, 日志写明未执行原因;界面新增「已跳过」状态、筛选与重试 - 停止、服务重启收敛、执行线程异常这几条路径也补单账号日志 - 修复刷新线程与收尾写库的覆盖竞态(旧快照会吃掉最后的失败原因) - 补测试:渠道回退、跳过行与日志、日志真正落库
This commit is contained in:
@@ -67,6 +67,7 @@ LOGIN_STATUS_LABELS: dict[str, str] = {
|
||||
"success": "成功",
|
||||
"failed": "失败",
|
||||
"error": "异常",
|
||||
"skipped": "已跳过",
|
||||
"stopped": "已停止",
|
||||
"account_cancelled": "账号已注销",
|
||||
"password_wrong": "账号密码错误",
|
||||
@@ -290,7 +291,9 @@ def _serialize_tasks(db: Session, rows) -> list[LoginTaskOut]:
|
||||
.order_by(LoginAttempt.id.asc())
|
||||
.all()
|
||||
):
|
||||
attempt_map[(str(attempt.batch_id or ""), int(attempt.account_id))] = attempt
|
||||
attempt_map[(str(attempt.batch_id or ""), int(attempt.account_id))] = (
|
||||
attempt
|
||||
)
|
||||
creator_ids = {
|
||||
int(value)
|
||||
for value in [
|
||||
@@ -405,9 +408,7 @@ def get_task_logs(
|
||||
):
|
||||
"""读取单个账号本次登录尝试的日志。"""
|
||||
task = (
|
||||
_visible_tasks_query(db, current, None)
|
||||
.filter(LoginTask.id == task_id)
|
||||
.first()
|
||||
_visible_tasks_query(db, current, None).filter(LoginTask.id == task_id).first()
|
||||
)
|
||||
if task is None:
|
||||
raise HTTPException(status_code=404, detail="登录任务不存在")
|
||||
@@ -826,16 +827,12 @@ async def ws_login_logs(websocket: WebSocket, batch_id: str):
|
||||
return
|
||||
continue
|
||||
if job is None or job.status in TERMINAL_STATUSES:
|
||||
await websocket.send_json(
|
||||
{"level": "result", "message": "批次已结束"}
|
||||
)
|
||||
await websocket.send_json({"level": "result", "message": "批次已结束"})
|
||||
return
|
||||
await asyncio.sleep(0.5)
|
||||
idle_seconds += 0.5
|
||||
if idle_seconds >= 30:
|
||||
await websocket.send_json(
|
||||
{"level": "heartbeat", "message": ""}
|
||||
)
|
||||
await websocket.send_json({"level": "heartbeat", "message": ""})
|
||||
idle_seconds = 0
|
||||
|
||||
log_queue: asyncio.Queue = batch["log_queue"]
|
||||
|
||||
@@ -53,6 +53,10 @@ _TASK_LOG_SINK_LOCK = threading.Lock()
|
||||
# 实时进度,必须由独立的刷新线程能读到登录线程写的内容。
|
||||
_TASK_LOGS: dict[int, list[dict[str, Any]]] = {}
|
||||
_TASK_LOGS_LOCK = threading.Lock()
|
||||
# 刷新线程和登录线程都会写 login_tasks.logs。没有这把锁时,刷新线程可能拿着
|
||||
# 「较早的快照」在收尾写库之后提交,把最后几条(往往正是失败原因)覆盖掉。
|
||||
# 所有落库动作都在这把锁内完成「取快照 + 写库」,保证收尾那一笔一定是最后写入。
|
||||
_TASK_LOG_PERSIST_LOCK = threading.Lock()
|
||||
_TASK_LOG_FLUSHER: threading.Thread | None = None
|
||||
_TASK_LOG_FLUSH_SECONDS = 3.0
|
||||
# 单任务最多保留条数;超出后优先丢 DEBUG,避免把关键步骤挤掉。
|
||||
@@ -101,14 +105,45 @@ def _drop_task_logs(task_id: int) -> list[dict[str, Any]]:
|
||||
return _TASK_LOGS.pop(task_id, [])
|
||||
|
||||
|
||||
def _task_log_entry(level: str, message: str, module: str = "login_service") -> dict:
|
||||
"""构造一条要直接落库的日志(不经过登录线程的 loguru sink)。"""
|
||||
return {
|
||||
"level": level,
|
||||
"message": str(message or "").strip()[:TASK_LOG_MESSAGE_LIMIT],
|
||||
"module": module,
|
||||
"at": datetime.now(UTC).isoformat(),
|
||||
}
|
||||
|
||||
|
||||
def _append_persisted_log(
|
||||
task: LoginTask,
|
||||
level: str,
|
||||
message: str,
|
||||
module: str = "login_service",
|
||||
) -> None:
|
||||
"""给「没有进入登录线程」的尝试补一条说明日志(跳过、停止、异常收尾)。
|
||||
|
||||
这类账号以前什么都不写:页面上既没有任务行也没有日志,运营只看到
|
||||
「点了登录没反应」。现在至少能看到一行原因。
|
||||
"""
|
||||
entry = _task_log_entry(level, message, module)
|
||||
if not entry["message"]:
|
||||
return
|
||||
existing = [item for item in (task.logs or []) if isinstance(item, dict)]
|
||||
task.logs = (existing + [entry])[-TASK_LOG_LIMIT:]
|
||||
|
||||
|
||||
def _flush_active_task_logs() -> None:
|
||||
"""把进行中的任务日志增量写库,页面就能看到实时进度。"""
|
||||
with _TASK_LOGS_LOCK:
|
||||
task_ids = list(_TASK_LOGS)
|
||||
for task_id in task_ids:
|
||||
logs = _snapshot_task_logs(task_id)
|
||||
if logs:
|
||||
_persist_task_logs(task_id, logs)
|
||||
# 锁内重新确认任务仍在进行中:收尾线程可能刚把日志取走并落库,
|
||||
# 这里再写一次旧快照就会覆盖掉最后的失败原因。
|
||||
with _TASK_LOG_PERSIST_LOCK:
|
||||
logs = _snapshot_task_logs(task_id)
|
||||
if logs:
|
||||
_persist_task_logs(task_id, logs)
|
||||
|
||||
|
||||
def _start_task_log_flusher() -> None:
|
||||
@@ -499,10 +534,15 @@ class LoginBatchRunner:
|
||||
)
|
||||
self.api_strategy = create_login_api_strategy(api_strategy)
|
||||
self.mode = mode if mode in ("login", "check", "relogin") else "login"
|
||||
self.trigger_source = trigger_source if trigger_source in {
|
||||
"manual",
|
||||
"automation",
|
||||
} else "manual"
|
||||
self.trigger_source = (
|
||||
trigger_source
|
||||
if trigger_source
|
||||
in {
|
||||
"manual",
|
||||
"automation",
|
||||
}
|
||||
else "manual"
|
||||
)
|
||||
self._stop = threading.Event()
|
||||
self._counter_lock = threading.Lock()
|
||||
self._completed = 0
|
||||
@@ -541,6 +581,9 @@ class LoginBatchRunner:
|
||||
task = worker_db.query(LoginTask).filter(LoginTask.id == task_id).first()
|
||||
if task and _attempt_in_flight(task):
|
||||
_mark_attempt_failed(task, message)
|
||||
# 停止也要留下原因:否则页面上只有一条「已停止」的状态,
|
||||
# 点开日志却什么都没有。
|
||||
_append_persisted_log(task, "warning", message)
|
||||
worker_db.commit()
|
||||
finally:
|
||||
worker_db.close()
|
||||
@@ -567,12 +610,40 @@ class LoginBatchRunner:
|
||||
for task in tasks:
|
||||
if _attempt_in_flight(task):
|
||||
_mark_attempt_failed(task, message)
|
||||
_append_persisted_log(task, "warning", message)
|
||||
changed = True
|
||||
if changed:
|
||||
worker_db.commit()
|
||||
finally:
|
||||
worker_db.close()
|
||||
|
||||
def _record_skipped_attempt(
|
||||
self,
|
||||
task: LoginTask,
|
||||
account: AccountModel,
|
||||
reason: str,
|
||||
) -> None:
|
||||
"""记录一次「点了登录但没执行」的尝试。
|
||||
|
||||
以前配额/权限/在途判定失败时只写一条批次级 warning,**不建任务行**:
|
||||
页面上账号凭空消失,运营既看不到原因也看不到日志,只能猜是不是
|
||||
「登录预算」或者「账号限制」。现在给账号落一行 `skipped` 并在日志里
|
||||
写明原因,和真正跑过的尝试在同一个列表里可见。
|
||||
"""
|
||||
now = datetime.now(UTC)
|
||||
message = f"未执行:{reason}"
|
||||
task.attempt_status = "skipped"
|
||||
task.attempt_message = message
|
||||
task.attempt_batch_id = self.batch_id
|
||||
task.attempt_at = now
|
||||
task.finished_at = now
|
||||
# 账号已有 CK 时不动 status/message(沿用失败尝试的规则:旧 CK 的
|
||||
# 成功语义不能被一次「没跑」覆盖)。
|
||||
if not account.cookie:
|
||||
task.status = "skipped"
|
||||
task.message = message
|
||||
task.logs = [_task_log_entry("warning", f"本次登录未执行:{reason}")]
|
||||
|
||||
def _push_log(self, level: str, message: str):
|
||||
# 逐账号日志由模块级 loguru sink 统一收集(含 core/ 的步骤日志);
|
||||
# 这里只负责 app.log、页面实时队列和外部 log_sink。
|
||||
@@ -612,19 +683,21 @@ class LoginBatchRunner:
|
||||
|
||||
def _execute_one(self, task_id: int, acc_info: dict, total: int):
|
||||
"""在独立线程中执行单个账号登录,使用独立的 DB 会话。"""
|
||||
if self._stop.is_set():
|
||||
self._push_log("warning", f"任务已停止,跳过: {acc_info['username']}")
|
||||
self._mark_relogin_stopped(task_id, "任务已停止,旧 Cookie 已保留")
|
||||
return
|
||||
|
||||
worker_db = WorkerSessionLocal()
|
||||
task = None
|
||||
# 日志上下文必须在**任何分支之前**建立:账号被停止跳过、任务行读不到、
|
||||
# 代理配置异常这些路径以前直接 return,页面上连一行原因都看不到。
|
||||
_LOG_CONTEXT.task_id = int(task_id or 0)
|
||||
_drop_task_logs(int(task_id or 0))
|
||||
worker_db = None
|
||||
try:
|
||||
if self._stop.is_set():
|
||||
self._push_log("warning", f"任务已停止,跳过: {acc_info['username']}")
|
||||
self._mark_relogin_stopped(task_id, "任务已停止,旧 Cookie 已保留")
|
||||
return
|
||||
|
||||
worker_db = WorkerSessionLocal()
|
||||
task = worker_db.query(LoginTask).filter(LoginTask.id == task_id).first()
|
||||
if not task:
|
||||
return
|
||||
_LOG_CONTEXT.task_id = int(task.id)
|
||||
_drop_task_logs(int(task.id))
|
||||
# CK、健康与重登状态都挂在账号上;登录记录只是一次尝试的历史。
|
||||
account = task.account
|
||||
|
||||
@@ -831,11 +904,13 @@ class LoginBatchRunner:
|
||||
|
||||
finally:
|
||||
_LOG_CONTEXT.task_id = 0
|
||||
logs = _drop_task_logs(task_id)
|
||||
# 先关会话释放行锁,再用独立短事务写日志;反过来会在异常路径上
|
||||
# 自己堵自己(同一行 UPDATE 等锁 50 秒)。
|
||||
worker_db.close()
|
||||
_persist_task_logs(task_id, logs)
|
||||
with _TASK_LOG_PERSIST_LOCK:
|
||||
logs = _drop_task_logs(task_id)
|
||||
if worker_db is not None:
|
||||
worker_db.close()
|
||||
_persist_task_logs(task_id, logs)
|
||||
|
||||
def run(self):
|
||||
"""在线程中执行批量登录。"""
|
||||
@@ -918,26 +993,14 @@ class LoginBatchRunner:
|
||||
self._push_log("warning", f"跳过无权账号: {acc.username}")
|
||||
continue
|
||||
|
||||
quota = reserve_login_attempt(
|
||||
self.db,
|
||||
account=acc,
|
||||
mode=self.mode,
|
||||
trigger_source=self.trigger_source,
|
||||
batch_id=batch_id,
|
||||
created_by=self.created_by,
|
||||
)
|
||||
if not quota.allowed:
|
||||
self._push_log(
|
||||
"warning",
|
||||
f"跳过账号 {acc.username}: {quota.reason}",
|
||||
)
|
||||
continue
|
||||
|
||||
# 解耦后不再需要「哪一行持有 CK」这个不变量(CK 在账号上)。
|
||||
# 这里只需要保证**同一账号不并发两行**:
|
||||
# ① 复用该账号在途的尝试(避免并发两个批次各建一行);
|
||||
# ② 否则复用最近一条失败/中断的历史,避免刷屏;
|
||||
# ③ 都没有就新建一行(历史而已,允许一个账号多行)。
|
||||
#
|
||||
# 先找行、再做配额判定:被配额挡下的账号也要有行可落日志,
|
||||
# 否则页面上「点了登录什么都没发生」。
|
||||
task = (
|
||||
self.db.query(LoginTask)
|
||||
.filter(
|
||||
@@ -956,7 +1019,7 @@ class LoginBatchRunner:
|
||||
.first()
|
||||
)
|
||||
if task is None:
|
||||
# 复用最近一条**失败/中断**的历史,避免每次失败都刷一行。
|
||||
# 复用最近一条**失败/中断/跳过**的历史,避免每次失败都刷一行。
|
||||
# 注意要同时看 attempt_status:账号有 CK 时 `_mark_attempt_failed`
|
||||
# 刻意不动 status(保护旧语义),所以失败记录的 status 可能还停在
|
||||
# pending —— 只看 status 就永远命不中,行数会无限长。
|
||||
@@ -965,8 +1028,10 @@ class LoginBatchRunner:
|
||||
.filter(
|
||||
LoginTask.account_id == aid,
|
||||
or_(
|
||||
LoginTask.status.in_(["failed", "error"]),
|
||||
LoginTask.attempt_status.in_(["failed", "error"]),
|
||||
LoginTask.status.in_(["failed", "error", "skipped"]),
|
||||
LoginTask.attempt_status.in_(
|
||||
["failed", "error", "skipped"]
|
||||
),
|
||||
),
|
||||
)
|
||||
.order_by(LoginTask.id.desc())
|
||||
@@ -981,6 +1046,26 @@ class LoginBatchRunner:
|
||||
)
|
||||
self.db.add(task)
|
||||
|
||||
quota = reserve_login_attempt(
|
||||
self.db,
|
||||
account=acc,
|
||||
mode=self.mode,
|
||||
trigger_source=self.trigger_source,
|
||||
batch_id=batch_id,
|
||||
created_by=self.created_by,
|
||||
)
|
||||
if not quota.allowed:
|
||||
self._push_log(
|
||||
"warning",
|
||||
f"跳过账号 {acc.username}: {quota.reason}",
|
||||
)
|
||||
if quota.reason == "该账号已有登录任务在执行":
|
||||
# 另一个批次正在跑这个账号:别碰它的行,它的日志由
|
||||
# 正在执行的那次尝试负责。
|
||||
continue
|
||||
self._record_skipped_attempt(task, acc, quota.reason)
|
||||
continue
|
||||
|
||||
_append_task_info(task, acc)
|
||||
|
||||
self.db.commit()
|
||||
@@ -1106,9 +1191,7 @@ def _settle_login_attempts(batch_id: str) -> None:
|
||||
elif task_status in CHECK_STATUS_MESSAGES:
|
||||
status = "failed"
|
||||
failure_kind = (
|
||||
"network"
|
||||
if task_status == "account_auth_unknown"
|
||||
else "credential"
|
||||
"network" if task_status == "account_auth_unknown" else "credential"
|
||||
)
|
||||
elif task_status in {"failed", "error"}:
|
||||
status = task_status
|
||||
@@ -1151,6 +1234,9 @@ def _converge_interrupted_attempts(db: Session, message: str) -> int:
|
||||
if not _attempt_in_flight(task):
|
||||
continue
|
||||
_mark_attempt_failed(task, message)
|
||||
# 进程重启会把这些尝试永远留在「进行中」;只改状态不留日志,
|
||||
# 页面恢复后就只剩一条失败状态,看不出是被重启打断的。
|
||||
_append_persisted_log(task, "warning", message)
|
||||
cleaned += 1
|
||||
if cleaned:
|
||||
db.commit()
|
||||
|
||||
Reference in New Issue
Block a user