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
@@ -0,0 +1,373 @@
|
||||
"""
|
||||
backend/tests/test_rpa_worker_heartbeat.py
|
||||
|
||||
用途:货代库存 RPA Worker 心跳存储、共享目录校验、就绪检查与 API 契约单测。
|
||||
依赖:rpa_worker_heartbeat、shipping_notice_tools heartbeat 路由。
|
||||
逻辑:覆盖跨平台 scope、哨兵、Redis 策略、环境匹配与 fail-fast 断言。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.errors import ServiceUnavailableError
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat import (
|
||||
INVENTORY_EXPORT_CAPABILITY,
|
||||
RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE,
|
||||
RPA_WORKER_OFFLINE_MESSAGE,
|
||||
assert_inventory_rpa_worker_ready,
|
||||
check_inventory_rpa_worker_ready,
|
||||
record_rpa_worker_heartbeat,
|
||||
resolve_backend_rpa_environment,
|
||||
shared_sentinel_name,
|
||||
)
|
||||
|
||||
|
||||
def _write_shared_sentinel(trigger_dir, *, scope_id: str, host: str = "WIN-RPA") -> None:
|
||||
body = "\n".join([
|
||||
f"scope_id={scope_id}",
|
||||
f"updated_at={datetime.now(timezone.utc).replace(tzinfo=None).isoformat()}",
|
||||
f"host={host}",
|
||||
])
|
||||
(trigger_dir / shared_sentinel_name()).write_text(body + "\n", encoding="utf-8")
|
||||
|
||||
|
||||
def _heartbeat_payload(
|
||||
*,
|
||||
worker_id: str = "win-rpa-1",
|
||||
trigger_dir: str,
|
||||
environment: str | None = None,
|
||||
capabilities: list[str] | None = None,
|
||||
shared_scope_id: str | None = None,
|
||||
timestamp: str | None = None,
|
||||
) -> dict:
|
||||
return {
|
||||
"worker_id": worker_id,
|
||||
"hostname": "WIN-RPA-HOST",
|
||||
"environment": environment or resolve_backend_rpa_environment(),
|
||||
"capabilities": capabilities or [INVENTORY_EXPORT_CAPABILITY],
|
||||
"status": "idle",
|
||||
"trigger_dir": trigger_dir,
|
||||
"drop_dir": str(trigger_dir).replace("triggers", "drop"),
|
||||
"shared_scope_id": shared_scope_id or "",
|
||||
"version": "test",
|
||||
"timestamp": timestamp or datetime.now(timezone.utc).replace(tzinfo=None).isoformat(),
|
||||
}
|
||||
|
||||
|
||||
def _enable_prod_like_checks(app, tmp_path, *, scope_id: str = "hxops-rpa-test-data"):
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
trigger_dir.mkdir()
|
||||
_write_shared_sentinel(trigger_dir, scope_id=scope_id)
|
||||
app.config["ENV_NAME"] = "test"
|
||||
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID"] = scope_id
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = False
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
|
||||
app.config["FREIGHT_RPA_MOCK"] = "false"
|
||||
return trigger_dir
|
||||
|
||||
|
||||
def test_cross_platform_paths_ready_with_shared_scope_id(app, tmp_path):
|
||||
"""Windows 与 Ubuntu 路径不同但 shared_scope_id 一致时应 ready。"""
|
||||
trigger_dir = _enable_prod_like_checks(app, tmp_path)
|
||||
windows_trigger = r"C:\HxopsRpaTest\data\inventory_triggers"
|
||||
|
||||
with app.app_context():
|
||||
record_rpa_worker_heartbeat(
|
||||
_heartbeat_payload(
|
||||
trigger_dir=windows_trigger,
|
||||
shared_scope_id="hxops-rpa-test-data",
|
||||
)
|
||||
)
|
||||
result = check_inventory_rpa_worker_ready()
|
||||
assert result.ready is True
|
||||
assert not any("trigger_dir_mismatch" in reason for reason in result.reasons)
|
||||
|
||||
|
||||
def test_environment_mismatch_marks_worker_ineligible(app, tmp_path):
|
||||
"""Worker 环境与后端不一致时应判定离线。"""
|
||||
trigger_dir = _enable_prod_like_checks(app, tmp_path)
|
||||
app.config["ENV_NAME"] = "test"
|
||||
|
||||
with app.app_context():
|
||||
record_rpa_worker_heartbeat(
|
||||
_heartbeat_payload(
|
||||
trigger_dir=r"C:\HxopsRpaTest\data\inventory_triggers",
|
||||
environment="prod",
|
||||
shared_scope_id="hxops-rpa-test-data",
|
||||
)
|
||||
)
|
||||
result = check_inventory_rpa_worker_ready()
|
||||
assert result.ready is False
|
||||
assert any("environment_mismatch" in reason for reason in result.reasons)
|
||||
|
||||
|
||||
def test_shared_scope_mismatch_marks_worker_ineligible(app, tmp_path):
|
||||
"""Worker scope 与后端配置不一致时应离线。"""
|
||||
trigger_dir = _enable_prod_like_checks(app, tmp_path)
|
||||
|
||||
with app.app_context():
|
||||
record_rpa_worker_heartbeat(
|
||||
_heartbeat_payload(
|
||||
trigger_dir=r"C:\HxopsRpaTest\data\inventory_triggers",
|
||||
shared_scope_id="hxops-rpa-prod-data",
|
||||
)
|
||||
)
|
||||
result = check_inventory_rpa_worker_ready()
|
||||
assert result.ready is False
|
||||
assert any("shared_scope_mismatch" in reason for reason in result.reasons)
|
||||
|
||||
|
||||
def test_missing_shared_sentinel_blocks_readiness_in_test_env(app, tmp_path):
|
||||
"""test 环境缺少哨兵文件时应判定共享目录不可用。"""
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
trigger_dir.mkdir()
|
||||
app.config["ENV_NAME"] = "test"
|
||||
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID"] = "hxops-rpa-test-data"
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
|
||||
app.config["FREIGHT_RPA_MOCK"] = "false"
|
||||
|
||||
with app.app_context():
|
||||
record_rpa_worker_heartbeat(
|
||||
_heartbeat_payload(
|
||||
trigger_dir=r"C:\HxopsRpaTest\data\inventory_triggers",
|
||||
shared_scope_id="hxops-rpa-test-data",
|
||||
)
|
||||
)
|
||||
result = check_inventory_rpa_worker_ready()
|
||||
assert result.ready is False
|
||||
assert "shared_sentinel_missing" in result.reasons
|
||||
|
||||
|
||||
def test_record_heartbeat_requires_redis_when_configured(app, tmp_path, monkeypatch):
|
||||
"""生产策略要求 Redis 时,写入失败应抛存储不可用。"""
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
trigger_dir.mkdir()
|
||||
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = True
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = False
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.rpa_worker_heartbeat._redis_store_worker",
|
||||
lambda _worker: False,
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
with pytest.raises(ServiceUnavailableError) as exc_info:
|
||||
record_rpa_worker_heartbeat(_heartbeat_payload(trigger_dir=str(trigger_dir)))
|
||||
assert exc_info.value.code == "RPA.HEARTBEAT_STORAGE_UNAVAILABLE"
|
||||
assert exc_info.value.message == RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE
|
||||
|
||||
|
||||
def test_assert_inventory_rpa_worker_ready_includes_reason_details(app, tmp_path):
|
||||
"""fail-fast 应附带 reasons 详情供排程日志与运维定位。"""
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
trigger_dir.mkdir()
|
||||
_write_shared_sentinel(trigger_dir, scope_id="hxops-rpa-test-data")
|
||||
app.config["ENV_NAME"] = "test"
|
||||
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID"] = "hxops-rpa-test-data"
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
|
||||
app.config["FREIGHT_RPA_MOCK"] = "false"
|
||||
|
||||
with app.app_context():
|
||||
with pytest.raises(ServiceUnavailableError) as exc_info:
|
||||
assert_inventory_rpa_worker_ready()
|
||||
assert exc_info.value.message == RPA_WORKER_OFFLINE_MESSAGE
|
||||
assert "no_worker_heartbeat" in (exc_info.value.details or {}).get("reasons", [])
|
||||
assert (exc_info.value.details or {}).get("detail_message")
|
||||
|
||||
|
||||
def test_check_inventory_rpa_worker_ready_rejects_stale_heartbeat(app, tmp_path, monkeypatch):
|
||||
"""超过 TTL 的心跳应视为离线。"""
|
||||
import time as time_module
|
||||
|
||||
trigger_dir = _enable_prod_like_checks(app, tmp_path)
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS"] = 90
|
||||
base_now = time_module.time()
|
||||
|
||||
with app.app_context():
|
||||
record_rpa_worker_heartbeat(
|
||||
_heartbeat_payload(
|
||||
trigger_dir=r"C:\HxopsRpaTest\data\inventory_triggers",
|
||||
shared_scope_id="hxops-rpa-test-data",
|
||||
)
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.rpa_worker_heartbeat.time.time",
|
||||
lambda: base_now + 120,
|
||||
)
|
||||
result = check_inventory_rpa_worker_ready()
|
||||
assert result.ready is False
|
||||
assert any("heartbeat_stale" in reason for reason in result.reasons)
|
||||
|
||||
|
||||
def test_rpa_heartbeat_api_records_worker(client, app, tmp_path):
|
||||
"""POST /rpa/heartbeat 应写入心跳并返回 ok。"""
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
trigger_dir.mkdir()
|
||||
app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = "test-tool-key"
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
|
||||
payload = _heartbeat_payload(trigger_dir=str(trigger_dir.resolve()))
|
||||
|
||||
res = client.post(
|
||||
"/api/shipping-notice/rpa/heartbeat",
|
||||
headers={"X-Integration-Key": "test-tool-key"},
|
||||
json=payload,
|
||||
)
|
||||
assert res.status_code == 200
|
||||
body = res.get_json()
|
||||
assert body.get("status") == "ok"
|
||||
assert body.get("data", {}).get("worker_id") == payload["worker_id"]
|
||||
|
||||
|
||||
def test_rpa_heartbeat_api_rejects_missing_auth(client, app, tmp_path):
|
||||
"""心跳接口缺少鉴权应返回未授权。"""
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
trigger_dir.mkdir()
|
||||
app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = "test-tool-key"
|
||||
payload = _heartbeat_payload(trigger_dir=str(trigger_dir.resolve()))
|
||||
|
||||
res = client.post("/api/shipping-notice/rpa/heartbeat", json=payload)
|
||||
assert res.status_code == 401
|
||||
|
||||
|
||||
def test_rpa_heartbeat_api_rejects_invalid_auth(client, app, tmp_path):
|
||||
"""心跳接口错误 key 应返回未授权。"""
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
trigger_dir.mkdir()
|
||||
app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = "test-tool-key"
|
||||
payload = _heartbeat_payload(trigger_dir=str(trigger_dir.resolve()))
|
||||
|
||||
res = client.post(
|
||||
"/api/shipping-notice/rpa/heartbeat",
|
||||
headers={"X-Integration-Key": "wrong-key"},
|
||||
json=payload,
|
||||
)
|
||||
assert res.status_code == 401
|
||||
|
||||
|
||||
def test_shipping_inventory_rpa_schedule_fails_fast_when_worker_offline(app, tmp_path):
|
||||
"""排程触发时 worker 离线应立即 failed,不进入 awaiting_rpa_callback。"""
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, User
|
||||
from app.services.schedule.shipping_inventory_rpa_job import run_shipping_inventory_rpa_schedule
|
||||
|
||||
trigger_dir = _enable_prod_like_checks(app, tmp_path)
|
||||
|
||||
with app.app_context():
|
||||
user = User(username="hb_offline_user", email="hb_offline_user@example.com")
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
task = ScheduleTask(
|
||||
schedule_no="SCH-HB-OFFLINE",
|
||||
name="货代库存每日导出",
|
||||
schedule_type="platform_job",
|
||||
platform_api_path="shipping-inventory-rpa",
|
||||
owner_user_id=user.id,
|
||||
cron_expr="0 3 * * *",
|
||||
enabled=True,
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
run = ScheduleRun(run_no="RUN20260711080000", schedule_task_id=task.id, status="running")
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
|
||||
total, success, failed, skipped, _details, errors, logs = run_shipping_inventory_rpa_schedule(task, run)
|
||||
assert total >= 1
|
||||
assert success == 0
|
||||
assert failed >= 1
|
||||
assert skipped == 0
|
||||
assert errors
|
||||
assert RPA_WORKER_OFFLINE_MESSAGE in errors[0]
|
||||
assert not list(trigger_dir.glob("inventory_export_batch_*.json"))
|
||||
failed_log = next(log for log in logs if isinstance(log, dict) and log.get("status") == "failed")
|
||||
assert failed_log["detail"].get("reasons")
|
||||
assert not any(
|
||||
isinstance(log, dict) and log.get("status") == "awaiting_rpa_callback"
|
||||
for log in logs
|
||||
)
|
||||
|
||||
|
||||
def test_redis_read_failure_reports_storage_unavailable_not_offline(app, tmp_path, monkeypatch):
|
||||
"""Redis 读取异常应报 heartbeat_storage_unavailable,而非 no_worker_heartbeat。"""
|
||||
trigger_dir = _enable_prod_like_checks(app, tmp_path)
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = True
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = False
|
||||
|
||||
class BrokenRedis:
|
||||
def smembers(self, _key):
|
||||
raise ConnectionError("redis read failed")
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.rpa_worker_heartbeat._redis_client",
|
||||
lambda: BrokenRedis(),
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
result = check_inventory_rpa_worker_ready()
|
||||
assert result.ready is False
|
||||
assert "heartbeat_storage_unavailable" in result.reasons
|
||||
assert "no_worker_heartbeat" not in result.reasons
|
||||
assert result.message == RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE
|
||||
|
||||
|
||||
def test_redis_store_and_list_ready_with_prod_policy(app, tmp_path, monkeypatch):
|
||||
"""test/prod Redis 策略:写入+读取成功时应 ready。"""
|
||||
trigger_dir = _enable_prod_like_checks(app, tmp_path)
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = True
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = False
|
||||
bucket: dict[str, Any] = {"index": set()}
|
||||
|
||||
class FakeRedis:
|
||||
def set(self, key, value, ex=None):
|
||||
bucket[key] = value
|
||||
|
||||
def sadd(self, key, value):
|
||||
bucket.setdefault(key, set()).add(value)
|
||||
|
||||
def expire(self, _key, _ttl):
|
||||
return True
|
||||
|
||||
def smembers(self, key):
|
||||
return bucket.get(key, set())
|
||||
|
||||
def get(self, key):
|
||||
return bucket.get(key)
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.rpa_worker_heartbeat._redis_client",
|
||||
lambda: FakeRedis(),
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
record_rpa_worker_heartbeat(
|
||||
_heartbeat_payload(
|
||||
trigger_dir=r"C:\HxopsRpaTest\data\inventory_triggers",
|
||||
shared_scope_id="hxops-rpa-test-data",
|
||||
)
|
||||
)
|
||||
result = check_inventory_rpa_worker_ready()
|
||||
assert result.ready is True
|
||||
|
||||
|
||||
def test_shared_scope_id_derived_from_mount_path_when_env_missing(app, tmp_path):
|
||||
"""未显式配置 scope 时,可从 /mnt/hxops-rpa-* 挂载路径推导。"""
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat import shared_scope_id
|
||||
|
||||
trigger_dir = tmp_path / "mnt" / "hxops-rpa-test-data" / "inventory_triggers"
|
||||
trigger_dir.mkdir(parents=True)
|
||||
_write_shared_sentinel(trigger_dir, scope_id="hxops-rpa-test-data")
|
||||
app.config.pop("SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID", None)
|
||||
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
|
||||
with app.app_context():
|
||||
assert shared_scope_id() == "hxops-rpa-test-data"
|
||||
Reference in new issue
Block a user