"""跨进程批次执行队列。""" from __future__ import annotations import os import socket import threading import time import uuid from collections import deque 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_events(events: list[dict[str, Any]]) -> bool: """批量写入执行任务日志事件,避免高频单条写库占满连接池。""" if not events: return True db = WorkerSessionLocal() try: db.add_all( [ ExecutionJobEvent( job_id=int(item["job_id"]), batch_id=str(item["batch_id"])[:64], level=str(item.get("level") or "info")[:16], message=str(item.get("message") or "")[:8000], payload_json=item.get("payload") or None, ) for item in events ] ) db.commit() return True except Exception: # noqa: BLE001 - 日志旁路不能中断任务 db.rollback() logger.exception("批量写入执行任务事件失败 count={}", len(events)) return False finally: db.close() def append_execution_event( *, job_id: int, batch_id: str, level: str, message: str = "", payload: dict[str, Any] | None = None, ) -> None: append_execution_events( [ { "job_id": int(job_id), "batch_id": batch_id, "level": level, "message": message, "payload": payload, } ] ) class ExecutionEventBatchWriter: """后台聚合写入执行事件,严格保持 FIFO 顺序并遵守 flush 超时上限。""" def __init__( self, *, flush_interval: float = 0.2, batch_size: int = 64, ) -> None: self._flush_interval = max(0.05, float(flush_interval)) self._batch_size = max(1, int(batch_size)) self._cond = threading.Condition() self._write_lock = threading.Lock() self._queue: deque[dict[str, Any]] = deque() self._flushing = False self._stop = False self._thread: threading.Thread | None = None self._failed_batches = 0 def start(self) -> None: with self._cond: if self._thread is not None and self._thread.is_alive(): return self._stop = False self._thread = threading.Thread( target=self._run, name="execution-event-writer", daemon=True, ) self._thread.start() def is_running(self) -> bool: with self._cond: return self._thread is not None and self._thread.is_alive() def status(self) -> dict[str, Any]: with self._cond: return { "running": self._thread is not None and self._thread.is_alive(), "pending": len(self._queue), "flushing": self._flushing, "failed_batches": self._failed_batches, } def _drain_sync(self) -> bool: """在后台线程未运行时按 FIFO 同步写完队列中剩余事件。""" with self._write_lock: with self._cond: remaining = list(self._queue) self._queue.clear() if not remaining: return True return append_execution_events(remaining) def stop(self, timeout: float = 5.0) -> bool: with self._cond: self._stop = True self._cond.notify_all() thread = self._thread if thread is not None and thread.is_alive(): thread.join(timeout=max(0.05, float(timeout))) with self._cond: still_alive = thread is not None and thread.is_alive() if not still_alive: self._thread = None if still_alive: # 后台线程仍在写库:保留线程与队列交由它按 FIFO 继续排空,不插队也不丢引用 return False return self._drain_sync() def enqueue( self, *, job_id: int, batch_id: str, level: str, message: str = "", payload: dict[str, Any] | None = None, ) -> None: item = { "job_id": int(job_id), "batch_id": batch_id, "level": level, "message": message, "payload": payload, } with self._cond: if self._thread is not None and self._thread.is_alive(): self._queue.append(item) if len(self._queue) >= self._batch_size: self._cond.notify_all() return self._queue.append(item) self._drain_sync() def flush(self, timeout: float = 5.0) -> bool: deadline = time.monotonic() + max(0.05, float(timeout)) with self._cond: thread = self._thread if thread is None or not thread.is_alive(): need_sync = bool(self._queue) self._thread = None else: need_sync = False self._cond.notify_all() while self._queue or self._flushing: left = deadline - time.monotonic() if left <= 0: return False self._cond.wait(timeout=min(left, 0.05)) return True if need_sync: return self._drain_sync() return True def _run(self) -> None: while True: batch: list[dict[str, Any]] = [] with self._cond: while not self._queue and not self._stop: self._cond.wait(timeout=self._flush_interval) if not self._queue and self._stop: self._cond.notify_all() return while self._queue and len(batch) < self._batch_size: batch.append(self._queue.popleft()) self._flushing = True try: with self._write_lock: ok = append_execution_events(batch) if not ok: with self._cond: self._failed_batches += 1 finally: with self._cond: self._flushing = False self._cond.notify_all() 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", "ExecutionEventBatchWriter", "append_execution_event", "append_execution_events", "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", ]