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,120 @@
|
||||
"""
|
||||
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 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"
|
||||
# 货代上传结果(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
|
||||
@@ -14,11 +14,11 @@ from pathlib import Path as _Path
|
||||
_RPA_ROOT = next(
|
||||
(_c for _c in _Path(__file__).resolve().parents
|
||||
if (_c / "connectors").is_dir() and (_c / "common").is_dir()
|
||||
and (_c / "inventory").is_dir() and (_c / "receipt").is_dir()),
|
||||
and (_c / "onhand").is_dir() and (_c / "inbound").is_dir()),
|
||||
None,
|
||||
)
|
||||
if _RPA_ROOT is not None:
|
||||
for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "inventory", "receipt"):
|
||||
for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "onhand", "inbound"):
|
||||
_dir = str(_RPA_ROOT) if not _rel else str(_RPA_ROOT / _rel)
|
||||
if _dir not in _sys.path:
|
||||
_sys.path.insert(0, _dir)
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
"""
|
||||
scripts/freight_rpa/common/rpa_heartbeat.py
|
||||
|
||||
用途:货代 RPA Worker 向后端上报心跳(POST /api/shipping-notice/rpa/heartbeat)。
|
||||
用途:货代 RPA Worker 向后端上报心跳(POST /api/freight-rpa/heartbeat(路径常量见 common/rpa_callbacks.HEARTBEAT))。
|
||||
依赖:rpa_common.env、urllib、socket。
|
||||
逻辑:由库存/收料 Worker 主循环或守护线程按 FREIGHT_RPA_WORKER_HEARTBEAT_SECONDS 周期调用;
|
||||
库存声明 inventory_export,收料声明 receipt_export;库存侧可写共享目录哨兵。
|
||||
逻辑:由 onhand/inbound Worker 主循环或守护线程按 FREIGHT_RPA_WORKER_HEARTBEAT_SECONDS 周期调用;
|
||||
onhand 声明 onhand_export,inbound(原收料)声明 inbound_export;onhand 侧可写共享目录哨兵。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -15,11 +15,11 @@ from pathlib import Path as _Path
|
||||
_RPA_ROOT = next(
|
||||
(_c for _c in _Path(__file__).resolve().parents
|
||||
if (_c / "connectors").is_dir() and (_c / "common").is_dir()
|
||||
and (_c / "inventory").is_dir() and (_c / "receipt").is_dir()),
|
||||
and (_c / "onhand").is_dir() and (_c / "inbound").is_dir()),
|
||||
None,
|
||||
)
|
||||
if _RPA_ROOT is not None:
|
||||
for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "inventory", "receipt"):
|
||||
for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "onhand", "inbound"):
|
||||
_dir = str(_RPA_ROOT) if not _rel else str(_RPA_ROOT / _rel)
|
||||
if _dir not in _sys.path:
|
||||
_sys.path.insert(0, _dir)
|
||||
@@ -37,6 +37,8 @@ from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from rpa_common import env as _env
|
||||
# 心跳路径单一真相(/api/freight-rpa/heartbeat),与业务回调共用 rpa_callbacks 常量。
|
||||
from rpa_callbacks import HEARTBEAT as _HEARTBEAT_PATH # noqa: E402
|
||||
|
||||
_RUNTIME_STATUS = "idle"
|
||||
_LAST_HEARTBEAT_MONO = 0.0
|
||||
@@ -82,7 +84,7 @@ def _resolve_shared_scope_id() -> str:
|
||||
value = str(raw or "").strip()
|
||||
if value:
|
||||
return value
|
||||
trigger = str(_env("FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR") or "").replace("\\", "/").lower()
|
||||
trigger = str(_env("FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR") or "").replace("\\", "/").lower()
|
||||
for token in ("hxops-rpa-test-data", "hxops-rpa-prod-data"):
|
||||
if token in trigger:
|
||||
return token
|
||||
@@ -136,14 +138,14 @@ def build_heartbeat_payload(
|
||||
"""
|
||||
组装心跳 payload。
|
||||
|
||||
核心逻辑:库存 Worker 声明 inventory_export;收料 Worker(worker_id 以 -receipt
|
||||
结尾,或 trigger_dir 路径含 /receipt/)声明 receipt_export;开启上传时附加 freight_upload。
|
||||
核心逻辑:onhand Worker 声明 onhand_export;inbound Worker(worker_id 以 -inbound
|
||||
结尾,或 trigger_dir 路径含 /inbound/)声明 inbound_export;开启上传时附加 freight_upload。
|
||||
"""
|
||||
hostname = socket.gethostname()
|
||||
worker_id = _resolve_worker_id(hostname)
|
||||
trigger_norm = str(trigger_dir or "").replace("\\", "/").lower()
|
||||
is_receipt = str(worker_id).lower().endswith("-receipt") or "/receipt/" in f"/{trigger_norm}/"
|
||||
capabilities = ["receipt_export" if is_receipt else "inventory_export"]
|
||||
is_inbound = str(worker_id).lower().endswith("-inbound") or "/inbound/" in f"/{trigger_norm}/"
|
||||
capabilities = ["inbound_export" if is_inbound else "onhand_export"]
|
||||
upload_enabled = str(_env("FREIGHT_RPA_WORKER_UPLOAD_ENABLED", "false") or "false").strip().lower() in {
|
||||
"1", "true", "yes", "on",
|
||||
}
|
||||
@@ -179,7 +181,7 @@ def post_heartbeat(payload: dict[str, Any]) -> bool:
|
||||
print("[heartbeat] skipped: missing SHIPPING_NOTICE_TOOL_API_KEY", file=sys.stderr)
|
||||
return False
|
||||
|
||||
url = f"{base}/api/shipping-notice/rpa/heartbeat"
|
||||
url = f"{base}{_HEARTBEAT_PATH}"
|
||||
data = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
||||
req = urllib.request.Request(
|
||||
url,
|
||||
@@ -225,7 +227,7 @@ def _start_heartbeat_request(payload: dict[str, Any]) -> bool:
|
||||
thread = threading.Thread(
|
||||
target=post_heartbeat,
|
||||
args=(payload,),
|
||||
name="shipping-rpa-heartbeat",
|
||||
name="freight-rpa-heartbeat",
|
||||
daemon=True,
|
||||
)
|
||||
_HEARTBEAT_THREAD = thread
|
||||
@@ -291,6 +293,6 @@ def start_heartbeat_loop(
|
||||
except Exception:
|
||||
print("[heartbeat] loop tick failed", file=sys.stderr)
|
||||
|
||||
thread = threading.Thread(target=_loop, name="shipping-rpa-heartbeat-loop", daemon=True)
|
||||
thread = threading.Thread(target=_loop, name="freight-rpa-heartbeat-loop", daemon=True)
|
||||
thread.start()
|
||||
return thread
|
||||
@@ -3,7 +3,7 @@ scripts/freight_rpa/common/worker_disk_cleanup.py
|
||||
|
||||
用途:RPA Worker 本机磁盘保留清理,防止 logs / 归档 trigger / drop 归档 / 孤儿临时 Profile 长期堆积撑爆盘符。
|
||||
依赖:rpa_common.env、pathlib、shutil、time。
|
||||
逻辑:由 inventory(及可复用的 receipt)Worker 主循环周期调用;只删超过保留期的归档与临时物,
|
||||
逻辑:由 onhand(及可复用的 inbound)Worker 主循环周期调用;只删超过保留期的归档与临时物,
|
||||
绝不删除进行中的 trigger 根目录 JSON、可复用会话 Profile(*_session)、以及活跃 cleanup 队列。
|
||||
"""
|
||||
|
||||
@@ -18,13 +18,13 @@ _RPA_ROOT = next(
|
||||
for _c in _Path(__file__).resolve().parents
|
||||
if (_c / "connectors").is_dir()
|
||||
and (_c / "common").is_dir()
|
||||
and (_c / "inventory").is_dir()
|
||||
and (_c / "receipt").is_dir()
|
||||
and (_c / "onhand").is_dir()
|
||||
and (_c / "inbound").is_dir()
|
||||
),
|
||||
None,
|
||||
)
|
||||
if _RPA_ROOT is not None:
|
||||
for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "inventory", "receipt"):
|
||||
for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "onhand", "inbound"):
|
||||
_dir = str(_RPA_ROOT) if not _rel else str(_RPA_ROOT / _rel)
|
||||
if _dir not in _sys.path:
|
||||
_sys.path.insert(0, _dir)
|
||||
@@ -48,9 +48,9 @@ _PROTECTED_DROP_DIRNAMES = frozenset(
|
||||
)
|
||||
_DROP_ROOT_SUFFIXES = frozenset({".xlsx", ".xls", ".csv", ".hxops_consumed"})
|
||||
_TRIGGER_ARCHIVE_DIRNAMES = ("processed", "failed")
|
||||
# 一次性运行 Profile 前缀:库存 Worker 用 run_*,收料 Worker 用 receipt_*,
|
||||
# 一次性运行 Profile 前缀:onhand Worker 用 run_*,inbound Worker 用 inbound_*,
|
||||
# 两者均为浏览器崩溃/异常中断后可能残留的临时目录,超期统一清理。
|
||||
_RUNTIME_PROFILE_TEMP_PREFIXES = ("run_", "receipt_")
|
||||
_RUNTIME_PROFILE_TEMP_PREFIXES = ("run_", "inbound_")
|
||||
_DEFAULT_RETENTION_DAYS = 7
|
||||
_DEFAULT_INTERVAL_SECONDS = 3600
|
||||
_DEFAULT_ORPHAN_PROFILE_HOURS = 24
|
||||
@@ -111,7 +111,7 @@ def cleanup_interval_seconds() -> int:
|
||||
|
||||
def orphan_profile_max_age_seconds() -> int:
|
||||
"""
|
||||
读取孤儿临时 Profile(run_* / receipt_*)最大存活秒数。
|
||||
读取孤儿临时 Profile(run_* / inbound_*)最大存活秒数。
|
||||
|
||||
核心逻辑:`FREIGHT_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS`,默认 24;
|
||||
`<=0` 禁用孤儿 Profile 清理。会话复用目录(*_session)永不删除。
|
||||
@@ -335,11 +335,11 @@ def cleanup_orphan_runtime_profiles(
|
||||
stats: DiskCleanupStats,
|
||||
) -> None:
|
||||
"""
|
||||
清理浏览器 Profile 根下过期的一次性 `run_*` / `receipt_*` 目录。
|
||||
清理浏览器 Profile 根下过期的一次性 `run_*` / `inbound_*` 目录。
|
||||
|
||||
核心逻辑:会话复用目录名以 `_session` 结尾或历史 `dsv360_session`,一律保留;
|
||||
仅删除 `run_*` / `receipt_*` 临时目录,避免异常中断后残留撑盘。
|
||||
收料 Worker 一次性 Profile 以 receipt_ 前缀创建,同属清理对象。
|
||||
仅删除 `run_*` / `inbound_*` 临时目录,避免异常中断后残留撑盘。
|
||||
inbound Worker 一次性 Profile 以 inbound_ 前缀创建,同属清理对象。
|
||||
"""
|
||||
if profile_root is None or not profile_root.is_dir():
|
||||
return
|
||||
@@ -365,7 +365,7 @@ def cleanup_orphan_runtime_profiles(
|
||||
|
||||
def run_worker_disk_cleanup(
|
||||
*,
|
||||
inventory_trigger_dir: Path | None = None,
|
||||
onhand_trigger_dir: Path | None = None,
|
||||
upload_trigger_dir: Path | None = None,
|
||||
drop_dir: Path | None = None,
|
||||
upload_queue_dir: Path | None = None,
|
||||
@@ -379,12 +379,12 @@ def run_worker_disk_cleanup(
|
||||
【AI 触发时机】:Worker 启动后及主循环按 `DISK_CLEANUP_INTERVAL_SECONDS` 周期调用。
|
||||
|
||||
核心逻辑:按 `DISK_RETENTION_DAYS` 清理归档/日志备份/队列残留;按
|
||||
`ORPHAN_PROFILE_MAX_AGE_HOURS` 清理孤儿 `run_*` / `receipt_*` Profile。全部 best-effort。
|
||||
`ORPHAN_PROFILE_MAX_AGE_HOURS` 清理孤儿 `run_*` / `inbound_*` Profile。全部 best-effort。
|
||||
|
||||
Args:
|
||||
inventory_trigger_dir: 库存 trigger 根目录。
|
||||
onhand_trigger_dir: onhand trigger 根目录。
|
||||
upload_trigger_dir: 上传 trigger 根目录。
|
||||
drop_dir: 库存 drop 根目录。
|
||||
drop_dir: onhand drop 根目录。
|
||||
upload_queue_dir: 上传队列目录。
|
||||
browser_profile_dir: 浏览器 Profile 根目录。
|
||||
log_file: 当前 worker 日志文件路径。
|
||||
@@ -398,7 +398,7 @@ def run_worker_disk_cleanup(
|
||||
days = retention_days()
|
||||
if days > 0:
|
||||
cutoff = now - (days * 86400)
|
||||
cleanup_trigger_archives(inventory_trigger_dir, cutoff_unix=cutoff, stats=stats)
|
||||
cleanup_trigger_archives(onhand_trigger_dir, cutoff_unix=cutoff, stats=stats)
|
||||
cleanup_trigger_archives(upload_trigger_dir, cutoff_unix=cutoff, stats=stats)
|
||||
cleanup_drop_archives(drop_dir, cutoff_unix=cutoff, stats=stats)
|
||||
cleanup_upload_queue(upload_queue_dir, cutoff_unix=cutoff, stats=stats)
|
||||
|
||||
Reference in new issue
Block a user