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