Files
syops/scripts/rpa/freight_rpa_heartbeat.py
T
hugo 3a9fbac2fc feat(shipping-notice): 新增发货通知自动上传功能与候选资格评估
- 在环境配置中新增 SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED 选项,默认关闭,需显式开启以支持自动上传。
- 引入新的 pytest.ini 文件,增加测试标记以支持自动化测试。
- 删除不再使用的 seed_shipping_notice_agents.py 文件,简化代码库。
- 更新相关 API,增强发货通知与候选资格评估功能,支持多种筛选条件。
- 增强文档与代码注释,反映新的业务逻辑与功能要求。
2026-08-02 19:26:35 +08:00

209 lines
6.6 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
scripts/rpa/freight_rpa_heartbeat.py
用途:货代 RPA Worker 向后端上报心跳(POST /api/shipping-notice/rpa/heartbeat)。
依赖:rpa_common.env、urllib、socket。
逻辑:由 freight_rpa_worker 主循环按 SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS 周期调用;同步写入共享目录哨兵文件。
"""
from __future__ import annotations
import json
import os
import socket
import sys
import time
import urllib.error
import urllib.request
from datetime import UTC, datetime
from pathlib import Path
from typing import Any
from rpa_common import env as _env
_RUNTIME_STATUS = "idle"
_LAST_HEARTBEAT_MONO = 0.0
_DEFAULT_SENTINEL_NAME = ".hxops_rpa_shared_mount"
def set_worker_runtime_status(status: str) -> None:
"""更新 worker 运行态(idle / busy),供心跳上报。"""
global _RUNTIME_STATUS
normalized = str(status or "idle").strip().lower()
_RUNTIME_STATUS = normalized if normalized in {"idle", "busy"} else "idle"
def get_worker_runtime_status() -> str:
return _RUNTIME_STATUS
def _resolve_worker_environment() -> str:
raw = (
_env("SHIPPING_NOTICE_RPA_WORKER_ENVIRONMENT")
or _env("ENV_NAME")
or _env("HXOPS_ENV")
or "dev"
)
value = str(raw or "dev").strip().lower()
if value in {"development", ""}:
return "dev"
if value in {"testing"}:
return "test"
if value in {"production"}:
return "prod"
return value
def _resolve_shared_scope_id() -> str:
raw = (
_env("SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID")
or _env("SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID")
or ""
)
value = str(raw or "").strip()
if value:
return value
trigger = str(_env("SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR") or "").replace("\\", "/").lower()
for token in ("hxops-rpa-test-data", "hxops-rpa-prod-data"):
if token in trigger:
return token
return ""
def _resolve_sentinel_name() -> str:
return str(
_env("SHIPPING_NOTICE_RPA_SHARED_SENTINEL_NAME")
or _env("SHIPPING_NOTICE_RPA_SHARED_SENTINEL_NAME")
or _DEFAULT_SENTINEL_NAME
).strip() or _DEFAULT_SENTINEL_NAME
def _resolve_worker_id(hostname: str) -> str:
explicit = str(_env("SHIPPING_NOTICE_RPA_WORKER_ID") or "").strip()
if explicit:
return explicit
pid = os.getpid()
return f"{hostname}-{pid}"
def write_shared_mount_sentinel(*, trigger_dir: str | Path, hostname: str | None = None) -> None:
"""
在 trigger 共享目录写入哨兵文件,供 Ubuntu 后端校验 CIFS 挂载与 scope 一致。
核心逻辑:不创建 trigger 根目录,仅更新已存在目录下的哨兵文件。
"""
scope_id = _resolve_shared_scope_id()
if not scope_id:
return
root = Path(trigger_dir)
if not root.is_dir():
return
host = hostname or socket.gethostname()
body = "\n".join([
f"scope_id={scope_id}",
f"updated_at={datetime.now(UTC).replace(tzinfo=None).isoformat()}",
f"host={host}",
f"worker_id={_resolve_worker_id(host)}",
])
sentinel_path = root / _resolve_sentinel_name()
sentinel_path.write_text(body + "\n", encoding="utf-8")
def build_heartbeat_payload(
*,
trigger_dir: str | Path,
drop_dir: str | Path,
status: str | None = None,
) -> dict[str, Any]:
"""
组装心跳 payload。
核心逻辑:capabilities 含 inventory_export;Worker 开启上传时附加 freight_upload;
shared_scope_id 用于跨平台路径对齐与环境隔离。
"""
hostname = socket.gethostname()
capabilities = ["inventory_export"]
upload_enabled = str(_env("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_ENABLED", "false") or "false").strip().lower() in {
"1", "true", "yes", "on",
}
if upload_enabled:
capabilities.append("freight_upload")
return {
"worker_id": _resolve_worker_id(hostname),
"hostname": hostname,
"environment": _resolve_worker_environment(),
"capabilities": capabilities,
"status": status or get_worker_runtime_status(),
"trigger_dir": str(trigger_dir),
"drop_dir": str(drop_dir),
"shared_scope_id": _resolve_shared_scope_id(),
"version": str(_env("SHIPPING_NOTICE_RPA_WORKER_VERSION", "rpa-poc") or "rpa-poc"),
"timestamp": datetime.now(UTC).replace(tzinfo=None).isoformat(),
}
def post_heartbeat(payload: dict[str, Any]) -> bool:
"""
向后端上报心跳。
Returns:
bool: HTTP 2xx 时 True,否则 False(不中断 worker 主循环)。
"""
base = str(_env("HXOPS_API_BASE", "http://127.0.0.1:5052") or "http://127.0.0.1:5052").rstrip("/")
key = (
_env("SHIPPING_NOTICE_TOOL_API_KEY")
or _env("INTEGRATION_API_KEY")
or _env("HXOPS_TOOLS_API_KEY")
)
if not key:
print("[heartbeat] skipped: missing SHIPPING_NOTICE_TOOL_API_KEY", file=sys.stderr)
return False
url = f"{base}/api/shipping-notice/rpa/heartbeat"
data = json.dumps(payload, ensure_ascii=False).encode("utf-8")
req = urllib.request.Request(
url,
data=data,
headers={
"Content-Type": "application/json",
"X-Integration-Key": key,
"X-Shipping-Tool-Key": key,
},
method="POST",
)
try:
with urllib.request.urlopen(req, timeout=8) as resp:
return 200 <= int(resp.status) < 300
except urllib.error.HTTPError as exc:
body = ""
try:
body = exc.read().decode("utf-8", errors="replace")[:500]
except Exception:
body = ""
print(f"[heartbeat] HTTP {exc.code} {body}", file=sys.stderr)
return False
except Exception as exc:
print(f"[heartbeat] failed: {exc}", file=sys.stderr)
return False
def maybe_send_heartbeat(
*,
trigger_dir: str | Path,
drop_dir: str | Path,
last_sent_mono: float,
force: bool = False,
) -> float:
"""
按 SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS 节流发送心跳。
Returns:
float: 最近一次尝试后的 monotonic 时间戳(成功或失败均更新节流时钟)。
"""
global _LAST_HEARTBEAT_MONO
interval = max(15, int(_env("SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS", "20") or "20"))
now = time.monotonic()
if not force and last_sent_mono and (now - last_sent_mono) < interval:
return last_sent_mono
write_shared_mount_sentinel(trigger_dir=trigger_dir)
payload = build_heartbeat_payload(trigger_dir=trigger_dir, drop_dir=drop_dir)
post_heartbeat(payload)
_LAST_HEARTBEAT_MONO = now
return now