"""后台服务生命周期:调度、轮询、Outbox 与履约 worker。""" 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: return os.getenv("BACKGROUND_CONTROL_PLANE_ENABLED", "true").strip().lower() not in { "0", "false", "no", "off", } 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 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 from .services.douyu_service import cleanup_orphan_douyu_tasks from .services.huya_service import cleanup_orphan_huya_tasks from .services.login_quota_service import cleanup_orphan_login_attempts from .services.login_service import ( cleanup_orphan_login_tasks, cleanup_orphan_relogin_tasks, ) from .services.platform_fulfillment.service import ( reconcile_binding_observations, ) from .services.yyb_service import cleanup_orphan_yyb_tasks 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="任务已中断(服务重启)", ) if cleaned_huya: logger.info("启动清理虎牙残留任务: {} 条", cleaned_huya) cleaned_douyu = cleanup_orphan_douyu_tasks( db, active_batch_ids=durable_batch_ids, message="任务已中断(服务重启)", ) if cleaned_douyu: logger.info("启动清理斗鱼残留任务: {} 条", cleaned_douyu) cleaned_relogin = cleanup_orphan_relogin_tasks(db) if cleaned_relogin: logger.info("启动清理 CK 重登残留任务: {} 条", cleaned_relogin) cleaned_runs = cleanup_orphan_runs(db) if cleaned_runs: logger.info("启动收尾中断的自动化运行记录: {} 条", cleaned_runs) cleaned_login = cleanup_orphan_login_tasks(db) if cleaned_login: logger.info("启动清理登录残留任务: {} 条", cleaned_login) cleaned_attempts = cleanup_orphan_login_attempts(db) if cleaned_attempts: logger.info("启动收敛中断的登录尝试流水: {} 条", cleaned_attempts) recovered_work = recover_running_account_work(db) if recovered_work: logger.info("启动恢复中断的账号内部工作项: {} 条", recovered_work) reconciled_bindings = reconcile_binding_observations(db) if reconciled_bindings: logger.info( "启动收敛履约绑定证据: {} 条", reconciled_bindings, ) seeded_targets = ensure_default_supply_targets(db) if seeded_targets: logger.info("已建立默认账号供给目标: {} 条", seeded_targets) cleaned_yyb = cleanup_orphan_yyb_tasks( db, message="任务已中断(服务重启)", ) if cleaned_yyb: logger.info("启动清理应用宝残留任务: {} 条", cleaned_yyb) finally: db.close() def start_background_services() -> bool: global _started if _started: 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 ( start_platform_fulfillment_auto_allocator, ) from .services.platform_fulfillment.reconciler import ( start_platform_fulfillment_reconciler, ) 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() _start_runtime_heartbeat() _started = True logger.info("后台服务已启动") return True def stop_background_services() -> None: global _started if not _started: 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 ( stop_platform_fulfillment_auto_allocator, ) from .services.platform_fulfillment.reconciler import ( stop_platform_fulfillment_reconciler, ) 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() _stop_runtime_heartbeat() _started = False logger.info("后台服务已停止") __all__ = [ "background_runtime_status", "recover_orphaned_work", "start_background_services", "stop_background_services", ]