Files
syops/scripts/freight_rpa/common/rpa_callbacks.py
T
hugo 911afa0f73 feat(freight-rpa): 增加出站报表配置与回调支持,重构相关服务
- 将 RPA 管理 API 扩展至出站报表配置,新增出站相关的回调接口。
- 重构 freight_rpa_report_config_service,支持入站与出站报表配置的管理。
- 更新 ORM 模型,增加出站报表相关的持久化模型。
- 统一命名规范,确保在手、入站与出站的概念一致性。
2026-10-19 18:45:16 +08:00

125 lines
5.5 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/freight_rpa/common/rpa_callbacks.py
用途:货代 RPA Worker → 后端回调 URL 的单一真相(/api/freight-rpa/* 前缀,批次 R 起
取代旧 shipping-notice rpa 回调前缀,无双路由、无兼容层)与统一 POST 实现。
依赖:rpa_common.env、urllib、json(Worker 独立运行,禁止 import 后端 app)。
逻辑:onhand/inbound/outbound Worker 与 rpa_heartbeat 一律从本模块常量取回调路径,禁止再硬编码;
post_callback 复用统一鉴权(双 Header 集成密钥)、脱敏请求日志与 HTTP 错误处理。
路径清单与后端 backend/app/api/freight_rpa.py 蓝图路由一一对应,改动须双侧同步。
"""
from __future__ import annotations
import json
import sys
import urllib.error
import urllib.request
from rpa_common import env as _env
_CALLBACK_BASE = "/api/freight-rpa"
# 心跳(rpa_heartbeat.post_heartbeat 使用;Worker 守护线程周期上报)。
HEARTBEAT = f"{_CALLBACK_BASE}/heartbeat"
# onhand(在手库存)Worker 回调。
ONHAND_READY = f"{_CALLBACK_BASE}/onhand-ready"
ONHAND_BATCH_CLAIMED = f"{_CALLBACK_BASE}/onhand-batch-claimed"
ONHAND_BATCH_PROGRESS = f"{_CALLBACK_BASE}/onhand-batch-progress"
ONHAND_BATCH_READY = f"{_CALLBACK_BASE}/onhand-batch-ready"
# onhand 配置测试(旧 inventory-configuration-test-*:batch-progress→start、ready→analyze、
# batch-ready→complete,与后端蓝图分发语义一一对应)。
ONHAND_CONFIGURATION_TEST_START = f"{_CALLBACK_BASE}/onhand-configuration-test-start"
ONHAND_CONFIGURATION_TEST_ANALYZE = f"{_CALLBACK_BASE}/onhand-configuration-test-analyze"
ONHAND_CONFIGURATION_TEST_COMPLETE = f"{_CALLBACK_BASE}/onhand-configuration-test-complete"
# onhand 受控修复(人工/运维补偿链路,复用正式 v2 ingest 流程)。
ONHAND_REPAIR = f"{_CALLBACK_BASE}/onhand-repair"
# inbound(入站,原收料)Worker 回调。
INBOUND_BATCH_READY = f"{_CALLBACK_BASE}/inbound-batch-ready"
INBOUND_UNIT_PROGRESS = f"{_CALLBACK_BASE}/inbound-unit-progress"
INBOUND_BATCH_PROGRESS = f"{_CALLBACK_BASE}/inbound-batch-progress"
# outbound(出站)Worker 回调。
OUTBOUND_BATCH_READY = f"{_CALLBACK_BASE}/outbound-batch-ready"
OUTBOUND_UNIT_PROGRESS = f"{_CALLBACK_BASE}/outbound-unit-progress"
OUTBOUND_BATCH_PROGRESS = f"{_CALLBACK_BASE}/outbound-batch-progress"
# 货代上传结果(URL 词根不变,仅前缀换为 /api/freight-rpa)。
UPLOAD_COMPLETE = f"{_CALLBACK_BASE}/upload-complete"
def _mask_secret(value: str) -> str:
"""对集成密钥做首尾保留脱敏:长度 ≤8 返回 ***,否则保留前 4 后 4。"""
value = str(value or "")
if len(value) <= 8:
return "***"
return f"{value[:4]}...{value[-4:]}"
def post_callback(path: str, payload: dict, *, timeout: int = 30) -> None:
"""
向 HXOPS 货代回调 API 发送 JSON 请求(所有 Worker 回调的统一出口)。
【AI 触发时机】:Worker 完成导出/上传/领取等节点需要回传后端时调用;
path 必须传本模块导出的常量,禁止拼接旧 shipping-notice rpa 回调前缀字符串。
核心逻辑:HXOPS_API_BASE + path 组装 URL → 双 Header 密钥鉴权 → 打印脱敏请求日志 →
POST;HTTP 非 2xx 时打印响应体摘要并抛 RuntimeError(由调用方决定归档 failed)。
Args:
path: 回调路径,仅允许本模块 *_READY / *_PROGRESS / *_CLAIMED / HEARTBEAT /
UPLOAD_COMPLETE 等常量;业务约束——禁止传入完整 URL 或未知路径。
payload: JSON 请求体(dict,UTF-8 序列化)。
timeout: 请求超时秒数,默认 30。
Raises:
SystemExit: 三个集成密钥环境变量全部缺失。
RuntimeError: 密钥含非 ASCII 字符,或后端返回 HTTP 非 2xx。
"""
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:
raise SystemExit("Missing SHIPPING_NOTICE_TOOL_API_KEY, INTEGRATION_API_KEY, or HXOPS_TOOLS_API_KEY")
try:
key.encode("latin-1")
except UnicodeEncodeError as exc:
raise RuntimeError(
"SHIPPING_NOTICE_TOOL_API_KEY/INTEGRATION_API_KEY must be an ASCII token, "
"not a Chinese placeholder or description"
) from exc
url = f"{base}{path}"
data = json.dumps(payload, ensure_ascii=False).encode("utf-8")
print(
"[callback-request] "
f"POST {url} "
f"headers={{'Content-Type': 'application/json', "
f"'X-Integration-Key': '{_mask_secret(key)}', "
f"'X-Shipping-Tool-Key': '{_mask_secret(key)}'}} "
f"payload={data.decode('utf-8', errors='replace')[:4000]}"
)
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=timeout) as resp:
body = resp.read().decode("utf-8")
print(f"[callback] {path} -> {resp.status} {body[:200]}")
except urllib.error.HTTPError as exc:
err = exc.read().decode("utf-8", errors="replace")
print(
"[callback-response] "
f"POST {url} -> HTTP {exc.code} {err[:1000]}",
file=sys.stderr,
)
raise RuntimeError(f"callback {path} HTTP {exc.code}: {err[:300]}") from exc