fix(douyu): unify binding state and scheduler health
This commit is contained in:
@@ -2,13 +2,23 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import threading
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from loguru import logger
|
||||
|
||||
from .database import SessionLocal
|
||||
|
||||
_started = False
|
||||
_heartbeat_thread: threading.Thread | None = None
|
||||
_heartbeat_stop = threading.Event()
|
||||
_heartbeat_lock = threading.Lock()
|
||||
_HEARTBEAT_INTERVAL_SECONDS = 5
|
||||
_HEARTBEAT_STALE_SECONDS = 30
|
||||
|
||||
|
||||
def _control_plane_enabled() -> bool:
|
||||
@@ -20,6 +30,103 @@ def _control_plane_enabled() -> bool:
|
||||
}
|
||||
|
||||
|
||||
def _runtime_heartbeat_path() -> Path:
|
||||
configured = os.getenv("BACKGROUND_RUNTIME_HEARTBEAT_PATH", "").strip()
|
||||
if configured:
|
||||
return Path(configured)
|
||||
return Path(__file__).resolve().parents[2] / "data" / "background_runtime.json"
|
||||
|
||||
|
||||
def _runtime_heartbeat_payload() -> dict[str, Any]:
|
||||
from .services.automation.scheduler import scheduler_status
|
||||
|
||||
return {
|
||||
"pid": os.getpid(),
|
||||
"updatedAt": datetime.now(UTC).isoformat(),
|
||||
"scheduler": scheduler_status(),
|
||||
}
|
||||
|
||||
|
||||
def _write_runtime_heartbeat() -> None:
|
||||
path = _runtime_heartbeat_path()
|
||||
try:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
temporary = path.with_suffix(f"{path.suffix}.tmp")
|
||||
temporary.write_text(
|
||||
json.dumps(_runtime_heartbeat_payload(), ensure_ascii=False),
|
||||
encoding="utf-8",
|
||||
)
|
||||
temporary.replace(path)
|
||||
except Exception: # noqa: BLE001 - heartbeat must not stop background services
|
||||
logger.exception("写入后台运行时心跳失败: {}", path)
|
||||
|
||||
|
||||
def _heartbeat_loop() -> None:
|
||||
while not _heartbeat_stop.wait(_HEARTBEAT_INTERVAL_SECONDS):
|
||||
_write_runtime_heartbeat()
|
||||
|
||||
|
||||
def _start_runtime_heartbeat() -> None:
|
||||
global _heartbeat_thread
|
||||
with _heartbeat_lock:
|
||||
if _heartbeat_thread is not None and _heartbeat_thread.is_alive():
|
||||
return
|
||||
_heartbeat_stop.clear()
|
||||
_write_runtime_heartbeat()
|
||||
_heartbeat_thread = threading.Thread(
|
||||
target=_heartbeat_loop,
|
||||
name="background-runtime-heartbeat",
|
||||
daemon=True,
|
||||
)
|
||||
_heartbeat_thread.start()
|
||||
|
||||
|
||||
def _stop_runtime_heartbeat() -> None:
|
||||
global _heartbeat_thread
|
||||
with _heartbeat_lock:
|
||||
thread = _heartbeat_thread
|
||||
_heartbeat_thread = None
|
||||
_heartbeat_stop.set()
|
||||
if thread is not None and thread.is_alive():
|
||||
thread.join(timeout=2)
|
||||
try:
|
||||
_runtime_heartbeat_path().unlink(missing_ok=True)
|
||||
except OSError:
|
||||
logger.exception("清理后台运行时心跳失败")
|
||||
|
||||
|
||||
def background_runtime_status() -> dict[str, Any]:
|
||||
"""读取独立后台进程心跳;API 进程据此展示真实调度状态。"""
|
||||
path = _runtime_heartbeat_path()
|
||||
try:
|
||||
payload = json.loads(path.read_text(encoding="utf-8"))
|
||||
heartbeat_at = datetime.fromisoformat(str(payload.get("updatedAt") or ""))
|
||||
if heartbeat_at.tzinfo is None:
|
||||
heartbeat_at = heartbeat_at.replace(tzinfo=UTC)
|
||||
age_seconds = max(
|
||||
0.0,
|
||||
(datetime.now(UTC) - heartbeat_at).total_seconds(),
|
||||
)
|
||||
except (OSError, ValueError, TypeError, json.JSONDecodeError):
|
||||
return {
|
||||
"running": False,
|
||||
"heartbeatAt": None,
|
||||
"ageSeconds": None,
|
||||
"staleAfterSeconds": _HEARTBEAT_STALE_SECONDS,
|
||||
"pid": None,
|
||||
"scheduler": {},
|
||||
}
|
||||
scheduler = payload.get("scheduler")
|
||||
return {
|
||||
"running": age_seconds <= _HEARTBEAT_STALE_SECONDS,
|
||||
"heartbeatAt": heartbeat_at.isoformat(),
|
||||
"ageSeconds": round(age_seconds, 1),
|
||||
"staleAfterSeconds": _HEARTBEAT_STALE_SECONDS,
|
||||
"pid": payload.get("pid"),
|
||||
"scheduler": scheduler if isinstance(scheduler, dict) else {},
|
||||
}
|
||||
|
||||
|
||||
def recover_orphaned_work() -> None:
|
||||
"""进程启动时收敛上次中断的任务和运行记录。"""
|
||||
from .models import ExecutionJob
|
||||
@@ -111,6 +218,7 @@ def start_background_services() -> bool:
|
||||
start_platform_fulfillment_auto_allocator()
|
||||
start_binding_poll_scheduler()
|
||||
start_payment_poll_scheduler()
|
||||
_start_runtime_heartbeat()
|
||||
_started = True
|
||||
logger.info("后台服务已启动")
|
||||
return True
|
||||
@@ -140,11 +248,13 @@ def stop_background_services() -> None:
|
||||
stop_integration_outbox_worker()
|
||||
stop_scheduler()
|
||||
stop_execution_job_worker()
|
||||
_stop_runtime_heartbeat()
|
||||
_started = False
|
||||
logger.info("后台服务已停止")
|
||||
|
||||
|
||||
__all__ = [
|
||||
"background_runtime_status",
|
||||
"recover_orphaned_work",
|
||||
"start_background_services",
|
||||
"stop_background_services",
|
||||
|
||||
Reference in New Issue
Block a user