feat(shipping-notice): 增加 RPA Worker 心跳上报与状态查询功能
This commit is contained in:
1 parent
c3f05ba96b
commit
5a147c4d85
49 files changed
+4032
-1500
No files matched your search
@@ -13,6 +13,7 @@ from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ServiceUnavailableError
|
||||
from app.models import ShippingTask, ShippingTaskEvent
|
||||
from app.services.shipping_notice.constants import CP_INVENTORY_SOURCE_REVIEW, CP_UPLOAD_REQ, PH_RPA_PENDING
|
||||
from app.services.shipping_notice.inventory_snapshot import ingest_inventory_file
|
||||
@@ -38,6 +39,7 @@ from app.services.shipping_notice.rpa import (
|
||||
inventory_processed_dir,
|
||||
write_inventory_export_trigger_for_task,
|
||||
)
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat import RPA_WORKER_OFFLINE_MESSAGE
|
||||
from app.services.shipping_notice.rpa_attempts import (
|
||||
inventory_rpa_attempts,
|
||||
max_rpa_inventory_attempts,
|
||||
@@ -475,14 +477,19 @@ def ensure_inventory_via_rpa(task: ShippingTask, *, mode: str) -> dict[str, Any]
|
||||
# [STEP 3] 触发下一次 RPA 导出或给出人工兜底提示。
|
||||
# 触发成功则推进到 pending;触发失败则明确要求用户改走手工上传。
|
||||
attempt_no = attempts + 1
|
||||
trigger = write_inventory_export_trigger_for_task(
|
||||
task.task_no,
|
||||
rpa_source,
|
||||
payload={
|
||||
"mode": mode,
|
||||
"attempt": attempt_no,
|
||||
},
|
||||
)
|
||||
try:
|
||||
trigger = write_inventory_export_trigger_for_task(
|
||||
task.task_no,
|
||||
rpa_source,
|
||||
payload={
|
||||
"mode": mode,
|
||||
"attempt": attempt_no,
|
||||
},
|
||||
)
|
||||
except ServiceUnavailableError as exc:
|
||||
trigger = None
|
||||
detail_message = str((exc.details or {}).get("detail_message") or exc.message or RPA_WORKER_OFFLINE_MESSAGE)
|
||||
task.error_message = detail_message[:500]
|
||||
if trigger:
|
||||
apply_task_transition(task, TaskTransition.RPA_PENDING)
|
||||
task.error_message = None
|
||||
@@ -534,24 +541,31 @@ def ensure_inventory_via_rpa(task: ShippingTask, *, mode: str) -> dict[str, Any]
|
||||
)
|
||||
|
||||
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
|
||||
task.error_message = "RPA 库存目录未配置或触发失败"
|
||||
offline_message = (task.error_message or "").strip()
|
||||
if offline_message == RPA_WORKER_OFFLINE_MESSAGE:
|
||||
human_message = RPA_WORKER_OFFLINE_MESSAGE
|
||||
detail = "请启动 Windows RPA 服务后重试,或手动上传货代库存 Excel。"
|
||||
else:
|
||||
human_message = "RPA 库存目录未配置或触发失败"
|
||||
detail = "请重新获取库存,或手动上传货代库存 Excel。"
|
||||
task.error_message = human_message[:500]
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step3_inventory_prepare",
|
||||
step_title="获取库存",
|
||||
status="needs_human",
|
||||
message="RPA 库存触发失败",
|
||||
message=human_message,
|
||||
progress_percent=100,
|
||||
current=0,
|
||||
total=max_attempts,
|
||||
detail="请重新获取库存,或手动上传货代库存 Excel。",
|
||||
detail=detail,
|
||||
)
|
||||
log_task_event(task, "inventory_rpa_retry_requested", {"reason": "trigger_failed"})
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message="RPA 库存目录未配置或触发失败。请上传货代库存 Excel。",
|
||||
message=f"{human_message}。请上传货代库存 Excel。" if human_message != RPA_WORKER_OFFLINE_MESSAGE else human_message,
|
||||
data=serialize_task_for_tool(task),
|
||||
checkpoint=CP_UPLOAD_REQ,
|
||||
)
|
||||
|
||||
@@ -79,8 +79,11 @@ def write_inventory_export_trigger(task_no: str, payload: dict[str, Any] | None
|
||||
写入 RPA 库存导出触发文件 inventory_export_{task_no}.json。
|
||||
|
||||
Returns:
|
||||
str | None: 触发文件绝对路径;目录未配置时返回 None。
|
||||
str | None: 触发文件绝对路径;目录未配置或 worker 未就绪时返回 None。
|
||||
"""
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat import assert_inventory_rpa_worker_ready
|
||||
|
||||
assert_inventory_rpa_worker_ready()
|
||||
trigger_dir = inventory_trigger_dir()
|
||||
if not trigger_dir:
|
||||
return None
|
||||
@@ -114,6 +117,9 @@ def write_inventory_export_batch_trigger(
|
||||
Returns:
|
||||
str | None: 触发文件绝对路径。
|
||||
"""
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat import assert_inventory_rpa_worker_ready
|
||||
|
||||
assert_inventory_rpa_worker_ready()
|
||||
trigger_dir = inventory_trigger_dir()
|
||||
if not trigger_dir or not sources:
|
||||
return None
|
||||
|
||||
@@ -0,0 +1,575 @@
|
||||
"""
|
||||
services/shipping_notice/rpa_worker_heartbeat.py
|
||||
|
||||
用途:货代库存 RPA Worker 心跳存储、共享目录校验、就绪检查与状态查询。
|
||||
依赖:Flask current_app、redis_client、shipping_notice.rpa(目录与 mock 模式)。
|
||||
逻辑:freight_rpa_worker 调 POST /rpa/heartbeat;写 trigger 前由 rpa / inventory_rpa_workflow / shipping_inventory_rpa_job 调用就绪检查。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from app.core.config.settings import _normalize_env_name
|
||||
from app.core.errors import ServiceUnavailableError
|
||||
from app.services.shipping_notice.rpa import inventory_trigger_dir, rpa_runtime_mode
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
RPA_WORKER_OFFLINE_MESSAGE = "RPA Worker 未在线,请启动 Windows RPA 服务后重试"
|
||||
RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE = "RPA Worker 心跳存储不可用,请检查 Redis 连接"
|
||||
INVENTORY_EXPORT_CAPABILITY = "inventory_export"
|
||||
_REDIS_INDEX_KEY = "shipping:rpa:heartbeat:index"
|
||||
_REDIS_WORKER_KEY_PREFIX = "shipping:rpa:heartbeat:worker:"
|
||||
_MEMORY_STORE: dict[str, dict[str, Any]] = {}
|
||||
_MEMORY_LOCK = threading.Lock()
|
||||
|
||||
_REASON_USER_HINTS: dict[str, str] = {
|
||||
"no_worker_heartbeat": "未收到任何 Worker 心跳",
|
||||
"heartbeat_storage_unavailable": "心跳存储不可用(Redis)",
|
||||
"trigger_dir_not_configured": "后端未配置库存 trigger 目录",
|
||||
"trigger_dir_not_accessible": "trigger 目录不存在或不可访问",
|
||||
"shared_sentinel_missing": "共享目录哨兵文件缺失,可能 CIFS 未挂载",
|
||||
"shared_scope_mismatch": "共享目录 scope 与后端配置不一致",
|
||||
"trigger_dir_not_writable": "trigger 目录不可写",
|
||||
"environment_mismatch": "Worker 环境与后端环境不一致",
|
||||
"missing_inventory_export_capability": "Worker 未声明 inventory_export 能力",
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class RpaWorkerReadiness:
|
||||
"""库存 RPA 触发前就绪检查结果。"""
|
||||
|
||||
ready: bool
|
||||
message: str
|
||||
workers: list[dict[str, Any]] = field(default_factory=list)
|
||||
reasons: list[str] = field(default_factory=list)
|
||||
checked_at: str = ""
|
||||
detail_message: str = ""
|
||||
|
||||
|
||||
def _utc_now_iso() -> str:
|
||||
return datetime.now(timezone.utc).replace(tzinfo=None).isoformat()
|
||||
|
||||
|
||||
def _config_bool(key: str, default: bool) -> bool:
|
||||
if current_app:
|
||||
raw = current_app.config.get(key, default)
|
||||
else:
|
||||
raw = os.getenv(key, str(default).lower())
|
||||
return str(raw).strip().lower() in {"1", "true", "yes", "on"}
|
||||
|
||||
|
||||
def _config_str(key: str, default: str = "") -> str:
|
||||
if current_app:
|
||||
raw = current_app.config.get(key, default)
|
||||
else:
|
||||
raw = os.getenv(key, default)
|
||||
return str(raw or default).strip()
|
||||
|
||||
|
||||
def _heartbeat_ttl_seconds() -> int:
|
||||
raw = 90
|
||||
if current_app:
|
||||
raw = int(current_app.config.get("SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS") or 90)
|
||||
else:
|
||||
raw = int(os.getenv("SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS") or "90")
|
||||
return max(60, raw)
|
||||
|
||||
|
||||
def _heartbeat_check_required() -> bool:
|
||||
"""Mock RPA 或显式关闭时跳过 worker 心跳就绪检查。"""
|
||||
if rpa_runtime_mode().get("mock"):
|
||||
return False
|
||||
return _config_bool("SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED", True)
|
||||
|
||||
|
||||
def _heartbeat_redis_required() -> bool:
|
||||
"""test/prod 默认要求 Redis;dev 仅显式开启时要求。"""
|
||||
explicit = os.getenv("SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS")
|
||||
if explicit is not None and str(explicit).strip() != "":
|
||||
return _config_bool("SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS", False)
|
||||
if current_app:
|
||||
configured = current_app.config.get("SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS")
|
||||
if configured is not None:
|
||||
return bool(configured)
|
||||
env_name = resolve_backend_rpa_environment()
|
||||
return env_name in {"test", "prod"}
|
||||
|
||||
|
||||
def _heartbeat_allow_memory_fallback() -> bool:
|
||||
return _config_bool("SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK", False)
|
||||
|
||||
|
||||
def resolve_backend_rpa_environment() -> str:
|
||||
"""将后端部署环境归一为 dev / test / prod。"""
|
||||
env_name = os.getenv("ENV_NAME") or os.getenv("FLASK_ENV")
|
||||
if current_app:
|
||||
env_name = current_app.config.get("ENV_NAME") or env_name
|
||||
return _normalize_env_name(env_name)
|
||||
|
||||
|
||||
def shared_scope_id() -> str:
|
||||
"""共享 SMB 目录逻辑标识(如 hxops-rpa-test-data),用于跨平台路径对齐。"""
|
||||
explicit = _config_str("SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID", "")
|
||||
if explicit:
|
||||
return explicit
|
||||
trigger_dir = inventory_trigger_dir()
|
||||
if not trigger_dir:
|
||||
return ""
|
||||
for part in Path(trigger_dir).parts:
|
||||
normalized = str(part).strip().lower()
|
||||
if normalized.startswith("hxops-rpa-"):
|
||||
return normalized
|
||||
return ""
|
||||
|
||||
|
||||
def shared_sentinel_name() -> str:
|
||||
return _config_str("SHIPPING_NOTICE_RPA_SHARED_SENTINEL_NAME", ".hxops_rpa_shared_mount")
|
||||
|
||||
|
||||
def _shared_mount_check_required() -> bool:
|
||||
"""配置了 scope_id 或 test/prod 环境时强制校验共享哨兵。"""
|
||||
if shared_scope_id():
|
||||
return True
|
||||
return resolve_backend_rpa_environment() in {"test", "prod"}
|
||||
|
||||
|
||||
def _parse_capabilities(raw: Any) -> set[str]:
|
||||
if isinstance(raw, str):
|
||||
values = [part.strip().lower() for part in raw.split(",")]
|
||||
elif isinstance(raw, list):
|
||||
values = [str(part).strip().lower() for part in raw]
|
||||
else:
|
||||
values = []
|
||||
return {value for value in values if value}
|
||||
|
||||
|
||||
def _coerce_worker_payload(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""校验并规范化 worker 心跳 payload。"""
|
||||
worker_id = str(payload.get("worker_id") or "").strip()
|
||||
if not worker_id:
|
||||
raise ValueError("worker_id is required")
|
||||
timestamp = str(payload.get("timestamp") or "").strip() or _utc_now_iso()
|
||||
environment = str(payload.get("environment") or "").strip().lower() or resolve_backend_rpa_environment()
|
||||
status = str(payload.get("status") or "idle").strip().lower()
|
||||
if status not in {"idle", "busy"}:
|
||||
status = "idle"
|
||||
scope = str(payload.get("shared_scope_id") or "").strip()
|
||||
return {
|
||||
"worker_id": worker_id,
|
||||
"hostname": str(payload.get("hostname") or "").strip(),
|
||||
"environment": environment,
|
||||
"capabilities": sorted(_parse_capabilities(payload.get("capabilities"))),
|
||||
"status": status,
|
||||
"trigger_dir": str(payload.get("trigger_dir") or "").strip(),
|
||||
"drop_dir": str(payload.get("drop_dir") or "").strip(),
|
||||
"shared_scope_id": scope,
|
||||
"version": str(payload.get("version") or "").strip(),
|
||||
"timestamp": timestamp,
|
||||
"received_at": _utc_now_iso(),
|
||||
}
|
||||
|
||||
|
||||
def _redis_client():
|
||||
from app.services.redis_client import get_redis_client
|
||||
|
||||
return get_redis_client()
|
||||
|
||||
|
||||
def _memory_store_worker(worker: dict[str, Any]) -> None:
|
||||
with _MEMORY_LOCK:
|
||||
_MEMORY_STORE[worker["worker_id"]] = dict(worker)
|
||||
|
||||
|
||||
def _memory_list_workers() -> list[dict[str, Any]]:
|
||||
with _MEMORY_LOCK:
|
||||
return [dict(item) for item in _MEMORY_STORE.values()]
|
||||
|
||||
|
||||
def reset_rpa_worker_heartbeat_state_for_tests() -> None:
|
||||
"""单测隔离:清空进程内内存心跳缓存。"""
|
||||
with _MEMORY_LOCK:
|
||||
_MEMORY_STORE.clear()
|
||||
|
||||
|
||||
def _redis_store_worker(worker: dict[str, Any]) -> bool:
|
||||
client = _redis_client()
|
||||
if client is None:
|
||||
return False
|
||||
ttl = _heartbeat_ttl_seconds() * 2
|
||||
key = f"{_REDIS_WORKER_KEY_PREFIX}{worker['worker_id']}"
|
||||
try:
|
||||
client.set(key, json.dumps(worker, ensure_ascii=False), ex=ttl)
|
||||
client.sadd(_REDIS_INDEX_KEY, worker["worker_id"])
|
||||
client.expire(_REDIS_INDEX_KEY, ttl * 4)
|
||||
return True
|
||||
except Exception:
|
||||
logger.exception("[rpa-heartbeat] redis store failed worker_id=%s", worker.get("worker_id"))
|
||||
return False
|
||||
|
||||
|
||||
def _redis_list_workers() -> tuple[list[dict[str, Any]], bool]:
|
||||
"""
|
||||
从 Redis 读取 worker 心跳列表。
|
||||
Returns:
|
||||
tuple[list, read_failed]: read_failed=True 表示 Redis 读取异常(非“无心跳”)。
|
||||
"""
|
||||
client = _redis_client()
|
||||
if client is None:
|
||||
return [], False
|
||||
workers: list[dict[str, Any]] = []
|
||||
try:
|
||||
worker_ids = client.smembers(_REDIS_INDEX_KEY) or []
|
||||
for worker_id in sorted(worker_ids):
|
||||
raw = client.get(f"{_REDIS_WORKER_KEY_PREFIX}{worker_id}")
|
||||
if not raw:
|
||||
continue
|
||||
parsed = json.loads(raw)
|
||||
if isinstance(parsed, dict):
|
||||
workers.append(parsed)
|
||||
except Exception:
|
||||
logger.exception("[rpa-heartbeat] redis list failed")
|
||||
return [], True
|
||||
return workers, False
|
||||
|
||||
|
||||
def record_rpa_worker_heartbeat(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
记录 RPA Worker 心跳。
|
||||
核心逻辑:test/prod 必须写 Redis;仅 dev 且显式允许时才降级进程内存。
|
||||
"""
|
||||
worker = _coerce_worker_payload(payload)
|
||||
stored_in_redis = _redis_store_worker(worker)
|
||||
if stored_in_redis:
|
||||
worker["storage"] = "redis"
|
||||
return worker
|
||||
|
||||
if _heartbeat_redis_required():
|
||||
raise ServiceUnavailableError(
|
||||
RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE,
|
||||
code="RPA.HEARTBEAT_STORAGE_UNAVAILABLE",
|
||||
details={"reason": "redis_write_failed", "worker_id": worker.get("worker_id")},
|
||||
)
|
||||
if _heartbeat_allow_memory_fallback():
|
||||
_memory_store_worker(worker)
|
||||
worker["storage"] = "memory"
|
||||
return worker
|
||||
|
||||
raise ServiceUnavailableError(
|
||||
RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE,
|
||||
code="RPA.HEARTBEAT_STORAGE_UNAVAILABLE",
|
||||
details={"reason": "memory_fallback_disabled", "worker_id": worker.get("worker_id")},
|
||||
)
|
||||
|
||||
|
||||
def list_rpa_worker_heartbeats() -> tuple[list[dict[str, Any]], bool]:
|
||||
"""
|
||||
返回当前已知 worker 心跳列表。
|
||||
Returns:
|
||||
tuple[workers, storage_read_failed]
|
||||
"""
|
||||
workers, read_failed = _redis_list_workers()
|
||||
if read_failed:
|
||||
return [], True
|
||||
if workers:
|
||||
return workers, False
|
||||
if _heartbeat_redis_required():
|
||||
if _redis_client() is None:
|
||||
return [], True
|
||||
return [], False
|
||||
if _heartbeat_allow_memory_fallback():
|
||||
return _memory_list_workers(), False
|
||||
return [], False
|
||||
|
||||
|
||||
def _heartbeat_age_seconds(worker: dict[str, Any], *, now: float | None = None) -> float | None:
|
||||
raw = str(worker.get("received_at") or worker.get("timestamp") or "").strip()
|
||||
if not raw:
|
||||
return None
|
||||
try:
|
||||
parsed = datetime.fromisoformat(raw.replace("Z", ""))
|
||||
if parsed.tzinfo is None:
|
||||
parsed = parsed.replace(tzinfo=timezone.utc)
|
||||
except ValueError:
|
||||
return None
|
||||
current = now if now is not None else time.time()
|
||||
return max(current - parsed.timestamp(), 0.0)
|
||||
|
||||
|
||||
def _parse_sentinel_content(raw: str) -> dict[str, str]:
|
||||
parsed: dict[str, str] = {}
|
||||
for line in raw.splitlines():
|
||||
if "=" not in line:
|
||||
continue
|
||||
key, value = line.split("=", 1)
|
||||
parsed[key.strip().lower()] = value.strip()
|
||||
return parsed
|
||||
|
||||
|
||||
def _read_shared_sentinel(trigger_dir: Path) -> tuple[dict[str, str] | None, str | None]:
|
||||
sentinel_path = trigger_dir / shared_sentinel_name()
|
||||
if not sentinel_path.is_file():
|
||||
return None, "shared_sentinel_missing"
|
||||
try:
|
||||
content = sentinel_path.read_text(encoding="utf-8")
|
||||
parsed = _parse_sentinel_content(content)
|
||||
if not parsed:
|
||||
return None, "shared_sentinel_invalid"
|
||||
return parsed, None
|
||||
except Exception:
|
||||
return None, "shared_sentinel_unreadable"
|
||||
|
||||
|
||||
def _verify_shared_trigger_mount(trigger_dir: Path | None) -> tuple[bool, list[str]]:
|
||||
"""
|
||||
校验 trigger 目录为真实共享挂载,而非 Ubuntu 本地误创建目录。
|
||||
核心逻辑:目录必须已存在;test/prod 或配置 scope_id 时要求哨兵文件且 scope 一致。
|
||||
"""
|
||||
reasons: list[str] = []
|
||||
if trigger_dir is None:
|
||||
return False, ["trigger_dir_not_configured"]
|
||||
if not trigger_dir.exists():
|
||||
return False, ["trigger_dir_not_accessible"]
|
||||
if not trigger_dir.is_dir():
|
||||
return False, ["trigger_dir_not_accessible"]
|
||||
|
||||
expected_scope = shared_scope_id()
|
||||
if _shared_mount_check_required():
|
||||
sentinel, sentinel_reason = _read_shared_sentinel(trigger_dir)
|
||||
if sentinel_reason:
|
||||
reasons.append(sentinel_reason)
|
||||
elif expected_scope:
|
||||
actual_scope = str(sentinel.get("scope_id") or "").strip()
|
||||
if actual_scope != expected_scope:
|
||||
reasons.append(f"shared_scope_mismatch:{actual_scope}!={expected_scope}")
|
||||
elif not str(sentinel.get("scope_id") or "").strip():
|
||||
reasons.append("shared_scope_mismatch:missing_scope_id")
|
||||
|
||||
if reasons:
|
||||
return False, reasons
|
||||
|
||||
try:
|
||||
probe = trigger_dir / ".hxops_rpa_write_probe"
|
||||
probe.write_text("ok", encoding="utf-8")
|
||||
probe.unlink(missing_ok=True)
|
||||
except Exception:
|
||||
reasons.append("trigger_dir_not_writable")
|
||||
return not reasons, reasons
|
||||
|
||||
|
||||
def _worker_scope_matches(worker: dict[str, Any]) -> tuple[bool, list[str]]:
|
||||
expected_scope = shared_scope_id()
|
||||
if not expected_scope:
|
||||
return True, []
|
||||
worker_scope = str(worker.get("shared_scope_id") or "").strip()
|
||||
if worker_scope == expected_scope:
|
||||
return True, []
|
||||
return False, [f"shared_scope_mismatch:{worker_scope or '-'}!={expected_scope}"]
|
||||
|
||||
|
||||
def _worker_is_eligible(
|
||||
worker: dict[str, Any],
|
||||
*,
|
||||
backend_env: str,
|
||||
ttl_seconds: int,
|
||||
now: float,
|
||||
) -> tuple[bool, list[str]]:
|
||||
reasons: list[str] = []
|
||||
age = _heartbeat_age_seconds(worker, now=now)
|
||||
if age is None:
|
||||
reasons.append("heartbeat_timestamp_invalid")
|
||||
elif age > ttl_seconds:
|
||||
reasons.append(f"heartbeat_stale:{int(age)}s")
|
||||
|
||||
capabilities = _parse_capabilities(worker.get("capabilities"))
|
||||
if INVENTORY_EXPORT_CAPABILITY not in capabilities:
|
||||
reasons.append("missing_inventory_export_capability")
|
||||
|
||||
worker_env = str(worker.get("environment") or "").strip().lower()
|
||||
if worker_env and worker_env != backend_env:
|
||||
reasons.append(f"environment_mismatch:{worker_env}!={backend_env}")
|
||||
|
||||
scope_ok, scope_reasons = _worker_scope_matches(worker)
|
||||
if not scope_ok:
|
||||
reasons.extend(scope_reasons)
|
||||
|
||||
return not reasons, reasons
|
||||
|
||||
|
||||
def _summarize_reasons(reasons: list[str]) -> str:
|
||||
hints: list[str] = []
|
||||
for reason in reasons:
|
||||
base = reason.split(":", 1)[0]
|
||||
hint = _REASON_USER_HINTS.get(base)
|
||||
if hint and hint not in hints:
|
||||
hints.append(hint)
|
||||
return ";".join(hints) if hints else ";".join(reasons[:5])
|
||||
|
||||
|
||||
def _build_failure_message(result: RpaWorkerReadiness) -> tuple[str, str]:
|
||||
"""返回 (用户可见 message, 运维 detail_message)。"""
|
||||
if any(reason == "heartbeat_storage_unavailable" for reason in result.reasons):
|
||||
return RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE, _summarize_reasons(result.reasons)
|
||||
detail = _summarize_reasons(result.reasons)
|
||||
if not detail:
|
||||
return RPA_WORKER_OFFLINE_MESSAGE, RPA_WORKER_OFFLINE_MESSAGE
|
||||
return RPA_WORKER_OFFLINE_MESSAGE, f"{RPA_WORKER_OFFLINE_MESSAGE}({detail})"
|
||||
|
||||
|
||||
def check_inventory_rpa_worker_ready() -> RpaWorkerReadiness:
|
||||
"""
|
||||
检查库存 RPA 触发前 worker 是否就绪。
|
||||
核心逻辑:Redis 可用、共享哨兵有效、最近心跳在 TTL 内、环境/scope 匹配。
|
||||
"""
|
||||
checked_at = _utc_now_iso()
|
||||
if not _heartbeat_check_required():
|
||||
return RpaWorkerReadiness(
|
||||
ready=True,
|
||||
message="heartbeat check skipped",
|
||||
checked_at=checked_at,
|
||||
)
|
||||
|
||||
reasons: list[str] = []
|
||||
if _heartbeat_redis_required() and _redis_client() is None:
|
||||
reasons.append("heartbeat_storage_unavailable")
|
||||
|
||||
trigger_dir = inventory_trigger_dir()
|
||||
mount_ok, mount_reasons = _verify_shared_trigger_mount(trigger_dir)
|
||||
reasons.extend(mount_reasons)
|
||||
|
||||
backend_env = resolve_backend_rpa_environment()
|
||||
ttl_seconds = _heartbeat_ttl_seconds()
|
||||
now = time.time()
|
||||
workers, storage_read_failed = list_rpa_worker_heartbeats()
|
||||
if storage_read_failed:
|
||||
reasons.append("heartbeat_storage_unavailable")
|
||||
eligible_workers: list[dict[str, Any]] = []
|
||||
enriched_workers: list[dict[str, Any]] = []
|
||||
|
||||
for worker in workers:
|
||||
eligible, worker_reasons = _worker_is_eligible(
|
||||
worker,
|
||||
backend_env=backend_env,
|
||||
ttl_seconds=ttl_seconds,
|
||||
now=now,
|
||||
)
|
||||
enriched = {
|
||||
**worker,
|
||||
"age_seconds": _heartbeat_age_seconds(worker, now=now),
|
||||
"eligible": eligible,
|
||||
"ineligible_reasons": worker_reasons,
|
||||
}
|
||||
enriched_workers.append(enriched)
|
||||
if eligible:
|
||||
eligible_workers.append(enriched)
|
||||
else:
|
||||
reasons.extend([f"{worker.get('worker_id')}:{reason}" for reason in worker_reasons])
|
||||
|
||||
if not workers and "heartbeat_storage_unavailable" not in reasons:
|
||||
reasons.append("no_worker_heartbeat")
|
||||
|
||||
mount_block_tokens = {
|
||||
"trigger_dir_not_configured",
|
||||
"trigger_dir_not_accessible",
|
||||
"shared_sentinel_missing",
|
||||
"shared_sentinel_invalid",
|
||||
"shared_sentinel_unreadable",
|
||||
"trigger_dir_not_writable",
|
||||
}
|
||||
blocking_mount = any(reason in mount_block_tokens for reason in reasons) or any(
|
||||
reason.startswith("shared_scope_mismatch") for reason in reasons
|
||||
)
|
||||
ready = bool(eligible_workers) and not blocking_mount and "heartbeat_storage_unavailable" not in reasons
|
||||
message, detail_message = ("ready", "ready") if ready else _build_failure_message(
|
||||
RpaWorkerReadiness(ready=False, message="", reasons=sorted(set(reasons)))
|
||||
)
|
||||
return RpaWorkerReadiness(
|
||||
ready=ready,
|
||||
message=message,
|
||||
detail_message=detail_message,
|
||||
workers=enriched_workers,
|
||||
reasons=sorted(set(reasons)),
|
||||
checked_at=checked_at,
|
||||
)
|
||||
|
||||
|
||||
def assert_inventory_rpa_worker_ready() -> None:
|
||||
"""
|
||||
写 trigger 前的强制就绪检查。
|
||||
Raises:
|
||||
ServiceUnavailableError: worker 未就绪、共享目录无效或心跳存储不可用。
|
||||
"""
|
||||
result = check_inventory_rpa_worker_ready()
|
||||
if result.ready:
|
||||
return
|
||||
code = "RPA.WORKER_OFFLINE"
|
||||
if "heartbeat_storage_unavailable" in result.reasons:
|
||||
code = "RPA.HEARTBEAT_STORAGE_UNAVAILABLE"
|
||||
logger.warning(
|
||||
"[rpa-heartbeat] readiness blocked code=%s reasons=%s detail=%s",
|
||||
code,
|
||||
result.reasons,
|
||||
result.detail_message,
|
||||
)
|
||||
raise ServiceUnavailableError(
|
||||
result.message,
|
||||
code=code,
|
||||
details={
|
||||
"reasons": result.reasons,
|
||||
"detail_message": result.detail_message,
|
||||
"checked_at": result.checked_at,
|
||||
"shared_scope_id": shared_scope_id(),
|
||||
"trigger_dir": str(inventory_trigger_dir() or ""),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def serialize_rpa_worker_status() -> dict[str, Any]:
|
||||
"""管理端展示:在线 worker 列表与就绪摘要(含详细 reasons)。"""
|
||||
readiness = check_inventory_rpa_worker_ready()
|
||||
ttl_seconds = _heartbeat_ttl_seconds()
|
||||
workers = []
|
||||
now = time.time()
|
||||
for worker in readiness.workers:
|
||||
workers.append({
|
||||
"worker_id": worker.get("worker_id"),
|
||||
"hostname": worker.get("hostname"),
|
||||
"environment": worker.get("environment"),
|
||||
"status": worker.get("status"),
|
||||
"capabilities": worker.get("capabilities") or [],
|
||||
"trigger_dir": worker.get("trigger_dir"),
|
||||
"drop_dir": worker.get("drop_dir"),
|
||||
"shared_scope_id": worker.get("shared_scope_id"),
|
||||
"version": worker.get("version"),
|
||||
"timestamp": worker.get("timestamp"),
|
||||
"received_at": worker.get("received_at"),
|
||||
"age_seconds": _heartbeat_age_seconds(worker, now=now),
|
||||
"online": (_heartbeat_age_seconds(worker, now=now) or 9999) <= ttl_seconds,
|
||||
"eligible": worker.get("eligible"),
|
||||
"ineligible_reasons": worker.get("ineligible_reasons") or [],
|
||||
})
|
||||
return {
|
||||
"ready": readiness.ready,
|
||||
"message": readiness.message,
|
||||
"detail_message": readiness.detail_message,
|
||||
"checked_at": readiness.checked_at,
|
||||
"heartbeat_ttl_seconds": ttl_seconds,
|
||||
"backend_environment": resolve_backend_rpa_environment(),
|
||||
"shared_scope_id": shared_scope_id(),
|
||||
"shared_sentinel_name": shared_sentinel_name(),
|
||||
"trigger_dir": str(inventory_trigger_dir() or ""),
|
||||
"reasons": readiness.reasons,
|
||||
"workers": workers,
|
||||
}
|
||||
@@ -0,0 +1,563 @@
|
||||
"""
|
||||
services/shipping_notice/rpa_worker_heartbeat_alert.py
|
||||
|
||||
用途:库存 RPA Worker 离线/恢复主动告警(企微 textcard + 冷却去重)。
|
||||
依赖:rpa_worker_heartbeat、redis_client、wecom_notify、models.User、models.AppSetting。
|
||||
逻辑:由 schedule worker 每轮循环调用;DB 为告警状态权威源,Redis 仅作缓存同步。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import threading
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from app import db
|
||||
from app.models import AppSetting, User
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat import (
|
||||
RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE,
|
||||
RPA_WORKER_OFFLINE_MESSAGE,
|
||||
_heartbeat_check_required,
|
||||
check_inventory_rpa_worker_ready,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_REDIS_ALERT_STATE_KEY = "shipping:rpa:heartbeat:alert:state"
|
||||
_DB_ALERT_STATE_KEY = "shipping:rpa:heartbeat:alert:state"
|
||||
_STATUS_SENDING = "sending"
|
||||
_LAST_CHECK_MONO = 0.0
|
||||
_MEMORY_ALERT_STATE: dict[str, Any] = {}
|
||||
_MEMORY_ALERT_LOCK = threading.Lock()
|
||||
_RECIPIENT_GAP_LOGGED = False
|
||||
|
||||
|
||||
def _config_bool(key: str, default: bool) -> bool:
|
||||
raw = current_app.config.get(key, default)
|
||||
return str(raw).strip().lower() in {"1", "true", "yes", "on"}
|
||||
|
||||
|
||||
def _alert_enabled() -> bool:
|
||||
if not _heartbeat_check_required():
|
||||
return False
|
||||
return _config_bool("SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED", True)
|
||||
|
||||
|
||||
def _alert_cooldown_seconds() -> int:
|
||||
return max(300, int(current_app.config.get("SHIPPING_NOTICE_RPA_WORKER_ALERT_COOLDOWN_SECONDS") or 1800))
|
||||
|
||||
|
||||
def _send_lock_seconds() -> int:
|
||||
"""企微发送中的短锁 TTL;发送失败过期后可重试,不进入长冷却。"""
|
||||
return max(60, int(current_app.config.get("SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS") or 120))
|
||||
|
||||
|
||||
def _alert_fallback_admin_enabled() -> bool:
|
||||
return _config_bool("SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN", True)
|
||||
|
||||
|
||||
def _alert_recipients() -> list[User]:
|
||||
"""
|
||||
解析告警接收人。
|
||||
核心逻辑:优先 SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES;未配置时可选回退已绑企微的 admin。
|
||||
"""
|
||||
raw = str(current_app.config.get("SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES") or "").strip()
|
||||
names = [part.strip() for part in raw.split(",") if part.strip()] if raw else []
|
||||
if names:
|
||||
users = (
|
||||
db.session.query(User)
|
||||
.filter(User.username.in_(names), User.wecom_userid.isnot(None))
|
||||
.all()
|
||||
)
|
||||
if users:
|
||||
return users
|
||||
logger.warning(
|
||||
"[rpa-heartbeat-alert] configured usernames have no bound wecom_userid: %s",
|
||||
names,
|
||||
)
|
||||
if _alert_fallback_admin_enabled():
|
||||
admins = (
|
||||
db.session.query(User)
|
||||
.filter(User.role == "admin", User.wecom_userid.isnot(None))
|
||||
.order_by(User.id.asc())
|
||||
.limit(20)
|
||||
.all()
|
||||
)
|
||||
if admins:
|
||||
logger.info(
|
||||
"[rpa-heartbeat-alert] using admin fallback recipients count=%d",
|
||||
len(admins),
|
||||
)
|
||||
return admins
|
||||
return []
|
||||
|
||||
|
||||
def _log_recipient_gap_once() -> None:
|
||||
"""部署缺口:未配置接收人且无已绑企微 admin 时仅打一次明确 warning。"""
|
||||
global _RECIPIENT_GAP_LOGGED
|
||||
if _RECIPIENT_GAP_LOGGED:
|
||||
return
|
||||
_RECIPIENT_GAP_LOGGED = True
|
||||
logger.warning(
|
||||
"[rpa-heartbeat-alert] no wecom recipients: set SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES "
|
||||
"or bind wecom_userid for at least one admin (FALLBACK_ADMIN=true)"
|
||||
)
|
||||
|
||||
|
||||
def _redis_client():
|
||||
from app.services.redis_client import get_redis_client
|
||||
|
||||
return get_redis_client()
|
||||
|
||||
|
||||
def _memory_load_alert_state() -> dict[str, Any]:
|
||||
with _MEMORY_ALERT_LOCK:
|
||||
return dict(_MEMORY_ALERT_STATE)
|
||||
|
||||
|
||||
def _memory_save_alert_state(state: dict[str, Any]) -> None:
|
||||
with _MEMORY_ALERT_LOCK:
|
||||
_MEMORY_ALERT_STATE.clear()
|
||||
_MEMORY_ALERT_STATE.update(state)
|
||||
|
||||
|
||||
def _load_alert_state_from_db() -> dict[str, Any] | None:
|
||||
state, _db_ok = _try_read_alert_state_from_db()
|
||||
return state
|
||||
|
||||
|
||||
def _try_read_alert_state_from_db() -> tuple[dict[str, Any] | None, bool]:
|
||||
"""
|
||||
读取 DB 告警状态。
|
||||
Returns:
|
||||
(state, db_available):无行时 state 为 None 但 db_available 仍为 True。
|
||||
"""
|
||||
try:
|
||||
row = db.session.get(AppSetting, _DB_ALERT_STATE_KEY)
|
||||
if row and row.value:
|
||||
parsed = json.loads(row.value)
|
||||
if isinstance(parsed, dict):
|
||||
return parsed, True
|
||||
return None, True
|
||||
except Exception:
|
||||
logger.exception("[rpa-heartbeat-alert] load state from db failed")
|
||||
db.session.rollback()
|
||||
return None, False
|
||||
|
||||
|
||||
def _persist_alert_state_to_db(state: dict[str, Any]) -> None:
|
||||
payload = json.dumps(state, ensure_ascii=False)
|
||||
row = db.session.get(AppSetting, _DB_ALERT_STATE_KEY)
|
||||
if row:
|
||||
row.value = payload
|
||||
else:
|
||||
db.session.add(AppSetting(key=_DB_ALERT_STATE_KEY, value=payload))
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def _normalize_alert_state(state: dict[str, Any]) -> dict[str, Any]:
|
||||
"""写入前补齐 updated_at,供跨存储源比较版本。"""
|
||||
normalized = dict(state)
|
||||
normalized["updated_at"] = time.time()
|
||||
return normalized
|
||||
|
||||
|
||||
def _try_load_alert_state_from_redis() -> dict[str, Any] | None:
|
||||
client = _redis_client()
|
||||
if client is None:
|
||||
return None
|
||||
try:
|
||||
raw = client.get(_REDIS_ALERT_STATE_KEY)
|
||||
if raw:
|
||||
parsed = json.loads(raw)
|
||||
if isinstance(parsed, dict):
|
||||
return parsed
|
||||
except Exception:
|
||||
logger.exception("[rpa-heartbeat-alert] load state from redis failed")
|
||||
return None
|
||||
|
||||
|
||||
def _sync_redis_cache_from_db(state: dict[str, Any]) -> None:
|
||||
"""DB 为权威源时,无条件用 DB 状态覆盖 Redis 缓存。"""
|
||||
_persist_alert_state_to_redis(state)
|
||||
|
||||
|
||||
def _persist_alert_state_to_redis(state: dict[str, Any]) -> None:
|
||||
client = _redis_client()
|
||||
if client is None:
|
||||
return
|
||||
try:
|
||||
client.set(_REDIS_ALERT_STATE_KEY, json.dumps(state, ensure_ascii=False), ex=86400 * 7)
|
||||
except Exception:
|
||||
logger.exception("[rpa-heartbeat-alert] save state to redis failed")
|
||||
|
||||
|
||||
def _delete_redis_alert_state_if_possible() -> None:
|
||||
"""DB 无状态时清理 Redis 残留缓存。"""
|
||||
client = _redis_client()
|
||||
if client is None:
|
||||
return
|
||||
try:
|
||||
client.delete(_REDIS_ALERT_STATE_KEY)
|
||||
except Exception:
|
||||
logger.exception("[rpa-heartbeat-alert] delete state from redis failed")
|
||||
|
||||
|
||||
def reset_rpa_worker_alert_state_for_tests() -> None:
|
||||
"""单测隔离:清空进程内告警冷却状态与 DB 行。"""
|
||||
global _LAST_CHECK_MONO, _RECIPIENT_GAP_LOGGED
|
||||
_LAST_CHECK_MONO = 0.0
|
||||
_RECIPIENT_GAP_LOGGED = False
|
||||
with _MEMORY_ALERT_LOCK:
|
||||
_MEMORY_ALERT_STATE.clear()
|
||||
try:
|
||||
from flask import has_app_context
|
||||
|
||||
if has_app_context():
|
||||
row = db.session.get(AppSetting, _DB_ALERT_STATE_KEY)
|
||||
if row:
|
||||
db.session.delete(row)
|
||||
db.session.commit()
|
||||
except Exception:
|
||||
db.session.rollback()
|
||||
|
||||
|
||||
def _load_alert_state() -> dict[str, Any]:
|
||||
"""
|
||||
加载告警冷却状态;DB 为权威源,Redis 仅作缓存,仅 DB 不可读时才回退 Redis/内存。
|
||||
"""
|
||||
db_state, db_ok = _try_read_alert_state_from_db()
|
||||
if db_ok:
|
||||
if db_state is not None:
|
||||
_memory_save_alert_state(db_state)
|
||||
_sync_redis_cache_from_db(db_state)
|
||||
return db_state
|
||||
_memory_save_alert_state({})
|
||||
_delete_redis_alert_state_if_possible()
|
||||
return {}
|
||||
|
||||
redis_state = _try_load_alert_state_from_redis()
|
||||
if redis_state is not None:
|
||||
_memory_save_alert_state(redis_state)
|
||||
return redis_state
|
||||
return _memory_load_alert_state()
|
||||
|
||||
|
||||
def _save_alert_state(state: dict[str, Any]) -> None:
|
||||
"""保存告警冷却状态;写内存 + DB + Redis(可用时)。"""
|
||||
payload = _normalize_alert_state(state) if state else {}
|
||||
_memory_save_alert_state(payload)
|
||||
if not payload:
|
||||
return
|
||||
try:
|
||||
_persist_alert_state_to_db(payload)
|
||||
except Exception:
|
||||
db.session.rollback()
|
||||
logger.exception("[rpa-heartbeat-alert] save state to db failed")
|
||||
_persist_alert_state_to_redis(payload)
|
||||
|
||||
|
||||
def _claim_alert_send_lock_db(
|
||||
*,
|
||||
lock_state: dict[str, Any],
|
||||
should_send_fn: Callable[[dict[str, Any]], bool],
|
||||
) -> tuple[bool, dict[str, Any]]:
|
||||
row = (
|
||||
db.session.query(AppSetting)
|
||||
.filter(AppSetting.key == _DB_ALERT_STATE_KEY)
|
||||
.with_for_update()
|
||||
.one_or_none()
|
||||
)
|
||||
existing: dict[str, Any] = {}
|
||||
if row and row.value:
|
||||
parsed = json.loads(row.value)
|
||||
if isinstance(parsed, dict):
|
||||
existing = parsed
|
||||
if not should_send_fn(existing):
|
||||
db.session.rollback()
|
||||
return False, existing
|
||||
|
||||
previous_state = dict(existing)
|
||||
lock_state = _normalize_alert_state(lock_state)
|
||||
payload = json.dumps(lock_state, ensure_ascii=False)
|
||||
if row:
|
||||
row.value = payload
|
||||
else:
|
||||
db.session.add(AppSetting(key=_DB_ALERT_STATE_KEY, value=payload))
|
||||
db.session.commit()
|
||||
_memory_save_alert_state(lock_state)
|
||||
_persist_alert_state_to_redis(lock_state)
|
||||
return True, previous_state
|
||||
|
||||
|
||||
def _claim_alert_send_lock_memory_only(
|
||||
*,
|
||||
lock_state: dict[str, Any],
|
||||
should_send_fn: Callable[[dict[str, Any]], bool],
|
||||
) -> tuple[bool, dict[str, Any]]:
|
||||
"""仅当 DB 不可读/不可写时使用的进程内 claim 兜底。"""
|
||||
mem = _memory_load_alert_state()
|
||||
if not should_send_fn(mem):
|
||||
return False, mem
|
||||
previous_state = dict(mem)
|
||||
_memory_save_alert_state(lock_state)
|
||||
return True, previous_state
|
||||
|
||||
|
||||
def _claim_alert_send_lock(
|
||||
*,
|
||||
lock_state: dict[str, Any],
|
||||
should_send_fn: Callable[[dict[str, Any]], bool],
|
||||
) -> tuple[bool, dict[str, Any]]:
|
||||
"""
|
||||
跨进程发送锁:仅写入 sending 状态,不更新 last_sent_at 冷却。
|
||||
Returns:
|
||||
(claimed, previous_state):claimed 为 True 时 previous_state 供发送失败回滚。
|
||||
"""
|
||||
try:
|
||||
return _claim_alert_send_lock_db(lock_state=lock_state, should_send_fn=should_send_fn)
|
||||
except IntegrityError:
|
||||
db.session.rollback()
|
||||
existing, db_ok = _try_read_alert_state_from_db()
|
||||
if existing:
|
||||
_memory_save_alert_state(existing)
|
||||
elif db_ok:
|
||||
_memory_save_alert_state({})
|
||||
return False, existing or {}
|
||||
except Exception:
|
||||
db.session.rollback()
|
||||
logger.exception("[rpa-heartbeat-alert] claim send lock in db failed")
|
||||
existing, db_ok = _try_read_alert_state_from_db()
|
||||
if db_ok:
|
||||
if existing:
|
||||
_memory_save_alert_state(existing)
|
||||
return False, existing or {}
|
||||
return _claim_alert_send_lock_memory_only(
|
||||
lock_state=lock_state,
|
||||
should_send_fn=should_send_fn,
|
||||
)
|
||||
|
||||
|
||||
def _commit_alert_sent(*, final_state: dict[str, Any]) -> None:
|
||||
"""企微发送成功后写入最终状态与 last_sent_at(进入长冷却)。"""
|
||||
_save_alert_state(final_state)
|
||||
|
||||
|
||||
def _release_alert_send_lock(*, previous_state: dict[str, Any]) -> None:
|
||||
"""企微发送失败:回滚 sending 锁,不推进 last_sent_at。"""
|
||||
if previous_state:
|
||||
_save_alert_state(previous_state)
|
||||
return
|
||||
_memory_save_alert_state({})
|
||||
try:
|
||||
row = db.session.get(AppSetting, _DB_ALERT_STATE_KEY)
|
||||
if row:
|
||||
db.session.delete(row)
|
||||
db.session.commit()
|
||||
except Exception:
|
||||
db.session.rollback()
|
||||
logger.exception("[rpa-heartbeat-alert] release send lock in db failed")
|
||||
_delete_redis_alert_state_if_possible()
|
||||
|
||||
|
||||
def _send_alert_to_recipients(*, title: str, content: str) -> bool:
|
||||
from app.services.wecom_notify import send_wecom_event_message
|
||||
|
||||
recipients = _alert_recipients()
|
||||
if not recipients:
|
||||
_log_recipient_gap_once()
|
||||
logger.warning("[rpa-heartbeat-alert] no recipients available, title=%s", title)
|
||||
return False
|
||||
sent_any = False
|
||||
for user in recipients:
|
||||
result = send_wecom_event_message(
|
||||
event_type="schedule_completed",
|
||||
user=user,
|
||||
title=title,
|
||||
content=content,
|
||||
jump_path="/admin/schedules",
|
||||
)
|
||||
if result.get("ok"):
|
||||
sent_any = True
|
||||
else:
|
||||
logger.warning(
|
||||
"[rpa-heartbeat-alert] notify failed user=%s reason=%s",
|
||||
user.username,
|
||||
result.get("reason"),
|
||||
)
|
||||
return sent_any
|
||||
|
||||
|
||||
def _is_active_send_lock(existing: dict[str, Any], *, now_ts: float) -> bool:
|
||||
if str(existing.get("status") or "").strip() != _STATUS_SENDING:
|
||||
return False
|
||||
started = float(existing.get("sending_started_at") or 0)
|
||||
return started > 0 and (now_ts - started) < _send_lock_seconds()
|
||||
|
||||
|
||||
def _effective_last_status(existing: dict[str, Any]) -> str:
|
||||
status = str(existing.get("status") or "").strip()
|
||||
if status == _STATUS_SENDING:
|
||||
return str(existing.get("sending_target") or "").strip()
|
||||
return status
|
||||
|
||||
|
||||
def _should_send_storage_or_offline(
|
||||
*,
|
||||
existing: dict[str, Any],
|
||||
target_status: str,
|
||||
now_ts: float,
|
||||
cooldown: int,
|
||||
) -> bool:
|
||||
if _is_active_send_lock(existing, now_ts=now_ts):
|
||||
return False
|
||||
last_status = _effective_last_status(existing)
|
||||
last_sent_at = float(existing.get("last_sent_at") or 0)
|
||||
return last_status != target_status or (now_ts - last_sent_at) >= cooldown
|
||||
|
||||
|
||||
def _try_send_with_claim(
|
||||
*,
|
||||
target_status: str,
|
||||
state: dict[str, Any],
|
||||
now_ts: float,
|
||||
cooldown: int,
|
||||
title: str,
|
||||
content: str,
|
||||
) -> bool:
|
||||
def should_send_fn(existing: dict[str, Any]) -> bool:
|
||||
if _is_active_send_lock(existing, now_ts=now_ts):
|
||||
return False
|
||||
if target_status == "ready":
|
||||
return _effective_last_status(existing) in {"offline", "storage_unavailable"}
|
||||
return _should_send_storage_or_offline(
|
||||
existing=existing,
|
||||
target_status=target_status,
|
||||
now_ts=now_ts,
|
||||
cooldown=cooldown,
|
||||
)
|
||||
|
||||
lock_state = {
|
||||
"status": _STATUS_SENDING,
|
||||
"sending_target": target_status,
|
||||
"sending_started_at": now_ts,
|
||||
"last_sent_at": float(state.get("last_sent_at") or 0),
|
||||
"reasons": state.get("reasons", []),
|
||||
}
|
||||
claimed, previous_state = _claim_alert_send_lock(lock_state=lock_state, should_send_fn=should_send_fn)
|
||||
if not claimed:
|
||||
return False
|
||||
if _send_alert_to_recipients(title=title, content=content):
|
||||
final_state = {
|
||||
"status": target_status,
|
||||
"last_sent_at": now_ts,
|
||||
"reasons": state.get("reasons", []),
|
||||
}
|
||||
_commit_alert_sent(final_state=final_state)
|
||||
return True
|
||||
_release_alert_send_lock(previous_state=previous_state)
|
||||
return False
|
||||
|
||||
|
||||
def maybe_alert_rpa_worker_status(*, force: bool = False) -> dict[str, Any]:
|
||||
"""
|
||||
周期检查 RPA Worker 就绪状态并按冷却时间发送离线/恢复告警。
|
||||
Returns:
|
||||
dict: 本次检查结果摘要(供运维日志)。
|
||||
"""
|
||||
global _LAST_CHECK_MONO
|
||||
if not _alert_enabled():
|
||||
return {"skipped": True, "reason": "alert_disabled"}
|
||||
|
||||
now_mono = time.monotonic()
|
||||
if not force and _LAST_CHECK_MONO and (now_mono - _LAST_CHECK_MONO) < 60:
|
||||
return {"skipped": True, "reason": "throttled"}
|
||||
_LAST_CHECK_MONO = now_mono
|
||||
|
||||
readiness = check_inventory_rpa_worker_ready()
|
||||
state = _load_alert_state()
|
||||
effective_status = _effective_last_status(state)
|
||||
last_sent_at = float(state.get("last_sent_at") or 0)
|
||||
cooldown = _alert_cooldown_seconds()
|
||||
now_ts = time.time()
|
||||
storage_unavailable = "heartbeat_storage_unavailable" in readiness.reasons
|
||||
|
||||
summary = {
|
||||
"ready": readiness.ready,
|
||||
"status": "storage_unavailable" if storage_unavailable else ("ready" if readiness.ready else "offline"),
|
||||
"reasons": readiness.reasons,
|
||||
"detail_message": readiness.detail_message,
|
||||
}
|
||||
|
||||
if storage_unavailable:
|
||||
should_send = _should_send_storage_or_offline(
|
||||
existing=state,
|
||||
target_status="storage_unavailable",
|
||||
now_ts=now_ts,
|
||||
cooldown=cooldown,
|
||||
)
|
||||
if should_send:
|
||||
title = "货代库存 RPA 心跳存储异常"
|
||||
content = (
|
||||
f"{RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE}\n\n"
|
||||
f"原因:{'; '.join(readiness.reasons[:8]) or 'unknown'}"
|
||||
)
|
||||
new_state = {
|
||||
"status": "storage_unavailable",
|
||||
"last_sent_at": last_sent_at,
|
||||
"reasons": readiness.reasons,
|
||||
}
|
||||
if _try_send_with_claim(
|
||||
target_status="storage_unavailable",
|
||||
state=new_state,
|
||||
now_ts=now_ts,
|
||||
cooldown=cooldown,
|
||||
title=title,
|
||||
content=content,
|
||||
):
|
||||
summary["storage_alert_sent"] = True
|
||||
return summary
|
||||
|
||||
if not readiness.ready:
|
||||
should_send = _should_send_storage_or_offline(
|
||||
existing=state,
|
||||
target_status="offline",
|
||||
now_ts=now_ts,
|
||||
cooldown=cooldown,
|
||||
)
|
||||
if should_send:
|
||||
detail = readiness.detail_message or RPA_WORKER_OFFLINE_MESSAGE
|
||||
title = "货代库存 RPA Worker 离线"
|
||||
content = f"{detail}\n\n原因:{'; '.join(readiness.reasons[:8]) or 'unknown'}"
|
||||
new_state = {"status": "offline", "last_sent_at": last_sent_at, "reasons": readiness.reasons}
|
||||
if _try_send_with_claim(
|
||||
target_status="offline",
|
||||
state=new_state,
|
||||
now_ts=now_ts,
|
||||
cooldown=cooldown,
|
||||
title=title,
|
||||
content=content,
|
||||
):
|
||||
summary["alert_sent"] = True
|
||||
return summary
|
||||
|
||||
if effective_status in {"offline", "storage_unavailable"}:
|
||||
title = "货代库存 RPA Worker 已恢复"
|
||||
content = "库存 RPA Worker 心跳已恢复,可正常触发库存导出。"
|
||||
new_state = {"status": "ready", "last_sent_at": last_sent_at, "reasons": []}
|
||||
if _try_send_with_claim(
|
||||
target_status="ready",
|
||||
state=new_state,
|
||||
now_ts=now_ts,
|
||||
cooldown=cooldown,
|
||||
title=title,
|
||||
content=content,
|
||||
):
|
||||
summary["recovery_sent"] = True
|
||||
return summary
|
||||
Reference in new issue
Block a user