fix(douyu): 修复斗鱼链路 P0/P1 隐患并增强 P2 运维队列可观测性

This commit is contained in:
yml
2026-11-29 14:10:24 +08:00
parent be7146a9ef
commit d12d9e02b3
51 changed files with 2510 additions and 561 deletions
+25
View File
@@ -38,12 +38,34 @@ def _runtime_heartbeat_path() -> Path:
def _runtime_heartbeat_payload() -> dict[str, Any]:
from .database import worker_engine
from .services.automation.scheduler import scheduler_status
from .services.binding_poll_scheduler import (
scheduler_status as binding_poll_status,
)
from .services.douyu_runner_core import douyu_batch_registry
from .services.execution_worker import execution_job_worker_status
from .services.payment_poll_scheduler import (
scheduler_status as payment_poll_status,
)
from .services.task_runtime import lane_stats
return {
"pid": os.getpid(),
"updatedAt": datetime.now(UTC).isoformat(),
"scheduler": scheduler_status(),
"runtime": {
"task_lanes": lane_stats(),
"worker_db_pool": (
getattr(worker_engine.pool, "status", lambda: "")()
if callable(getattr(worker_engine.pool, "status", None))
else ""
),
"binding_poll": binding_poll_status(),
"payment_poll": payment_poll_status(),
"execution_jobs": execution_job_worker_status(),
"douyu_batches": douyu_batch_registry.stats(),
},
}
@@ -115,8 +137,10 @@ def background_runtime_status() -> dict[str, Any]:
"staleAfterSeconds": _HEARTBEAT_STALE_SECONDS,
"pid": None,
"scheduler": {},
"runtime": {},
}
scheduler = payload.get("scheduler")
runtime = payload.get("runtime")
return {
"running": age_seconds <= _HEARTBEAT_STALE_SECONDS,
"heartbeatAt": heartbeat_at.isoformat(),
@@ -124,6 +148,7 @@ def background_runtime_status() -> dict[str, Any]:
"staleAfterSeconds": _HEARTBEAT_STALE_SECONDS,
"pid": payload.get("pid"),
"scheduler": scheduler if isinstance(scheduler, dict) else {},
"runtime": runtime if isinstance(runtime, dict) else {},
}
+18
View File
@@ -246,12 +246,30 @@ class UTCDateTime(TypeDecorator):
def get_db():
"""FastAPI 依赖:提供数据库会话,请求结束自动关闭。"""
db = SessionLocal()
db.info["managed_request_session"] = True
try:
yield db
finally:
db.close()
def release_idle_session(db) -> bool:
"""在执行阻塞 HTTP / sleep 前释放干净托管会话的事务与连接池连接。
仅对通过 ``get_db()`` 或 worker 托管标记创建的会话生效,且会话内不能有
未提交的新增/修改/删除对象,避免误伤单元测试中的未提交夹具或脏写状态。
"""
info = getattr(db, "info", None)
if not isinstance(info, dict) or not (
info.get("managed_request_session") or info.get("managed_worker_session")
):
return False
if getattr(db, "new", None) or getattr(db, "dirty", None) or getattr(db, "deleted", None):
return False
db.rollback()
return True
def init_db():
"""执行数据库迁移 + 写入初始数据。"""
run_migrations()
@@ -561,6 +561,10 @@
"20261129_0140_add_account_elite_capability_projection.py": {
"revision": "20261129_0140",
"sha256": "c19909f65b4826cd292176b71481f45eb4c1fb211b1db7923df7e92e54903c6d"
},
"20261129_0141_douyu_slow_query_indexes.py": {
"revision": "20261129_0141",
"sha256": "537ffb0a472c80d3a499c3c268aa62a2f5235ccc5399a81955a0e14d8721ea1f"
}
}
}
@@ -0,0 +1,175 @@
"""add douyu slow query covering indexes and role_norm column
Revision ID: 20261129_0141
Revises: 20261129_0140
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
revision: str = "20261129_0141"
down_revision: str | None = "20261129_0140"
branch_labels: str | None = None
depends_on: str | None = None
def _has_column(inspector: sa.Inspector, table: str, column: str) -> bool:
return any(col["name"] == column for col in inspector.get_columns(table))
def _has_index(inspector: sa.Inspector, table: str, index_name: str) -> bool:
return any(idx["name"] == index_name for idx in inspector.get_indexes(table))
def upgrade() -> None:
bind = op.get_bind()
inspector = sa.inspect(bind)
if inspector.has_table("account_events"):
if not _has_index(
inspector, "account_events", "ix_account_events_event_subject_occurred"
):
op.create_index(
"ix_account_events_event_subject_occurred",
"account_events",
["event_type", "subject_type", "subject_key", "occurred_at"],
)
if not _has_index(
inspector, "account_events", "ix_account_events_type_occurred"
):
op.create_index(
"ix_account_events_type_occurred",
"account_events",
["event_type", "occurred_at"],
)
if inspector.has_table("account_sync_runs"):
if not _has_index(
inspector, "account_sync_runs", "ix_account_sync_runs_trend_cover"
):
op.create_index(
"ix_account_sync_runs_trend_cover",
"account_sync_runs",
["started_at", "domain", "status", "duration_ms"],
)
if _has_index(
inspector,
"account_sync_runs",
"ix_account_sync_runs_started_domain_status",
):
op.drop_index(
"ix_account_sync_runs_started_domain_status",
table_name="account_sync_runs",
)
if inspector.has_table("account_commodity_states") and not _has_index(
inspector,
"account_commodity_states",
"ix_account_commodity_skin_options",
):
op.create_index(
"ix_account_commodity_skin_options",
"account_commodity_states",
[
"platform",
"account_eligibility",
"offer_state",
"valid_until",
"scope",
"commodity_id",
"commodity_name",
],
)
if inspector.has_table("platform_fulfillment_tasks"):
if not _has_column(
inspector, "platform_fulfillment_tasks", "customer_role_norm"
):
op.add_column(
"platform_fulfillment_tasks",
sa.Column(
"customer_role_norm",
sa.String(length=128),
sa.Computed(
"lower(trim(customer_role_name))",
persisted=False,
),
nullable=True,
),
)
inspector = sa.inspect(bind)
if not _has_index(
inspector,
"platform_fulfillment_tasks",
"ix_platform_fulfillment_role_norm",
):
op.create_index(
"ix_platform_fulfillment_role_norm",
"platform_fulfillment_tasks",
["flow_version", "customer_role_norm", "execution_status"],
)
def downgrade() -> None:
bind = op.get_bind()
inspector = sa.inspect(bind)
if inspector.has_table("platform_fulfillment_tasks"):
if _has_index(
inspector,
"platform_fulfillment_tasks",
"ix_platform_fulfillment_role_norm",
):
op.drop_index(
"ix_platform_fulfillment_role_norm",
table_name="platform_fulfillment_tasks",
)
if _has_column(inspector, "platform_fulfillment_tasks", "customer_role_norm"):
op.drop_column("platform_fulfillment_tasks", "customer_role_norm")
if inspector.has_table("account_commodity_states") and _has_index(
inspector,
"account_commodity_states",
"ix_account_commodity_skin_options",
):
op.drop_index(
"ix_account_commodity_skin_options",
table_name="account_commodity_states",
)
if inspector.has_table("account_sync_runs"):
if not _has_index(
inspector,
"account_sync_runs",
"ix_account_sync_runs_started_domain_status",
):
op.create_index(
"ix_account_sync_runs_started_domain_status",
"account_sync_runs",
["started_at", "domain", "status"],
)
if _has_index(
inspector, "account_sync_runs", "ix_account_sync_runs_trend_cover"
):
op.drop_index(
"ix_account_sync_runs_trend_cover",
table_name="account_sync_runs",
)
if inspector.has_table("account_events"):
if _has_index(
inspector, "account_events", "ix_account_events_type_occurred"
):
op.drop_index(
"ix_account_events_type_occurred",
table_name="account_events",
)
if _has_index(
inspector, "account_events", "ix_account_events_event_subject_occurred"
):
op.drop_index(
"ix_account_events_event_subject_occurred",
table_name="account_events",
)
+35 -1
View File
@@ -2039,6 +2039,18 @@ class AccountEvent(Base):
# 「某个客服这段时间做了什么」——池化后客服不再持有账号,
# 这条是管理侧追责与对账的主查询路径,此前没有任何索引可用。
Index("ix_account_events_actor_occurred", "actor_id", "occurred_at"),
Index(
"ix_account_events_event_subject_occurred",
"event_type",
"subject_type",
"subject_key",
"occurred_at",
),
Index(
"ix_account_events_type_occurred",
"event_type",
"occurred_at",
),
)
@@ -2197,6 +2209,16 @@ class AccountCommodityState(Base):
"account_eligibility",
"valid_until",
),
Index(
"ix_account_commodity_skin_options",
"platform",
"account_eligibility",
"offer_state",
"valid_until",
"scope",
"commodity_id",
"commodity_name",
),
)
@@ -2493,6 +2515,11 @@ class PlatformFulfillmentTask(Base):
customer_role_name: Mapped[str] = mapped_column(
String(128), nullable=False, default="", server_default=""
)
customer_role_norm: Mapped[str | None] = mapped_column(
String(128),
Computed("lower(trim(customer_role_name))", persisted=False),
nullable=True,
)
customer_platform: Mapped[str] = mapped_column(
String(16), nullable=False, default="", server_default=""
)
@@ -2581,6 +2608,12 @@ class PlatformFulfillmentTask(Base):
"next_allocate_at",
"id",
),
Index(
"ix_platform_fulfillment_role_norm",
"flow_version",
"customer_role_norm",
"execution_status",
),
)
@@ -2739,10 +2772,11 @@ class AccountSyncRun(Base):
"started_at",
),
Index(
"ix_account_sync_runs_started_domain_status",
"ix_account_sync_runs_trend_cover",
"started_at",
"domain",
"status",
"duration_ms",
),
)
+89 -8
View File
@@ -12,7 +12,7 @@ from typing import Any
from fastapi import APIRouter, Depends, HTTPException, Query
from pydantic import BaseModel, Field
from sqlalchemy import select
from sqlalchemy import case, func, select
from sqlalchemy.orm import Session
from ..database import get_db
@@ -21,6 +21,8 @@ from ..models import (
Account,
AutomationJob,
AutomationRun,
DouyuTask,
ExecutionJob,
LoginQuotaSetting,
LoginTask,
User,
@@ -180,6 +182,8 @@ def list_jobs(
from ..services.binding_poll_scheduler import (
scheduler_status as binding_poll_status,
)
from ..services.douyu_runner_core import douyu_batch_registry
from ..services.execution_jobs import STATUS_QUEUED, STATUS_RUNNING
from ..services.execution_worker import execution_job_worker_status
from ..services.payment_poll_scheduler import (
scheduler_status as payment_poll_status,
@@ -203,6 +207,8 @@ def list_jobs(
"pid": background_runtime.get("pid"),
"heartbeatAt": background_runtime.get("heartbeatAt"),
}
if "in_flight" in background_scheduler:
scheduler_state["in_flight"] = background_scheduler["in_flight"]
else:
scheduler_state = {
**scheduler_state,
@@ -210,16 +216,91 @@ def list_jobs(
"heartbeatAt": background_runtime.get("heartbeatAt"),
}
bg_rt_raw = background_runtime.get("runtime")
bg_rt = (
bg_rt_raw
if scheduler_state["process"] == "background" and isinstance(bg_rt_raw, dict)
else {}
)
local_worker_pool = (
getattr(worker_engine.pool, "status", lambda: "")()
if callable(getattr(worker_engine.pool, "status", None))
else ""
)
now = datetime.now(UTC)
exec_rows = (
db.query(
ExecutionJob.lane_scope,
ExecutionJob.status,
func.count(ExecutionJob.id),
)
.filter(ExecutionJob.status.in_((STATUS_QUEUED, STATUS_RUNNING)))
.group_by(ExecutionJob.lane_scope, ExecutionJob.status)
.all()
)
exec_backlog: dict[str, dict[str, int]] = {}
for lane_scope, status, count in exec_rows:
bucket = exec_backlog.setdefault(str(lane_scope), {"queued": 0, "running": 0})
if status in bucket:
bucket[str(status)] = int(count or 0)
poll_rows = (
db.query(
DouyuTask.queue_lane,
func.count(DouyuTask.id),
func.sum(
case(
(
DouyuTask.next_run_at <= now,
1,
),
else_=0,
)
),
)
.filter(
DouyuTask.queue_lane.in_(("binding_poll", "payment_poll")),
DouyuTask.status == "running",
)
.group_by(DouyuTask.queue_lane)
.all()
)
poll_backlog: dict[str, dict[str, int]] = {
"binding_poll": {"running": 0, "due": 0},
"payment_poll": {"running": 0, "due": 0},
}
for queue_lane, total, due in poll_rows:
poll_backlog[str(queue_lane)] = {
"running": int(total or 0),
"due": int(due or 0),
}
return {
"scheduler": scheduler_state,
"runtime": {
"task_lanes": lane_stats(),
"worker_db_pool": getattr(worker_engine.pool, "status", lambda: "")()
if callable(getattr(worker_engine.pool, "status", None))
else "",
"binding_poll": binding_poll_status(),
"payment_poll": payment_poll_status(),
"execution_jobs": execution_job_worker_status(),
"task_lanes": bg_rt.get("task_lanes")
if isinstance(bg_rt.get("task_lanes"), dict)
else lane_stats(),
"worker_db_pool": bg_rt["worker_db_pool"]
if isinstance(bg_rt.get("worker_db_pool"), str)
else local_worker_pool,
"binding_poll": bg_rt.get("binding_poll")
if isinstance(bg_rt.get("binding_poll"), dict)
else binding_poll_status(),
"payment_poll": bg_rt.get("payment_poll")
if isinstance(bg_rt.get("payment_poll"), dict)
else payment_poll_status(),
"execution_jobs": bg_rt.get("execution_jobs")
if isinstance(bg_rt.get("execution_jobs"), dict)
else execution_job_worker_status(),
"douyu_batches": bg_rt.get("douyu_batches")
if isinstance(bg_rt.get("douyu_batches"), dict)
else douyu_batch_registry.stats(),
"queues": {
"execution_jobs": exec_backlog,
**poll_backlog,
},
"background_runtime": background_runtime,
},
"pending_relogin": pending_relogin,
+23 -4
View File
@@ -193,7 +193,13 @@ async def supplier_recharge_callback(request: Request, db: Session = Depends(get
except FishFinRechargeConfigError as exc:
logger.error("[douyu] 供应商直充回调配置无效: {}", exc)
raise HTTPException(status_code=503, detail="供应商直充回调未配置") from exc
if not client.verify_response_sign(payload, "POST"):
try:
verified = client.verify_response_sign(payload, "POST")
finally:
close = getattr(client, "close", None)
if callable(close):
close()
if not verified:
logger.warning("[douyu] 供应商直充回调验签失败: keys={}", sorted(payload))
raise HTTPException(status_code=401, detail="供应商回调签名无效")
@@ -1285,14 +1291,19 @@ def list_live_goods(
"""实时读取精英宝典活动商品,不依赖账号或本地刷新任务。"""
del current
config = ensure_douyu_config(db)
client = activity_client()
try:
goods = query_activity_goods(
activity_client(),
client,
manual_id=str(douyu_config_value("manual_id", config.manual_id)),
rid=str(douyu_config_value("rid", config.rid)),
)
except DouyuActivityError as exc:
raise HTTPException(status_code=502, detail=f"活动商品加载失败:{exc}") from exc
finally:
close = getattr(client, "close", None)
if callable(close):
close()
now = datetime.now(UTC)
return [
DouyuGoodsOut(
@@ -1858,10 +1869,18 @@ def cleanup_orphan_tasks(
db: Session = Depends(get_db),
current: User = Depends(require_permission("douyu:task")),
):
"""手动清理没有内存执行器接管的斗鱼任务。"""
"""手动清理没有内存执行器或持久队列接管的斗鱼任务。"""
durable_batch_ids = {
str(batch_id)
for (batch_id,) in (
db.query(ExecutionJob.batch_id)
.filter(ExecutionJob.status.in_((STATUS_QUEUED, STATUS_RUNNING)))
.all()
)
}
cleaned = cleanup_orphan_douyu_tasks(
db,
active_batch_ids=douyu_batch_registry.active_ids(),
active_batch_ids=douyu_batch_registry.active_ids() | durable_batch_ids,
statuses=DOUYU_ACTIVE_TASK_STATUSES,
message="任务已中断(无执行器接管)",
)
+2 -1
View File
@@ -20,7 +20,7 @@ from fastapi import (
)
from sqlalchemy.orm import Session
from ..database import get_db
from ..database import get_db, release_idle_session
from ..deps import authenticate_websocket, get_current_user, require_permission
from ..errors import ApiError
from ..models import User
@@ -425,6 +425,7 @@ def verify_external_orders_batch(
interval = _verify_batch_interval()
for index, order_id in enumerate(ids):
if index and interval:
release_idle_session(db)
time.sleep(interval)
try:
order = collab.get_order(db, order_id)
@@ -308,7 +308,7 @@ class AccountCheckRunner:
finished_at=None,
)
try:
result = DouyuLogin(
loginer = DouyuLogin(
cast(
AccountLike,
SimpleNamespace(
@@ -327,7 +327,13 @@ class AccountCheckRunner:
proxy_fetcher=self._shared_proxy_fetcher,
stop_event=self._stop,
api_strategy=create_login_api_strategy(self.batch.api_strategy),
).check_account()
)
try:
result = loginer.check_account()
finally:
close = getattr(loginer, "close", None)
if callable(close):
close()
except Exception as exc: # noqa: BLE001 外部接口与任务边界需要保留宽泛异常兜底
self._set_item(
index, status="error", message=f"检测异常: {exc}", finished_at=_now()
@@ -9,10 +9,12 @@ from sqlalchemy.orm import Session
from core.douyu import DouyuActivityClient
from ..database import release_idle_session
from ..models import Account
from .account_sync_service import (
DOMAIN_EXCHANGE_RECORDS,
get_sync_state,
lock_account_row,
record_sync_success,
)
from .business_events import record_official_exchange
@@ -74,6 +76,8 @@ def persist_official_exchange_records(
pairs: list[tuple[str, dict[str, Any]]],
) -> int:
"""把官方记录幂等补成账号事件,返回新写入数量。"""
if account.id is not None and pairs:
lock_account_row(db, int(account.id))
added = 0
for scope, record in pairs:
if not isinstance(record, dict):
@@ -195,7 +199,9 @@ def sync_exchange_records(
max_pages: int = 1,
) -> dict[str, Any]:
"""同步官方记录、补事件并保存可回放的按作用域原始投影。"""
account_id = int(account.id) if account.id is not None else None
observed_at = datetime.now(UTC)
released = release_idle_session(db)
pairs, errors = fetch_exchange_records(
client,
config,
@@ -203,6 +209,10 @@ def sync_exchange_records(
scopes=scopes,
max_pages=max_pages,
)
if released and account_id is not None:
account = db.get(Account, account_id) or account
if account.id is not None:
lock_account_row(db, int(account.id))
changed = persist_official_exchange_records(db, account, pairs)
previous = get_sync_state(
db,
@@ -26,6 +26,7 @@ from .account_supply_service import (
load_supply_snapshot_inventories,
supply_snapshot_max_age_seconds,
)
from .account_work_queue import STALE_RUNNING_SECONDS
from .external_order_source import get_cross_db_lookup_counts
TREND_DAYS = 7
@@ -495,6 +496,15 @@ def account_platform_status(
bucket[str(status)] = int(count or 0)
if status == "pending":
bucket["oldest_pending_due_at"] = oldest_due
if isinstance(oldest_due, datetime):
due_utc = (
oldest_due.replace(tzinfo=UTC)
if oldest_due.tzinfo is None
else oldest_due.astimezone(UTC)
)
bucket["oldest_pending_age_seconds"] = max(
0, int((moment - due_utc).total_seconds())
)
sync_domains: dict[str, dict[str, Any]] = {}
if include_diagnostics:
@@ -664,6 +674,29 @@ def account_platform_status(
"message": f"账号内部工作队列有 {overdue_work} 项待处理已过期",
}
)
stale_running_work = int(
db.query(func.count(AccountWorkItem.id))
.filter(
AccountWorkItem.status == "running",
AccountWorkItem.started_at.isnot(None),
AccountWorkItem.started_at
<= moment - timedelta(seconds=STALE_RUNNING_SECONDS),
)
.scalar()
or 0
)
if stale_running_work:
alerts.append(
{
"code": "account_work_stale_running",
"severity": "warning",
"count": stale_running_work,
"message": (
f"账号内部工作队列有 {stale_running_work} 项运行超过 "
f"{STALE_RUNNING_SECONDS // 60} 分钟未结束"
),
}
)
trends = _platform_trends(db, moment) if include_trends else None
if trends is not None:
+35 -19
View File
@@ -111,11 +111,16 @@ def _execute_storehome_sync(
if not manual_id:
raise RuntimeError("未配置精英宝典 manualID")
client = client_factory(account.cookie)
snapshot = snapshot_fetcher(
client,
manual_id=manual_id,
rid=rid,
)
try:
snapshot = snapshot_fetcher(
client,
manual_id=manual_id,
rid=rid,
)
finally:
close = getattr(client, "close", None)
if callable(close):
close()
result = sync_storehome_snapshot(
db,
account,
@@ -211,13 +216,18 @@ def _execute_profile_sync(
)
config = ensure_douyu_config(db)
client = client_factory(account.cookie)
probe = probe_fetcher(
account,
config,
client=client,
session_checker=None,
**_profile_probe_kwargs(item.work_type, config),
)
try:
probe = probe_fetcher(
account,
config,
client=client,
session_checker=None,
**_profile_probe_kwargs(item.work_type, config),
)
finally:
close = getattr(client, "close", None)
if callable(close):
close()
errors = probe.get("errors") or {}
domain_error = {
WORK_POINTS_SYNC: "points",
@@ -269,13 +279,19 @@ def _execute_exchange_records_sync(
session_checker=session_checker,
)
config = ensure_douyu_config(db)
result = sync_exchange_records(
db,
account,
client_factory(account.cookie),
config_mapping(config),
source=f"account_work.{item.work_type}",
)
client = client_factory(account.cookie)
try:
result = sync_exchange_records(
db,
account,
client,
config_mapping(config),
source=f"account_work.{item.work_type}",
)
finally:
close = getattr(client, "close", None)
if callable(close):
close()
return {
"ok": True,
"work_id": int(item.id),
+63 -19
View File
@@ -98,6 +98,18 @@ def is_domain_fresh(
)
def lock_account_row(db: Session, account_id: int | None) -> None:
"""写账号派生表前先对账号主键加 X 锁,避免子表外键 S 锁与后续 UPDATE accounts 互锁成死锁。"""
if not account_id:
return
(
db.query(Account.id)
.filter(Account.id == int(account_id))
.with_for_update()
.first()
)
def _get_or_create_state(
db: Session,
*,
@@ -105,11 +117,15 @@ def _get_or_create_state(
domain: str,
platform: str = "douyu",
) -> AccountSyncState:
state = get_sync_state(
db,
account_id=account_id,
domain=domain,
platform=platform,
state = (
db.query(AccountSyncState)
.filter(
AccountSyncState.account_id == account_id,
AccountSyncState.platform == platform,
AccountSyncState.domain == domain,
)
.with_for_update()
.first()
)
if state is None:
state = AccountSyncState(
@@ -129,6 +145,7 @@ def mark_domain_dirty(
domain: str,
reason: str = "",
) -> AccountSyncState:
lock_account_row(db, account_id)
state = _get_or_create_state(db, account_id=account_id, domain=domain)
state.status = "dirty"
state.valid_until = None
@@ -148,6 +165,7 @@ def start_sync_run(
source: str,
task_id: int | None = None,
) -> AccountSyncRun:
lock_account_row(db, account_id)
moment = datetime.now(UTC)
state = _get_or_create_state(db, account_id=account_id, domain=domain)
state.last_attempt_at = moment
@@ -322,25 +340,51 @@ def record_sync_success(
) -> StorehomeSyncResult:
"""登记一次已经完成的官方查询投影。
适用于探针已经拿到并完成归一化的结果,避免调用方为了同步记录再重复请求。
适用于探针已经拿到并完成归一化的结果,避免调用方为了同步记录再重复请求,
也避免同一次查询把 account_sync_states 先改成 running 再改成 success 的双倍锁更新。
"""
moment = observed_at or datetime.now(UTC)
run = start_sync_run(
db,
lock_account_row(db, account_id)
now = datetime.now(UTC)
moment = observed_at or now
ttl_seconds = max(
1,
int(
valid_for_seconds
if valid_for_seconds is not None
else capability_ttl_seconds()
),
)
state = _get_or_create_state(db, account_id=account_id, domain=domain)
state.last_attempt_at = now
state.last_success_at = now
state.status = "success"
state.valid_until = now + timedelta(seconds=ttl_seconds)
state.next_retry_at = state.valid_until
state.error_code = ""
state.error_message = ""
state.source = source[:32]
if raw_payload is not None:
safe_payload = _json_safe(raw_payload)
state.raw_payload_json = safe_payload
state.payload_hash = _payload_hash(safe_payload)
state.state_version = int(state.state_version or 0) + 1
run = AccountSyncRun(
account_id=account_id,
platform="douyu",
domain=domain,
source=source,
task_id=task_id,
started_at=now,
finished_at=now,
status="success",
source=source[:32],
item_count=int(item_count),
changed_count=int(changed_count),
duration_ms=0,
official_observed_at=moment,
)
finish_sync_success(
db,
run,
item_count=item_count,
changed_count=changed_count,
observed_at=moment,
raw_payload=raw_payload,
valid_for_seconds=valid_for_seconds,
)
db.add(run)
db.flush()
return StorehomeSyncResult(
item_count=int(item_count),
changed_count=int(changed_count),
+52 -1
View File
@@ -5,13 +5,14 @@ from __future__ import annotations
from datetime import UTC, datetime, timedelta
from typing import Any
from sqlalchemy import case, func, select
from sqlalchemy import case, func, or_, select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
from ..models import Account, AccountWorkItem
WORK_AGING_SECONDS = 30 * 60
STALE_RUNNING_SECONDS = 30 * 60
#: 供给补货任务的 reason 前缀;队列靠它给通用供给保留固定处理配额。
SUPPLY_REASON_PREFIX = "供给短缺:"
@@ -293,6 +294,54 @@ def recover_running_account_work(
return len(items)
def _stale_running_seconds(override: int | None = None) -> int:
import os
if override is not None:
return max(60, int(override))
try:
return max(
60,
int(os.getenv("ACCOUNT_WORK_STALE_RUNNING_SECONDS", str(STALE_RUNNING_SECONDS))),
)
except ValueError:
return STALE_RUNNING_SECONDS
def recover_stale_running_account_work(
db: Session,
*,
work_types: tuple[str, ...] | None = None,
stale_seconds: int | None = None,
now: datetime | None = None,
) -> int:
"""回收运行超时仍停留在 running 的工作项,防止单线程异常后永久占住队列去重键。"""
moment = (now or datetime.now(UTC)).replace(microsecond=0)
seconds = _stale_running_seconds(stale_seconds)
cutoff = moment - timedelta(seconds=seconds)
query = db.query(AccountWorkItem).filter(
AccountWorkItem.status == "running",
or_(
AccountWorkItem.started_at <= cutoff,
(AccountWorkItem.started_at.is_(None) & (AccountWorkItem.updated_at <= cutoff)),
),
)
if work_types:
query = query.filter(AccountWorkItem.work_type.in_(work_types))
items = query.all()
for item in items:
fail_account_work(
db,
item,
error=f"工作执行超过 {seconds // 60} 分钟未完成(疑似卡死),已回收",
retry_after_seconds=60,
now=moment,
)
if items:
db.flush()
return len(items)
def expire_stale_login_work(
db: Session,
*,
@@ -398,6 +447,7 @@ def fail_account_work_type(
__all__ = [
"STALE_RUNNING_SECONDS",
"active_account_work_count",
"active_account_work_exists",
"claim_account_work",
@@ -407,5 +457,6 @@ __all__ = [
"fail_account_work",
"fail_account_work_type",
"recover_running_account_work",
"recover_stale_running_account_work",
"reschedule_account_work_type",
]
@@ -9,7 +9,10 @@ from sqlalchemy.orm import Session
from ....models import AccountWorkItem, AutomationJob
from ...account_sync_runner import ACCOUNT_SYNC_WORK_TYPES, run_account_sync_queue
from ...account_work_queue import expire_stale_login_work
from ...account_work_queue import (
expire_stale_login_work,
recover_stale_running_account_work,
)
JOB_KEY = "account_sync_queue"
@@ -34,7 +37,12 @@ def run_account_sync_queue_job(
) -> dict[str, Any]:
moment = datetime.now(UTC)
expired = expire_stale_login_work(db, now=moment)
if expired:
recovered_stale = recover_stale_running_account_work(
db,
work_types=ACCOUNT_SYNC_WORK_TYPES,
now=moment,
)
if expired or recovered_stale:
db.commit()
result = run_account_sync_queue(
db,
@@ -42,11 +50,16 @@ def run_account_sync_queue_job(
)
if result.get("scanned"):
result["remaining"] = count_pending_work(db)
notes: list[str] = []
if recovered_stale:
result["recovered_stale"] = recovered_stale
notes.append(f"回收卡死工作 {recovered_stale} 条")
if expired:
result["expired_login"] = expired
notes.append(f"过期重登转人工 {expired} 条")
if notes:
result["message"] = (
f"{result.get('message') or '账号同步完成'},"
f"过期重登转人工 {expired} 条"
f"{result.get('message') or '账号同步完成'}," + ",".join(notes)
)
return result
@@ -48,7 +48,13 @@ from loguru import logger
from sqlalchemy import and_, or_
from sqlalchemy.orm import Session
from ....models import AutomationJob, DouyuTask, ExecutionJob, ExecutionJobEvent
from ....models import (
AccountSyncRun,
AutomationJob,
DouyuTask,
ExecutionJob,
ExecutionJobEvent,
)
JOB_KEY = "douyu_tasks_retention"
@@ -74,6 +80,7 @@ NOISE_TASK_TYPES: tuple[str, ...] = (
DEFAULT_NOISE_DAYS = 7
DEFAULT_BUSINESS_DAYS = 90
DEFAULT_SYNC_RUN_DAYS = 14
DEFAULT_BATCH = 2000
DEFAULT_MAX_BATCHES = 50
@@ -167,10 +174,50 @@ def _delete_batch(
return deleted, candidates[-1].created_at, ids[-1]
def _delete_sync_run_batch(
db: Session,
*,
cutoff: datetime,
batch: int,
cursor_started_at: datetime | None = None,
cursor_id: int = 0,
) -> tuple[int, datetime | None, int]:
"""按游标分批清理过期 `account_sync_runs`,避免全表长时间持锁。"""
query = db.query(AccountSyncRun.id, AccountSyncRun.started_at).filter(
AccountSyncRun.started_at < cutoff
)
if cursor_started_at is not None:
query = query.filter(
or_(
AccountSyncRun.started_at > cursor_started_at,
and_(
AccountSyncRun.started_at == cursor_started_at,
AccountSyncRun.id > cursor_id,
),
)
)
candidates = (
query.order_by(AccountSyncRun.started_at.asc(), AccountSyncRun.id.asc())
.limit(batch)
.all()
)
if not candidates:
return 0, cursor_started_at, cursor_id
ids = [int(row.id) for row in candidates]
deleted = int(
db.query(AccountSyncRun)
.filter(AccountSyncRun.id.in_(ids))
.delete(synchronize_session=False)
or 0
)
return deleted, candidates[-1].started_at, ids[-1]
def run_douyu_tasks_retention(db: Session, job: AutomationJob) -> dict[str, Any]:
config = _load_config(job)
noise_days = _positive_int(config.get("noise_days"), DEFAULT_NOISE_DAYS)
business_days = _positive_int(config.get("business_days"), DEFAULT_BUSINESS_DAYS)
sync_run_days = _positive_int(config.get("sync_run_days"), DEFAULT_SYNC_RUN_DAYS)
batch = _positive_int(job.batch_size, DEFAULT_BATCH)
max_batches = _positive_int(config.get("max_batches"), DEFAULT_MAX_BATCHES)
@@ -179,6 +226,7 @@ def run_douyu_tasks_retention(db: Session, job: AutomationJob) -> dict[str, Any]
# 带 tzinfo 会被驱动按本地时区处理(参见设计文档里那次 8 小时偏移事故)。
noise_cutoff = (now - timedelta(days=noise_days)).replace(tzinfo=None)
business_cutoff = (now - timedelta(days=business_days)).replace(tzinfo=None)
sync_run_cutoff = (now - timedelta(days=sync_run_days)).replace(tzinfo=None)
total_deleted = 0
batches = 0
@@ -259,6 +307,27 @@ def run_douyu_tasks_retention(db: Session, job: AutomationJob) -> dict[str, Any]
batches += 1
db.commit()
deleted_sync_runs = 0
sync_run_cursor_started_at: datetime | None = None
sync_run_cursor_id = 0
while batches < max_batches:
deleted_runs, sync_run_cursor_started_at, sync_run_cursor_id = (
_delete_sync_run_batch(
db,
cutoff=sync_run_cutoff,
batch=batch,
cursor_started_at=sync_run_cursor_started_at,
cursor_id=sync_run_cursor_id,
)
)
if deleted_runs <= 0:
break
batches += 1
deleted_sync_runs += deleted_runs
db.commit()
if deleted_runs < batch:
break
# 注意措辞:这只说明「批次预算用光了」,**不等于**「确实还有积压」——
# 预算在上一档用完时,下一档根本没轮到执行,这里无法区分「没得删」和「没轮到」。
# 所以做成提示而非结论,措辞上也别谎称「仍有积压」。
@@ -283,9 +352,11 @@ def run_douyu_tasks_retention(db: Session, job: AutomationJob) -> dict[str, Any]
"deleted_rest": per_pass.get("rest", 0),
"deleted_execution_events": deleted_execution_events,
"deleted_execution_jobs": deleted_execution_jobs,
"deleted_sync_runs": deleted_sync_runs,
"batches": batches,
"noise_days": noise_days,
"business_days": business_days,
"sync_run_days": sync_run_days,
"batch_budget_exhausted": batch_budget_exhausted,
"message": message,
}
@@ -473,10 +473,13 @@ def stop_scheduler() -> None:
def scheduler_status() -> dict[str, Any]:
with _IN_FLIGHT_LOCK:
in_flight = sorted(_IN_FLIGHT)
return {
"enabled": automation_enabled(),
"running": _thread is not None and _thread.is_alive(),
"tick_seconds": TICK_SECONDS,
"job_interval_seconds": JOB_INTERVAL_SECONDS,
"registered": sorted(_REGISTRY),
"in_flight": in_flight,
}
@@ -24,6 +24,17 @@ _thread: threading.Thread | None = None
_lock = threading.Lock()
_in_flight: set[int] = set()
_in_flight_lock = threading.Lock()
_metrics_lock = threading.Lock()
_metrics: dict[str, object] = {
"last_tick_at": None,
"last_dispatched_at": None,
"last_claimed": 0,
"last_submitted": 0,
"total_dispatched": 0,
"consecutive_errors": 0,
"last_error": None,
"last_error_at": None,
}
def _env_int(name: str, default: int, minimum: int, maximum: int) -> int:
@@ -128,6 +139,9 @@ def _release_callback(_future: Future) -> None:
def run_binding_poll_dispatch_once(limit: int = DEFAULT_BATCH_SIZE) -> int:
capacity = available_slots(TaskLane.BINDING_POLL)
if capacity <= 0:
with _metrics_lock:
_metrics["last_claimed"] = 0
_metrics["last_submitted"] = 0
return 0
claimed = _claim_due_binding_tasks(min(max(1, limit), capacity))
submitted = 0
@@ -144,6 +158,12 @@ def run_binding_poll_dispatch_once(limit: int = DEFAULT_BATCH_SIZE) -> int:
break
future.add_done_callback(_release_callback)
submitted += 1
with _metrics_lock:
_metrics["last_claimed"] = len(claimed)
_metrics["last_submitted"] = submitted
if submitted:
_metrics["total_dispatched"] = int(_metrics["total_dispatched"] or 0) + submitted
_metrics["last_dispatched_at"] = datetime.now(UTC).isoformat()
return submitted
@@ -155,6 +175,9 @@ def _run() -> None:
30,
)
while not _stop_event.is_set():
now_iso = datetime.now(UTC).isoformat()
with _metrics_lock:
_metrics["last_tick_at"] = now_iso
try:
batch_size = _env_int(
"BINDING_POLL_DISPATCH_BATCH",
@@ -163,7 +186,15 @@ def _run() -> None:
200,
)
run_binding_poll_dispatch_once(batch_size)
with _metrics_lock:
_metrics["consecutive_errors"] = 0
except Exception as exc: # noqa: BLE001 - scheduler must survive one bad tick
with _metrics_lock:
_metrics["consecutive_errors"] = (
int(_metrics["consecutive_errors"] or 0) + 1
)
_metrics["last_error"] = f"{type(exc).__name__}: {exc}"[:500]
_metrics["last_error_at"] = now_iso
logger.warning("绑定扫码调度轮次失败: {}", exc)
_stop_event.wait(interval)
@@ -199,10 +230,13 @@ def scheduler_status() -> dict[str, object]:
running = _thread is not None and _thread.is_alive()
with _in_flight_lock:
in_flight = len(_in_flight)
with _metrics_lock:
metrics = dict(_metrics)
return {
"running": running,
"in_flight": in_flight,
"claim_seconds": CLAIM_SECONDS,
**metrics,
}
@@ -47,6 +47,7 @@ from .account_sync_service import (
DOMAIN_POINTS,
DOMAIN_ROLE,
DOMAIN_SESSION,
lock_account_row,
record_sync_success,
)
from .cookie_check_service import check_douyu_cookie, classify_douyu_cookie_result
@@ -755,6 +756,7 @@ def probe_account(
cookie = str(account.cookie or "").strip()
checked_at = _now()
errors: dict[str, str] = {}
owns_client = client is None
active_client = client or activity_client(
cookie,
logger_callback=logger_callback
@@ -764,6 +766,57 @@ def probe_account(
)
),
)
try:
return _probe_account_with_client(
account,
config_info,
active_client=active_client,
cookie=cookie,
checked_at=checked_at,
errors=errors,
session_checker=session_checker,
with_elite=with_elite,
with_esports=with_esports,
with_storehome=with_storehome,
with_eligibility=with_eligibility,
with_limited_goods=with_limited_goods,
with_gold=with_gold,
with_goods=with_goods,
with_elite_role=with_elite_role,
include_esports=include_esports,
include_peace=include_peace,
use_cache=use_cache,
cache_key=cache_key,
)
finally:
if owns_client:
close = getattr(active_client, "close", None)
if callable(close):
close()
def _probe_account_with_client(
account: Account,
config_info: dict[str, Any],
*,
active_client: DouyuActivityClient,
cookie: str,
checked_at: datetime,
errors: dict[str, str],
session_checker: Any,
with_elite: bool,
with_esports: bool,
with_storehome: bool,
with_eligibility: bool,
with_limited_goods: bool,
with_gold: bool,
with_goods: bool,
with_elite_role: bool,
include_esports: bool,
include_peace: bool,
use_cache: bool,
cache_key: str,
) -> dict[str, Any]:
if session_checker is _DEFAULT_SESSION_CHECKER:
session_checker = check_douyu_cookie
session = (
@@ -1121,6 +1174,9 @@ def persist_probe_result(
) -> None:
"""把一次探针结果写回账号和生命周期,是账号能力的唯一落库入口。"""
now = _now()
if account.id is not None:
# 严格先锁 accounts 主行,再写 account_sync_states / account_sync_runs / account_events
lock_account_row(db, int(account.id))
identity = probe.get("identity") or {}
if identity.get("uid"):
account.uid = str(identity["uid"])[:32]
@@ -54,6 +54,7 @@ def _run_batch(
douyu_batch_registry.register(batch_id, log_queue, loop, runner)
runner.run()
finally:
douyu_batch_registry.mark_finished(batch_id)
thread_db.close()
@@ -276,6 +276,7 @@ def refresh_activity_goods(
)
if account is None:
raise CollabError("没有带 CK 的斗鱼账号,无法刷新活动商品", code="no_account")
owns_client = client is None
active_client = client or _client_for_account(account)
config_info = config_mapping(config)
db.expunge(account)
@@ -316,6 +317,11 @@ def refresh_activity_goods(
)
db.commit()
raise
finally:
if owns_client:
close = getattr(active_client, "close", None)
if callable(close):
close()
upsert_goods_snapshot(db, goods, commit=False)
record_account_query(
db,
+136 -43
View File
@@ -25,6 +25,7 @@ from sqlalchemy.orm import Session
from core.douyu import DouyuActivityClient
from ..database import release_idle_session
from ..models import (
Account,
AccountEvent,
@@ -52,6 +53,7 @@ from .account_events_service import (
from .account_exchange_sync_service import sync_exchange_records
from .account_query_filters import ACTIVE_COLLAB_STATUSES
from .account_sync_runner import WORK_STOREHOME_SYNC
from .account_sync_service import lock_account_row
from .account_work_queue import enqueue_account_work
from .audit_service import record_account_action, record_audit
from .binding_ownership import role_names_match
@@ -203,6 +205,22 @@ from .platform_fulfillment.account_selector import (
)
def _detached_account_snapshot(account: Account) -> Account:
"""构造脱离 ORM 会话的轻量账号快照,供无数据库连接的外网探针读取。"""
return Account(
id=account.id,
uid=account.uid,
username=account.username,
nickname=account.nickname,
cookie=account.cookie,
elite_opened=account.elite_opened,
esports_opened=account.esports_opened,
points=account.points,
points_expire_at=account.points_expire_at,
gold_balance=account.gold_balance,
)
def _probe_with_client(
account: Account,
*,
@@ -235,15 +253,21 @@ def _probe_with_client(
"legacy_act_alias": legacy_act_alias,
}
)
result = probe_account(
account,
config_info,
client=active_client,
session_checker=None if caller_supplied_client else check_douyu_cookie,
with_gold=True,
with_goods=with_goods,
use_cache=not caller_supplied_client,
)
try:
result = probe_account(
account,
config_info,
client=active_client,
session_checker=None if caller_supplied_client else check_douyu_cookie,
with_gold=True,
with_goods=with_goods,
use_cache=not caller_supplied_client,
)
finally:
if not caller_supplied_client and isinstance(
active_client, DouyuActivityClient
):
active_client.close()
elite = result.get("elite") or {}
role = (result.get("roles") or {}).get("elite") or {}
identity = result.get("identity") or {}
@@ -1043,6 +1067,7 @@ def update_order(
client=client,
with_goods=True,
)
lock_account_row(db, int(account.id))
_ensure_order_account_lease(
db,
current,
@@ -1137,17 +1162,31 @@ def set_account(
if account is None:
raise CollabError("斗鱼账号不存在", code="account_not_found")
previous_account_id = int(order.account_id or 0)
order_id = int(order.id)
account_id = int(account.id)
current_id = int(current.id)
config = resolve_config(db)
manual_id = str(config.manual_id or "")
rid = str(config.rid or "")
bind_act_alias = str(config.bind_act_alias or "")
confirm_act_alias = str(config.confirm_act_alias or "")
legacy_act_alias = str(config.legacy_act_alias or "")
account_snapshot = _detached_account_snapshot(account)
release_idle_session(db)
probe = _probe_with_client(
account,
manual_id=str(config.manual_id or ""),
rid=str(config.rid or ""),
act_alias=str(config.bind_act_alias or ""),
confirm_act_alias=str(config.confirm_act_alias or ""),
legacy_act_alias=str(config.legacy_act_alias or ""),
account_snapshot,
manual_id=manual_id,
rid=rid,
act_alias=bind_act_alias,
confirm_act_alias=confirm_act_alias,
legacy_act_alias=legacy_act_alias,
client=client,
with_goods=True,
)
order = db.get(DouyuExternalOrder, order_id) or order
account = db.get(Account, account_id) or account
current = db.get(User, current_id) or current
lock_account_row(db, int(account.id))
_ensure_order_account_lease(
db,
current,
@@ -1208,17 +1247,36 @@ def verify_order(
)
if account is None:
raise CollabError("订单关联的斗鱼账号不存在", code="account_not_found")
order_id = int(order.id)
account_id = int(account.id)
current_id = int(current.id)
config = resolve_config(db)
manual_id = str(config.manual_id or "")
rid = str(config.rid or "")
bind_act_alias = str(config.bind_act_alias or "")
confirm_act_alias = str(config.confirm_act_alias or "")
legacy_act_alias = str(config.legacy_act_alias or "")
account_snapshot = _detached_account_snapshot(account)
release_idle_session(db)
probe = _probe_with_client(
account,
manual_id=str(config.manual_id or ""),
rid=str(config.rid or ""),
act_alias=str(config.bind_act_alias or ""),
confirm_act_alias=str(config.confirm_act_alias or ""),
legacy_act_alias=str(config.legacy_act_alias or ""),
account_snapshot,
manual_id=manual_id,
rid=rid,
act_alias=bind_act_alias,
confirm_act_alias=confirm_act_alias,
legacy_act_alias=legacy_act_alias,
client=client,
with_goods=True,
)
reloaded_order = db.get(DouyuExternalOrder, order_id)
if reloaded_order is None:
raise CollabError("订单不存在", status_code=404, code="order_not_found")
reloaded_account = db.get(Account, account_id)
if reloaded_account is None:
raise CollabError("订单关联的斗鱼账号不存在", code="account_not_found")
order = reloaded_order
account = reloaded_account
current = db.get(User, current_id) or current
apply_probe_snapshot(
db,
current,
@@ -1757,11 +1815,19 @@ def list_order_exchange_records(
error_text = ""
if refresh:
order_id = int(order.id)
account_id = int(account.id)
current_id = int(current.id)
try:
raw_records = _load_exchange_records_for_orders(db, [order], client=client)
synced_at = _now()
except Exception as exc: # noqa: BLE001
error_text = str(exc)
order = db.get(DouyuExternalOrder, order_id) or order
account = db.get(Account, account_id) or account
current = db.get(User, current_id) or current
if account.id is not None:
lock_account_row(db, int(account.id))
record_account_query(
db,
account,
@@ -1864,18 +1930,22 @@ def _load_exchange_records_for_orders(
)
if account is None:
raise CollabError("订单关联的斗鱼账号不存在", code="account_not_found")
config = resolve_config(db)
active_client = client or _client_for_account(account)
result = sync_exchange_records(
db,
account,
active_client,
config_mapping(config),
source="douyu_collab.activity",
scopes=("elite",),
limit=ACTIVITY_RECORD_FETCH_LIMIT,
max_pages=ACTIVITY_RECORD_MAX_PAGES,
)
config_map = config_mapping(resolve_config(db))
active_client = client or _client_for_account(_detached_account_snapshot(account))
try:
result = sync_exchange_records(
db,
account,
active_client,
config_map,
source="douyu_collab.activity",
scopes=("elite",),
limit=ACTIVITY_RECORD_FETCH_LIMIT,
max_pages=ACTIVITY_RECORD_MAX_PAGES,
)
finally:
if client is None and isinstance(active_client, DouyuActivityClient):
active_client.close()
return [
dict(record)
for record in (result.get("records") or {}).get("elite", [])
@@ -1901,6 +1971,9 @@ def query_activity(
)
if account is None:
raise CollabError("订单关联的斗鱼账号不存在", code="account_not_found")
order_id = int(order.id)
account_id = int(account.id)
current_id = int(current.id)
errors: list[str] = []
probe: dict[str, Any] = {}
loaded_records: list[dict[str, Any]] = []
@@ -1912,8 +1985,13 @@ def query_activity(
)
except Exception as exc: # noqa: BLE001
errors.append(f"兑换记录: {exc}")
order = db.get(DouyuExternalOrder, order_id) or order
account = db.get(Account, account_id) or account
current = db.get(User, current_id) or current
else:
loaded_records = [dict(record) for record in records]
if account.id is not None:
lock_account_row(db, int(account.id))
if record_query_error:
errors.append(f"兑换记录: {record_query_error}")
manual_score = _to_int(order.points_balance)
@@ -1924,16 +2002,26 @@ def query_activity(
points_message = _text(order.points_check_message)
threshold = normalize_threshold(order.points_threshold)
else:
config = resolve_config(db)
active_client = client or _client_for_account(account)
probe = probe_account(
account,
config,
client=active_client,
session_checker=None,
with_gold=True,
with_elite_role=False,
)
config_map = config_mapping(resolve_config(db))
account_snapshot = _detached_account_snapshot(account)
active_client = client or _client_for_account(account_snapshot)
release_idle_session(db)
try:
probe = probe_account(
account_snapshot,
config_map,
client=active_client,
session_checker=None,
with_gold=True,
with_elite_role=False,
)
finally:
if client is None and isinstance(active_client, DouyuActivityClient):
active_client.close()
order = db.get(DouyuExternalOrder, order_id) or order
account = db.get(Account, account_id) or account
current = db.get(User, current_id) or current
lock_account_row(db, int(account.id))
elite = (probe.get("elite") or {}).get("raw") or {}
gold = {
"gold": (probe.get("gold") or {}).get("balance"),
@@ -2187,11 +2275,16 @@ def query_activity_batch(
_load_exchange_records_for_orders(db, account_orders),
"",
)
if (db.info or {}).get("managed_request_session"):
# 逐账号持久化官方同步快照并归还连接,避免下一个账号拉取期间占着事务
db.commit()
except Exception as exc: # noqa: BLE001 - 账号级错误复用到同账号订单
db.rollback()
records_by_account[account_key] = ([], str(exc))
results: list[dict[str, Any]] = []
for order in orders:
order = db.get(DouyuExternalOrder, int(order.id)) or order
if order.account_id:
account_key = ("id", int(order.account_id))
else:
+133 -57
View File
@@ -9,12 +9,13 @@ from sqlalchemy.orm import joinedload
from core.douyu import DouyuActivityError
from ..database import WorkerSessionLocal
from ..database import WorkerSessionLocal, release_idle_session
from ..models import DouyuTask
from .cookie_check_service import check_douyu_cookie
from .douyu_account_probe import verify_account_session
from .douyu_account_probe import persist_probe_result, probe_session
from .douyu_runner_bind import BindMixin
from .douyu_runner_core import ( # noqa: F401 (douyu_batch_registry 供 routers 重导出)
from .douyu_runner_core import (
DOUYU_PROXY_TASK_TYPES,
DouyuBatchRunnerCore,
douyu_batch_registry,
)
@@ -62,35 +63,39 @@ class DouyuBatchRunner(
result,
)
return
if task.task_type == "create_gold_qr":
if str(result.get("recharge_channel") or "") == "supplier_api":
amount = int(
result.get("buy_num")
or self._task_payload(task).get("amount")
or self._task_payload(task).get("gold_amount")
or 1
)
self._poll_create_gold_supplier_once(
previous_clients = self._begin_client_tracking()
try:
if task.task_type == "create_gold_qr":
if str(result.get("recharge_channel") or "") == "supplier_api":
amount = int(
result.get("buy_num")
or self._task_payload(task).get("amount")
or self._task_payload(task).get("gold_amount")
or 1
)
self._poll_create_gold_supplier_once(
db,
task,
account,
cookie,
amount=amount,
)
else:
self._poll_create_gold_qr_once(db, task, account, cookie, config)
elif task.task_type == "create_elite_qr":
self._poll_create_elite_qr_once(db, task, account, cookie, config)
elif task.task_type == "create_esports_qr":
self._poll_create_esports_qr_once(db, task, account, cookie, config)
else:
self._mark_task(
db,
task,
account,
cookie,
amount=amount,
"failed",
f"不支持的支付轮询任务: {task.task_type}",
result,
)
else:
self._poll_create_gold_qr_once(db, task, account, cookie, config)
elif task.task_type == "create_elite_qr":
self._poll_create_elite_qr_once(db, task, account, cookie, config)
elif task.task_type == "create_esports_qr":
self._poll_create_esports_qr_once(db, task, account, cookie, config)
else:
self._mark_task(
db,
task,
"failed",
f"不支持的支付轮询任务: {task.task_type}",
result,
)
finally:
self._end_client_tracking(previous_clients)
def mark_payment_poll_timeout(self, db, task: DouyuTask) -> None:
result = dict(task.result or {})
@@ -105,7 +110,56 @@ class DouyuBatchRunner(
self._execute_one_with_slot(task_id, config, total)
def _execute_one_with_slot(self, task_id: int, config: dict, total: int):
with self._counter_lock:
self._task_started_at[int(task_id)] = time.monotonic()
# 阶段一:短事务抢占任务并标记 running,随后立即释放连接
cookie = ""
task_type = ""
account_name = f"task#{task_id}"
current = 0
preflight_db = SessionLocal()
try:
task = (
preflight_db.query(DouyuTask)
.options(joinedload(DouyuTask.account))
.filter(DouyuTask.id == task_id)
.first()
)
if not task or self._stop.is_set():
return
account = task.account
account_name = self._account_name(account)
task_type = str(task.task_type or "")
self._update_task_progress(preflight_db, task, "running", "执行中")
with self._counter_lock:
self._started += 1
current = self._started
self._push_log("info", f"[{current}/{total}] 开始: {account_name}")
# CK 与健康状态都挂在账号上(2026-10-04 CK 解耦)。
cookie = account.cookie or ""
if not cookie:
self._mark_task(preflight_db, task, "failed", "账号没有可用登录 Cookie")
self._push_log("warning", f"[{current}] {account_name} 无 Cookie")
return
finally:
preflight_db.close()
# 阶段二:不持数据库连接做外网 CK 预检和代理探活
cookie_check = probe_session(cookie, checker=check_douyu_cookie)
ck_verdict = str(cookie_check["status"])
prefetched_proxies = (
self._proxies_for_task()
if ck_verdict == "valid" and task_type in DOUYU_PROXY_TASK_TYPES
else None
)
# 阶段三:打开正式执行会话落库预检结论并执行任务处理
worker_db = SessionLocal()
task = None
if isinstance(getattr(worker_db, "info", None), dict):
worker_db.info["managed_worker_session"] = True
try:
task = (
worker_db.query(DouyuTask)
@@ -116,33 +170,32 @@ class DouyuBatchRunner(
if not task or self._stop.is_set():
return
account = task.account
self._update_task_progress(worker_db, task, "running", "执行中")
with self._counter_lock:
self._started += 1
current = self._started
self._push_log(
"info", f"[{current}/{total}] 开始: {self._account_name(account)}"
)
# CK 与健康状态都挂在账号上(2026-10-04 CK 解耦)。
cookie = account.cookie or ""
if not cookie:
self._mark_task(worker_db, task, "failed", "账号没有可用登录 Cookie")
self._push_log(
"warning", f"[{current}] {self._account_name(account)} 无 Cookie"
)
return
cookie_check = verify_account_session(
raw_detail = cookie_check.get("detail")
detail = raw_detail if isinstance(raw_detail, dict) else {}
persist_probe_result(
worker_db,
account,
{
"probe_id": f"douyu_task.preflight:{task_id}:{account.id or 0}",
"identity": {
"uid": account.uid,
"username": account.username,
"nickname": detail.get("nickname") or "",
"nickname_source": "session",
},
"session": cookie_check,
"elite": {},
"eligibility": {},
"roles": {},
"gold": {},
"goods": {},
"errors": {},
},
source="douyu_task.preflight",
checker=check_douyu_cookie,
record_event=False,
commit=True,
update_session=True,
)
ck_verdict = str(cookie_check["status"])
if ck_verdict != "valid":
prefix = (
"Cookie 已失效,请重新登录"
@@ -157,6 +210,8 @@ class DouyuBatchRunner(
return
update_account_profile_from_cookie(account, cookie)
if worker_db.dirty or worker_db.new or worker_db.deleted:
worker_db.commit()
handler = {
"refresh_esports_goods": self._execute_refresh_esports_goods,
@@ -199,19 +254,34 @@ class DouyuBatchRunner(
self._mark_task(worker_db, task, "failed", "不支持的任务类型")
return
handler(worker_db, task, account, cookie, config)
self._hook_local.prefetched_proxies = prefetched_proxies
self._hook_local.has_prefetched_proxies = (
ck_verdict == "valid" and task_type in DOUYU_PROXY_TASK_TYPES
)
previous_clients = self._begin_client_tracking()
try:
handler(worker_db, task, account, cookie, config)
finally:
self._end_client_tracking(previous_clients)
self._hook_local.has_prefetched_proxies = False
self._hook_local.prefetched_proxies = None
task = worker_db.get(DouyuTask, task_id) or task
account = task.account
self._push_log(
"success", f"[{current}] {self._account_name(account)} {task.message}"
)
except DouyuActivityError as exc:
if "task" in locals() and task:
self._mark_task(worker_db, task, "failed", str(exc))
active_task = (worker_db.get(DouyuTask, task_id) or task) if task else None
if active_task is not None:
self._mark_task(worker_db, active_task, "failed", str(exc))
self._push_log("warning", f"斗鱼任务失败: {exc}")
except Exception as exc: # noqa: BLE001 外部接口与任务边界需要保留宽泛异常兜底
if "task" in locals() and task:
self._mark_task(worker_db, task, "error", str(exc))
active_task = (worker_db.get(DouyuTask, task_id) or task) if task else None
if active_task is not None:
self._mark_task(worker_db, active_task, "error", str(exc))
self._push_log("error", f"斗鱼任务异常: {exc}")
finally:
release_idle_session(worker_db)
worker_db.close()
def run(self):
@@ -265,7 +335,7 @@ class DouyuBatchRunner(
)
if future is None:
break
pending[future] = (int(task.id), time.monotonic())
pending[future] = (int(task_id), time.monotonic())
next_index += 1
if not pending:
@@ -277,6 +347,7 @@ class DouyuBatchRunner(
continue
for future in completed:
task_id, submitted_at = pending.pop(future)
started_at = self._task_started_at.pop(int(task_id), None)
try:
future.result()
except Exception as exc: # noqa: BLE001 外部接口与任务边界需要保留宽泛异常兜底
@@ -285,7 +356,11 @@ class DouyuBatchRunner(
f"Worker 异常 task_id={task_id}: {exc}",
)
else:
waited = time.monotonic() - submitted_at
waited = (
max(0.0, started_at - submitted_at)
if started_at is not None
else 0.0
)
if waited >= 5:
self._push_log(
"info",
@@ -298,5 +373,6 @@ class DouyuBatchRunner(
self._push_log("info", f"斗鱼任务批次 {self.batch_id} 完成")
self._push_log("result", "")
finally:
douyu_batch_registry.mark_finished(self.batch_id)
if getattr(self, "close_db", True):
self.db.close()
+101 -22
View File
@@ -131,6 +131,7 @@ class DouyuBatchRunnerCore:
self._stop = threading.Event()
self._counter_lock = threading.Lock()
self._hook_local = threading.local()
self._task_started_at: dict[int, float] = {}
self._started = 0
# 代理接入 (配置源 = 代理配置页, 与 CK 检测/虎牙注册同款):
# 仅兑换/锁单/支付/充值/送礼等写操作任务走代理, 查询/刷新/绑定类直连
@@ -162,6 +163,11 @@ class DouyuBatchRunnerCore:
写/读分离:仅兑换/锁单/支付/开通/充值/送礼等写操作任务走代理(应对 IP 频控);
查询/刷新/绑定/扫码等读操作任务始终直连,不消耗代理额度。
"""
if getattr(self._hook_local, "has_prefetched_proxies", False):
self._hook_local.has_prefetched_proxies = False
prefetched = getattr(self._hook_local, "prefetched_proxies", None)
self._hook_local.prefetched_proxies = None
return prefetched
if self.task_type not in DOUYU_PROXY_TASK_TYPES:
return None
if self._static_proxies:
@@ -615,6 +621,30 @@ class DouyuBatchRunnerCore:
payload = payload_raw if isinstance(payload_raw, dict) else {}
return {**payload, **self.payload}
def _track_client(self, client: DouyuActivityClient) -> DouyuActivityClient:
clients = getattr(self._hook_local, "clients", None)
if isinstance(clients, list):
clients.append(client)
return client
def _begin_client_tracking(self) -> list[Any] | None:
previous = getattr(self._hook_local, "clients", None)
self._hook_local.clients = []
return previous
def _end_client_tracking(self, previous: list[Any] | None = None) -> None:
clients = getattr(self._hook_local, "clients", None)
self._hook_local.clients = previous
if not isinstance(clients, list):
return
for client in clients:
close = getattr(client, "close", None)
if callable(close):
try:
close()
except Exception: # noqa: BLE001 - 收尾清理不能覆盖主流程结果
logger.debug("关闭 DouyuActivityClient 会话失败", exc_info=True)
def _client(
self,
cookie: str,
@@ -623,10 +653,12 @@ class DouyuBatchRunnerCore:
) -> DouyuActivityClient:
"""任务 HTTP 客户端:写操作任务注入会话级代理(兑换/锁单/支付/充值/送礼),
读操作任务直连;持久支付轮询显式 ``direct=True``,不能每轮取新代理。"""
return activity_client(
cookie,
logger_callback=lambda msg: self._push_log("debug", msg),
proxies=None if direct else self._proxies_for_task(),
return self._track_client(
activity_client(
cookie,
logger_callback=lambda msg: self._push_log("debug", msg),
proxies=None if direct else self._proxies_for_task(),
)
)
def _sleep_interruptible(self, seconds: float) -> bool:
@@ -641,11 +673,37 @@ class DouyuBatchRunnerCore:
return not self._stop.is_set()
def _finished_batch_ttl_seconds() -> int:
import os
raw = os.getenv("DOUYU_BATCH_REGISTRY_FINISHED_TTL_SECONDS", "600")
try:
return max(1, int(raw))
except ValueError:
return 600
class DouyuBatchRegistry:
"""管理运行中的斗鱼任务批次。"""
"""管理运行中的斗鱼任务批次,并对已结束批次做 TTL 清理防止内存泄漏。"""
def __init__(self):
self._batches: dict[str, dict] = {}
self._lock = threading.RLock()
def _prune_expired_locked(self, now: float | None = None) -> int:
cutoff = (time.time() if now is None else float(now)) - _finished_batch_ttl_seconds()
expired = [
batch_id
for batch_id, info in self._batches.items()
if info.get("finished") and float(info.get("updated_at") or 0) <= cutoff
]
for batch_id in expired:
self._batches.pop(batch_id, None)
return len(expired)
def prune_expired(self, now: float | None = None) -> int:
with self._lock:
return self._prune_expired_locked(now=now)
def register(
self,
@@ -654,31 +712,52 @@ class DouyuBatchRegistry:
loop: asyncio.AbstractEventLoop | None,
runner: DouyuBatchRunner,
):
self._batches[batch_id] = {
"log_queue": log_queue,
"loop": loop,
"runner": runner,
"finished": False,
"updated_at": time.time(),
}
with self._lock:
self._prune_expired_locked()
self._batches[batch_id] = {
"log_queue": log_queue,
"loop": loop,
"runner": runner,
"finished": False,
"updated_at": time.time(),
}
def get(self, batch_id: str):
return self._batches.get(batch_id)
with self._lock:
return self._batches.get(batch_id)
def pop(self, batch_id: str):
return self._batches.pop(batch_id, None)
with self._lock:
return self._batches.pop(batch_id, None)
def mark_finished(self, batch_id: str):
if batch_id in self._batches:
self._batches[batch_id]["finished"] = True
self._batches[batch_id]["updated_at"] = time.time()
with self._lock:
if batch_id in self._batches:
self._batches[batch_id]["finished"] = True
self._batches[batch_id]["updated_at"] = time.time()
self._prune_expired_locked()
def active_ids(self) -> set[str]:
return {
batch_id
for batch_id, info in self._batches.items()
if not info.get("finished")
}
with self._lock:
self._prune_expired_locked()
return {
batch_id
for batch_id, info in self._batches.items()
if not info.get("finished")
}
def stats(self) -> dict[str, int]:
with self._lock:
self._prune_expired_locked()
active = sum(
1 for info in self._batches.values() if not info.get("finished")
)
total = len(self._batches)
return {
"active": active,
"finished": max(0, total - active),
"total": total,
}
douyu_batch_registry = DouyuBatchRegistry()
@@ -10,6 +10,7 @@ from sqlalchemy.orm import Session
from core.douyu import DouyuActivityClient
from ..models import Account, DouyuTask
from .account_sync_service import lock_account_row
from .business_events import record_gold_spent, record_points_credit
from .douyu_activity_query import extract_points_expire_time, query_csrf
@@ -196,6 +197,8 @@ class DonateMixin:
message += f",电竞积分: {account.esports_points}"
# 电竞礼物同样产生积分到账 —— 这一类此前**从来不在收集范围**
# (不在 COLLECTED_TASK_TYPES 里),时间线上一直是空白。
if account.id is not None:
lock_account_row(db, int(account.id))
record_points_credit(
db,
account,
@@ -334,6 +337,8 @@ class DonateMixin:
# 旧收集器把「预期涨幅」当既成事实写进台账(未确认时也记 +980),
# 那是把预期记成到账。这里宁可标清楚,也不假装它是确认过的数字。
# 金额用本地可等价重算的值(1 个精英令 ≈ 10 分),不再依赖 result 里的字段。
if account.id is not None:
lock_account_row(db, int(account.id))
record_points_credit(
db,
account,
+22 -11
View File
@@ -335,6 +335,7 @@ class GoldMixin:
except Exception as exc: # noqa: BLE001 余额核对失败仍继续查供应商
gold_error = str(exc)
client = None
try:
client = FishFinRechargeClient(FishFinRechargeConfig.from_env())
payload = client.query_order(order_no)
@@ -349,6 +350,11 @@ class GoldMixin:
)
except Exception as exc: # noqa: BLE001 供应商查询异常由持久调度继续重试
supplier_error = str(exc)
finally:
if client is not None:
close = getattr(client, "close", None)
if callable(close):
close()
# 查询期间供应商回调可能已经把任务收口。重新锁行后再决定是否写入,
# 避免长时间 HTTP 调用结束后用旧状态覆盖回调结果。
@@ -667,17 +673,22 @@ class GoldMixin:
)
client = FishFinRechargeClient(FishFinRechargeConfig.from_env(), trace=trace)
order_payload = client.create_order(
buy_num=amount,
pay_amount=pay_amount,
out_order_id=order_no,
product_id=product_id,
recharge_arg=[
{"templateName": template_name, "templateVal": recharge_account}
],
order_type=0,
notify_url=client.config.notify_url,
)
try:
order_payload = client.create_order(
buy_num=amount,
pay_amount=pay_amount,
out_order_id=order_no,
product_id=product_id,
recharge_arg=[
{"templateName": template_name, "templateVal": recharge_account}
],
order_type=0,
notify_url=client.config.notify_url,
)
finally:
close = getattr(client, "close", None)
if callable(close):
close()
code = self._to_int(self._supplier_value(order_payload, "code"))
status = self._supplier_order_status(order_payload)
result = {
+251 -224
View File
@@ -11,8 +11,10 @@ from sqlalchemy.orm import Session
from core.douyu import DouyuActivityClient, DouyuActivityError
from ..database import release_idle_session
from ..models import Account, DouyuEsportsGoodsSnapshot, DouyuGoodsSnapshot, DouyuTask
from .account_exchange_sync_service import sync_exchange_records
from .account_sync_service import lock_account_row
from .binding_ownership import role_names_match, workbench_task_occupation_error
from .business_events import record_exchange
from .douyu_activity_query import (
@@ -279,6 +281,8 @@ class GoodsMixin:
score = int(goods.score) * (
int(num) if isinstance(num, (int, float)) else 1
)
if account.id is not None:
lock_account_row(db, int(account.id))
record_exchange(
db,
account,
@@ -374,156 +378,148 @@ class GoodsMixin:
if not commodity_id:
self._mark_task(db, task, "failed", "请选择兑换商品")
return
client = self._client(cookie)
manual_id = str(config["manual_id"])
rid = str(config.get("rid") or "")
result: dict = {"commodity_id": commodity_id}
# ---- 对齐浏览器:先查手册状态 + 商品详情,按页面状态机选兑换链路 ----
manual_type = None
try:
user_info = query_elite_user_info(client, manual_id=manual_id, rid=rid)
manual_type = user_info.get("manual_type")
except DouyuActivityError as exc:
self._push_log("warning", f"查询手册状态失败,按经典流程继续: {exc}")
detail = None
try:
detail = client.query_goods_detail(
manual_id=manual_id, commodity_id=commodity_id, rid=rid
)["detail"]
except DouyuActivityError as exc:
self._push_log("warning", f"查询商品详情失败,按经典流程继续: {exc}")
batch_num_limit = None
if detail and int(detail.get("batchExchange") or 0) > 0:
try:
batch_num_limit = client.batch_exchange_limit(
manual_id=manual_id, commodity_id=commodity_id, rid=rid
)["limit"]
except DouyuActivityError as exc:
self._push_log("warning", f"查询批量兑换上限失败: {exc}")
plan = DouyuActivityClient.resolve_exchange_plan(
detail or {}, manual_type=manual_type, batch_num_limit=batch_num_limit
)
result["plan"] = plan
if detail:
result["detail"] = detail
action = plan["action"]
def finish_failed(message: str) -> None:
self._mark_task(
db,
task,
"failed",
message,
{"commodity_id": commodity_id, "plan": plan, "detail": detail},
)
if action in ("blocked", "wait"):
finish_failed(f"兑换失败: {plan['text']}")
return
goods = (
db.query(DouyuGoodsSnapshot)
.filter(DouyuGoodsSnapshot.commodity_id == commodity_id)
.first()
)
goods_raw = goods.raw if goods else None
name = (goods.name if goods else "") or commodity_id
if action == "subscribe":
task_id = int(task.id)
account_id = int(account.id)
created_by = int(task.created_by)
manual_id = str(config["manual_id"])
rid = str(config.get("rid") or "")
result: dict[str, Any] = {"commodity_id": commodity_id}
client = self._client(cookie)
# 锁单、退避睡眠和支付轮询耗时可能高达数分钟,期间释放干净的托管连接。
release_idle_session(db)
try:
# ---- 对齐浏览器:先查手册状态 + 商品详情,按页面状态机选兑换链路 ----
manual_type = None
try:
client.subscribe_commodity(
manual_id=manual_id, commodity_id=commodity_id
)
user_info = query_elite_user_info(client, manual_id=manual_id, rid=rid)
manual_type = user_info.get("manual_type")
except DouyuActivityError as exc:
finish_failed(f"预约到货失败: {exc}")
return
account.updated_at = datetime.now(UTC)
self._mark_task(
db,
task,
"success",
f"已预约到货: {name} ({plan['text']})",
{"commodity_id": commodity_id, "plan": plan, "detail": detail},
)
return
if action == "pre_exchange":
self._push_log("warning", f"查询手册状态失败,按经典流程继续: {exc}")
detail = None
try:
check = client.pre_exchange_check(
manual_id=manual_id, commodity_id=commodity_id
)
user_status = int((check.get("data") or {}).get("userStatus") or 0)
if user_status == 1 and not plan["pre_exchange"]:
self._mark_task(
db,
task,
"success",
f"已预兑: {name},等待开放后继续兑换",
{
"commodity_id": commodity_id,
"plan": plan,
"detail": detail,
"check": check,
},
)
return
confirm = client.confirm_pre_exchange(
detail = client.query_goods_detail(
manual_id=manual_id, commodity_id=commodity_id, rid=rid
)
)["detail"]
except DouyuActivityError as exc:
finish_failed(f"预兑失败: {exc}")
self._push_log("warning", f"查询商品详情失败,按经典流程继续: {exc}")
batch_num_limit = None
if detail and int(detail.get("batchExchange") or 0) > 0:
try:
batch_num_limit = client.batch_exchange_limit(
manual_id=manual_id, commodity_id=commodity_id, rid=rid
)["limit"]
except DouyuActivityError as exc:
self._push_log("warning", f"查询批量兑换上限失败: {exc}")
plan = DouyuActivityClient.resolve_exchange_plan(
detail or {}, manual_type=manual_type, batch_num_limit=batch_num_limit
)
result["plan"] = plan
if detail:
result["detail"] = detail
action = plan["action"]
def finish_failed(message: str) -> None:
active_task = db.get(DouyuTask, task_id) or task
self._mark_task(
db,
active_task,
"failed",
message,
{"commodity_id": commodity_id, "plan": plan, "detail": detail},
)
if action in ("blocked", "wait"):
finish_failed(f"兑换失败: {plan['text']}")
return
account.updated_at = datetime.now(UTC)
self._mark_task(
db,
task,
"success",
f"预兑成功: {name},开放后可继续兑换",
{
"commodity_id": commodity_id,
"plan": plan,
"detail": detail,
"check": check,
"confirm": confirm,
},
)
return
# ---- 经典链路:锁单 -> 人类节奏等待 -> 支付(错误分类退避重试)----
try:
num = max(1, int(payload.get("num") or 1))
except (TypeError, ValueError):
num = 1
num = min(num, int(plan.get("max_num") or 1))
if action == "subscribe":
try:
client.subscribe_commodity(
manual_id=manual_id, commodity_id=commodity_id
)
except DouyuActivityError as exc:
finish_failed(f"预约到货失败: {exc}")
return
active_task = db.get(DouyuTask, task_id) or task
active_account = db.get(Account, account_id) or account
active_account.updated_at = datetime.now(UTC)
self._mark_task(
db,
active_task,
"success",
f"已预约到货: {name} ({plan['text']})",
{"commodity_id": commodity_id, "plan": plan, "detail": detail},
)
return
# 少量随机抖动(浏览器点击商品到锁单之间有人工间隔)
self._push_log("info", f" 兑换 {name}: {plan['text']}")
if not self._sleep_interruptible(
random.uniform(*DOUYU_EXCHANGE_PRE_CREATE_JITTER)
):
self._mark_task(db, task, "stopped", "任务已停止", result)
return
try:
locked = client.create_exchange_order(
manual_id=manual_id,
rid=rid,
commodity_id=commodity_id,
num=num,
)
except DouyuActivityError as exc:
# 锁单本身被频控时做一次长退避重试,避免无脑连打
backoff = (
DOUYU_EXCHANGE_RATE_LIMIT_BACKOFFS[0]
if self._is_rate_limited_error(str(exc))
else 3
)
self._push_log(
"info", f" 锁定兑换商品失败({exc}),{backoff:.0f}s 后重试一次"
)
if not self._sleep_interruptible(backoff):
self._mark_task(db, task, "stopped", "任务已停止", result)
if action == "pre_exchange":
try:
check = client.pre_exchange_check(
manual_id=manual_id, commodity_id=commodity_id
)
user_status = int((check.get("data") or {}).get("userStatus") or 0)
if user_status == 1 and not plan["pre_exchange"]:
active_task = db.get(DouyuTask, task_id) or task
self._mark_task(
db,
active_task,
"success",
f"已预兑: {name},等待开放后继续兑换",
{
"commodity_id": commodity_id,
"plan": plan,
"detail": detail,
"check": check,
},
)
return
confirm = client.confirm_pre_exchange(
manual_id=manual_id, commodity_id=commodity_id, rid=rid
)
except DouyuActivityError as exc:
finish_failed(f"预兑失败: {exc}")
return
active_task = db.get(DouyuTask, task_id) or task
active_account = db.get(Account, account_id) or account
active_account.updated_at = datetime.now(UTC)
self._mark_task(
db,
active_task,
"success",
f"预兑成功: {name},开放后可继续兑换",
{
"commodity_id": commodity_id,
"plan": plan,
"detail": detail,
"check": check,
"confirm": confirm,
},
)
return
# ---- 经典链路:锁单 -> 人类节奏等待 -> 支付(错误分类退避重试)----
try:
num = max(1, int(payload.get("num") or 1))
except (TypeError, ValueError):
num = 1
num = min(num, int(plan.get("max_num") or 1))
# 少量随机抖动(浏览器点击商品到锁单之间有人工间隔)
self._push_log("info", f" 兑换 {name}: {plan['text']}")
if not self._sleep_interruptible(
random.uniform(*DOUYU_EXCHANGE_PRE_CREATE_JITTER)
):
active_task = db.get(DouyuTask, task_id) or task
self._mark_task(db, active_task, "stopped", "任务已停止", result)
return
try:
locked = client.create_exchange_order(
@@ -532,103 +528,132 @@ class GoodsMixin:
commodity_id=commodity_id,
num=num,
)
except DouyuActivityError as exc2:
finish_failed(f"锁定兑换商品失败: {exc2}")
except DouyuActivityError as exc:
# 锁单本身被频控时做一次长退避重试,避免无脑连打
backoff = (
DOUYU_EXCHANGE_RATE_LIMIT_BACKOFFS[0]
if self._is_rate_limited_error(str(exc))
else 3
)
self._push_log(
"info", f" 锁定兑换商品失败({exc}),{backoff:.0f}s 后重试一次"
)
if not self._sleep_interruptible(backoff):
active_task = db.get(DouyuTask, task_id) or task
self._mark_task(db, active_task, "stopped", "任务已停止", result)
return
try:
locked = client.create_exchange_order(
manual_id=manual_id,
rid=rid,
commodity_id=commodity_id,
num=num,
)
except DouyuActivityError as exc2:
finish_failed(f"锁定兑换商品失败: {exc2}")
return
result.update(
{**locked, "lock_order": locked, "goods": goods_raw}
)
# 锁单成功后按浏览器节奏(抓包实测 2.24s~4.2s)等待再支付
delay = random.uniform(*DOUYU_EXCHANGE_LOCK_PAY_DELAY_RANGE)
self._push_log(
"info", f" 锁单成功(订单 {locked['order_id']}),{delay:.1f}s 后支付"
)
if not self._sleep_interruptible(delay):
active_task = db.get(DouyuTask, task_id) or task
self._mark_task(
db, active_task, "stopped", "任务已停止,商品锁单仍可能有效", locked
)
return
try:
payment = self._pay_exchange_with_backoff(
client,
manual_id=manual_id,
order_id=locked["order_id"],
rid=rid,
locked_at=locked["locked_at"],
)
except DouyuActivityError as exc:
finish_failed(str(exc))
return
if payment is None:
active_task = db.get(DouyuTask, task_id) or task
self._mark_task(
db, active_task, "stopped", "任务已停止,商品锁单仍可能有效", locked
)
return
result.update(
{**locked, "lock_order": locked, "goods": goods.raw if goods else None}
)
# 锁单成功后按浏览器节奏(抓包实测 2.24s~4.2s)等待再支付
delay = random.uniform(*DOUYU_EXCHANGE_LOCK_PAY_DELAY_RANGE)
self._push_log(
"info", f" 锁单成功(订单 {locked['order_id']}),{delay:.1f}s 后支付"
)
if not self._sleep_interruptible(delay):
self._mark_task(
db, task, "stopped", "任务已停止,商品锁单仍可能有效", locked
result.update(
{
"order_id": locked["order_id"],
"exchange_id": payment["exchange_id"],
"commodity_image": payment["commodity_image"]
or locked["commodity_image"],
"exchange_num": payment["exchange_num"],
"payment": payment,
}
)
return
try:
payment = self._pay_exchange_with_backoff(
active_task = db.get(DouyuTask, task_id) or task
active_account = db.get(Account, account_id) or account
active_account.updated_at = datetime.now(UTC)
# 兑换成功后自动刷新积分,更新账号最新积分信息(失败不阻断兑换成功)
points_refresh = None
try:
ctn = query_csrf(client)
points_refresh = self._refresh_account_points(
client, active_account, cookie, ctn=ctn
)
except Exception as exc: # noqa: BLE001 外部接口与任务边界需要保留宽泛异常兜底
self._push_log("warning", f"兑换后刷新积分失败: {exc}")
# ⚠️ **只有这一条 success 是真的兑换**。同一个 handler 里还有三条
# 「预约到货 / 已预兑 / 预兑确认」的 success —— 它们不消耗积分、也没换到东西,
# 所以**不发事件**。旧收集器只按 status=="success" 收集,导致每预约一次
# 就生成一条金额为空的 exchange,把 accounts 的 exchange_count 灌大。
lock_account_row(db, account_id)
record_exchange(
db,
active_account,
task_id=active_task.id,
name=name,
score=locked.get("score"),
commodity_id=commodity_id,
order_id=str(locked.get("order_id") or ""),
exchange_id=str(payment.get("exchange_id") or ""),
game_name=active_account.game_name or "",
game_channel=active_account.game_channel or "",
points_after=(points_refresh or {}).get("points"),
scope="elite",
actor_id=created_by,
)
self._refresh_high_value_after_exchange(
client,
active_account,
manual_id=manual_id,
order_id=locked["order_id"],
rid=rid,
locked_at=locked["locked_at"],
commodity_name=name,
)
except DouyuActivityError as exc:
finish_failed(str(exc))
return
if payment is None:
self._mark_task(
db, task, "stopped", "任务已停止,商品锁单仍可能有效", locked
db,
active_task,
"success",
f"兑换成功: {name}",
{
"goods": goods_raw,
"game_name": active_account.game_name or "",
"game_channel": active_account.game_channel or "",
"account_name": active_account.nickname
or active_account.username
or active_account.uid
or f"#{active_account.id}",
**result,
**(points_refresh or {}),
},
)
return
result.update(
{
"order_id": locked["order_id"],
"exchange_id": payment["exchange_id"],
"commodity_image": payment["commodity_image"]
or locked["commodity_image"],
"exchange_num": payment["exchange_num"],
"payment": payment,
}
)
account.updated_at = datetime.now(UTC)
# 兑换成功后自动刷新积分,更新账号最新积分信息(失败不阻断兑换成功)
points_refresh = None
try:
ctn = query_csrf(client)
points_refresh = self._refresh_account_points(
client, account, cookie, ctn=ctn
)
except Exception as exc: # noqa: BLE001 外部接口与任务边界需要保留宽泛异常兜底
self._push_log("warning", f"兑换后刷新积分失败: {exc}")
# ⚠️ **只有这一条 success 是真的兑换**。同一个 handler 里还有三条
# 「预约到货 / 已预兑 / 预兑确认」的 success —— 它们不消耗积分、也没换到东西,
# 所以**不发事件**。旧收集器只按 status=="success" 收集,导致每预约一次
# 就生成一条金额为空的 exchange,把 accounts 的 exchange_count 灌大。
record_exchange(
db,
account,
task_id=task.id,
name=name,
score=locked.get("score"),
commodity_id=commodity_id,
order_id=str(locked.get("order_id") or ""),
exchange_id=str(payment.get("exchange_id") or ""),
game_name=account.game_name or "",
game_channel=account.game_channel or "",
points_after=(points_refresh or {}).get("points"),
scope="elite",
actor_id=int(task.created_by),
)
self._refresh_high_value_after_exchange(
client,
account,
manual_id=manual_id,
rid=rid,
commodity_name=name,
)
self._mark_task(
db,
task,
"success",
f"兑换成功: {name}",
{
"goods": goods.raw if goods else None,
"game_name": account.game_name or "",
"game_channel": account.game_channel or "",
"account_name": account.nickname
or account.username
or account.uid
or f"#{account.id}",
**result,
**(points_refresh or {}),
},
)
finally:
if isinstance(client, DouyuActivityClient):
client.close()
def _execute_exchange_esports_goods(
self,
@@ -713,6 +738,8 @@ class GoodsMixin:
and isinstance(after_points, (int, float))
else None
)
if account.id is not None:
lock_account_row(db, int(account.id))
record_exchange(
db,
account,
+3
View File
@@ -18,6 +18,7 @@ from .account_binding import (
SCOPE_PEACE,
set_bind_status,
)
from .account_sync_service import lock_account_row
from .business_events import record_exchange
from .douyu_activity_query import (
query_xpd_bind_info,
@@ -597,6 +598,8 @@ class XpdMixin:
# 和平小店兑换 —— 此前从不发事件(不在旧收集器的 allowlist 里)。
# 消耗的是点券或扭蛋碎片,不是积分;金额用本地已知的 price(快照标价,
# 已在上面校验过 > 0),作用域标成 peace 以便和精英/电竞区分。
if account.id is not None:
lock_account_row(db, int(account.id))
record_exchange(
db,
account,
+14 -1
View File
@@ -384,6 +384,7 @@ class ExecutionEventBatchWriter:
self._flushing = False
self._stop = False
self._thread: threading.Thread | None = None
self._failed_batches = 0
def start(self) -> None:
with self._cond:
@@ -401,6 +402,15 @@ class ExecutionEventBatchWriter:
with self._cond:
return self._thread is not None and self._thread.is_alive()
def status(self) -> dict[str, Any]:
with self._cond:
return {
"running": self._thread is not None and self._thread.is_alive(),
"pending": len(self._queue),
"flushing": self._flushing,
"failed_batches": self._failed_batches,
}
def _drain_sync(self) -> bool:
"""在后台线程未运行时按 FIFO 同步写完队列中剩余事件。"""
with self._write_lock:
@@ -486,7 +496,10 @@ class ExecutionEventBatchWriter:
self._flushing = True
try:
with self._write_lock:
append_execution_events(batch)
ok = append_execution_events(batch)
if not ok:
with self._cond:
self._failed_batches += 1
finally:
with self._cond:
self._flushing = False
+46 -16
View File
@@ -100,6 +100,10 @@ class ExecutionJobWorker:
self._inflight: dict[str, int] = {}
self._owner = execution_worker_owner()
self._event_writer = ExecutionEventBatchWriter()
self._last_poll_at: str | None = None
self._last_claim_error: str | None = None
self._last_claim_error_at: str | None = None
self._total_claimed = 0
def start(self) -> bool:
with self._lock:
@@ -159,23 +163,27 @@ class ExecutionJobWorker:
DEFAULT_POLL_SECONDS,
)
while not self._stop.is_set():
# 回收已完成的 job,同时把 lane 的在途计数减回来。
for future in [item for item in futures if item.done()]:
lane = futures.pop(future)
self._inflight[lane] = max(0, self._inflight.get(lane, 0) - 1)
try:
future.result()
except Exception: # noqa: BLE001, S110 - 结果已落库,这里只消费异常
pass
executors = self._executors
if not executors:
break
slots = max_jobs - sum(self._inflight.values())
now_iso = datetime.now(UTC).isoformat()
with self._lock:
self._last_poll_at = now_iso
# 回收已完成的 job,同时把 lane 的在途计数减回来。
for future in [item for item in futures if item.done()]:
lane = futures.pop(future)
self._inflight[lane] = max(0, self._inflight.get(lane, 0) - 1)
try:
future.result()
except Exception: # noqa: BLE001, S110 - 结果已落库,这里只消费异常
pass
executors = dict(self._executors)
if not executors:
break
slots = max_jobs - sum(self._inflight.values())
inflight_snapshot = dict(self._inflight)
if slots > 0:
# 履约优先:先把 fulfillment 的槽填满,登录只用剩下的。
# 登录批次等邮箱验证码时可能持槽 25 分钟,绝不能把履约饿死。
for lane in _lane_claim_order():
lane_free = lane_limits.get(lane, 0) - self._inflight.get(lane, 0)
lane_free = lane_limits.get(lane, 0) - inflight_snapshot.get(lane, 0)
take = min(slots, lane_free)
if take <= 0:
continue
@@ -185,7 +193,12 @@ class ExecutionJobWorker:
owner=self._owner,
limit=take,
)
except Exception: # noqa: BLE001 - 消费循环必须存活
with self._lock:
self._last_claim_error = None
except Exception as exc: # noqa: BLE001 - 消费循环必须存活
with self._lock:
self._last_claim_error = f"{type(exc).__name__}: {exc}"[:500]
self._last_claim_error_at = now_iso
logger.exception("领取执行任务失败 lane={}", lane)
jobs = []
executor = executors.get(lane)
@@ -196,7 +209,10 @@ class ExecutionJobWorker:
future = executor.submit(self._run_job, job.id)
except RuntimeError:
break
self._inflight[lane] = self._inflight.get(lane, 0) + 1
with self._lock:
self._inflight[lane] = self._inflight.get(lane, 0) + 1
self._total_claimed += 1
inflight_snapshot[lane] = inflight_snapshot.get(lane, 0) + 1
futures[future] = lane
slots -= len(jobs)
if futures:
@@ -384,16 +400,30 @@ def stop_execution_job_worker() -> None:
def execution_job_worker_status() -> dict[str, Any]:
thread = execution_job_worker._thread
with execution_job_worker._lock:
thread = execution_job_worker._thread
inflight = dict(execution_job_worker._inflight)
last_poll_at = execution_job_worker._last_poll_at
last_claim_error = execution_job_worker._last_claim_error
last_claim_error_at = execution_job_worker._last_claim_error_at
total_claimed = execution_job_worker._total_claimed
event_writer = execution_job_worker._event_writer.status()
return {
"running": bool(thread and thread.is_alive()),
"lanes": list(_lane_scopes()),
"lane_slots": _lane_slot_limits(),
"inflight": inflight,
"inflight_total": sum(inflight.values()),
"max_jobs": _env_positive_int(
"EXECUTION_WORKER_MAX_JOBS",
DEFAULT_EXECUTION_WORKERS,
),
"owner": execution_job_worker._owner,
"total_claimed": total_claimed,
"last_poll_at": last_poll_at,
"last_claim_error": last_claim_error,
"last_claim_error_at": last_claim_error_at,
"event_writer": event_writer,
}
+10 -3
View File
@@ -836,9 +836,16 @@ class LoginBatchRunner:
stop_event=self._stop,
api_strategy=self.api_strategy,
)
result = (
loginer.check_account() if self.mode == "check" else loginer.login()
)
try:
result = (
loginer.check_account()
if self.mode == "check"
else loginer.login()
)
finally:
close = getattr(loginer, "close", None)
if callable(close):
close()
if self.mode == "check" and result.success:
status = (
@@ -32,6 +32,17 @@ _thread: threading.Thread | None = None
_lock = threading.Lock()
_in_flight: set[int] = set()
_in_flight_lock = threading.Lock()
_metrics_lock = threading.Lock()
_metrics: dict[str, object] = {
"last_tick_at": None,
"last_dispatched_at": None,
"last_claimed": 0,
"last_submitted": 0,
"total_dispatched": 0,
"consecutive_errors": 0,
"last_error": None,
"last_error_at": None,
}
def _env_int(name: str, default: int, minimum: int, maximum: int) -> int:
@@ -184,6 +195,9 @@ def _release_callback(future: Future) -> None:
def run_payment_poll_dispatch_once(limit: int = DEFAULT_BATCH_SIZE) -> int:
capacity = available_slots(TaskLane.PAYMENT_POLL)
if capacity <= 0:
with _metrics_lock:
_metrics["last_claimed"] = 0
_metrics["last_submitted"] = 0
return 0
claimed = _claim_due_payment_tasks(min(max(1, limit), capacity))
submitted = 0
@@ -200,6 +214,12 @@ def run_payment_poll_dispatch_once(limit: int = DEFAULT_BATCH_SIZE) -> int:
break
future.add_done_callback(_release_callback)
submitted += 1
with _metrics_lock:
_metrics["last_claimed"] = len(claimed)
_metrics["last_submitted"] = submitted
if submitted:
_metrics["total_dispatched"] = int(_metrics["total_dispatched"] or 0) + submitted
_metrics["last_dispatched_at"] = datetime.now(UTC).isoformat()
return submitted
@@ -211,6 +231,9 @@ def _run() -> None:
30,
)
while not _stop_event.is_set():
now_iso = datetime.now(UTC).isoformat()
with _metrics_lock:
_metrics["last_tick_at"] = now_iso
try:
batch_size = _env_int(
"PAYMENT_POLL_DISPATCH_BATCH",
@@ -219,7 +242,15 @@ def _run() -> None:
200,
)
run_payment_poll_dispatch_once(batch_size)
with _metrics_lock:
_metrics["consecutive_errors"] = 0
except Exception as exc: # noqa: BLE001 - scheduler survives any one bad tick
with _metrics_lock:
_metrics["consecutive_errors"] = (
int(_metrics["consecutive_errors"] or 0) + 1
)
_metrics["last_error"] = f"{type(exc).__name__}: {exc}"[:500]
_metrics["last_error_at"] = now_iso
logger.warning("支付到账调度轮次失败: {}", exc)
_stop_event.wait(interval)
@@ -255,10 +286,13 @@ def scheduler_status() -> dict[str, object]:
running = _thread is not None and _thread.is_alive()
with _in_flight_lock:
in_flight = len(_in_flight)
with _metrics_lock:
metrics = dict(_metrics)
return {
"running": running,
"in_flight": in_flight,
"claim_seconds": CLAIM_SECONDS,
**metrics,
}
@@ -527,8 +527,7 @@ def _find_reusable_same_role_target(
PlatformFulfillmentTask.id != int(task.id),
PlatformFulfillmentTask.account_id.isnot(None),
PlatformFulfillmentTask.execution_status != "cancelled",
func.lower(func.trim(PlatformFulfillmentTask.customer_role_name))
== role.casefold(),
PlatformFulfillmentTask.customer_role_norm == role.strip().casefold(),
)
.order_by(
case((PlatformFulfillmentTask.lease_id.isnot(None), 0), else_=1),
@@ -7,7 +7,7 @@ from datetime import timedelta
from typing import Any
from fastapi import HTTPException
from sqlalchemy import case, func
from sqlalchemy import case
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
from starlette.concurrency import run_in_threadpool
@@ -249,8 +249,8 @@ def _propagate_same_role_binding_to_siblings(
PlatformFulfillmentTask.execution_status.notin_(("completed", "cancelled")),
PlatformFulfillmentTask.binding_status.in_(ACTIVE_BINDING_STATUSES),
PlatformFulfillmentTask.customer_role_name != "",
func.lower(func.trim(PlatformFulfillmentTask.customer_role_name))
== role_name.casefold(),
PlatformFulfillmentTask.customer_role_norm
== role_name.strip().casefold(),
)
.order_by(PlatformFulfillmentTask.id.asc())
.with_for_update(skip_locked=True)
@@ -2286,6 +2286,10 @@ def verify_task_binding_sync(
role = resolve_elite_role(client, config)
except Exception as exc: # noqa: BLE001
role = {"status": ROLE_ERROR, "errors": [str(exc)], "bind_infos": []}
finally:
close = getattr(client, "close", None)
if callable(close):
close()
bind_infos = [
item for item in (role.get("bind_infos") or []) if isinstance(item, dict)
+52 -9
View File
@@ -12,7 +12,7 @@ import os
import threading
from collections.abc import Callable
from concurrent.futures import Future, ThreadPoolExecutor
from dataclasses import dataclass
from dataclasses import dataclass, field
from enum import StrEnum
from typing import Any
@@ -97,6 +97,12 @@ class _LaneRuntime:
config: LaneConfig
executor: ThreadPoolExecutor
admission: threading.BoundedSemaphore
lock: threading.Lock = field(default_factory=threading.Lock)
in_flight: int = 0
active: int = 0
waiting: int = 0
submitted: int = 0
rejected: int = 0
_LOCK = threading.RLock()
@@ -134,21 +140,44 @@ def _submit[T](
if stopped is not None and stopped():
return None
if wait:
while True:
if stopped is not None and stopped():
return None
if runtime.admission.acquire(timeout=0.2):
break
with runtime.lock:
runtime.waiting += 1
try:
while True:
if stopped is not None and stopped():
return None
if runtime.admission.acquire(timeout=0.2):
break
finally:
with runtime.lock:
runtime.waiting = max(0, runtime.waiting - 1)
elif not runtime.admission.acquire(blocking=False):
with runtime.lock:
runtime.rejected += 1
return None
with runtime.lock:
runtime.in_flight += 1
runtime.submitted += 1
def run() -> T:
with runtime.lock:
runtime.active += 1
try:
return fn(*args, **kwargs)
finally:
with runtime.lock:
runtime.active = max(0, runtime.active - 1)
runtime.in_flight = max(0, runtime.in_flight - 1)
runtime.admission.release()
return runtime.executor.submit(run)
try:
return runtime.executor.submit(run)
except Exception:
with runtime.lock:
runtime.in_flight = max(0, runtime.in_flight - 1)
runtime.admission.release()
raise
def submit[T](
@@ -196,7 +225,8 @@ def try_submit[T](
def available_slots(lane: TaskLane) -> int:
"""Return the number of tasks that can currently enter a lane immediately."""
runtime = _runtime(lane)
return max(0, int(runtime.admission._value))
with runtime.lock:
return max(0, runtime.config.max_in_flight - runtime.in_flight)
def lane_stats() -> dict[str, dict[str, int]]:
@@ -204,10 +234,23 @@ def lane_stats() -> dict[str, dict[str, int]]:
runtimes = list(_RUNTIMES.items())
stats: dict[str, dict[str, int]] = {}
for lane, runtime in runtimes:
with runtime.lock:
in_flight = runtime.in_flight
active = runtime.active
waiting = runtime.waiting
submitted = runtime.submitted
rejected = runtime.rejected
available = max(0, runtime.config.max_in_flight - in_flight)
stats[lane.value] = {
"workers": runtime.config.workers,
"max_in_flight": runtime.config.max_in_flight,
"admission_value": runtime.admission._value,
"admission_value": available,
"in_flight": in_flight,
"active": active,
"queued": max(0, in_flight - active),
"waiting": waiting,
"submitted": submitted,
"rejected": rejected,
}
return stats