feat(automation): 持久执行队列与重复充值确认

This commit is contained in:
yml
2026-11-23 15:47:56 +08:00
parent 2549511598
commit aaacbea10a
29 changed files with 2147 additions and 178 deletions
+40 -13
View File
@@ -2,6 +2,8 @@
from __future__ import annotations
import os
from loguru import logger
from .database import SessionLocal
@@ -9,8 +11,18 @@ from .database import SessionLocal
_started = False
def _control_plane_enabled() -> bool:
return os.getenv("BACKGROUND_CONTROL_PLANE_ENABLED", "true").strip().lower() not in {
"0",
"false",
"no",
"off",
}
def recover_orphaned_work() -> None:
"""进程启动时收敛上次中断的任务和运行记录。"""
from .models import ExecutionJob
from .services.account_supply_service import ensure_default_supply_targets
from .services.account_work_queue import recover_running_account_work
from .services.automation.scheduler import cleanup_orphan_runs
@@ -25,6 +37,14 @@ def recover_orphaned_work() -> None:
db = SessionLocal()
try:
durable_batch_ids = {
str(batch_id)
for (batch_id,) in (
db.query(ExecutionJob.batch_id)
.filter(ExecutionJob.status.in_(("queued", "running")))
.all()
)
}
cleaned_huya = cleanup_orphan_huya_tasks(
db,
message="任务已中断(服务重启)",
@@ -33,6 +53,7 @@ def recover_orphaned_work() -> None:
logger.info("启动清理虎牙残留任务: {} 条", cleaned_huya)
cleaned_douyu = cleanup_orphan_douyu_tasks(
db,
active_batch_ids=durable_batch_ids,
message="任务已中断(服务重启)",
)
if cleaned_douyu:
@@ -71,6 +92,7 @@ def start_background_services() -> bool:
return False
from .services.automation import register_default_jobs, start_scheduler
from .services.binding_poll_scheduler import start_binding_poll_scheduler
from .services.execution_worker import start_execution_job_worker
from .services.integration import start_integration_outbox_worker
from .services.payment_poll_scheduler import start_payment_poll_scheduler
from .services.platform_fulfillment.auto_allocator import (
@@ -80,13 +102,15 @@ def start_background_services() -> bool:
start_platform_fulfillment_reconciler,
)
register_default_jobs()
start_scheduler()
start_integration_outbox_worker()
start_platform_fulfillment_reconciler()
start_platform_fulfillment_auto_allocator()
start_binding_poll_scheduler()
start_payment_poll_scheduler()
start_execution_job_worker()
if _control_plane_enabled():
register_default_jobs()
start_scheduler()
start_integration_outbox_worker()
start_platform_fulfillment_reconciler()
start_platform_fulfillment_auto_allocator()
start_binding_poll_scheduler()
start_payment_poll_scheduler()
_started = True
logger.info("后台服务已启动")
return True
@@ -98,6 +122,7 @@ def stop_background_services() -> None:
return
from .services.automation import stop_scheduler
from .services.binding_poll_scheduler import stop_binding_poll_scheduler
from .services.execution_worker import stop_execution_job_worker
from .services.integration import stop_integration_outbox_worker
from .services.payment_poll_scheduler import stop_payment_poll_scheduler
from .services.platform_fulfillment.auto_allocator import (
@@ -107,12 +132,14 @@ def stop_background_services() -> None:
stop_platform_fulfillment_reconciler,
)
stop_payment_poll_scheduler()
stop_binding_poll_scheduler()
stop_platform_fulfillment_auto_allocator()
stop_platform_fulfillment_reconciler()
stop_integration_outbox_worker()
stop_scheduler()
if _control_plane_enabled():
stop_payment_poll_scheduler()
stop_binding_poll_scheduler()
stop_platform_fulfillment_auto_allocator()
stop_platform_fulfillment_reconciler()
stop_integration_outbox_worker()
stop_scheduler()
stop_execution_job_worker()
_started = False
logger.info("后台服务已停止")
@@ -485,6 +485,10 @@
"20261123_0121_douyu_tasks_retention_index.py": {
"revision": "20261123_0121",
"sha256": "82b5732895b1613cb017a7ea28f39b4c5b53bc48b0c92422b6ac2fca3bf7b92b"
},
"20261123_0122_execution_jobs_recharge_guard.py": {
"revision": "20261123_0122",
"sha256": "e3549ea76a9da00d1e6e01e11d25fbb6fca3cce64b26223a8f0352a6fbec4c7d"
}
}
}
@@ -0,0 +1,231 @@
"""add durable execution jobs and recharge duplicate guard.
Revision ID: 20261123_0122
Revises: 20261123_0121
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
revision: str = "20261123_0122"
down_revision: str | None = "20261123_0121"
branch_labels: str | None = None
depends_on: str | None = None
def _columns(table: str) -> set[str]:
return {
str(column["name"])
for column in sa.inspect(op.get_bind()).get_columns(table)
}
def _indexes(table: str) -> set[str]:
return {
str(index["name"])
for index in sa.inspect(op.get_bind()).get_indexes(table)
if index.get("name")
}
def upgrade() -> None:
inspector = sa.inspect(op.get_bind())
if not inspector.has_table("execution_jobs"):
op.create_table(
"execution_jobs",
sa.Column("id", sa.BigInteger(), primary_key=True, autoincrement=True),
sa.Column("job_type", sa.String(length=32), nullable=False),
sa.Column("lane_scope", sa.String(length=16), nullable=False),
sa.Column("batch_id", sa.String(length=64), nullable=False),
sa.Column("payload_json", sa.JSON(), nullable=True),
sa.Column(
"status",
sa.String(length=16),
nullable=False,
server_default="queued",
),
sa.Column(
"priority",
sa.Integer(),
nullable=False,
server_default="100",
),
sa.Column("available_at", sa.DateTime(), nullable=False),
sa.Column(
"created_by",
sa.Integer(),
sa.ForeignKey("users.id", ondelete="RESTRICT"),
nullable=False,
),
sa.Column(
"lease_owner",
sa.String(length=96),
nullable=False,
server_default="",
),
sa.Column("lease_expires_at", sa.DateTime(), nullable=True),
sa.Column("heartbeat_at", sa.DateTime(), nullable=True),
sa.Column("cancel_requested_at", sa.DateTime(), nullable=True),
sa.Column(
"attempt_count",
sa.Integer(),
nullable=False,
server_default="0",
),
sa.Column(
"max_attempts",
sa.Integer(),
nullable=False,
server_default="2",
),
sa.Column("last_error", sa.Text(), nullable=False),
sa.Column("summary_json", sa.JSON(), nullable=True),
sa.Column(
"created_at",
sa.DateTime(),
nullable=False,
server_default=sa.text("CURRENT_TIMESTAMP"),
),
sa.Column("started_at", sa.DateTime(), nullable=True),
sa.Column("finished_at", sa.DateTime(), nullable=True),
sa.Column(
"updated_at",
sa.DateTime(),
nullable=False,
server_default=sa.text("CURRENT_TIMESTAMP"),
),
sa.UniqueConstraint("batch_id", name="uq_execution_jobs_batch_id"),
)
op.create_index(
"ix_execution_jobs_claim",
"execution_jobs",
["status", "lane_scope", "available_at", "priority", "id"],
)
op.create_index(
"ix_execution_jobs_lease",
"execution_jobs",
["status", "lease_expires_at"],
)
op.create_index(
"ix_execution_jobs_created_by",
"execution_jobs",
["created_by", "id"],
)
if not sa.inspect(op.get_bind()).has_table("execution_job_events"):
op.create_table(
"execution_job_events",
sa.Column("id", sa.BigInteger(), primary_key=True, autoincrement=True),
sa.Column(
"job_id",
sa.BigInteger(),
sa.ForeignKey("execution_jobs.id", ondelete="CASCADE"),
nullable=False,
),
sa.Column("batch_id", sa.String(length=64), nullable=False),
sa.Column("level", sa.String(length=16), nullable=False),
sa.Column("message", sa.Text(), nullable=False),
sa.Column("payload_json", sa.JSON(), nullable=True),
sa.Column(
"created_at",
sa.DateTime(),
nullable=False,
server_default=sa.text("CURRENT_TIMESTAMP"),
),
)
op.create_index(
"ix_execution_job_events_batch_id",
"execution_job_events",
["batch_id", "id"],
)
op.create_index(
"ix_execution_job_events_created_at",
"execution_job_events",
["created_at"],
)
if not sa.inspect(op.get_bind()).has_table("douyu_recharge_confirmations"):
op.create_table(
"douyu_recharge_confirmations",
sa.Column("id", sa.BigInteger(), primary_key=True, autoincrement=True),
sa.Column("token", sa.String(length=64), nullable=False),
sa.Column(
"user_id",
sa.Integer(),
sa.ForeignKey("users.id", ondelete="CASCADE"),
nullable=False,
),
sa.Column("amount", sa.Integer(), nullable=False),
sa.Column("account_ids_json", sa.JSON(), nullable=False),
sa.Column("expires_at", sa.DateTime(), nullable=False),
sa.Column("used_at", sa.DateTime(), nullable=True),
sa.Column(
"created_at",
sa.DateTime(),
nullable=False,
server_default=sa.text("CURRENT_TIMESTAMP"),
),
sa.UniqueConstraint("token", name="uq_douyu_recharge_confirmation_token"),
)
op.create_index(
"ix_douyu_recharge_confirmation_lookup",
"douyu_recharge_confirmations",
["user_id", "expires_at"],
)
douyu_task_columns = _columns("douyu_tasks")
for name, ddl in (
(
"recharge_channel",
"VARCHAR(16) NOT NULL DEFAULT ''",
),
("recharge_amount", "INTEGER NULL"),
("recharge_requested_at", "DATETIME NULL"),
):
if name not in douyu_task_columns:
op.execute(
sa.text(f"ALTER TABLE douyu_tasks ADD COLUMN `{name}` {ddl}")
)
if "ix_douyu_tasks_recharge_guard" not in _indexes("douyu_tasks"):
op.create_index(
"ix_douyu_tasks_recharge_guard",
"douyu_tasks",
[
"account_id",
"task_type",
"recharge_channel",
"recharge_amount",
"created_at",
],
)
if "recharge_duplicate_confirm_minutes" not in _columns("douyu_config"):
op.add_column(
"douyu_config",
sa.Column(
"recharge_duplicate_confirm_minutes",
sa.Integer(),
nullable=False,
server_default="10",
),
)
def downgrade() -> None:
if "recharge_duplicate_confirm_minutes" in _columns("douyu_config"):
op.drop_column("douyu_config", "recharge_duplicate_confirm_minutes")
if "ix_douyu_tasks_recharge_guard" in _indexes("douyu_tasks"):
op.drop_index("ix_douyu_tasks_recharge_guard", table_name="douyu_tasks")
douyu_task_columns = _columns("douyu_tasks")
for name in ("recharge_requested_at", "recharge_amount", "recharge_channel"):
if name in douyu_task_columns:
op.drop_column("douyu_tasks", name)
for table in (
"douyu_recharge_confirmations",
"execution_job_events",
"execution_jobs",
):
if sa.inspect(op.get_bind()).has_table(table):
op.drop_table(table)
+124
View File
@@ -424,6 +424,14 @@ class DouyuTask(Base):
nullable=True,
index=True,
)
# 鱼翅重复请求保护需要稳定列,不能依赖 JSON 内字段做窗口查询。
recharge_channel: Mapped[str] = mapped_column(
String(16), nullable=False, default="", server_default=""
)
recharge_amount: Mapped[int | None] = mapped_column(Integer, nullable=True)
recharge_requested_at: Mapped[datetime | None] = mapped_column(
UTCDateTime, nullable=True
)
# 账号归属客服冗余字段,配合复合索引消除任务列表全表 filesort。
account_assigned_to: Mapped[int | None] = mapped_column(
ForeignKey("users.id"), nullable=True
@@ -474,6 +482,14 @@ class DouyuTask(Base):
"created_at",
"id",
),
Index(
"ix_douyu_tasks_recharge_guard",
"account_id",
"task_type",
"recharge_channel",
"recharge_amount",
"created_at",
),
Index(
"uq_douyu_tasks_active_binding",
"active_binding_key",
@@ -606,6 +622,9 @@ class DouyuConfig(Base):
gold_api_account_template_name: Mapped[str] = mapped_column(
String(64), default="斗鱼昵称"
)
recharge_duplicate_confirm_minutes: Mapped[int] = mapped_column(
Integer, nullable=False, default=10, server_default="10"
)
gift_id: Mapped[str] = mapped_column(String(64), default="23643")
skin_id: Mapped[str] = mapped_column(String(64), default="2942")
updated_at: Mapped[datetime] = mapped_column(
@@ -613,6 +632,111 @@ class DouyuConfig(Base):
)
class ExecutionJob(Base):
"""跨进程可恢复的批次执行请求。业务任务行仍保存逐账号结果。"""
__tablename__ = "execution_jobs"
id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
job_type: Mapped[str] = mapped_column(String(32), nullable=False)
lane_scope: Mapped[str] = mapped_column(String(16), nullable=False)
batch_id: Mapped[str] = mapped_column(String(64), nullable=False, unique=True)
payload_json: Mapped[dict | None] = mapped_column(JSON, nullable=True)
status: Mapped[str] = mapped_column(
String(16), nullable=False, default="queued", server_default="queued"
)
priority: Mapped[int] = mapped_column(
Integer, nullable=False, default=100, server_default="100"
)
available_at: Mapped[datetime] = mapped_column(UTCDateTime, nullable=False)
created_by: Mapped[int] = mapped_column(
ForeignKey("users.id", ondelete="RESTRICT"), nullable=False
)
lease_owner: Mapped[str] = mapped_column(
String(96), nullable=False, default="", server_default=""
)
lease_expires_at: Mapped[datetime | None] = mapped_column(
UTCDateTime, nullable=True
)
heartbeat_at: Mapped[datetime | None] = mapped_column(UTCDateTime, nullable=True)
cancel_requested_at: Mapped[datetime | None] = mapped_column(
UTCDateTime, nullable=True
)
attempt_count: Mapped[int] = mapped_column(
Integer, nullable=False, default=0, server_default="0"
)
max_attempts: Mapped[int] = mapped_column(
Integer, nullable=False, default=2, server_default="2"
)
last_error: Mapped[str] = mapped_column(Text, nullable=False, default="")
summary_json: Mapped[dict | None] = mapped_column(JSON, nullable=True)
created_at: Mapped[datetime] = mapped_column(UTCDateTime, default=_utcnow)
started_at: Mapped[datetime | None] = mapped_column(UTCDateTime, nullable=True)
finished_at: Mapped[datetime | None] = mapped_column(UTCDateTime, nullable=True)
updated_at: Mapped[datetime] = mapped_column(
UTCDateTime, default=_utcnow, onupdate=_utcnow
)
__table_args__ = (
Index(
"ix_execution_jobs_claim",
"status",
"lane_scope",
"available_at",
"priority",
"id",
),
Index("ix_execution_jobs_lease", "status", "lease_expires_at"),
Index("ix_execution_jobs_created_by", "created_by", "id"),
)
class ExecutionJobEvent(Base):
"""worker 日志和任务事件,供 API 跨进程回放。"""
__tablename__ = "execution_job_events"
id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
job_id: Mapped[int] = mapped_column(
ForeignKey("execution_jobs.id", ondelete="CASCADE"), nullable=False
)
batch_id: Mapped[str] = mapped_column(String(64), nullable=False)
level: Mapped[str] = mapped_column(String(16), nullable=False)
message: Mapped[str] = mapped_column(Text, nullable=False, default="")
payload_json: Mapped[dict | None] = mapped_column(JSON, nullable=True)
created_at: Mapped[datetime] = mapped_column(UTCDateTime, default=_utcnow)
__table_args__ = (
Index("ix_execution_job_events_batch_id", "batch_id", "id"),
Index("ix_execution_job_events_created_at", "created_at"),
)
class DouyuRechargeConfirmation(Base):
"""重复 API 充值的人工确认令牌。"""
__tablename__ = "douyu_recharge_confirmations"
id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
token: Mapped[str] = mapped_column(String(64), nullable=False, unique=True)
user_id: Mapped[int] = mapped_column(
ForeignKey("users.id", ondelete="CASCADE"), nullable=False
)
amount: Mapped[int] = mapped_column(Integer, nullable=False)
account_ids_json: Mapped[list] = mapped_column(JSON, nullable=False)
expires_at: Mapped[datetime] = mapped_column(UTCDateTime, nullable=False)
used_at: Mapped[datetime | None] = mapped_column(UTCDateTime, nullable=True)
created_at: Mapped[datetime] = mapped_column(UTCDateTime, default=_utcnow)
__table_args__ = (
Index(
"ix_douyu_recharge_confirmation_lookup",
"user_id",
"expires_at",
),
)
class DouyuRoleApiLog(Base):
"""斗鱼角色接口原始响应与归一状态,仅追加。
+2
View File
@@ -148,6 +148,7 @@ def list_jobs(
from ..services.binding_poll_scheduler import (
scheduler_status as binding_poll_status,
)
from ..services.execution_worker import execution_job_worker_status
from ..services.payment_poll_scheduler import (
scheduler_status as payment_poll_status,
)
@@ -164,6 +165,7 @@ def list_jobs(
else "",
"binding_poll": binding_poll_status(),
"payment_poll": payment_poll_status(),
"execution_jobs": execution_job_worker_status(),
},
"pending_relogin": pending_relogin,
"jobs": [
+48 -44
View File
@@ -18,7 +18,7 @@ CK 从 `login_tasks.cookie` 迁到 `accounts.cookie`,因此本页面的**记
import csv
import hashlib
import io
import threading
import uuid
from concurrent.futures import ThreadPoolExecutor, as_completed
from datetime import UTC, datetime
@@ -27,11 +27,10 @@ from fastapi.responses import StreamingResponse
from sqlalchemy import case, func, or_
from sqlalchemy.orm import Session, defer, joinedload
from ..database import WorkerSessionLocal, get_db
from ..database import get_db
from ..deps import get_current_user, require_permission
from ..models import Account, AuditLog, LoginTask, User
from ..models import ProxyConfig as ProxyConfigModel
from ..permissions import get_user_permissions, user_has_permission
from ..permissions import user_has_permission
from ..schemas import CookieReloginRequest
from ..services.account_lifecycle import on_ck_cleared
from ..services.cookie_check_service import check_douyu_cookie
@@ -41,7 +40,15 @@ from ..services.douyu_service import (
cookie_holding_filter,
cookie_operable_filter,
)
from ..services.login_service import BatchRegistry, LoginBatchRunner, get_relogin_limits
from ..services.execution_jobs import (
JOB_RELOGIN_BATCH,
LANE_AUTH,
TERMINAL_STATUSES,
enqueue_execution_job,
get_execution_job,
request_execution_cancel,
)
from ..services.login_service import BatchRegistry, get_relogin_limits
def _fmt_dt(dt) -> str | None:
@@ -648,23 +655,26 @@ def _start_relogin_accounts(
status_code=400, detail="没有可重登的账号,请检查账号凭据或当前重登状态"
)
proxy = db.query(ProxyConfigModel).first()
thread_db = WorkerSessionLocal()
max_login_retries, max_total_time = get_relogin_limits()
runner = LoginBatchRunner(
db=thread_db,
account_ids=account_ids,
created_by=current.id,
creator_permissions=get_user_permissions(current),
max_login_retries=max_login_retries,
max_total_time=max_total_time,
proxy_config=proxy,
log_queue=None,
loop=None,
concurrency=3,
mode="relogin",
batch_id = uuid.uuid4().hex[:12]
enqueue_execution_job(
db,
job_type=JOB_RELOGIN_BATCH,
lane_scope=LANE_AUTH,
batch_id=batch_id,
payload={
"account_ids": account_ids,
"max_login_retries": max_login_retries,
"max_total_time": max_total_time,
"concurrency": 3,
"api_strategy": "wgapi",
"mode": "relogin",
"trigger_source": "manual",
},
created_by=int(current.id),
priority=15,
max_attempts=2,
)
batch_id = runner.batch_id
db.add(
AuditLog(
user_id=current.id,
@@ -675,21 +685,6 @@ def _start_relogin_accounts(
)
)
db.commit()
cookie_relogin_registry.register(batch_id, None, None, runner, owner_id=current.id)
def run_relogin_batch():
try:
runner.run()
except Exception as exc: # noqa: BLE001 外部接口与任务边界需要保留宽泛异常兜底
runner._push_log("error", f"批量重新登录异常: {exc}")
message = f"重新登录异常: {exc}(旧 Cookie 已保留)"
for account_id in account_ids:
runner._mark_account_relogin_stopped(account_id, message)
runner.db.close()
finally:
cookie_relogin_registry.pop(batch_id)
threading.Thread(target=run_relogin_batch, daemon=True).start()
return {
"batch_id": batch_id,
"count": len(account_ids),
@@ -708,15 +703,24 @@ def stop_cookie_relogin(
_require_cookie_operation_perm(current)
batch = cookie_relogin_registry.get(batch_id)
if not batch:
raise HTTPException(
status_code=404, detail="重登批次不存在、已结束或服务已重启"
)
if batch.get("owner_id") != current.id and not user_has_permission(
current, "login:view_all"
):
raise HTTPException(status_code=403, detail="无权限停止该重登批次")
batch["runner"].stop()
job = get_execution_job(db, batch_id=batch_id)
if job is None:
raise HTTPException(
status_code=404, detail="重登批次不存在、已结束或服务已重启"
)
if job.created_by != current.id and not user_has_permission(
current, "login:view_all"
):
raise HTTPException(status_code=403, detail="无权限停止该重登批次")
if job.status in TERMINAL_STATUSES:
raise HTTPException(status_code=404, detail="重登批次已结束")
request_execution_cancel(db, batch_id=batch_id)
else:
if batch.get("owner_id") != current.id and not user_has_permission(
current, "login:view_all"
):
raise HTTPException(status_code=403, detail="无权限停止该重登批次")
batch["runner"].stop()
db.add(
AuditLog(
user_id=current.id,
+264 -33
View File
@@ -3,7 +3,8 @@
from __future__ import annotations
import asyncio
from datetime import UTC, datetime
import secrets
from datetime import UTC, datetime, timedelta
from typing import Any, cast
from weakref import WeakKeyDictionary
@@ -39,10 +40,12 @@ from ..models import (
DouyuConfig,
DouyuEsportsGoodsSnapshot,
DouyuGoodsSnapshot,
DouyuRechargeConfirmation,
DouyuTask,
DouyuWorkbench,
DouyuWorkbenchAccount,
DouyuXpdGoodsSnapshot,
ExecutionJob,
PlatformFulfillmentTask,
User,
)
@@ -89,7 +92,6 @@ from ..services.douyu_activity_query import activity_client, query_activity_good
from ..services.douyu_batch_launcher import (
DOUYU_BATCH_CREATE_CONCURRENCY,
DOUYU_MAX_ACTIVE_BATCHES,
start_douyu_batch,
)
from ..services.douyu_exchange_result_image import (
ExchangeResultImageError,
@@ -112,6 +114,17 @@ from ..services.douyu_service import (
douyu_task_payload,
ensure_douyu_config,
)
from ..services.execution_jobs import (
JOB_DOUYU_BATCH,
LANE_FULFILLMENT,
STATUS_QUEUED,
STATUS_RUNNING,
TERMINAL_STATUSES,
event_payload,
execution_events_after,
get_execution_job,
request_execution_cancel,
)
from ..services.file_service import FileUploadError
from ..services.file_storage import StorageUnavailableError, max_upload_size_bytes
from ..services.platform_fulfillment import service as platform_fulfillment_service
@@ -721,6 +734,9 @@ def _config_out(config: DouyuConfig) -> DouyuConfigOut:
gold_recharge_channel=text("gold_recharge_channel"),
gold_api_product_id=text("gold_api_product_id"),
gold_api_account_template_name=text("gold_api_account_template_name"),
recharge_duplicate_confirm_minutes=number(
"recharge_duplicate_confirm_minutes"
),
gift_id=text("gift_id"),
skin_id=text("skin_id"),
updated_at=config.updated_at,
@@ -1311,11 +1327,127 @@ def list_xpd_goods(
return rows
def _api_recharge_duplicate_guard(
db: Session,
*,
req: DouyuTaskBatchRequest,
current: User,
config: DouyuConfig,
account_ids: list[int],
amount: int,
) -> dict[str, Any] | None:
"""API 直充二次确认:令牌一次性消费,任务与令牌在同一事务落库。"""
normalized_ids = sorted({int(account_id) for account_id in account_ids})
now = datetime.now(UTC)
if req.recharge_confirmation_token:
confirmation = (
db.query(DouyuRechargeConfirmation)
.filter(
DouyuRechargeConfirmation.token
== req.recharge_confirmation_token,
)
.with_for_update()
.first()
)
stored_ids = (
sorted(
{
int(account_id)
for account_id in (confirmation.account_ids_json or [])
}
)
if confirmation
else []
)
if (
confirmation is None
or confirmation.user_id != current.id
or confirmation.used_at is not None
or confirmation.expires_at <= now
or confirmation.amount != amount
or stored_ids != normalized_ids
):
raise HTTPException(
status_code=409,
detail="充值确认已失效,请重新发起充值",
)
confirmation.used_at = now
return None
window_minutes = max(
0,
int(
douyu_config_value(
"recharge_duplicate_confirm_minutes",
config.recharge_duplicate_confirm_minutes,
)
or 0
),
)
if window_minutes <= 0:
return None
cutoff = now - timedelta(minutes=window_minutes)
previous = (
db.query(DouyuTask)
.filter(
DouyuTask.account_id.in_(normalized_ids),
DouyuTask.task_type == "create_gold_qr",
DouyuTask.recharge_channel == "supplier_api",
DouyuTask.recharge_amount == amount,
DouyuTask.recharge_requested_at.isnot(None),
DouyuTask.recharge_requested_at >= cutoff,
DouyuTask.status.notin_(DOUYU_ACTIVE_TASK_STATUSES),
)
.order_by(DouyuTask.id.desc())
.all()
)
if not previous:
return None
duplicate_account_ids = {
int(task.account_id) for task in previous
}
account_rows = (
db.query(Account)
.filter(Account.id.in_(duplicate_account_ids))
.order_by(Account.id.asc())
.all()
)
token = secrets.token_urlsafe(32)
db.add(
DouyuRechargeConfirmation(
token=token,
user_id=int(current.id),
amount=amount,
account_ids_json=normalized_ids,
expires_at=now + timedelta(minutes=5),
)
)
db.commit()
names = [
row.nickname or row.username or row.uid or f"#{row.id}"
for row in account_rows
]
return {
"batch_id": "",
"count": 0,
"requires_confirmation": True,
"confirmation_token": token,
"window_minutes": window_minutes,
"amount": amount,
"account_names": names,
"message": (
f"所选账号在最近 {window_minutes} 分钟内已请求过相同金额的 API 充值,"
"请确认是否继续"
),
"success": False,
}
def _prepare_task_batch(
req: DouyuTaskBatchRequest,
db: Session,
current: User,
) -> tuple[str, int]:
) -> dict[str, Any]:
"""在线程池中完成全部同步 DB 工作,避免阻塞 Uvicorn 事件循环。"""
if not req.account_ids:
raise HTTPException(status_code=400, detail="请选择斗鱼账号")
@@ -1346,14 +1478,53 @@ def _prepare_task_batch(
)
platform_task = db.get(PlatformFulfillmentTask, int(platform_task.id))
active_batch_ids = douyu_batch_registry.active_ids()
cleanup_orphan_douyu_tasks(
db,
active_batch_ids=active_batch_ids,
statuses=DOUYU_ACTIVE_TASK_STATUSES,
message="任务已中断(无执行器接管)",
active_batches = int(
db.query(func.count(ExecutionJob.id))
.filter(
ExecutionJob.job_type == JOB_DOUYU_BATCH,
ExecutionJob.lane_scope == LANE_FULFILLMENT,
ExecutionJob.status.in_((STATUS_QUEUED, STATUS_RUNNING)),
)
.scalar()
or 0
)
_ensure_active_batch_budget(len(active_batch_ids))
_ensure_active_batch_budget(active_batches)
config = ensure_douyu_config(db)
recharge_channel = (
str(
douyu_config_value(
"gold_recharge_channel",
config.gold_recharge_channel,
)
).strip()
if req.task_type == "create_gold_qr"
else ""
)
recharge_amount = (
max(
1,
int(req.payload.get("amount") or req.payload.get("gold_amount") or 1),
)
if req.task_type == "create_gold_qr"
else None
)
if (
req.task_type == "create_gold_qr"
and recharge_channel == "supplier_api"
):
guard = _api_recharge_duplicate_guard(
db,
req=req,
current=current,
config=config,
account_ids=req.account_ids,
amount=int(recharge_amount or 1),
)
if guard is not None:
return guard
task_payload = dict(req.payload)
if req.recharge_confirmation_token:
task_payload["recharge_confirmation_used"] = True
try:
batch_id, count = create_douyu_planned_tasks(
@@ -1362,8 +1533,11 @@ def _prepare_task_batch(
req.task_type,
req.handbook_scope,
current.id,
req.payload,
task_payload,
platform_task_id=req.platform_task_id,
concurrency=req.concurrency,
recharge_channel=recharge_channel,
recharge_amount=recharge_amount,
)
except DouyuActivePaymentError as exc:
raise HTTPException(status_code=409, detail=str(exc)) from exc
@@ -1401,10 +1575,6 @@ def _prepare_task_batch(
)
if req.task_type == "create_gold_qr":
config = ensure_douyu_config(db)
recharge_channel = str(
douyu_config_value("gold_recharge_channel", config.gold_recharge_channel)
).strip()
payment_method = (
"API 直充支付" if recharge_channel == "supplier_api" else "微信扫码支付"
)
@@ -1431,6 +1601,8 @@ def _prepare_task_batch(
"account_count": len(req.account_ids),
"handbook_scope": req.handbook_scope,
"recharge_channel": recharge_channel,
"recharge_amount": recharge_amount,
"recharge_confirmed": bool(req.recharge_confirmation_token),
"payment_method": payment_method,
# 仅记录充值身份,禁止在审计中写入 Cookie、密码等凭据。
"recharge_accounts": [
@@ -1447,7 +1619,7 @@ def _prepare_task_batch(
)
db.commit()
return batch_id, count
return {"batch_id": batch_id, "count": count, "success": True}
@router.post("/tasks/batch")
@@ -1456,26 +1628,14 @@ async def create_task_batch(
db: Session = Depends(get_db),
current: User = Depends(require_permission("douyu:task")),
):
"""创建斗鱼任务记录并启动后台执行器。"""
# 同步 SQLAlchemy 段必须在线程池执行;事件循环只负责最后启动后台线程。
"""创建斗鱼任务记录和持久 execution job。"""
async with _batch_create_semaphore():
batch_id, count = await run_in_threadpool(
return await run_in_threadpool(
_prepare_task_batch,
req,
db,
current,
)
await run_in_threadpool(
start_douyu_batch,
batch_id=batch_id,
task_type=req.task_type,
payload=req.payload,
concurrency=req.concurrency,
loop=asyncio.get_running_loop(),
log_queue=asyncio.Queue(),
)
return {"batch_id": batch_id, "count": count, "success": True}
@router.get("/tasks")
@@ -1664,6 +1824,33 @@ def stop_batch(
.first()
is not None
)
job = get_execution_job(db, batch_id=batch_id)
if job is not None:
if job.status not in TERMINAL_STATUSES:
request_execution_cancel(db, batch_id=batch_id)
if is_recharge_batch:
record_audit(
db,
current,
action="recharge:douyu:stop",
target=f"douyu_batch:{batch_id}",
detail={"batch_id": batch_id, "mode": "durable_queue"},
)
db.commit()
return {"message": "已发送停止信号", "success": True}
cleaned = cleanup_orphan_douyu_tasks(
db,
batch_id=batch_id,
include_durable=True,
message="批次已结束",
)
if cleaned:
return {
"message": f"批次已结束,已清理 {cleaned} 个残留任务",
"success": True,
}
raise HTTPException(status_code=404, detail="批次已结束")
batch = douyu_batch_registry.get(batch_id)
if batch:
if batch.get("finished"):
@@ -1738,9 +1925,53 @@ async def ws_douyu_logs(websocket: WebSocket, batch_id: str):
batch = douyu_batch_registry.get(batch_id)
if not batch:
await websocket.send_json({"level": "error", "message": "批次不存在或已结束"})
await websocket.close()
return
initial_db = WorkerSessionLocal()
try:
job = get_execution_job(initial_db, batch_id=batch_id)
finally:
initial_db.close()
if job is None:
await websocket.send_json(
{"level": "error", "message": "批次不存在或已结束"}
)
await websocket.close()
return
last_event_id = 0
idle_seconds = 0
while True:
poll_db = WorkerSessionLocal()
try:
events = execution_events_after(
poll_db,
batch_id=batch_id,
after_id=last_event_id,
limit=200,
)
job = get_execution_job(poll_db, batch_id=batch_id)
finally:
poll_db.close()
if events:
idle_seconds = 0
for event in events:
last_event_id = int(event.id)
payload = event_payload(event)
await websocket.send_json(payload)
if payload.get("level") == "result":
await asyncio.sleep(0.1)
return
continue
if job is None or job.status in TERMINAL_STATUSES:
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": ""}
)
idle_seconds = 0
log_queue: asyncio.Queue = batch["log_queue"]
try:
+103 -41
View File
@@ -3,7 +3,7 @@
import asyncio
import csv
import io
import threading
import uuid
from datetime import UTC, datetime
from fastapi import (
@@ -19,13 +19,22 @@ from sqlalchemy.orm import Session
from ..database import WorkerSessionLocal, get_db
from ..deps import authenticate_websocket, get_current_user, require_permission
from ..models import Account, LoginTask, User
from ..models import ProxyConfig as ProxyConfigModel
from ..permissions import get_user_permissions, user_has_permission
from ..models import Account, ExecutionJob, LoginTask, User
from ..permissions import user_has_permission
from ..schemas import LOGIN_BATCH_MAX_ACCOUNTS, LoginBatchRequest, LoginTaskOut
from ..services.audit_service import record_audit
from ..services.execution_jobs import (
JOB_LOGIN_BATCH,
LANE_AUTH,
TERMINAL_STATUSES,
enqueue_execution_job,
event_payload,
execution_events_after,
get_execution_job,
request_execution_cancel,
)
from ..services.login_failure import classify_failure, failure_kind_label
from ..services.login_service import LoginBatchRunner, batch_registry
from ..services.login_service import batch_registry
router = APIRouter(prefix="/api/login", tags=["登录任务"])
@@ -161,9 +170,6 @@ async def create_batch(
if not req.account_ids:
raise HTTPException(status_code=400, detail="请选择账号")
# 读取代理配置
proxy = db.query(ProxyConfigModel).first()
# 权限过滤账号
valid_ids = []
seen_ids = set()
@@ -185,35 +191,26 @@ async def create_batch(
action_name = "检测" if req.mode == "check" else "登录"
raise HTTPException(status_code=403, detail=f"没有可{action_name}的账号")
# 在主事件循环中创建 log_queue,传给后台线程
log_queue = asyncio.Queue()
loop = asyncio.get_running_loop()
# 创建执行器(用独立的 DB 会话,因为在线程中运行)
thread_db = WorkerSessionLocal()
runner = LoginBatchRunner(
db=thread_db,
account_ids=valid_ids,
created_by=current.id,
creator_permissions=get_user_permissions(current),
max_login_retries=req.max_login_retries,
max_total_time=req.max_total_time,
proxy_config=proxy,
log_queue=log_queue,
loop=loop,
concurrency=req.concurrency,
api_strategy=req.api_strategy,
mode=req.mode,
batch_id = uuid.uuid4().hex[:12]
enqueue_execution_job(
db,
job_type=JOB_LOGIN_BATCH,
lane_scope=LANE_AUTH,
batch_id=batch_id,
payload={
"account_ids": valid_ids,
"max_login_retries": req.max_login_retries,
"max_total_time": req.max_total_time,
"concurrency": req.concurrency,
"api_strategy": req.api_strategy,
"mode": req.mode,
"trigger_source": "manual",
},
created_by=int(current.id),
priority=20,
max_attempts=2,
)
batch_id = runner.batch_id
# 先注册到批次注册表,再启动线程,确保 WebSocket 连接时能找到
batch_registry.register(batch_id, log_queue, loop, runner)
# 启动线程
thread = threading.Thread(target=runner.run, daemon=True)
thread.start()
db.commit()
# 审计:批次是谁在什么时候发起、多少个账号、什么模式。
# 自动重登与人工登录共用同一条链路,没有这条记录就无法追溯来源。
@@ -671,6 +668,7 @@ def delete_tasks(
@router.post("/stop/{batch_id}")
def stop_batch(
batch_id: str,
db: Session = Depends(get_db),
current: User = Depends(require_permission("login:batch")),
):
batch = batch_registry.get(batch_id)
@@ -681,7 +679,18 @@ def stop_batch(
raise HTTPException(status_code=404, detail="批次已结束")
batch["runner"].stop()
return {"message": "已发送停止信号", "success": True}
raise HTTPException(status_code=404, detail="批次不存在或已结束")
job = get_execution_job(db, batch_id=batch_id)
if job is None:
raise HTTPException(status_code=404, detail="批次不存在")
if job.status in TERMINAL_STATUSES:
raise HTTPException(status_code=404, detail="批次已结束")
if job.created_by != current.id and not user_has_permission(
current, "login:view_all"
):
raise HTTPException(status_code=403, detail="无权停止该批次")
request_execution_cancel(db, batch_id=batch_id)
db.commit()
return {"message": "已发送停止信号", "success": True}
@router.websocket("/ws/login/{batch_id}")
@@ -702,6 +711,15 @@ async def ws_login_logs(websocket: WebSocket, batch_id: str):
.filter(LoginTask.batch_id == batch_id, LoginTask.created_by == user.id)
.first()
)
if not owned:
owned = (
check_db.query(ExecutionJob.id)
.filter(
ExecutionJob.batch_id == batch_id,
ExecutionJob.created_by == user.id,
)
.first()
)
finally:
check_db.close()
if not owned:
@@ -710,12 +728,56 @@ async def ws_login_logs(websocket: WebSocket, batch_id: str):
await websocket.accept()
# 从已注册的批次中获取 log_queue(由 create_batch 创建)
# 同进程兼容模式优先使用内存队列;生产 worker 模式回放数据库事件。
batch = batch_registry.get(batch_id)
if not batch:
await websocket.send_json({"level": "error", "message": "批次不存在或已结束"})
await websocket.close()
return
initial_db = WorkerSessionLocal()
try:
job = get_execution_job(initial_db, batch_id=batch_id)
finally:
initial_db.close()
if job is None:
await websocket.send_json(
{"level": "error", "message": "批次不存在或已结束"}
)
await websocket.close()
return
last_event_id = 0
idle_seconds = 0
while True:
poll_db = WorkerSessionLocal()
try:
events = execution_events_after(
poll_db,
batch_id=batch_id,
after_id=last_event_id,
limit=200,
)
job = get_execution_job(poll_db, batch_id=batch_id)
finally:
poll_db.close()
if events:
idle_seconds = 0
for event in events:
last_event_id = int(event.id)
payload = event_payload(event)
await websocket.send_json(payload)
if payload.get("level") == "result":
await asyncio.sleep(0.1)
return
continue
if job is None or job.status in TERMINAL_STATUSES:
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": ""}
)
idle_seconds = 0
log_queue: asyncio.Queue = batch["log_queue"]
+6
View File
@@ -1522,6 +1522,7 @@ class DouyuConfigOut(BaseModel):
gold_recharge_channel: str = "wechat_qr"
gold_api_product_id: str = "111570"
gold_api_account_template_name: str = "斗鱼昵称"
recharge_duplicate_confirm_minutes: int = 10
gift_id: str = "23643"
skin_id: str = "2942"
updated_at: datetime | None = None
@@ -1551,6 +1552,9 @@ class DouyuConfigOut(BaseModel):
"gold_recharge_channel": self.gold_recharge_channel,
"gold_api_product_id": self.gold_api_product_id,
"gold_api_account_template_name": self.gold_api_account_template_name,
"recharge_duplicate_confirm_minutes": (
self.recharge_duplicate_confirm_minutes
),
"gift_id": self.gift_id,
"skin_id": self.skin_id,
"updated_at": _isoformat(self.updated_at),
@@ -1582,6 +1586,7 @@ class DouyuConfigUpdate(BaseModel):
)
gold_api_product_id: str | None = Field(None, max_length=128)
gold_api_account_template_name: str | None = Field(None, max_length=64)
recharge_duplicate_confirm_minutes: int | None = Field(None, ge=0, le=1440)
gift_id: str | None = None
skin_id: str | None = None
@@ -1754,6 +1759,7 @@ class DouyuTaskBatchRequest(BaseModel):
concurrency: int = Field(3, ge=1, le=10)
payload: dict[str, Any] = Field(default_factory=dict)
platform_task_id: int | None = Field(None, gt=0)
recharge_confirmation_token: str | None = Field(None, max_length=64)
class DouyuWorkbenchAccountsUpdate(BaseModel):
@@ -48,7 +48,7 @@ from loguru import logger
from sqlalchemy import and_, or_
from sqlalchemy.orm import Session
from ....models import AutomationJob, DouyuTask
from ....models import AutomationJob, DouyuTask, ExecutionJob, ExecutionJobEvent
JOB_KEY = "douyu_tasks_retention"
@@ -202,6 +202,53 @@ def run_douyu_tasks_retention(db: Session, job: AutomationJob) -> dict[str, Any]
break
per_pass[label] = deleted_this_pass
deleted_execution_events = 0
deleted_execution_jobs = 0
if batches < max_batches:
event_ids = [
int(row[0])
for row in (
db.query(ExecutionJobEvent.id)
.filter(ExecutionJobEvent.created_at < business_cutoff)
.order_by(ExecutionJobEvent.id.asc())
.limit(batch)
.all()
)
]
if event_ids:
deleted_execution_events = int(
db.query(ExecutionJobEvent)
.filter(ExecutionJobEvent.id.in_(event_ids))
.delete(synchronize_session=False)
or 0
)
batches += 1
db.commit()
if batches < max_batches:
job_ids = [
int(row[0])
for row in (
db.query(ExecutionJob.id)
.filter(
ExecutionJob.status.in_(("succeeded", "failed", "cancelled")),
ExecutionJob.finished_at.isnot(None),
ExecutionJob.finished_at < business_cutoff,
)
.order_by(ExecutionJob.id.asc())
.limit(batch)
.all()
)
]
if job_ids:
deleted_execution_jobs = int(
db.query(ExecutionJob)
.filter(ExecutionJob.id.in_(job_ids))
.delete(synchronize_session=False)
or 0
)
batches += 1
db.commit()
# 注意措辞:这只说明「批次预算用光了」,**不等于**「确实还有积压」——
# 预算在上一档用完时,下一档根本没轮到执行,这里无法区分「没得删」和「没轮到」。
# 所以做成提示而非结论,措辞上也别谎称「仍有积压」。
@@ -224,6 +271,8 @@ def run_douyu_tasks_retention(db: Session, job: AutomationJob) -> dict[str, Any]
"deleted": total_deleted,
"deleted_noise": per_pass.get("noise", 0),
"deleted_rest": per_pass.get("rest", 0),
"deleted_execution_events": deleted_execution_events,
"deleted_execution_jobs": deleted_execution_jobs,
"batches": batches,
"noise_days": noise_days,
"business_days": business_days,
+18 -5
View File
@@ -5,6 +5,7 @@ from __future__ import annotations
import asyncio
import threading
import time
from collections.abc import Callable
from datetime import UTC, datetime, timedelta
from typing import TYPE_CHECKING, Any
@@ -106,6 +107,7 @@ class DouyuBatchRunnerCore:
loop: asyncio.AbstractEventLoop | None = None,
concurrency: int = 3,
close_db: bool = True,
log_sink: Callable[[dict[str, Any]], None] | None = None,
):
self.db = db
self.close_db = close_db
@@ -115,6 +117,7 @@ class DouyuBatchRunnerCore:
self.log_queue = log_queue
self.loop = loop
self.concurrency = clamp_douyu_task_concurrency(task_type, concurrency)
self.log_sink = log_sink
self._stop = threading.Event()
self._counter_lock = threading.Lock()
self._started = 0
@@ -179,6 +182,11 @@ class DouyuBatchRunnerCore:
self.log_queue.put({"level": level, "message": message}),
self.loop,
)
if self.log_sink is not None:
try:
self.log_sink({"level": level, "message": message})
except Exception: # noqa: BLE001 - 日志落库不能中断任务
logger.exception("写入斗鱼批次持久日志失败: {}", self.batch_id)
@staticmethod
def _account_name(account: Account) -> str:
@@ -209,8 +217,6 @@ class DouyuBatchRunnerCore:
def _push_task_event(self, task: DouyuTask) -> None:
"""向批次 WS 推送任务状态事件(level=task),前端即时更新不依赖轮询。"""
if not self.log_queue or not self.loop:
return
try:
payload = douyu_task_payload(task)
except Exception: # noqa: BLE001 外部接口与任务边界需要保留宽泛异常兜底
@@ -221,7 +227,13 @@ class DouyuBatchRunnerCore:
"message": "",
"task": payload,
}
asyncio.run_coroutine_threadsafe(self.log_queue.put(event), self.loop)
if self.log_queue and self.loop:
asyncio.run_coroutine_threadsafe(self.log_queue.put(event), self.loop)
if self.log_sink is not None:
try:
self.log_sink(event)
except Exception: # noqa: BLE001 - 日志落库不能中断任务
logger.exception("写入斗鱼任务事件失败: {}", self.batch_id)
def _sync_platform_fulfillment(self, douyu_task_id: int, *, enabled: bool) -> None:
"""绑定/确认任务完成后立即刷新履约投影并写 Outbox。"""
@@ -358,8 +370,9 @@ class DouyuBatchRunnerCore:
task.next_run_at = now + timedelta(seconds=max(1, int(delay_seconds)))
task.last_run_at = now
if task.run_deadline_at is None:
task.run_deadline_at = now + timedelta(seconds=DOUYU_PAYMENT_POLL_SECONDS)
result["payment_deadline_at"] = task.run_deadline_at.isoformat()
deadline = now + timedelta(seconds=DOUYU_PAYMENT_POLL_SECONDS)
task.run_deadline_at = deadline
result["payment_deadline_at"] = deadline.isoformat()
self._update_task_progress(db, task, "running", message, result)
def _update_task_progress(
+33 -1
View File
@@ -131,6 +131,7 @@ DOUYU_CONFIG_DEFAULTS = {
"gold_recharge_channel": "wechat_qr",
"gold_api_product_id": "111570",
"gold_api_account_template_name": "斗鱼昵称",
"recharge_duplicate_confirm_minutes": 10,
"gift_id": "23643",
"skin_id": "2942",
# 和平小店总开关,默认关(小店当前关闭;关着时一键查询完全跳过它的请求)
@@ -342,6 +343,10 @@ def create_douyu_planned_tasks(
created_by: int,
payload: dict | None = None,
platform_task_id: int | None = None,
concurrency: int = 3,
enqueue_execution: bool = True,
recharge_channel: str = "",
recharge_amount: int | None = None,
) -> tuple[str, int]:
"""创建斗鱼任务记录,等待后台执行器消费。"""
if task_type not in SUPPORTED_DOUYU_TASK_TYPES:
@@ -363,6 +368,7 @@ def create_douyu_planned_tasks(
batch_id = uuid.uuid4().hex[:12]
payload = payload or {}
recharge_requested_at = datetime.now(UTC)
task_rows: list[tuple[DouyuTask, Account]] = []
for account in accounts:
task = DouyuTask(
@@ -376,6 +382,11 @@ def create_douyu_planned_tasks(
result={"payload": payload} if payload else None,
created_by=created_by,
platform_task_id=platform_task_id,
recharge_channel=recharge_channel,
recharge_amount=recharge_amount,
recharge_requested_at=(
recharge_requested_at if recharge_amount is not None else None
),
)
db.add(task)
task_rows.append((task, account))
@@ -404,7 +415,28 @@ def create_douyu_planned_tasks(
}
for task, account in task_rows
]
# 任务行必须先独立提交。账号事件是旁路,不能在持有任务行锁时批量插入。
if task_rows and enqueue_execution:
from .execution_jobs import (
JOB_DOUYU_BATCH,
LANE_FULFILLMENT,
enqueue_execution_job,
)
enqueue_execution_job(
db,
job_type=JOB_DOUYU_BATCH,
lane_scope=LANE_FULFILLMENT,
batch_id=batch_id,
payload={
"task_type": task_type,
"payload": payload,
"concurrency": max(1, min(int(concurrency), 10)),
},
created_by=int(created_by),
priority=40,
max_attempts=2,
)
# 任务行与 execution job 必须同一事务提交;账号事件随后旁路写入。
db.commit()
if events:
try:
+394
View File
@@ -0,0 +1,394 @@
"""跨进程批次执行队列。"""
from __future__ import annotations
import os
import socket
import uuid
from datetime import UTC, datetime, timedelta
from typing import Any
from loguru import logger
from sqlalchemy import or_
from sqlalchemy.orm import Session
from ..database import WorkerSessionLocal
from ..models import ExecutionJob, ExecutionJobEvent
JOB_LOGIN_BATCH = "login_batch"
JOB_RELOGIN_BATCH = "relogin_batch"
JOB_DOUYU_BATCH = "douyu_batch"
JOB_DOUYU_BINDING = "douyu_binding"
LANE_AUTH = "auth"
LANE_FULFILLMENT = "fulfillment"
STATUS_QUEUED = "queued"
STATUS_RUNNING = "running"
STATUS_SUCCEEDED = "succeeded"
STATUS_FAILED = "failed"
STATUS_CANCELLED = "cancelled"
TERMINAL_STATUSES = frozenset({STATUS_SUCCEEDED, STATUS_FAILED, STATUS_CANCELLED})
def _lease_seconds() -> int:
raw = os.getenv("EXECUTION_JOB_LEASE_SECONDS", "90")
try:
return max(30, int(raw))
except ValueError:
return 90
def execution_worker_owner() -> str:
return f"{socket.gethostname()}:{os.getpid()}:{uuid.uuid4().hex[:8]}"
def enqueue_execution_job(
db: Session,
*,
job_type: str,
lane_scope: str,
batch_id: str,
payload: dict[str, Any],
created_by: int,
priority: int = 100,
available_at: datetime | None = None,
max_attempts: int = 2,
) -> ExecutionJob:
existing = (
db.query(ExecutionJob)
.filter(ExecutionJob.batch_id == batch_id)
.first()
)
if existing is not None:
return existing
moment = available_at or datetime.now(UTC)
job = ExecutionJob(
job_type=job_type[:32],
lane_scope=lane_scope[:16],
batch_id=batch_id[:64],
payload_json=payload,
status=STATUS_QUEUED,
priority=int(priority),
available_at=moment.replace(microsecond=0),
created_by=int(created_by),
max_attempts=max(1, int(max_attempts)),
)
db.add(job)
db.flush()
return job
def _recover_expired_jobs(db: Session, now: datetime) -> int:
rows = (
db.query(ExecutionJob)
.filter(
ExecutionJob.status == STATUS_RUNNING,
or_(
ExecutionJob.lease_expires_at.is_(None),
ExecutionJob.lease_expires_at <= now,
),
)
.order_by(ExecutionJob.id.asc())
.with_for_update(skip_locked=True)
.limit(50)
.all()
)
for job in rows:
job.lease_owner = ""
job.lease_expires_at = None
job.heartbeat_at = now
job.updated_at = now
if job.cancel_requested_at is not None:
job.status = STATUS_CANCELLED
job.finished_at = now
job.last_error = "执行租约过期,且已请求取消"
elif int(job.attempt_count or 0) >= int(job.max_attempts or 1):
job.status = STATUS_FAILED
job.finished_at = now
job.last_error = "执行租约过期,重试次数已用尽"
else:
job.status = STATUS_QUEUED
job.available_at = now
job.last_error = "执行租约过期,已重新排队"
if rows:
db.commit()
return len(rows)
def claim_execution_jobs(
*,
lane_scopes: tuple[str, ...],
owner: str,
limit: int = 1,
now: datetime | None = None,
) -> list[ExecutionJob]:
moment = (now or datetime.now(UTC)).replace(microsecond=0)
db = WorkerSessionLocal()
try:
_recover_expired_jobs(db, moment)
rows = (
db.query(ExecutionJob)
.filter(
ExecutionJob.status == STATUS_QUEUED,
ExecutionJob.lane_scope.in_(lane_scopes),
ExecutionJob.available_at <= moment,
)
.order_by(
ExecutionJob.priority.asc(),
ExecutionJob.available_at.asc(),
ExecutionJob.id.asc(),
)
.with_for_update(skip_locked=True)
.limit(max(1, int(limit)))
.all()
)
lease_until = moment + timedelta(seconds=_lease_seconds())
for job in rows:
job.status = STATUS_RUNNING
job.lease_owner = owner
job.lease_expires_at = lease_until
job.heartbeat_at = moment
job.started_at = job.started_at or moment
job.attempt_count = int(job.attempt_count or 0) + 1
job.updated_at = moment
if rows:
db.commit()
for job in rows:
db.refresh(job)
return rows
except Exception:
db.rollback()
raise
finally:
db.close()
def heartbeat_execution_job(
*,
job_id: int,
owner: str,
now: datetime | None = None,
) -> tuple[bool, bool]:
"""返回 (是否仍由本 worker 持有, 是否请求取消)。"""
moment = (now or datetime.now(UTC)).replace(microsecond=0)
db = WorkerSessionLocal()
try:
job = (
db.query(ExecutionJob)
.filter(
ExecutionJob.id == int(job_id),
ExecutionJob.status == STATUS_RUNNING,
ExecutionJob.lease_owner == owner,
)
.with_for_update()
.first()
)
if job is None:
return False, False
job.lease_expires_at = moment + timedelta(seconds=_lease_seconds())
job.heartbeat_at = moment
job.updated_at = moment
cancel_requested = job.cancel_requested_at is not None
db.commit()
return True, cancel_requested
finally:
db.close()
def finish_execution_job(
*,
job_id: int,
owner: str,
status: str,
summary: dict[str, Any] | None = None,
error: str = "",
now: datetime | None = None,
) -> bool:
moment = (now or datetime.now(UTC)).replace(microsecond=0)
db = WorkerSessionLocal()
try:
job = (
db.query(ExecutionJob)
.filter(
ExecutionJob.id == int(job_id),
ExecutionJob.status == STATUS_RUNNING,
ExecutionJob.lease_owner == owner,
)
.with_for_update()
.first()
)
if job is None:
return False
job.status = status
job.summary_json = summary
job.last_error = (error or "")[:4000]
job.lease_owner = ""
job.lease_expires_at = None
job.finished_at = moment
job.updated_at = moment
db.commit()
return True
finally:
db.close()
def fail_execution_job(
*,
job_id: int,
owner: str,
error: str,
retry_delay_seconds: int = 15,
now: datetime | None = None,
) -> bool:
moment = (now or datetime.now(UTC)).replace(microsecond=0)
db = WorkerSessionLocal()
try:
job = (
db.query(ExecutionJob)
.filter(
ExecutionJob.id == int(job_id),
ExecutionJob.status == STATUS_RUNNING,
ExecutionJob.lease_owner == owner,
)
.with_for_update()
.first()
)
if job is None:
return False
job.last_error = (error or "")[:4000]
job.lease_owner = ""
job.lease_expires_at = None
job.updated_at = moment
if job.cancel_requested_at is not None:
job.status = STATUS_CANCELLED
job.finished_at = moment
elif int(job.attempt_count or 0) >= int(job.max_attempts or 1):
job.status = STATUS_FAILED
job.finished_at = moment
else:
job.status = STATUS_QUEUED
job.available_at = moment + timedelta(
seconds=max(1, int(retry_delay_seconds))
)
db.commit()
return True
finally:
db.close()
def request_execution_cancel(
db: Session,
*,
batch_id: str,
now: datetime | None = None,
) -> ExecutionJob | None:
job = (
db.query(ExecutionJob)
.filter(ExecutionJob.batch_id == batch_id)
.with_for_update()
.first()
)
if job is None:
return None
if job.status not in TERMINAL_STATUSES and job.cancel_requested_at is None:
cancelled_at = (now or datetime.now(UTC)).replace(microsecond=0)
job.cancel_requested_at = cancelled_at
job.updated_at = cancelled_at
if job.status == STATUS_QUEUED:
job.status = STATUS_CANCELLED
job.finished_at = cancelled_at
db.flush()
return job
def get_execution_job(
db: Session,
*,
batch_id: str,
) -> ExecutionJob | None:
return (
db.query(ExecutionJob)
.filter(ExecutionJob.batch_id == batch_id)
.first()
)
def append_execution_event(
*,
job_id: int,
batch_id: str,
level: str,
message: str = "",
payload: dict[str, Any] | None = None,
) -> None:
db = WorkerSessionLocal()
try:
db.add(
ExecutionJobEvent(
job_id=int(job_id),
batch_id=batch_id[:64],
level=level[:16],
message=(message or "")[:8000],
payload_json=payload,
)
)
db.commit()
except Exception: # noqa: BLE001 - 日志旁路不能中断任务
db.rollback()
logger.exception("写入执行任务事件失败 job_id={}", job_id)
finally:
db.close()
def execution_events_after(
db: Session,
*,
batch_id: str,
after_id: int = 0,
limit: int = 200,
) -> list[ExecutionJobEvent]:
return (
db.query(ExecutionJobEvent)
.filter(
ExecutionJobEvent.batch_id == batch_id,
ExecutionJobEvent.id > int(after_id),
)
.order_by(ExecutionJobEvent.id.asc())
.limit(max(1, int(limit)))
.all()
)
def event_payload(event: ExecutionJobEvent) -> dict[str, Any]:
payload = dict(event.payload_json or {})
payload.setdefault("level", event.level)
payload.setdefault("message", event.message)
return payload
__all__ = [
"JOB_DOUYU_BATCH",
"JOB_DOUYU_BINDING",
"JOB_LOGIN_BATCH",
"JOB_RELOGIN_BATCH",
"LANE_AUTH",
"LANE_FULFILLMENT",
"STATUS_CANCELLED",
"STATUS_FAILED",
"STATUS_QUEUED",
"STATUS_RUNNING",
"STATUS_SUCCEEDED",
"append_execution_event",
"claim_execution_jobs",
"enqueue_execution_job",
"event_payload",
"execution_events_after",
"execution_worker_owner",
"fail_execution_job",
"finish_execution_job",
"get_execution_job",
"heartbeat_execution_job",
"request_execution_cancel",
]
+312
View File
@@ -0,0 +1,312 @@
"""持久执行任务的 worker 消费循环。"""
from __future__ import annotations
import os
import threading
from concurrent.futures import Future, ThreadPoolExecutor, wait
from datetime import UTC, datetime
from typing import Any
from loguru import logger
from ..database import WorkerSessionLocal
from ..models import DouyuTask, ExecutionJob, ProxyConfig, User
from ..permissions import get_user_permissions
from .douyu_runner import DouyuBatchRunner
from .execution_jobs import (
JOB_DOUYU_BATCH,
JOB_DOUYU_BINDING,
JOB_LOGIN_BATCH,
JOB_RELOGIN_BATCH,
LANE_AUTH,
LANE_FULFILLMENT,
STATUS_CANCELLED,
STATUS_SUCCEEDED,
append_execution_event,
claim_execution_jobs,
execution_worker_owner,
fail_execution_job,
finish_execution_job,
heartbeat_execution_job,
)
from .login_service import LoginBatchRunner
DEFAULT_EXECUTION_WORKERS = 2
DEFAULT_POLL_SECONDS = 1
def _env_positive_int(name: str, default: int, minimum: int = 1) -> int:
try:
value = int(os.getenv(name, str(default)))
except ValueError:
return default
return max(minimum, value)
def _lane_scopes() -> tuple[str, ...]:
raw = os.getenv("EXECUTION_WORKER_LANES", "auth,fulfillment")
allowed = {LANE_AUTH, LANE_FULFILLMENT}
scopes = tuple(
item.strip().lower()
for item in raw.split(",")
if item.strip().lower() in allowed
)
return scopes or (LANE_AUTH, LANE_FULFILLMENT)
class ExecutionJobWorker:
def __init__(self) -> None:
self._stop = threading.Event()
self._thread: threading.Thread | None = None
self._lock = threading.Lock()
self._executor: ThreadPoolExecutor | None = None
self._owner = execution_worker_owner()
def start(self) -> bool:
with self._lock:
if self._thread is not None and self._thread.is_alive():
return False
self._stop.clear()
max_workers = _env_positive_int(
"EXECUTION_WORKER_MAX_JOBS",
DEFAULT_EXECUTION_WORKERS,
)
self._executor = ThreadPoolExecutor(
max_workers=max_workers,
thread_name_prefix="execution-job",
)
self._thread = threading.Thread(
target=self._run,
name="execution-job-consumer",
daemon=True,
)
self._thread.start()
logger.info(
"执行任务 worker 已启动 lanes={} max_jobs={}",
",".join(_lane_scopes()),
max_workers,
)
return True
def stop(self) -> None:
self._stop.set()
with self._lock:
thread = self._thread
executor = self._executor
self._thread = None
self._executor = None
if thread is not None and thread.is_alive():
thread.join(timeout=5)
if executor is not None:
executor.shutdown(wait=True, cancel_futures=True)
def _run(self) -> None:
futures: set[Future] = set()
max_jobs = _env_positive_int(
"EXECUTION_WORKER_MAX_JOBS",
DEFAULT_EXECUTION_WORKERS,
)
poll_seconds = _env_positive_int(
"EXECUTION_WORKER_POLL_SECONDS",
DEFAULT_POLL_SECONDS,
)
while not self._stop.is_set():
futures = {future for future in futures if not future.done()}
executor = self._executor
if executor is None:
break
slots = max_jobs - len(futures)
if slots > 0:
try:
jobs = claim_execution_jobs(
lane_scopes=_lane_scopes(),
owner=self._owner,
limit=slots,
)
except Exception: # noqa: BLE001 - 消费循环必须存活
logger.exception("领取执行任务失败")
jobs = []
for job in jobs:
futures.add(executor.submit(self._run_job, job.id))
if futures:
wait(futures, timeout=poll_seconds)
else:
self._stop.wait(poll_seconds)
def _run_job(self, job_id: int) -> None:
db = WorkerSessionLocal()
job: ExecutionJob | None = None
runner: Any = None
cancelled = threading.Event()
heartbeat_stop = threading.Event()
try:
job = db.get(ExecutionJob, int(job_id))
if job is None or job.status != "running":
return
payload = dict(job.payload_json or {})
user = db.get(User, int(job.created_by))
if user is None:
raise RuntimeError("执行任务创建人不存在")
def log_sink(event: dict[str, Any]) -> None:
event_payload = dict(event)
level = str(event_payload.pop("level", "info") or "info")
message = str(event_payload.pop("message", "") or "")
append_execution_event(
job_id=int(job.id),
batch_id=job.batch_id,
level=level,
message=message,
payload=event_payload or None,
)
def heartbeat_loop() -> None:
while not heartbeat_stop.wait(5):
if self._stop.is_set():
cancelled.set()
if runner is not None:
runner.stop()
return
held, cancel_requested = heartbeat_execution_job(
job_id=int(job.id),
owner=self._owner,
)
if not held:
cancelled.set()
return
if cancel_requested and not cancelled.is_set():
cancelled.set()
if runner is not None:
runner.stop()
log_sink(
{
"level": "warning",
"message": "收到停止请求,正在安全收尾",
}
)
heartbeat = threading.Thread(
target=heartbeat_loop,
name=f"execution-heartbeat-{job.id}",
daemon=True,
)
heartbeat.start()
summary: dict[str, Any] = {}
if job.job_type in {JOB_LOGIN_BATCH, JOB_RELOGIN_BATCH}:
proxy = db.query(ProxyConfig).first()
runner = LoginBatchRunner(
db=db,
account_ids=[
int(value)
for value in payload.get("account_ids", [])
],
created_by=int(job.created_by),
creator_permissions=get_user_permissions(user),
max_login_retries=int(payload.get("max_login_retries", 0) or 0),
max_total_time=float(payload.get("max_total_time", 300) or 0),
proxy_config=proxy,
log_queue=None,
loop=None,
concurrency=int(payload.get("concurrency", 3) or 3),
api_strategy=str(payload.get("api_strategy", "wgapi") or "wgapi"),
mode=str(payload.get("mode", "login") or "login"),
trigger_source=str(payload.get("trigger_source", "manual") or "manual"),
batch_id=job.batch_id,
log_sink=log_sink,
)
runner.run()
elif job.job_type in {JOB_DOUYU_BATCH, JOB_DOUYU_BINDING}:
if int(job.attempt_count or 0) > 1:
# 进程中断会留下 pending/running 的初始任务;支付轮询有独立
# queue_lane,不能被重放。重试只重置尚无后置 lane 的行。
db.query(DouyuTask).filter(
DouyuTask.batch_id == job.batch_id,
DouyuTask.status.in_(("planned", "pending", "running")),
DouyuTask.queue_lane == "",
).update(
{
DouyuTask.status: "planned",
DouyuTask.message: "执行进程中断,已恢复排队",
},
synchronize_session=False,
)
db.commit()
runner = DouyuBatchRunner(
db=db,
batch_id=job.batch_id,
task_type=str(payload.get("task_type") or ""),
payload=dict(payload.get("payload") or {}),
log_queue=None,
loop=None,
concurrency=int(payload.get("concurrency", 3) or 3),
close_db=False,
log_sink=log_sink,
)
runner.run()
else:
raise RuntimeError(f"不支持的执行任务类型: {job.job_type}")
summary = {"finished_at": datetime.now(UTC).isoformat()}
held, cancel_requested = heartbeat_execution_job(
job_id=int(job.id),
owner=self._owner,
)
if not held:
return
finish_execution_job(
job_id=int(job.id),
owner=self._owner,
status=(
STATUS_CANCELLED
if cancelled.is_set() or cancel_requested
else STATUS_SUCCEEDED
),
summary=summary,
)
except Exception as exc: # noqa: BLE001 - job 边界必须收口
logger.exception("执行任务失败 job_id={}", job_id)
append_execution_event(
job_id=int(job_id),
batch_id=str(job.batch_id) if job is not None else "",
level="error",
message=f"{type(exc).__name__}: {exc}",
)
fail_execution_job(
job_id=int(job_id),
owner=self._owner,
error=f"{type(exc).__name__}: {exc}",
)
finally:
heartbeat_stop.set()
db.close()
execution_job_worker = ExecutionJobWorker()
def start_execution_job_worker() -> bool:
return execution_job_worker.start()
def stop_execution_job_worker() -> None:
execution_job_worker.stop()
def execution_job_worker_status() -> dict[str, Any]:
thread = execution_job_worker._thread
return {
"running": bool(thread and thread.is_alive()),
"lanes": list(_lane_scopes()),
"max_jobs": _env_positive_int(
"EXECUTION_WORKER_MAX_JOBS",
DEFAULT_EXECUTION_WORKERS,
),
"owner": execution_job_worker._owner,
}
__all__ = [
"execution_job_worker_status",
"start_execution_job_worker",
"stop_execution_job_worker",
]
+12 -3
View File
@@ -5,10 +5,11 @@ import os
import threading
import time
import uuid
from collections.abc import Callable
from concurrent.futures import as_completed
from datetime import UTC, datetime
from types import SimpleNamespace
from typing import cast
from typing import Any, cast
from loguru import logger
from sqlalchemy import and_, func, or_
@@ -292,7 +293,7 @@ def _persist_login_cookie_verification(
"identity": {
"uid": account.uid,
"username": account.username,
"nickname": detail.get("nickname") or "",
"nickname": (detail or {}).get("nickname") or "",
"nickname_source": "session",
},
"session": check_result,
@@ -338,6 +339,8 @@ class LoginBatchRunner:
api_strategy: str = "wgapi",
mode: str = "login",
trigger_source: str = "manual",
batch_id: str | None = None,
log_sink: Callable[[dict[str, Any]], None] | None = None,
):
self.db = db
self.account_ids = account_ids
@@ -350,7 +353,8 @@ class LoginBatchRunner:
self.proxy_config = _snapshot_proxy_config(proxy_config)
self.log_queue = log_queue
self.loop = loop
self.batch_id = uuid.uuid4().hex[:12]
self.batch_id = (batch_id or uuid.uuid4().hex[:12])[:64]
self.log_sink = log_sink
self.concurrency = max(
1,
min(concurrency, 10, login_concurrency_limit(db)),
@@ -441,6 +445,11 @@ class LoginBatchRunner:
self.log_queue.put({"level": level, "message": message}),
self.loop,
)
if self.log_sink is not None:
try:
self.log_sink({"level": level, "message": message})
except Exception: # noqa: BLE001 - 日志落库不能中断登录
logger.exception("写入登录批次持久日志失败: {}", self.batch_id)
def _resolve_static_proxy(self) -> tuple[dict | None, str]:
"""解析静态代理配置。"""
@@ -21,7 +21,11 @@ from ..account_binding import (
pending_binding_role_from_result,
)
from ..business_events import record_douyu_task_started
from ..douyu_batch_launcher import start_douyu_batch
from ..execution_jobs import (
JOB_DOUYU_BINDING,
LANE_FULFILLMENT,
enqueue_execution_job,
)
from .binding_status import (
_binding_failure_issue,
_binding_failure_raw_message,
@@ -129,14 +133,21 @@ def start_binding_sync(
detail={"bindTaskId": bind_task.id},
)
_emit_order_site_binding_state(db, task.id)
db.commit()
start_douyu_batch(
enqueue_execution_job(
db,
job_type=JOB_DOUYU_BINDING,
lane_scope=LANE_FULFILLMENT,
batch_id=batch_id,
task_type="get_bind_qr",
payload={},
concurrency=1,
capture_event_loop=False,
payload={
"task_type": "get_bind_qr",
"payload": {},
"concurrency": 1,
},
created_by=int(current.id),
priority=10,
max_attempts=2,
)
db.commit()
return get_task_detail(db, task.id)
@@ -368,14 +379,21 @@ def confirm_binding_sync(db: Session, *, task_id: int, current: User) -> dict[st
detail={"confirmTaskId": confirm_task.id},
)
_emit_order_site_binding_state(db, task.id)
db.commit()
start_douyu_batch(
enqueue_execution_job(
db,
job_type=JOB_DOUYU_BINDING,
lane_scope=LANE_FULFILLMENT,
batch_id=batch_id,
task_type="confirm_bind",
payload={},
concurrency=1,
capture_event_loop=False,
payload={
"task_type": "confirm_bind",
"payload": {},
"concurrency": 1,
},
created_by=int(current.id),
priority=10,
max_attempts=1,
)
db.commit()
return get_task_detail(db, task.id)