feat(freight-rpa): 批次R解耦编排层并切换 onhand/inbound 契约
将 RPA 编排收编至 freight_rpa,回调迁 /api/freight-rpa/*。 共享目录与 Worker 契约一次切换至 onhand/inbound/upload, 并补 outbound 骨架与 tt16 排程 job key 迁移。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
bf3154033b
commit
ffc0d4a430
147 files changed
+4221
-2678
No files matched your search
@@ -0,0 +1,39 @@
|
||||
"""freight_rpa 包 import 边界适应度测试。
|
||||
|
||||
用途:锁死阶段 A 验收标准——freight_rpa 不寄生业务编排。
|
||||
依赖:app/services/freight_rpa 包、ast。
|
||||
逻辑:遍历包内 .py 的 import(ast 解析),命中禁列即失败;
|
||||
白名单是 RPA 归档/凭据所需的两块业务工具(阶段 B 收敛为零)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
from pathlib import Path
|
||||
|
||||
PKG = Path(__file__).resolve().parents[3] / "app" / "services" / "freight_rpa"
|
||||
|
||||
ALLOWED_SHIPPING_NOTICE = {
|
||||
"app.services.shipping_notice.audit_service",
|
||||
"app.services.shipping_notice.file_assets",
|
||||
}
|
||||
|
||||
|
||||
def _imported_modules(path: Path) -> set[str]:
|
||||
tree = ast.parse(path.read_text(encoding="utf-8"))
|
||||
mods: set[str] = set()
|
||||
for node in ast.walk(tree):
|
||||
if isinstance(node, ast.Import):
|
||||
mods.update(a.name for a in node.names)
|
||||
elif isinstance(node, ast.ImportFrom) and node.module:
|
||||
mods.add(node.module)
|
||||
return mods
|
||||
|
||||
|
||||
def test_freight_rpa_import_boundary():
|
||||
assert PKG.exists(), "freight_rpa 包不存在"
|
||||
violations: list[str] = []
|
||||
for py in PKG.rglob("*.py"):
|
||||
for mod in _imported_modules(py):
|
||||
if mod.startswith("app.services.shipping_notice") and mod not in ALLOWED_SHIPPING_NOTICE:
|
||||
violations.append(f"{py.name}: {mod}")
|
||||
assert not violations, "freight_rpa 违规 import:\n" + "\n".join(violations)
|
||||
@@ -0,0 +1,584 @@
|
||||
"""
|
||||
backend/tests/services/freight_rpa/test_worker_heartbeat.py
|
||||
|
||||
用途:货代库存/上传 RPA Worker 心跳存储、共享目录校验、就绪检查与 API 契约单测。
|
||||
依赖:freight_rpa.common.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.freight_rpa.common.worker_heartbeat import (
|
||||
FREIGHT_UPLOAD_CAPABILITY,
|
||||
ONHAND_EXPORT_CAPABILITY,
|
||||
INBOUND_EXPORT_CAPABILITY,
|
||||
RPA_FREIGHT_UPLOAD_NOT_READY_MESSAGE,
|
||||
RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE,
|
||||
RPA_WORKER_OFFLINE_MESSAGE,
|
||||
assert_freight_upload_rpa_ready,
|
||||
assert_inventory_rpa_worker_ready,
|
||||
check_freight_upload_rpa_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 [ONHAND_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_SHARED_ONHAND_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_SCOPE_ID"] = scope_id
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = False
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
|
||||
app.config["FREIGHT_RPA_WORKER_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_SHARED_ONHAND_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_SCOPE_ID"] = "hxops-rpa-test-data"
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
|
||||
app.config["FREIGHT_RPA_WORKER_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_SHARED_ONHAND_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = True
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = False
|
||||
monkeypatch.setattr(
|
||||
"app.services.freight_rpa.common.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, monkeypatch):
|
||||
"""fail-fast 应附带 reasons 详情供排程日志与运维定位。"""
|
||||
from app.services.freight_rpa.common.worker_heartbeat import (
|
||||
reset_rpa_worker_heartbeat_state_for_tests,
|
||||
)
|
||||
|
||||
# 隔离:强制无 Redis 分支(_redis_client 为模块级单例,config 置空不可靠,须 monkeypatch);
|
||||
# 并清空心跳存储,确保走 no_worker_heartbeat + 进程内存储原因码。
|
||||
from app.services.freight_rpa.common import worker_heartbeat as heartbeat_module
|
||||
monkeypatch.setattr(heartbeat_module, "_redis_client", lambda: None)
|
||||
reset_rpa_worker_heartbeat_state_for_tests()
|
||||
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_SHARED_ONHAND_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_SCOPE_ID"] = "hxops-rpa-test-data"
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
|
||||
app.config["FREIGHT_RPA_WORKER_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
|
||||
reasons = (exc_info.value.details or {}).get("reasons", [])
|
||||
assert "no_worker_heartbeat" in reasons
|
||||
# [断言意图] 无 Redis 时心跳存储为本进程内存,必须给出原因码与本地测试指引
|
||||
assert "heartbeat_store_process_local" in reasons
|
||||
assert (exc_info.value.details or {}).get("detail_message")
|
||||
|
||||
|
||||
def test_assert_receipt_rpa_worker_ready_includes_reason_details(app, tmp_path, monkeypatch):
|
||||
"""收料 fail-fast 应附带 reasons,且与库存同口径要求共享哨兵。"""
|
||||
from app.core.errors import ServiceUnavailableError
|
||||
from app.services.freight_rpa.common import worker_heartbeat as heartbeat_module
|
||||
from app.services.freight_rpa.common.worker_heartbeat import (
|
||||
RPA_WORKER_OFFLINE_MESSAGE,
|
||||
assert_receipt_rpa_worker_ready,
|
||||
reset_rpa_worker_heartbeat_state_for_tests,
|
||||
)
|
||||
|
||||
monkeypatch.setattr(heartbeat_module, '_redis_client', lambda: None)
|
||||
reset_rpa_worker_heartbeat_state_for_tests()
|
||||
trigger_dir = tmp_path / 'receipt_triggers'
|
||||
trigger_dir.mkdir()
|
||||
app.config['ENV_NAME'] = 'test'
|
||||
app.config['FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR'] = str(trigger_dir)
|
||||
app.config['FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED'] = True
|
||||
app.config['FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK'] = True
|
||||
app.config['FREIGHT_RPA_WORKER_MOCK'] = 'false'
|
||||
|
||||
with app.app_context():
|
||||
with pytest.raises(ServiceUnavailableError) as exc_info:
|
||||
assert_receipt_rpa_worker_ready()
|
||||
# [断言意图] 与库存同构的用户可见文案与 reasons;缺哨兵与无心跳同时暴露,
|
||||
# 对应部署侧必须由 ps1 注入 FREIGHT_RPA_SHARED_SCOPE_ID 写哨兵。
|
||||
assert exc_info.value.message == RPA_WORKER_OFFLINE_MESSAGE
|
||||
reasons = (exc_info.value.details or {}).get('reasons', [])
|
||||
assert 'no_worker_heartbeat' in reasons
|
||||
assert 'shared_sentinel_missing' in reasons
|
||||
|
||||
|
||||
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["FREIGHT_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.freight_rpa.common.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 /api/freight-rpa/heartbeat 应写入心跳并返回 ok(旧 shipping-notice 路由已删)。"""
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
trigger_dir.mkdir()
|
||||
app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = "test-tool-key"
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
|
||||
payload = _heartbeat_payload(trigger_dir=str(trigger_dir.resolve()))
|
||||
|
||||
res = client.post(
|
||||
"/api/freight-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/freight-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/freight-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, monkeypatch):
|
||||
"""排程触发时 worker 离线应立即 failed,不进入 awaiting_rpa_callback。"""
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, User
|
||||
from app.services.schedule.freight_onhand_rpa_job import run_shipping_inventory_rpa_schedule
|
||||
from app.services.freight_rpa.common import worker_heartbeat as heartbeat_module
|
||||
from app.services.freight_rpa.common.worker_heartbeat import (
|
||||
reset_rpa_worker_heartbeat_state_for_tests,
|
||||
)
|
||||
|
||||
# 隔离:强制无 Redis 分支(防真实心跳/单例缓存混入测试窗口)并清空存储,锁定离线 fail-fast 分支。
|
||||
monkeypatch.setattr(heartbeat_module, "_redis_client", lambda: None)
|
||||
reset_rpa_worker_heartbeat_state_for_tests()
|
||||
|
||||
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="freight-rpa-onhand",
|
||||
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["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = True
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = False
|
||||
|
||||
class BrokenRedis:
|
||||
def smembers(self, _key):
|
||||
raise ConnectionError("redis read failed")
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.freight_rpa.common.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["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = True
|
||||
app.config["FREIGHT_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.freight_rpa.common.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.freight_rpa.common.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("FREIGHT_RPA_SHARED_SCOPE_ID", None)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR"] = str(trigger_dir)
|
||||
|
||||
with app.app_context():
|
||||
assert shared_scope_id() == "hxops-rpa-test-data"
|
||||
|
||||
|
||||
def _enable_freight_upload_checks(app, tmp_path, *, scope_id: str = "hxops-rpa-test-data"):
|
||||
"""配置货代上传 trigger/queue 与心跳策略,供上传就绪单测复用。"""
|
||||
upload_trigger = tmp_path / "upload_triggers"
|
||||
upload_queue = tmp_path / "upload_queue"
|
||||
upload_trigger.mkdir()
|
||||
upload_queue.mkdir()
|
||||
_write_shared_sentinel(upload_trigger, scope_id=scope_id)
|
||||
app.config["ENV_NAME"] = "test"
|
||||
app.config["FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR"] = str(upload_trigger)
|
||||
app.config["FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR"] = str(upload_queue)
|
||||
app.config["FREIGHT_RPA_SHARED_SCOPE_ID"] = scope_id
|
||||
app.config["FREIGHT_RPA_CREDENTIAL_KEY"] = "dGVzdC1rZXktMzItYnl0ZXMtZm9yLWZlcm5ldCE="
|
||||
app.config["INTERNAL_API_BASE_URL"] = "http://127.0.0.1:5052"
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = False
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
|
||||
app.config["FREIGHT_RPA_WORKER_MOCK"] = "false"
|
||||
return upload_trigger
|
||||
|
||||
|
||||
def test_check_freight_upload_rpa_ready_requires_freight_upload_capability(app, tmp_path):
|
||||
"""仅 inventory_export 能力时货代上传不得 ready。"""
|
||||
upload_trigger = _enable_freight_upload_checks(app, tmp_path)
|
||||
with app.app_context():
|
||||
record_rpa_worker_heartbeat(
|
||||
_heartbeat_payload(
|
||||
trigger_dir=str(upload_trigger),
|
||||
shared_scope_id="hxops-rpa-test-data",
|
||||
capabilities=[ONHAND_EXPORT_CAPABILITY],
|
||||
)
|
||||
)
|
||||
result = check_freight_upload_rpa_ready()
|
||||
# 关键断言:缺少 freight_upload 能力必须阻断自动上传。
|
||||
assert result.ready is False
|
||||
assert any("missing_freight_upload_capability" in reason for reason in result.reasons)
|
||||
|
||||
|
||||
def test_check_freight_upload_rpa_ready_when_worker_and_dirs_ok(app, tmp_path):
|
||||
"""Worker 声明 freight_upload 且目录/凭据齐全时应 ready。"""
|
||||
upload_trigger = _enable_freight_upload_checks(app, tmp_path)
|
||||
with app.app_context():
|
||||
record_rpa_worker_heartbeat(
|
||||
_heartbeat_payload(
|
||||
trigger_dir=str(upload_trigger),
|
||||
shared_scope_id="hxops-rpa-test-data",
|
||||
capabilities=[ONHAND_EXPORT_CAPABILITY, FREIGHT_UPLOAD_CAPABILITY],
|
||||
)
|
||||
)
|
||||
result = check_freight_upload_rpa_ready()
|
||||
assert result.ready is True
|
||||
|
||||
|
||||
def test_assert_freight_upload_rpa_ready_includes_reasons(app, tmp_path):
|
||||
"""上传 fail-fast 须带 reasons,供建单前/触发时展示阻断原因。"""
|
||||
from app.services.freight_rpa.common.worker_heartbeat import (
|
||||
reset_rpa_worker_heartbeat_state_for_tests,
|
||||
)
|
||||
|
||||
_enable_freight_upload_checks(app, tmp_path)
|
||||
# 去掉凭据主密钥:即使 Redis 残留心跳,静态配置缺失也必须阻断。
|
||||
app.config.pop("FREIGHT_RPA_CREDENTIAL_KEY", None)
|
||||
reset_rpa_worker_heartbeat_state_for_tests()
|
||||
with app.app_context():
|
||||
with pytest.raises(ServiceUnavailableError) as exc_info:
|
||||
assert_freight_upload_rpa_ready()
|
||||
assert exc_info.value.message == RPA_FREIGHT_UPLOAD_NOT_READY_MESSAGE
|
||||
reasons = (exc_info.value.details or {}).get("reasons", [])
|
||||
assert "credential_key_missing" in reasons
|
||||
|
||||
|
||||
def test_receipt_worker_status_requires_sentinel_like_inventory(app, tmp_path):
|
||||
"""收料 ready 与库存同口径:要求共享哨兵;仅有库存 Worker 不能冒充收料在线。"""
|
||||
from app.services.freight_rpa.common.worker_heartbeat import (
|
||||
check_receipt_rpa_worker_ready,
|
||||
reset_rpa_worker_heartbeat_state_for_tests,
|
||||
serialize_rpa_worker_status,
|
||||
)
|
||||
|
||||
receipt_trigger = tmp_path / "receipt" / "triggers"
|
||||
receipt_trigger.mkdir(parents=True)
|
||||
inventory_trigger = tmp_path / "inventory" / "triggers"
|
||||
inventory_trigger.mkdir(parents=True)
|
||||
_write_shared_sentinel(inventory_trigger, scope_id="hxops-rpa-test-data")
|
||||
app.config["ENV_NAME"] = "test"
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR"] = str(inventory_trigger)
|
||||
app.config["FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR"] = str(receipt_trigger)
|
||||
app.config["FREIGHT_RPA_SHARED_SCOPE_ID"] = "hxops-rpa-test-data"
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = False
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
|
||||
app.config["FREIGHT_RPA_WORKER_MOCK"] = "false"
|
||||
reset_rpa_worker_heartbeat_state_for_tests()
|
||||
|
||||
with app.app_context():
|
||||
record_rpa_worker_heartbeat(_heartbeat_payload(
|
||||
worker_id="HOST-inventory",
|
||||
trigger_dir=str(inventory_trigger),
|
||||
shared_scope_id="hxops-rpa-test-data",
|
||||
))
|
||||
receipt_offline = check_receipt_rpa_worker_ready()
|
||||
assert receipt_offline.ready is False
|
||||
assert receipt_offline.workers == []
|
||||
|
||||
# 无哨兵时即便有收料心跳也不得 ready。
|
||||
record_rpa_worker_heartbeat(_heartbeat_payload(
|
||||
worker_id="HOST-receipt",
|
||||
trigger_dir=str(receipt_trigger),
|
||||
shared_scope_id="hxops-rpa-test-data",
|
||||
capabilities=[INBOUND_EXPORT_CAPABILITY],
|
||||
))
|
||||
without_sentinel = check_receipt_rpa_worker_ready()
|
||||
assert without_sentinel.ready is False
|
||||
|
||||
_write_shared_sentinel(receipt_trigger, scope_id="hxops-rpa-test-data")
|
||||
receipt_ready = check_receipt_rpa_worker_ready()
|
||||
assert receipt_ready.ready is True
|
||||
assert [w["worker_id"] for w in receipt_ready.workers] == ["HOST-receipt"]
|
||||
|
||||
payload = serialize_rpa_worker_status(scope="inbound")
|
||||
assert payload["scope"] == "inbound"
|
||||
assert payload["ready"] is True
|
||||
assert payload["trigger_dir"] == str(receipt_trigger)
|
||||
assert [w["worker_id"] for w in payload["workers"]] == ["HOST-receipt"]
|
||||
|
||||
|
||||
def test_receipt_worker_recognized_by_trigger_dir_without_receipt_suffix(app, tmp_path):
|
||||
"""未注入 *-receipt 身份时,仍可用收料 trigger_dir 识别在线收料 Worker。"""
|
||||
from app.services.freight_rpa.common.worker_heartbeat import (
|
||||
check_receipt_rpa_worker_ready,
|
||||
reset_rpa_worker_heartbeat_state_for_tests,
|
||||
)
|
||||
|
||||
receipt_trigger = tmp_path / "receipt" / "triggers"
|
||||
receipt_trigger.mkdir(parents=True)
|
||||
app.config["ENV_NAME"] = "dev"
|
||||
app.config["FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR"] = str(receipt_trigger)
|
||||
app.config["FREIGHT_RPA_SHARED_SCOPE_ID"] = ""
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = False
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
|
||||
app.config["FREIGHT_RPA_WORKER_MOCK"] = "false"
|
||||
reset_rpa_worker_heartbeat_state_for_tests()
|
||||
|
||||
with app.app_context():
|
||||
record_rpa_worker_heartbeat(_heartbeat_payload(
|
||||
worker_id="Hugo-30820",
|
||||
trigger_dir=str(receipt_trigger),
|
||||
shared_scope_id="",
|
||||
capabilities=[INBOUND_EXPORT_CAPABILITY],
|
||||
))
|
||||
result = check_receipt_rpa_worker_ready()
|
||||
assert result.ready is True
|
||||
assert [w["worker_id"] for w in result.workers] == ["Hugo-30820"]
|
||||
@@ -0,0 +1,498 @@
|
||||
"""
|
||||
backend/tests/services/freight_rpa/test_worker_heartbeat_alert.py
|
||||
|
||||
用途:RPA Worker 心跳告警冷却、Redis/DB 不可用兜底与接收人回退单测。
|
||||
依赖:freight_rpa.common.worker_heartbeat_alert、freight_rpa.common.worker_heartbeat、models.AppSetting。
|
||||
逻辑:验证 DB 权威读取、Redis 陈旧/空 DB 清理、并发 claim、企微失败可重试、恢复与 admin 回退。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from app import db
|
||||
from app.models import AppSetting, User
|
||||
from app.services.freight_rpa.common.worker_heartbeat_alert import (
|
||||
_DB_ALERT_STATE_KEY,
|
||||
_STATUS_SENDING,
|
||||
_claim_alert_send_lock,
|
||||
_load_alert_state,
|
||||
_save_alert_state,
|
||||
maybe_alert_rpa_worker_status,
|
||||
reset_rpa_worker_alert_state_for_tests,
|
||||
)
|
||||
|
||||
|
||||
def _enable_alert_checks(app, tmp_path, *, scope_id: str = "hxops-rpa-test-data"):
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
trigger_dir.mkdir()
|
||||
app.config["ENV_NAME"] = "test"
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_SCOPE_ID"] = scope_id
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = True
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = False
|
||||
app.config["FREIGHT_RPA_WORKER_ALERT_ENABLED"] = True
|
||||
app.config["FREIGHT_RPA_WORKER_ALERT_COOLDOWN_SECONDS"] = 3600
|
||||
app.config["FREIGHT_RPA_WORKER_ALERT_USERNAMES"] = ""
|
||||
app.config["FREIGHT_RPA_WORKER_ALERT_FALLBACK_ADMIN"] = True
|
||||
app.config["FREIGHT_RPA_WORKER_MOCK"] = "false"
|
||||
return trigger_dir
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _reset_alert_state():
|
||||
reset_rpa_worker_alert_state_for_tests()
|
||||
yield
|
||||
reset_rpa_worker_alert_state_for_tests()
|
||||
|
||||
|
||||
def test_alert_state_memory_fallback_when_redis_save_fails(app, monkeypatch):
|
||||
"""Redis set 失败时进程内仍保留冷却状态,避免重复告警。"""
|
||||
class BrokenRedis:
|
||||
def get(self, _key):
|
||||
return None
|
||||
|
||||
def set(self, _key, _value, ex=None):
|
||||
raise ConnectionError("redis down")
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.freight_rpa.common.worker_heartbeat_alert._redis_client",
|
||||
lambda: BrokenRedis(),
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
_save_alert_state({"status": "storage_unavailable", "last_sent_at": time.time()})
|
||||
loaded = _load_alert_state()
|
||||
assert loaded.get("status") == "storage_unavailable"
|
||||
assert loaded.get("last_sent_at")
|
||||
|
||||
|
||||
def test_storage_unavailable_alert_respects_memory_cooldown(app, tmp_path, monkeypatch):
|
||||
"""存储异常告警在冷却期内不重复发送(Redis 不可写时依赖进程内状态)。"""
|
||||
_enable_alert_checks(app, tmp_path)
|
||||
send_calls: list[str] = []
|
||||
|
||||
class BrokenRedis:
|
||||
def smembers(self, _key):
|
||||
raise ConnectionError("redis read failed")
|
||||
|
||||
def get(self, _key):
|
||||
return None
|
||||
|
||||
def set(self, _key, _value, ex=None):
|
||||
raise ConnectionError("redis write failed")
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.freight_rpa.common.worker_heartbeat._redis_client",
|
||||
lambda: BrokenRedis(),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.freight_rpa.common.worker_heartbeat_alert._redis_client",
|
||||
lambda: BrokenRedis(),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.freight_rpa.common.worker_heartbeat_alert._send_alert_to_recipients",
|
||||
lambda **kwargs: send_calls.append(kwargs["title"]) or True,
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
first = maybe_alert_rpa_worker_status(force=True)
|
||||
assert first.get("storage_alert_sent") is True
|
||||
assert len(send_calls) == 1
|
||||
|
||||
second = maybe_alert_rpa_worker_status(force=True)
|
||||
assert second.get("storage_alert_sent") is not True
|
||||
assert len(send_calls) == 1
|
||||
|
||||
|
||||
def test_alert_fallback_admin_recipients(app, tmp_path, monkeypatch):
|
||||
"""未配置 ALERT_USERNAMES 时回退已绑企微的 admin。"""
|
||||
_enable_alert_checks(app, tmp_path)
|
||||
|
||||
with app.app_context():
|
||||
from app import db
|
||||
|
||||
admin = User(username="ops_admin", role="admin", email="ops@test.com", wecom_userid="WX001")
|
||||
db.session.add(admin)
|
||||
db.session.commit()
|
||||
|
||||
captured: dict[str, Any] = {}
|
||||
|
||||
def _capture_send(**kwargs):
|
||||
captured.update(kwargs)
|
||||
return True
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.freight_rpa.common.worker_heartbeat_alert._send_alert_to_recipients",
|
||||
_capture_send,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.freight_rpa.common.worker_heartbeat_alert.check_inventory_rpa_worker_ready",
|
||||
lambda: type(
|
||||
"Ready",
|
||||
(),
|
||||
{
|
||||
"ready": False,
|
||||
"reasons": ["no_worker_heartbeat"],
|
||||
"detail_message": "offline",
|
||||
"message": "offline",
|
||||
},
|
||||
)(),
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
from app.services.freight_rpa.common.worker_heartbeat_alert import _alert_recipients
|
||||
|
||||
recipients = _alert_recipients()
|
||||
assert len(recipients) == 1
|
||||
assert recipients[0].username == "ops_admin"
|
||||
|
||||
result = maybe_alert_rpa_worker_status(force=True)
|
||||
assert result.get("alert_sent") is True
|
||||
assert captured.get("title") == "货代库存 RPA Worker 离线"
|
||||
|
||||
|
||||
def test_alert_state_persists_to_db_when_redis_unavailable(app, monkeypatch):
|
||||
"""Redis 不可用时告警状态应落 AppSetting,供跨进程加载。"""
|
||||
from app.models import AppSetting
|
||||
|
||||
class BrokenRedis:
|
||||
def get(self, _key):
|
||||
return None
|
||||
|
||||
def set(self, _key, _value, ex=None):
|
||||
raise ConnectionError("redis down")
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.freight_rpa.common.worker_heartbeat_alert._redis_client",
|
||||
lambda: BrokenRedis(),
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
_save_alert_state({"status": "offline", "last_sent_at": 123.0})
|
||||
row = db.session.get(AppSetting, "shipping:rpa:heartbeat:alert:state")
|
||||
assert row is not None
|
||||
loaded = _load_alert_state()
|
||||
assert loaded.get("status") == "offline"
|
||||
assert loaded.get("last_sent_at") == 123.0
|
||||
|
||||
|
||||
def test_alert_logs_recipient_gap_when_no_wecom_users(app, tmp_path, monkeypatch, caplog):
|
||||
"""无接收人且无 admin 企微绑定时应打出部署缺口 warning。"""
|
||||
import logging
|
||||
|
||||
_enable_alert_checks(app, tmp_path)
|
||||
app.config["FREIGHT_RPA_WORKER_ALERT_FALLBACK_ADMIN"] = True
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.freight_rpa.common.worker_heartbeat_alert.check_inventory_rpa_worker_ready",
|
||||
lambda: type(
|
||||
"Ready",
|
||||
(),
|
||||
{
|
||||
"ready": False,
|
||||
"reasons": ["no_worker_heartbeat"],
|
||||
"detail_message": "offline",
|
||||
"message": "offline",
|
||||
},
|
||||
)(),
|
||||
)
|
||||
|
||||
with caplog.at_level(logging.WARNING):
|
||||
with app.app_context():
|
||||
result = maybe_alert_rpa_worker_status(force=True)
|
||||
assert result.get("alert_sent") is not True
|
||||
assert any("no wecom recipients" in record.message for record in caplog.records)
|
||||
|
||||
|
||||
def test_alert_prefers_configured_usernames_over_admin(app, tmp_path, monkeypatch):
|
||||
"""显式配置的用户名优先于 admin 回退。"""
|
||||
_enable_alert_checks(app, tmp_path)
|
||||
app.config["FREIGHT_RPA_WORKER_ALERT_USERNAMES"] = "oncall_user"
|
||||
|
||||
with app.app_context():
|
||||
from app import db
|
||||
|
||||
db.session.add(User(username="ops_admin", role="admin", email="ops@test.com", wecom_userid="WX001"))
|
||||
db.session.add(
|
||||
User(username="oncall_user", role="user", email="oncall@test.com", wecom_userid="WX002")
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
from app.services.freight_rpa.common.worker_heartbeat_alert import _alert_recipients
|
||||
|
||||
recipients = _alert_recipients()
|
||||
assert len(recipients) == 1
|
||||
assert recipients[0].username == "oncall_user"
|
||||
|
||||
|
||||
def test_alert_wecom_send_failure_allows_retry_before_cooldown(app, tmp_path, monkeypatch):
|
||||
"""企微首次发送失败时不应进入长冷却,下一次检查应允许重试。"""
|
||||
_enable_alert_checks(app, tmp_path)
|
||||
send_attempts = {"count": 0}
|
||||
|
||||
def _flaky_send(**_kwargs):
|
||||
send_attempts["count"] += 1
|
||||
return send_attempts["count"] >= 2
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.freight_rpa.common.worker_heartbeat_alert._send_alert_to_recipients",
|
||||
_flaky_send,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.freight_rpa.common.worker_heartbeat_alert.check_inventory_rpa_worker_ready",
|
||||
lambda: type(
|
||||
"Ready",
|
||||
(),
|
||||
{
|
||||
"ready": False,
|
||||
"reasons": ["no_worker_heartbeat"],
|
||||
"detail_message": "offline",
|
||||
"message": "offline",
|
||||
},
|
||||
)(),
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
db.session.add(
|
||||
User(username="ops_admin", role="admin", email="ops@test.com", wecom_userid="WX001")
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
first = maybe_alert_rpa_worker_status(force=True)
|
||||
assert first.get("alert_sent") is not True
|
||||
assert send_attempts["count"] == 1
|
||||
after_fail = _load_alert_state()
|
||||
assert after_fail.get("status") != "offline"
|
||||
assert float(after_fail.get("last_sent_at") or 0) == 0
|
||||
|
||||
second = maybe_alert_rpa_worker_status(force=True)
|
||||
assert second.get("alert_sent") is True
|
||||
assert send_attempts["count"] == 2
|
||||
after_success = _load_alert_state()
|
||||
assert after_success.get("status") == "offline"
|
||||
assert float(after_success.get("last_sent_at") or 0) > 0
|
||||
|
||||
third = maybe_alert_rpa_worker_status(force=True)
|
||||
assert third.get("alert_sent") is not True
|
||||
assert send_attempts["count"] == 2
|
||||
|
||||
|
||||
def test_concurrent_first_claim_integrity_error_does_not_claim(app, monkeypatch):
|
||||
"""并发首次插入竞争:IntegrityError 后应回读 DB 并放弃 claim,不走内存兜底发送。"""
|
||||
winner_lock = {
|
||||
"status": _STATUS_SENDING,
|
||||
"sending_target": "offline",
|
||||
"sending_started_at": time.time(),
|
||||
"last_sent_at": 0,
|
||||
"reasons": ["no_worker_heartbeat"],
|
||||
}
|
||||
|
||||
with app.app_context():
|
||||
db.session.add(AppSetting(key=_DB_ALERT_STATE_KEY, value=json.dumps(winner_lock)))
|
||||
db.session.commit()
|
||||
|
||||
def _raise_integrity(**_kwargs):
|
||||
raise IntegrityError("INSERT", {}, Exception("duplicate key"))
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.freight_rpa.common.worker_heartbeat_alert._claim_alert_send_lock_db",
|
||||
_raise_integrity,
|
||||
)
|
||||
|
||||
lock_state = {
|
||||
"status": _STATUS_SENDING,
|
||||
"sending_target": "offline",
|
||||
"sending_started_at": time.time(),
|
||||
"last_sent_at": 0,
|
||||
"reasons": ["no_worker_heartbeat"],
|
||||
}
|
||||
claimed, existing = _claim_alert_send_lock(
|
||||
lock_state=lock_state,
|
||||
should_send_fn=lambda _existing: True,
|
||||
)
|
||||
assert claimed is False
|
||||
assert existing.get("status") == _STATUS_SENDING
|
||||
assert existing.get("sending_target") == "offline"
|
||||
|
||||
|
||||
def test_recovery_after_stale_sending_lock(app, tmp_path, monkeypatch):
|
||||
"""过期 sending 锁且 sending_target=offline 时,Worker 恢复后应发送恢复通知。"""
|
||||
_enable_alert_checks(app, tmp_path)
|
||||
app.config["FREIGHT_RPA_WORKER_ALERT_SEND_LOCK_SECONDS"] = 60
|
||||
|
||||
stale_sending = {
|
||||
"status": _STATUS_SENDING,
|
||||
"sending_target": "offline",
|
||||
"sending_started_at": time.time() - 120,
|
||||
"last_sent_at": time.time() - 3600,
|
||||
"reasons": ["no_worker_heartbeat"],
|
||||
}
|
||||
|
||||
captured: dict[str, Any] = {}
|
||||
|
||||
def _capture_send(**kwargs):
|
||||
captured.update(kwargs)
|
||||
return True
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.freight_rpa.common.worker_heartbeat_alert._send_alert_to_recipients",
|
||||
_capture_send,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.freight_rpa.common.worker_heartbeat_alert.check_inventory_rpa_worker_ready",
|
||||
lambda: type(
|
||||
"Ready",
|
||||
(),
|
||||
{
|
||||
"ready": True,
|
||||
"reasons": [],
|
||||
"detail_message": "",
|
||||
"message": "",
|
||||
},
|
||||
)(),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.freight_rpa.common.worker_heartbeat_alert._redis_client",
|
||||
lambda: type("BrokenRedis", (), {"get": lambda *_a, **_k: None, "set": lambda *_a, **_k: None, "delete": lambda *_a, **_k: None})(),
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
db.session.add(
|
||||
User(username="ops_admin", role="admin", email="ops@test.com", wecom_userid="WX001")
|
||||
)
|
||||
db.session.commit()
|
||||
_save_alert_state(stale_sending)
|
||||
|
||||
result = maybe_alert_rpa_worker_status(force=True)
|
||||
assert result.get("recovery_sent") is True
|
||||
assert captured.get("title") == "货代库存 RPA Worker 已恢复"
|
||||
after = _load_alert_state()
|
||||
assert after.get("status") == "ready"
|
||||
|
||||
|
||||
def test_load_alert_state_prefers_db_over_stale_redis(app, monkeypatch):
|
||||
"""Redis 缓存为旧 offline 时,应以 DB 中较新的 ready 状态为准并回写 Redis。"""
|
||||
stale_redis = {
|
||||
"status": "offline",
|
||||
"last_sent_at": 100.0,
|
||||
"updated_at": 100.0,
|
||||
}
|
||||
fresh_db = {
|
||||
"status": "ready",
|
||||
"last_sent_at": 200.0,
|
||||
"updated_at": 200.0,
|
||||
}
|
||||
redis_bucket: dict[str, str] = {
|
||||
"shipping:rpa:heartbeat:alert:state": json.dumps(stale_redis, ensure_ascii=False),
|
||||
}
|
||||
|
||||
class FakeRedis:
|
||||
def get(self, key):
|
||||
return redis_bucket.get(key)
|
||||
|
||||
def set(self, key, value, ex=None):
|
||||
redis_bucket[key] = value
|
||||
|
||||
def delete(self, key):
|
||||
redis_bucket.pop(key, None)
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.freight_rpa.common.worker_heartbeat_alert._redis_client",
|
||||
lambda: FakeRedis(),
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
db.session.add(AppSetting(key=_DB_ALERT_STATE_KEY, value=json.dumps(fresh_db, ensure_ascii=False)))
|
||||
db.session.commit()
|
||||
|
||||
loaded = _load_alert_state()
|
||||
assert loaded.get("status") == "ready"
|
||||
assert float(loaded.get("updated_at") or 0) == 200.0
|
||||
|
||||
cached = json.loads(redis_bucket[_DB_ALERT_STATE_KEY])
|
||||
assert cached.get("status") == "ready"
|
||||
assert float(cached.get("updated_at") or 0) == 200.0
|
||||
|
||||
|
||||
def test_load_alert_state_overwrites_newer_stale_redis_from_db(app, monkeypatch):
|
||||
"""Redis 时间戳更新但内容错误时,仍应以 DB 状态无条件覆盖 Redis。"""
|
||||
newer_wrong_redis = {
|
||||
"status": "offline",
|
||||
"last_sent_at": 300.0,
|
||||
"updated_at": 300.0,
|
||||
}
|
||||
authoritative_db = {
|
||||
"status": "ready",
|
||||
"last_sent_at": 200.0,
|
||||
"updated_at": 200.0,
|
||||
}
|
||||
redis_bucket: dict[str, str] = {
|
||||
"shipping:rpa:heartbeat:alert:state": json.dumps(newer_wrong_redis, ensure_ascii=False),
|
||||
}
|
||||
|
||||
class FakeRedis:
|
||||
def get(self, key):
|
||||
return redis_bucket.get(key)
|
||||
|
||||
def set(self, key, value, ex=None):
|
||||
redis_bucket[key] = value
|
||||
|
||||
def delete(self, key):
|
||||
redis_bucket.pop(key, None)
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.freight_rpa.common.worker_heartbeat_alert._redis_client",
|
||||
lambda: FakeRedis(),
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
db.session.add(
|
||||
AppSetting(key=_DB_ALERT_STATE_KEY, value=json.dumps(authoritative_db, ensure_ascii=False))
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
loaded = _load_alert_state()
|
||||
assert loaded.get("status") == "ready"
|
||||
|
||||
cached = json.loads(redis_bucket[_DB_ALERT_STATE_KEY])
|
||||
assert cached.get("status") == "ready"
|
||||
assert float(cached.get("updated_at") or 0) == 200.0
|
||||
|
||||
|
||||
def test_load_alert_state_clears_stale_redis_when_db_has_no_row(app, monkeypatch):
|
||||
"""DB 可读但无状态行时,应返回空状态并清理 Redis 残留,不回退旧缓存。"""
|
||||
stale_redis = {
|
||||
"status": "offline",
|
||||
"last_sent_at": 100.0,
|
||||
"updated_at": 100.0,
|
||||
}
|
||||
redis_bucket: dict[str, str] = {
|
||||
"shipping:rpa:heartbeat:alert:state": json.dumps(stale_redis, ensure_ascii=False),
|
||||
}
|
||||
|
||||
class FakeRedis:
|
||||
def get(self, key):
|
||||
return redis_bucket.get(key)
|
||||
|
||||
def set(self, key, value, ex=None):
|
||||
redis_bucket[key] = value
|
||||
|
||||
def delete(self, key):
|
||||
redis_bucket.pop(key, None)
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.freight_rpa.common.worker_heartbeat_alert._redis_client",
|
||||
lambda: FakeRedis(),
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
loaded = _load_alert_state()
|
||||
assert loaded == {}
|
||||
assert "shipping:rpa:heartbeat:alert:state" not in redis_bucket
|
||||
@@ -62,7 +62,7 @@ def test_trigger_inbound_rpa_writes_batch_trigger(app, receipt_source):
|
||||
{'name': 'Warehouse', 'mode': 'single', 'values': ['AWSDU'], 'required': False, 'select_all': False},
|
||||
]
|
||||
assert calls['units'][0]['credential_envelope']
|
||||
assert calls['payload']['schema_version'] == 'shipping_receipt_rpa.v1'
|
||||
assert calls['payload']['schema_version'] == 'freight_rpa.inbound.v1'
|
||||
|
||||
|
||||
def test_trigger_inbound_rpa_disabled_source_fails_closed(app):
|
||||
@@ -139,27 +139,28 @@ def test_default_rpa_trigger_writes_real_trigger_file(app, receipt_source, tmp_p
|
||||
inventory_source_id=receipt_source.id).one()
|
||||
_bind_published_inbound_profile(config)
|
||||
|
||||
monkeypatch.setitem(app.config, 'FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR', str(tmp_path))
|
||||
monkeypatch.setitem(app.config, 'FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR', str(tmp_path))
|
||||
outcome = _DefaultRpaTrigger().trigger(
|
||||
source_code=receipt_source.source_code, business_date="2026-09-17", reason="matching_missing_ready_file",
|
||||
)
|
||||
assert outcome["ok"] is True
|
||||
# [断言意图] 真实落盘:Worker 轮询目录必须能看到待领取 trigger
|
||||
assert list(tmp_path.glob("receipt_export_batch_*.json")), "trigger file not written"
|
||||
# [断言意图] 真实落盘:Worker 轮询目录必须能看到 inbound_export_batch_*.json
|
||||
# (批次 R 自 receipt_export_batch_* 改名,旧 glob 会把已写入的文件判成没写)。
|
||||
assert list(tmp_path.glob("inbound_export_batch_*.json")), "trigger file not written"
|
||||
|
||||
|
||||
def test_default_trigger_fails_closed_when_inbound_profile_missing(app, receipt_source, tmp_path, monkeypatch):
|
||||
"""收料配置存在但未绑已发布 inbound 规则 → ok=False 且不写 trigger(防徒劳抓取)。"""
|
||||
from app.services.in_transit_transfer.deps import _DefaultRpaTrigger
|
||||
|
||||
monkeypatch.setitem(app.config, 'FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR', str(tmp_path))
|
||||
monkeypatch.setitem(app.config, 'FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR', str(tmp_path))
|
||||
outcome = _DefaultRpaTrigger().trigger(
|
||||
source_code=receipt_source.source_code, business_date="2026-09-17", reason="matching_missing_ready_file",
|
||||
)
|
||||
# [断言意图] 未绑规则时抓回文件也无法解析复用,必须 fail-closed 且不落 trigger 文件。
|
||||
# [断言意图] 未绑规则时抓回文件也无法解析复用,必须 fail-closed 且不落 inbound trigger 文件。
|
||||
assert outcome["ok"] is False
|
||||
assert outcome["error_code"] == "RPA_INBOUND_PROFILE_MISSING"
|
||||
assert list(tmp_path.glob("receipt_export_batch_*.json")) == []
|
||||
assert list(tmp_path.glob("inbound_export_batch_*.json")) == []
|
||||
|
||||
|
||||
def test_trigger_inbound_rpa_marks_unit_failed_when_trigger_unavailable(app, receipt_source):
|
||||
@@ -233,7 +234,7 @@ def test_trigger_inbound_rpa_batch_writes_one_trigger_for_all_units(app, receipt
|
||||
assert outcome['ok'] is True and outcome['triggered'] is True
|
||||
assert calls[0]['run_no'].startswith('TRIG-BATCH-')
|
||||
assert [u['source_code'] for u in calls[0]['units']] == ['DSV360_AWSDU', 'DSV360_AWSSG']
|
||||
assert calls[0]['payload']['schema_version'] == 'shipping_receipt_rpa.v1'
|
||||
assert calls[0]['payload']['schema_version'] == 'freight_rpa.inbound.v1'
|
||||
# 每单元独立回调身份,且单元行先落库(回调按 callback_id 可达)。
|
||||
callback_ids = {u['callback_id'] for u in calls[0]['units']}
|
||||
assert len(callback_ids) == 2
|
||||
|
||||
@@ -229,10 +229,10 @@ def test_stale_orphan_unit_sweeps_projection_to_failed(app):
|
||||
"""
|
||||
from app import db
|
||||
from app.models import ShippingInventorySource, ShippingReceiptRpaUnitRun
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import recover_all_stale_orphan_receipt_units
|
||||
from app.services.schedule.freight_inbound_rpa_finalize import recover_all_stale_orphan_receipt_units
|
||||
|
||||
with app.app_context():
|
||||
app.config['FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS'] = 60
|
||||
app.config['FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS'] = 60
|
||||
source = ShippingInventorySource.query.filter_by(source_code=SOURCE_CODE).one()
|
||||
db.session.add(ShippingReceiptRpaUnitRun(
|
||||
schedule_run_id=None, inventory_source_id=source.id, source_code=source.source_code,
|
||||
|
||||
Reference in new issue
Block a user