feat(automation): 持久执行队列与重复充值确认
This commit is contained in:
@@ -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,
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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",
|
||||
]
|
||||
@@ -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",
|
||||
]
|
||||
@@ -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)
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user