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:
hugoandCursor committed 2026-10-17 23:18:48 +08:00
1 parent bf3154033b
commit ffc0d4a430
147 files changed
+4221 -2678

No files matched your search

@@ -0,0 +1 @@
"""货代 RPA 模块根:承载 freight_rpa 域代码(common/onhand/inbound/upload)。"""
@@ -0,0 +1 @@
"""common:域中立件(跨 RPA Worker 共用、不依赖具体业务域)。"""
@@ -0,0 +1,53 @@
"""
services/freight_rpa/common/callback_sinks.py
用途:RPA 回调业务 sink 注册表——freight_rpa 侧的回调分发缝。
依赖:app.core.errors.AppError。
逻辑:Worker 回调进入 /api/freight-rpa/* 蓝图后,onhand 等待拆端点按 kind 分发到
组合根(create_app / api 层)注册的业务处理器;未注册的 kind 显式 404,
绝不静默吞回调。Task 9/10 落地 workflow_protocol / report_archive 时由
组合根调用 register_sink 注入真实业务持久化处理器。
"""
from __future__ import annotations
from typing import Any, Callable
from app.core.errors import AppError
_SINKS: dict[str, Callable[..., Any]] = {}
def register_sink(kind: str, handler: Callable[..., Any]) -> None:
"""
注册一个回调 sink 处理器(由组合根在应用启动时调用)。
Args:
kind: 回调种类,命名 = 回调路由名去前缀(如 "onhand-ready"、
"onhand-configuration-test-complete");同一 kind 重复注册为覆盖。
handler: 业务处理器;契约:接收回调载荷的关键字参数并返回可 jsonify 的业务结果。
"""
_SINKS[kind] = handler
def dispatch_sink(kind: str, **payload: Any) -> Any:
"""
按 kind 分发回调载荷到已注册 sink。
Args:
kind: register_sink 注册过的回调种类。
payload: 回调载荷键值对;键必须为合法 Python 标识符(回调 schema 均为 snake_case)。
Returns:
handler 的返回值(业务结果 dict,由蓝图 jsonify)。
Raises:
AppError: code=FREIGHT_RPA.SINK_NOT_REGISTERED、http_status=404——kind 未注册时
显式失败(Task 9/10 注册真实 sink 前的既定语义)。
"""
handler = _SINKS.get(kind)
if handler is None:
raise AppError(
code='FREIGHT_RPA.SINK_NOT_REGISTERED',
message=f'No callback sink registered for kind: {kind}',
http_status=404,
)
return handler(**payload)
@@ -0,0 +1,57 @@
"""
services/freight_rpa/common/credential_crypto.py
用途:加密和解密库存 RPA Profile 的登录凭据(委托通用 core 模块,仅固定本域密钥键与错误码)。
依赖:app.core.credential_crypto(Fernet 加解密);调用方仅保存密文,不将凭据写入日志或 API 响应。
逻辑:管理服务写入 Profile 前调用 encrypt_credential;RPA 配置读取服务在受控内存中调用
decrypt_credential。主密钥键 FREIGHT_RPA_CREDENTIAL_KEY(2026-09-18 RPA 命名空间)。
"""
from __future__ import annotations
from app.core.credential_crypto import CredentialCryptoErrorCodes, decrypt_secret, encrypt_secret
# 本域历史错误码原样保留,调用方(管理服务/测试)不受重构影响。
_RPA_CODES = CredentialCryptoErrorCodes(
key_missing='SHIPPING.RPA_CREDENTIAL_KEY_MISSING',
key_invalid='SHIPPING.RPA_CREDENTIAL_KEY_INVALID',
secret_empty='SHIPPING.RPA_CREDENTIAL_EMPTY',
secret_missing='SHIPPING.RPA_CREDENTIAL_MISSING',
secret_invalid='SHIPPING.RPA_CREDENTIAL_INVALID',
)
_KEY_CONFIG_NAME = 'FREIGHT_RPA_CREDENTIAL_KEY'
def encrypt_credential(value: str) -> str:
"""
加密单个 RPA 凭据字段以便持久化。
Args:
value: 非空明文凭据;调用方不得记录此值。
Returns:
str: 可安全保存到数据库的 Fernet 密文。
Raises:
ServiceUnavailableError: 未配置或配置了无效的主密钥。
ValidationError: 传入空凭据。
"""
return encrypt_secret(value, key_config_name=_KEY_CONFIG_NAME, codes=_RPA_CODES)
def decrypt_credential(ciphertext: str) -> str:
"""
在受控运行时解密 RPA 凭据。
Args:
ciphertext: 数据库中保存的 Fernet 密文。
Returns:
str: 仅供 RPA 执行内存使用的明文。
Raises:
ServiceUnavailableError: 未配置或配置了无效的主密钥。
ValidationError: 密文为空、已损坏或使用了错误主密钥。
"""
return decrypt_secret(ciphertext, key_config_name=_KEY_CONFIG_NAME, codes=_RPA_CODES)
@@ -0,0 +1,36 @@
"""
services/freight_rpa/common/rpa_runtime.py
用途:RPA 运行模式(browser/mock)的展示助手——把任务回调记录或后端配置规范化为前端安全摘要。
依赖:Flask current_app 配置(FREIGHT_RPA_WORKER_MOCK);不依赖目录 IO 与 Worker 文件契约。
逻辑:由 shipping_notice.query_service(任务序列化注入 rpa_runtime 摘要)、
同包 worker_heartbeat(mock 模式下跳过真实 Worker 在线探测)消费;
仅做展示归一,不承载触发/回调逻辑。
"""
from __future__ import annotations
from typing import Any
from flask import current_app
def _runtime_summary(mode: str) -> dict[str, str | bool]:
"""将 browser/mock 规范化为前端安全展示摘要。"""
normalized = "mock" if str(mode or "").strip().lower() == "mock" else "browser"
mock_enabled = normalized == "mock"
return {
"mode": normalized,
"label": "Mock RPA" if mock_enabled else "真实 RPA",
"mock": mock_enabled,
}
def rpa_runtime_mode(runtime: dict[str, Any] | None = None) -> dict[str, str | bool]:
"""返回 RPA 运行模式摘要;优先使用任务最近一次回调实际模式,兜底读取当前后端配置。"""
if isinstance(runtime, dict):
mode = str(runtime.get("mode") or runtime.get("rpa_mode") or "").strip().lower()
if mode in {"browser", "mock"}:
return _runtime_summary(mode)
raw = str(current_app.config.get("FREIGHT_RPA_WORKER_MOCK", "false") or "false").strip().lower()
return _runtime_summary("mock" if raw in {"1", "true", "yes", "on"} else "browser")
@@ -0,0 +1,917 @@
"""
services/freight_rpa/common/worker_heartbeat.py
用途:货代 RPA Worker 心跳存储、共享目录校验、库存/上传/收料就绪检查与状态查询。
依赖:Flask current_app、redis_client、同包 rpa_runtime(mock 模式)、
freight_rpa.onhand.trigger_io(onhand trigger 目录)、
freight_rpa.upload.trigger_io(上传目录)、
freight_rpa.inbound.trigger_io(inbound trigger 目录)。
逻辑:Windows Worker 调 POST /api/freight-rpa/heartbeat;写 onhand/upload/inbound trigger 前强制就绪检查;
管理端 /rpa-workers/status?scope=onhand|inbound 展示对应 Worker 心跳徽标。
"""
from __future__ import annotations
import json
import logging
import os
import threading
import time
from dataclasses import dataclass, field
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
from flask import current_app
from app.core.config.settings import _normalize_env_name
from app.core.errors import ServiceUnavailableError
from app.services.freight_rpa.onhand.trigger_io import onhand_trigger_dir
from .rpa_runtime import rpa_runtime_mode
logger = logging.getLogger(__name__)
RPA_WORKER_OFFLINE_MESSAGE = "RPA Worker 未在线,请启动 Windows RPA 服务后重试"
RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE = "RPA Worker 心跳存储不可用,请检查 Redis 连接"
RPA_FREIGHT_UPLOAD_NOT_READY_MESSAGE = "货代上传 RPA 未就绪,请检查 Worker、凭据与共享目录后重试"
# [PROMPT_UPDATE] 2026-10-16 freight_rpa 解耦批次 R:能力串随 Worker 侧(Task 12)切换——
# inventory_export→onhand_export、receipt_export→inbound_export(freight_upload 不变);
# worker_id 后缀判定 -receipt→-inbound(ps1 注入值随发布窗口改配,见 cutover runbook)。
ONHAND_EXPORT_CAPABILITY = "onhand_export"
FREIGHT_UPLOAD_CAPABILITY = "freight_upload"
INBOUND_EXPORT_CAPABILITY = "inbound_export"
# inbound Worker 由 start_inbound_worker.ps1 注入 FREIGHT_RPA_WORKER_ID=<主机名>-inbound。
INBOUND_WORKER_ID_SUFFIX = "-inbound"
_REDIS_INDEX_KEY = "shipping:rpa:heartbeat:index"
_REDIS_WORKER_KEY_PREFIX = "shipping:rpa:heartbeat:worker:"
_MEMORY_STORE: dict[str, dict[str, Any]] = {}
_MEMORY_LOCK = threading.Lock()
_REASON_USER_HINTS: dict[str, str] = {
"no_worker_heartbeat": "未收到任何 Worker 心跳",
"heartbeat_store_process_local": "未配置 REDIS_URL(或 Redis 不可达),心跳存储为本进程内存,跨进程不可见;请配置 REDIS_URL 或设 FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED=false 跳过心跳检查",
"heartbeat_storage_unavailable": "心跳存储不可用(Redis)",
"trigger_dir_not_configured": "后端未配置 trigger 目录",
"trigger_dir_not_accessible": "trigger 目录不存在或不可访问",
"shared_sentinel_missing": "共享目录哨兵文件缺失,可能 CIFS 未挂载",
"shared_scope_mismatch": "共享目录 scope 与后端配置不一致",
"trigger_dir_not_writable": "trigger 目录不可写",
"environment_mismatch": "Worker 环境与后端环境不一致",
"missing_onhand_export_capability": "Worker 未声明 onhand_export 能力",
"missing_inbound_export_capability": "Worker 未声明 inbound_export 能力",
"missing_freight_upload_capability": "Worker 未声明 freight_upload 能力",
"credential_key_missing": "未配置 FREIGHT_RPA_CREDENTIAL_KEY",
"upload_queue_dir_not_configured": "未配置货代上传队列目录",
"upload_queue_dir_not_accessible": "货代上传队列目录不可访问",
"callback_api_base_missing": "未配置 Worker 回调可达的 API 基址",
"auto_upload_disabled": "SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED 未显式开启",
}
@dataclass
class RpaWorkerReadiness:
"""库存 RPA 触发前就绪检查结果。"""
ready: bool
message: str
workers: list[dict[str, Any]] = field(default_factory=list)
reasons: list[str] = field(default_factory=list)
checked_at: str = ""
detail_message: str = ""
def _utc_now_iso() -> str:
return datetime.now(timezone.utc).replace(tzinfo=None).isoformat()
def _config_bool(key: str, default: bool) -> bool:
if current_app:
raw = current_app.config.get(key, default)
else:
raw = os.getenv(key, str(default).lower())
return str(raw).strip().lower() in {"1", "true", "yes", "on"}
def _config_str(key: str, default: str = "") -> str:
if current_app:
raw = current_app.config.get(key, default)
else:
raw = os.getenv(key, default)
return str(raw or default).strip()
def _heartbeat_ttl_seconds() -> int:
raw = 90
if current_app:
raw = int(current_app.config.get("FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS") or 90)
else:
raw = int(os.getenv("FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS") or "90")
return max(60, raw)
def _heartbeat_check_required() -> bool:
"""Mock RPA 或显式关闭时跳过 worker 心跳就绪检查。"""
if rpa_runtime_mode().get("mock"):
return False
return _config_bool("FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED", True)
def _heartbeat_redis_required() -> bool:
"""test/prod 默认要求 Redis;dev 仅显式开启时要求。"""
explicit = os.getenv("FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS")
if explicit is not None and str(explicit).strip() != "":
return _config_bool("FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS", False)
if current_app:
configured = current_app.config.get("FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS")
if configured is not None:
return bool(configured)
env_name = resolve_backend_rpa_environment()
return env_name in {"test", "prod"}
def _heartbeat_allow_memory_fallback() -> bool:
return _config_bool("FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK", False)
def resolve_backend_rpa_environment() -> str:
"""将后端部署环境归一为 dev / test / prod。"""
env_name = os.getenv("ENV_NAME") or os.getenv("FLASK_ENV")
if current_app:
env_name = current_app.config.get("ENV_NAME") or env_name
return _normalize_env_name(env_name)
def shared_scope_id() -> str:
"""共享 SMB 目录逻辑标识(如 hxops-rpa-test-data),用于跨平台路径对齐。"""
explicit = _config_str("FREIGHT_RPA_SHARED_SCOPE_ID", "")
if explicit:
return explicit
trigger_dir = onhand_trigger_dir()
if not trigger_dir:
return ""
for part in Path(trigger_dir).parts:
normalized = str(part).strip().lower()
if normalized.startswith("hxops-rpa-"):
return normalized
return ""
def shared_sentinel_name() -> str:
return _config_str("FREIGHT_RPA_SHARED_SENTINEL_NAME", ".hxops_rpa_shared_mount")
def _shared_mount_check_required() -> bool:
"""配置了 scope_id 或 test/prod 环境时强制校验共享哨兵。"""
if shared_scope_id():
return True
return resolve_backend_rpa_environment() in {"test", "prod"}
def _parse_capabilities(raw: Any) -> set[str]:
if isinstance(raw, str):
values = [part.strip().lower() for part in raw.split(",")]
elif isinstance(raw, list):
values = [str(part).strip().lower() for part in raw]
else:
values = []
return {value for value in values if value}
def _coerce_worker_payload(payload: dict[str, Any]) -> dict[str, Any]:
"""校验并规范化 worker 心跳 payload。"""
worker_id = str(payload.get("worker_id") or "").strip()
if not worker_id:
raise ValueError("worker_id is required")
timestamp = str(payload.get("timestamp") or "").strip() or _utc_now_iso()
environment = str(payload.get("environment") or "").strip().lower() or resolve_backend_rpa_environment()
status = str(payload.get("status") or "idle").strip().lower()
if status not in {"idle", "busy"}:
status = "idle"
scope = str(payload.get("shared_scope_id") or "").strip()
return {
"worker_id": worker_id,
"hostname": str(payload.get("hostname") or "").strip(),
"environment": environment,
"capabilities": sorted(_parse_capabilities(payload.get("capabilities"))),
"status": status,
"trigger_dir": str(payload.get("trigger_dir") or "").strip(),
"drop_dir": str(payload.get("drop_dir") or "").strip(),
"shared_scope_id": scope,
"version": str(payload.get("version") or "").strip(),
"timestamp": timestamp,
"received_at": _utc_now_iso(),
}
def _redis_client():
from app.services.redis_client import get_redis_client
return get_redis_client()
def _memory_store_worker(worker: dict[str, Any]) -> None:
with _MEMORY_LOCK:
_MEMORY_STORE[worker["worker_id"]] = dict(worker)
def _memory_list_workers() -> list[dict[str, Any]]:
with _MEMORY_LOCK:
return [dict(item) for item in _MEMORY_STORE.values()]
def reset_rpa_worker_heartbeat_state_for_tests() -> None:
"""单测隔离:清空进程内内存心跳缓存,并尽力清除 Redis 中的持久心跳记录。"""
with _MEMORY_LOCK:
_MEMORY_STORE.clear()
try:
client = _redis_client()
if client is None:
return
worker_ids = list(client.smembers(_REDIS_INDEX_KEY) or [])
stale_worker_keys = [f"{_REDIS_WORKER_KEY_PREFIX}{worker_id}" for worker_id in worker_ids]
if stale_worker_keys:
client.delete(*stale_worker_keys)
client.delete(_REDIS_INDEX_KEY)
except Exception:
# 隔离辅助尽力而为:Redis 不可用时内存清空已足够单测运行。
pass
def _redis_store_worker(worker: dict[str, Any]) -> bool:
client = _redis_client()
if client is None:
return False
ttl = _heartbeat_ttl_seconds() * 2
key = f"{_REDIS_WORKER_KEY_PREFIX}{worker['worker_id']}"
try:
client.set(key, json.dumps(worker, ensure_ascii=False), ex=ttl)
client.sadd(_REDIS_INDEX_KEY, worker["worker_id"])
client.expire(_REDIS_INDEX_KEY, ttl * 4)
return True
except Exception:
logger.exception("[rpa-heartbeat] redis store failed worker_id=%s", worker.get("worker_id"))
return False
def _redis_list_workers() -> tuple[list[dict[str, Any]], bool]:
"""
从 Redis 读取 worker 心跳列表。
Returns:
tuple[list, read_failed]: read_failed=True 表示 Redis 读取异常(非“无心跳”)。
"""
client = _redis_client()
if client is None:
return [], False
workers: list[dict[str, Any]] = []
try:
worker_ids = client.smembers(_REDIS_INDEX_KEY) or []
for worker_id in sorted(worker_ids):
raw = client.get(f"{_REDIS_WORKER_KEY_PREFIX}{worker_id}")
if not raw:
continue
parsed = json.loads(raw)
if isinstance(parsed, dict):
workers.append(parsed)
except Exception:
logger.exception("[rpa-heartbeat] redis list failed")
return [], True
return workers, False
def record_rpa_worker_heartbeat(payload: dict[str, Any]) -> dict[str, Any]:
"""
记录 RPA Worker 心跳。
核心逻辑:test/prod 必须写 Redis;仅 dev 且显式允许时才降级进程内存。
"""
worker = _coerce_worker_payload(payload)
stored_in_redis = _redis_store_worker(worker)
if stored_in_redis:
worker["storage"] = "redis"
return worker
if _heartbeat_redis_required():
raise ServiceUnavailableError(
RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE,
code="RPA.HEARTBEAT_STORAGE_UNAVAILABLE",
details={"reason": "redis_write_failed", "worker_id": worker.get("worker_id")},
)
if _heartbeat_allow_memory_fallback():
_memory_store_worker(worker)
worker["storage"] = "memory"
return worker
raise ServiceUnavailableError(
RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE,
code="RPA.HEARTBEAT_STORAGE_UNAVAILABLE",
details={"reason": "memory_fallback_disabled", "worker_id": worker.get("worker_id")},
)
def list_rpa_worker_heartbeats() -> tuple[list[dict[str, Any]], bool]:
"""
返回当前已知 worker 心跳列表。
Returns:
tuple[workers, storage_read_failed]
"""
workers, read_failed = _redis_list_workers()
if read_failed:
return [], True
if workers:
return workers, False
if _heartbeat_redis_required():
if _redis_client() is None:
return [], True
return [], False
if _heartbeat_allow_memory_fallback():
return _memory_list_workers(), False
return [], False
def _heartbeat_age_seconds(worker: dict[str, Any], *, now: float | None = None) -> float | None:
raw = str(worker.get("received_at") or worker.get("timestamp") or "").strip()
if not raw:
return None
try:
parsed = datetime.fromisoformat(raw.replace("Z", ""))
if parsed.tzinfo is None:
parsed = parsed.replace(tzinfo=timezone.utc)
except ValueError:
return None
current = now if now is not None else time.time()
return max(current - parsed.timestamp(), 0.0)
def _parse_sentinel_content(raw: str) -> dict[str, str]:
parsed: dict[str, str] = {}
for line in raw.splitlines():
if "=" not in line:
continue
key, value = line.split("=", 1)
parsed[key.strip().lower()] = value.strip()
return parsed
def _read_shared_sentinel(trigger_dir: Path) -> tuple[dict[str, str] | None, str | None]:
sentinel_path = trigger_dir / shared_sentinel_name()
if not sentinel_path.is_file():
return None, "shared_sentinel_missing"
try:
content = sentinel_path.read_text(encoding="utf-8")
parsed = _parse_sentinel_content(content)
if not parsed:
return None, "shared_sentinel_invalid"
return parsed, None
except Exception:
return None, "shared_sentinel_unreadable"
def _verify_shared_trigger_mount(
trigger_dir: Path | None, *, require_sentinel: bool = True,
) -> tuple[bool, list[str]]:
"""
校验 trigger 目录可写;默认要求共享哨兵(库存与收料同口径)。
Args:
trigger_dir: 共享 trigger 目录。
require_sentinel: 为 True 时在 test/prod 或配置了 scope 时校验哨兵。
"""
reasons: list[str] = []
if trigger_dir is None:
return False, ["trigger_dir_not_configured"]
if not trigger_dir.exists():
return False, ["trigger_dir_not_accessible"]
if not trigger_dir.is_dir():
return False, ["trigger_dir_not_accessible"]
expected_scope = shared_scope_id()
if require_sentinel and _shared_mount_check_required():
sentinel, sentinel_reason = _read_shared_sentinel(trigger_dir)
if sentinel_reason:
reasons.append(sentinel_reason)
elif expected_scope:
actual_scope = str(sentinel.get("scope_id") or "").strip()
if actual_scope != expected_scope:
reasons.append(f"shared_scope_mismatch:{actual_scope}!={expected_scope}")
elif not str(sentinel.get("scope_id") or "").strip():
reasons.append("shared_scope_mismatch:missing_scope_id")
if reasons:
return False, reasons
try:
probe = trigger_dir / ".hxops_rpa_write_probe"
probe.write_text("ok", encoding="utf-8")
probe.unlink(missing_ok=True)
except Exception:
reasons.append("trigger_dir_not_writable")
return not reasons, reasons
def is_receipt_rpa_worker(worker: dict[str, Any]) -> bool:
"""
判断心跳是否来自 inbound(原收料)Worker。
优先认 <主机名>-inbound(ps1 注入);兼容未注入 FREIGHT_RPA_WORKER_ID、
回退为 <主机名>-<pid> 的进程——用心跳 trigger_dir 与 inbound 目录对齐判定。
"""
if str(worker.get("worker_id") or "").strip().lower().endswith(INBOUND_WORKER_ID_SUFFIX):
return True
from app.services.freight_rpa.inbound.trigger_io import inbound_trigger_dir
expected = inbound_trigger_dir()
actual = str(worker.get("trigger_dir") or "").strip()
if expected is None or not actual:
return False
try:
return Path(actual).resolve() == expected.resolve()
except OSError:
return False
def _worker_scope_matches(worker: dict[str, Any]) -> tuple[bool, list[str]]:
expected_scope = shared_scope_id()
if not expected_scope:
return True, []
worker_scope = str(worker.get("shared_scope_id") or "").strip()
if worker_scope == expected_scope:
return True, []
return False, [f"shared_scope_mismatch:{worker_scope or '-'}!={expected_scope}"]
def _worker_is_eligible(
worker: dict[str, Any],
*,
backend_env: str,
ttl_seconds: int,
now: float,
required_capability: str = ONHAND_EXPORT_CAPABILITY,
) -> tuple[bool, list[str]]:
"""
判断单 Worker 是否满足心跳新鲜度、能力声明与环境/scope 隔离。
Args:
worker: 心跳记录。
backend_env: 后端归一环境(dev/test/prod)。
ttl_seconds: 心跳 TTL。
now: 当前 epoch 秒。
required_capability: 必选能力(onhand_export / inbound_export / freight_upload)。
Returns:
(是否合格, 不合格原因列表)。
"""
reasons: list[str] = []
age = _heartbeat_age_seconds(worker, now=now)
if age is None:
reasons.append("heartbeat_timestamp_invalid")
elif age > ttl_seconds:
reasons.append(f"heartbeat_stale:{int(age)}s")
capabilities = _parse_capabilities(worker.get("capabilities"))
if required_capability and required_capability not in capabilities:
reasons.append(_missing_capability_reason(required_capability))
worker_env = str(worker.get("environment") or "").strip().lower()
if worker_env and worker_env != backend_env:
reasons.append(f"environment_mismatch:{worker_env}!={backend_env}")
scope_ok, scope_reasons = _worker_scope_matches(worker)
if not scope_ok:
reasons.extend(scope_reasons)
return not reasons, reasons
def _missing_capability_reason(required_capability: str) -> str:
"""按必选能力生成缺失原因码(onhand_export / inbound_export / freight_upload)。"""
return f"missing_{required_capability}_capability"
def _summarize_reasons(reasons: list[str]) -> str:
hints: list[str] = []
for reason in reasons:
base = reason.split(":", 1)[0]
hint = _REASON_USER_HINTS.get(base)
if hint and hint not in hints:
hints.append(hint)
return ";".join(hints) if hints else ";".join(reasons[:5])
def _build_failure_message(result: RpaWorkerReadiness) -> tuple[str, str]:
"""返回 (用户可见 message, 运维 detail_message)。"""
if any(reason == "heartbeat_storage_unavailable" for reason in result.reasons):
return RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE, _summarize_reasons(result.reasons)
detail = _summarize_reasons(result.reasons)
if not detail:
return RPA_WORKER_OFFLINE_MESSAGE, RPA_WORKER_OFFLINE_MESSAGE
return RPA_WORKER_OFFLINE_MESSAGE, f"{RPA_WORKER_OFFLINE_MESSAGE}({detail})"
def _check_rpa_worker_ready_for_capability(
*,
trigger_dir: Path | None,
required_capability: str,
extra_reasons: list[str] | None = None,
worker_predicate: Any | None = None,
require_sentinel: bool = True,
) -> RpaWorkerReadiness:
"""
通用 Worker 就绪检查:心跳存储、共享挂载、能力声明与环境隔离。
Args:
trigger_dir: 待校验的共享 trigger 目录。
required_capability: 必选 Worker 能力;空字符串表示不校验能力。
extra_reasons: 调用方预检附加原因(凭据/队列等)。
worker_predicate: 可选过滤(如仅收料 Worker);不匹配的心跳不进入列表。
require_sentinel: 是否要求共享哨兵(库存/收料同口径均 True)。
Returns:
RpaWorkerReadiness。
"""
checked_at = _utc_now_iso()
if not _heartbeat_check_required():
return RpaWorkerReadiness(
ready=True,
message="heartbeat check skipped",
checked_at=checked_at,
)
reasons: list[str] = list(extra_reasons or [])
if _heartbeat_redis_required() and _redis_client() is None:
reasons.append("heartbeat_storage_unavailable")
_mount_ok, mount_reasons = _verify_shared_trigger_mount(
trigger_dir, require_sentinel=require_sentinel,
)
reasons.extend(mount_reasons)
backend_env = resolve_backend_rpa_environment()
ttl_seconds = _heartbeat_ttl_seconds()
now = time.time()
workers, storage_read_failed = list_rpa_worker_heartbeats()
if storage_read_failed:
reasons.append("heartbeat_storage_unavailable")
if worker_predicate is not None:
workers = [worker for worker in workers if worker_predicate(worker)]
eligible_workers: list[dict[str, Any]] = []
enriched_workers: list[dict[str, Any]] = []
for worker in workers:
eligible, worker_reasons = _worker_is_eligible(
worker,
backend_env=backend_env,
ttl_seconds=ttl_seconds,
now=now,
required_capability=required_capability,
)
enriched = {
**worker,
"age_seconds": _heartbeat_age_seconds(worker, now=now),
"eligible": eligible,
"ineligible_reasons": worker_reasons,
}
enriched_workers.append(enriched)
if eligible:
eligible_workers.append(enriched)
else:
reasons.extend([f"{worker.get('worker_id')}:{reason}" for reason in worker_reasons])
if not workers and "heartbeat_storage_unavailable" not in reasons:
reasons.append("no_worker_heartbeat")
if _redis_client() is None and not eligible_workers:
# 无 Redis 时心跳存储为本进程内存:写方(API 进程收 Worker POST)与读方(排程/告警进程)
# 互不可见,本地排程必然命中 no_worker_heartbeat;追加原因码提示存储模式与本地测试姿势。
reasons.append("heartbeat_store_process_local")
mount_block_tokens = {
"trigger_dir_not_configured",
"trigger_dir_not_accessible",
"shared_sentinel_missing",
"shared_sentinel_invalid",
"shared_sentinel_unreadable",
"trigger_dir_not_writable",
}
blocking_mount = any(reason in mount_block_tokens for reason in reasons) or any(
reason.startswith("shared_scope_mismatch") for reason in reasons
)
config_block_tokens = {
"credential_key_missing",
"upload_queue_dir_not_configured",
"upload_queue_dir_not_accessible",
"callback_api_base_missing",
}
blocking_config = any(reason in config_block_tokens for reason in reasons)
ready = (
bool(eligible_workers)
and not blocking_mount
and not blocking_config
and "heartbeat_storage_unavailable" not in reasons
)
if ready:
message, detail_message = "ready", "ready"
else:
failure = RpaWorkerReadiness(ready=False, message="", reasons=sorted(set(reasons)))
if required_capability == FREIGHT_UPLOAD_CAPABILITY:
detail = _summarize_reasons(failure.reasons)
message = RPA_FREIGHT_UPLOAD_NOT_READY_MESSAGE
detail_message = f"{message}({detail})" if detail else message
else:
message, detail_message = _build_failure_message(failure)
return RpaWorkerReadiness(
ready=ready,
message=message,
detail_message=detail_message,
workers=enriched_workers,
reasons=sorted(set(reasons)),
checked_at=checked_at,
)
def check_inventory_rpa_worker_ready() -> RpaWorkerReadiness:
"""
检查库存 RPA 触发前 worker 是否就绪。
核心逻辑:Redis 可用、共享哨兵有效、最近心跳在 TTL 内、环境/scope 匹配。
"""
return _check_rpa_worker_ready_for_capability(
trigger_dir=onhand_trigger_dir(),
required_capability=ONHAND_EXPORT_CAPABILITY,
)
def check_receipt_rpa_worker_ready() -> RpaWorkerReadiness:
"""
检查收料 RPA Worker 是否在线(管理端徽标 + 写 trigger 前 fail-fast)。
核心逻辑:仅看 inbound Worker 心跳(*-inbound 或 trigger_dir 对齐);要求
inbound_export 能力;校验 inbound trigger 目录可写;与 onhand 同口径要求共享哨兵。
"""
from app.services.freight_rpa.inbound.trigger_io import inbound_trigger_dir
return _check_rpa_worker_ready_for_capability(
trigger_dir=inbound_trigger_dir(),
required_capability=INBOUND_EXPORT_CAPABILITY,
worker_predicate=is_receipt_rpa_worker,
require_sentinel=True,
)
def assert_receipt_rpa_worker_ready() -> None:
"""
写收料 trigger 前的强制就绪检查。
核心逻辑:镜像 assert_inventory_rpa_worker_ready;离线则抛 ServiceUnavailableError,
排程不得进入 awaiting_receipt_rpa。
Raises:
ServiceUnavailableError: worker 未就绪、共享目录无效或心跳存储不可用。
"""
from app.services.freight_rpa.inbound.trigger_io import inbound_trigger_dir
result = check_receipt_rpa_worker_ready()
if result.ready:
return
code = 'RPA.WORKER_OFFLINE'
if 'heartbeat_storage_unavailable' in result.reasons:
code = 'RPA.HEARTBEAT_STORAGE_UNAVAILABLE'
logger.warning(
'[rpa-heartbeat] receipt readiness blocked code=%s reasons=%s detail=%s',
code,
result.reasons,
result.detail_message,
)
raise ServiceUnavailableError(
result.message,
code=code,
details={
'reasons': result.reasons,
'detail_message': result.detail_message,
'checked_at': result.checked_at,
'shared_scope_id': shared_scope_id(),
'trigger_dir': str(inbound_trigger_dir() or ''),
},
)
def _freight_upload_config_reasons() -> list[str]:
"""
预检货代上传静态配置:凭据主密钥、上传队列目录、回调 API 基址。
Returns:
不合规原因码列表(空表示静态配置通过)。
"""
from app.services.freight_rpa.upload.trigger_io import upload_queue_dir, upload_trigger_dir
reasons: list[str] = []
credential_key = _config_str("FREIGHT_RPA_CREDENTIAL_KEY", "")
if not credential_key:
reasons.append("credential_key_missing")
queue_dir = upload_queue_dir()
if queue_dir is None:
reasons.append("upload_queue_dir_not_configured")
elif not queue_dir.exists() or not queue_dir.is_dir():
reasons.append("upload_queue_dir_not_accessible")
# Worker 经 HXOPS_API_BASE / INTERNAL_API_BASE_URL 回调 upload-complete。
callback_base = (
_config_str("INTERNAL_API_BASE_URL", "")
or _config_str("HXOPS_API_BASE", "")
or _config_str("HXOPS_TOOLS_API_BASE", "")
)
if not callback_base:
reasons.append("callback_api_base_missing")
# 触发目录缺失由通用挂载检查覆盖;此处仅保证 upload_trigger 配置存在。
if upload_trigger_dir() is None:
reasons.append("trigger_dir_not_configured")
return reasons
def check_freight_upload_rpa_ready() -> RpaWorkerReadiness:
"""
检查货代上传 RPA 是否可安全自动触发。
核心逻辑:凭据/队列/回调基址预检 + 上传 trigger 共享挂载 + Worker 心跳与
freight_upload 能力 + 环境/scope 隔离。Mock 模式跳过心跳。
Returns:
RpaWorkerReadiness(含 reasons 供建单前/启动日志展示)。
"""
from app.services.freight_rpa.upload.trigger_io import upload_trigger_dir
return _check_rpa_worker_ready_for_capability(
trigger_dir=upload_trigger_dir(),
required_capability=FREIGHT_UPLOAD_CAPABILITY,
extra_reasons=_freight_upload_config_reasons(),
)
def assert_freight_upload_rpa_ready() -> None:
"""
写货代上传 trigger 前的强制就绪检查。
Raises:
ServiceUnavailableError: Worker/凭据/共享目录/回调基址未就绪。
"""
result = check_freight_upload_rpa_ready()
if result.ready:
return
code = "RPA.FREIGHT_UPLOAD_NOT_READY"
if "heartbeat_storage_unavailable" in result.reasons:
code = "RPA.HEARTBEAT_STORAGE_UNAVAILABLE"
elif "credential_key_missing" in result.reasons:
code = "RPA.CREDENTIAL_KEY_MISSING"
logger.warning(
"[rpa-heartbeat] freight upload readiness blocked code=%s reasons=%s detail=%s",
code,
result.reasons,
result.detail_message,
)
from app.services.freight_rpa.upload.trigger_io import upload_trigger_dir
raise ServiceUnavailableError(
result.message,
code=code,
details={
"reasons": result.reasons,
"detail_message": result.detail_message,
"checked_at": result.checked_at,
"shared_scope_id": shared_scope_id(),
"trigger_dir": str(upload_trigger_dir() or ""),
"capability": FREIGHT_UPLOAD_CAPABILITY,
},
)
def log_auto_upload_readiness_at_startup(app: Any = None) -> RpaWorkerReadiness | None:
"""
应用启动时:若 AUTO_UPLOAD 显式开启则校验货代上传就绪并打日志(不阻断启动)。
Args:
app: Flask app;缺省用 current_app。
Returns:
校验结果;AUTO_UPLOAD 关闭时返回 None。
"""
flask_app = app
if flask_app is None:
flask_app = current_app
enabled = str(flask_app.config.get("SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED", False)).strip().lower() in {
"1", "true", "yes", "on",
}
if not enabled:
flask_app.logger.info(
"[rpa-upload] AUTO_UPLOAD disabled (fail-closed default); skip freight upload readiness"
)
return None
with flask_app.app_context():
result = check_freight_upload_rpa_ready()
if result.ready:
flask_app.logger.info(
"[rpa-upload] AUTO_UPLOAD enabled and freight upload RPA ready checked_at=%s",
result.checked_at,
)
else:
flask_app.logger.warning(
"[rpa-upload] AUTO_UPLOAD enabled but freight upload RPA NOT ready: %s reasons=%s",
result.detail_message or result.message,
result.reasons,
)
return result
def assert_inventory_rpa_worker_ready() -> None:
"""
写 trigger 前的强制就绪检查。
Raises:
ServiceUnavailableError: worker 未就绪、共享目录无效或心跳存储不可用。
"""
result = check_inventory_rpa_worker_ready()
if result.ready:
return
code = "RPA.WORKER_OFFLINE"
if "heartbeat_storage_unavailable" in result.reasons:
code = "RPA.HEARTBEAT_STORAGE_UNAVAILABLE"
logger.warning(
"[rpa-heartbeat] readiness blocked code=%s reasons=%s detail=%s",
code,
result.reasons,
result.detail_message,
)
raise ServiceUnavailableError(
result.message,
code=code,
details={
"reasons": result.reasons,
"detail_message": result.detail_message,
"checked_at": result.checked_at,
"shared_scope_id": shared_scope_id(),
"trigger_dir": str(onhand_trigger_dir() or ""),
},
)
def serialize_rpa_worker_status(*, scope: str = "onhand") -> dict[str, Any]:
"""
管理端展示:按 scope 返回在手(onhand)或入站(inbound)Worker 心跳摘要。
Args:
scope: onhand(默认,库存 RPA 工作台)或 inbound(入站 RPA 工作台);
取值为后端内部与前端查询参数约定,与 Worker 上报能力标识(Task 12)无关。
"""
from app.services.freight_rpa.upload.trigger_io import upload_trigger_dir
from app.services.freight_rpa.inbound.trigger_io import inbound_trigger_dir
normalized = str(scope or "onhand").strip().lower()
if normalized == "inbound":
readiness = check_receipt_rpa_worker_ready()
trigger_path = str(inbound_trigger_dir() or "")
else:
readiness = check_inventory_rpa_worker_ready()
trigger_path = str(onhand_trigger_dir() or "")
normalized = "onhand"
freight_readiness = check_freight_upload_rpa_ready()
ttl_seconds = _heartbeat_ttl_seconds()
workers = []
now = time.time()
for worker in readiness.workers:
workers.append({
"worker_id": worker.get("worker_id"),
"hostname": worker.get("hostname"),
"environment": worker.get("environment"),
"status": worker.get("status"),
"capabilities": worker.get("capabilities") or [],
"trigger_dir": worker.get("trigger_dir"),
"drop_dir": worker.get("drop_dir"),
"shared_scope_id": worker.get("shared_scope_id"),
"version": worker.get("version"),
"timestamp": worker.get("timestamp"),
"received_at": worker.get("received_at"),
"age_seconds": _heartbeat_age_seconds(worker, now=now),
"online": (_heartbeat_age_seconds(worker, now=now) or 9999) <= ttl_seconds,
"eligible": worker.get("eligible"),
"ineligible_reasons": worker.get("ineligible_reasons") or [],
})
return {
"scope": normalized,
"ready": readiness.ready,
"message": readiness.message,
"detail_message": readiness.detail_message,
"checked_at": readiness.checked_at,
"heartbeat_ttl_seconds": ttl_seconds,
"backend_environment": resolve_backend_rpa_environment(),
"shared_scope_id": shared_scope_id(),
"shared_sentinel_name": shared_sentinel_name(),
"trigger_dir": trigger_path,
"upload_trigger_dir": str(upload_trigger_dir() or ""),
"reasons": readiness.reasons,
"workers": workers,
"freight_upload": {
"ready": freight_readiness.ready,
"message": freight_readiness.message,
"detail_message": freight_readiness.detail_message,
"reasons": freight_readiness.reasons,
"checked_at": freight_readiness.checked_at,
"auto_upload_enabled": _config_bool("SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED", False),
},
}
@@ -0,0 +1,558 @@
"""
services/freight_rpa/common/worker_heartbeat_alert.py
用途:库存 RPA Worker 离线/恢复主动告警(企微 textcard + 冷却去重)。
依赖:同包 worker_heartbeat、redis_client、wecom_notify、models.User、models.AppSetting。
逻辑:由 schedule worker 每轮循环调用;默认 ALERT_ENABLED=false 不发送;DB 为告警状态权威源,Redis 仅作缓存同步。
"""
from __future__ import annotations
import json
import logging
import threading
import time
from collections.abc import Callable
from typing import Any
from flask import current_app
from sqlalchemy.exc import IntegrityError
from app import db
from app.models import AppSetting, User
from app.services.permission_roles.service import list_platform_admin_users
from .worker_heartbeat import (
RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE,
RPA_WORKER_OFFLINE_MESSAGE,
_heartbeat_check_required,
check_inventory_rpa_worker_ready,
)
logger = logging.getLogger(__name__)
_REDIS_ALERT_STATE_KEY = "shipping:rpa:heartbeat:alert:state"
_DB_ALERT_STATE_KEY = "shipping:rpa:heartbeat:alert:state"
_STATUS_SENDING = "sending"
_LAST_CHECK_MONO = 0.0
_MEMORY_ALERT_STATE: dict[str, Any] = {}
_MEMORY_ALERT_LOCK = threading.Lock()
_RECIPIENT_GAP_LOGGED = False
def _config_bool(key: str, default: bool) -> bool:
raw = current_app.config.get(key, default)
return str(raw).strip().lower() in {"1", "true", "yes", "on"}
def _alert_enabled() -> bool:
if not _heartbeat_check_required():
return False
return _config_bool("FREIGHT_RPA_WORKER_ALERT_ENABLED", False)
def _alert_cooldown_seconds() -> int:
return max(300, int(current_app.config.get("FREIGHT_RPA_WORKER_ALERT_COOLDOWN_SECONDS") or 1800))
def _send_lock_seconds() -> int:
"""企微发送中的短锁 TTL;发送失败过期后可重试,不进入长冷却。"""
return max(60, int(current_app.config.get("FREIGHT_RPA_WORKER_ALERT_SEND_LOCK_SECONDS") or 120))
def _alert_fallback_admin_enabled() -> bool:
return _config_bool("FREIGHT_RPA_WORKER_ALERT_FALLBACK_ADMIN", True)
def _alert_recipients() -> list[User]:
"""
解析告警接收人。
核心逻辑:优先 FREIGHT_RPA_WORKER_ALERT_USERNAMES;未配置时可选回退已绑企微的平台管理员。
"""
raw = str(current_app.config.get("FREIGHT_RPA_WORKER_ALERT_USERNAMES") or "").strip()
names = [part.strip() for part in raw.split(",") if part.strip()] if raw else []
if names:
users = (
db.session.query(User)
.filter(User.username.in_(names), User.wecom_userid.isnot(None))
.all()
)
if users:
return users
logger.warning(
"[rpa-heartbeat-alert] configured usernames have no bound wecom_userid: %s",
names,
)
if _alert_fallback_admin_enabled():
admins = list_platform_admin_users(wecom_bound=True, limit=20)
if admins:
logger.info(
"[rpa-heartbeat-alert] using admin fallback recipients count=%d",
len(admins),
)
return admins
return []
def _log_recipient_gap_once() -> None:
"""部署缺口:未配置接收人且无已绑企微 admin 时仅打一次明确 warning。"""
global _RECIPIENT_GAP_LOGGED
if _RECIPIENT_GAP_LOGGED:
return
_RECIPIENT_GAP_LOGGED = True
logger.warning(
"[rpa-heartbeat-alert] no wecom recipients: set FREIGHT_RPA_WORKER_ALERT_USERNAMES "
"or bind wecom_userid for at least one platform admin (FALLBACK_ADMIN=true)"
)
def _redis_client():
from app.services.redis_client import get_redis_client
return get_redis_client()
def _memory_load_alert_state() -> dict[str, Any]:
with _MEMORY_ALERT_LOCK:
return dict(_MEMORY_ALERT_STATE)
def _memory_save_alert_state(state: dict[str, Any]) -> None:
with _MEMORY_ALERT_LOCK:
_MEMORY_ALERT_STATE.clear()
_MEMORY_ALERT_STATE.update(state)
def _load_alert_state_from_db() -> dict[str, Any] | None:
state, _db_ok = _try_read_alert_state_from_db()
return state
def _try_read_alert_state_from_db() -> tuple[dict[str, Any] | None, bool]:
"""
读取 DB 告警状态。
Returns:
(state, db_available):无行时 state 为 None 但 db_available 仍为 True。
"""
try:
row = db.session.get(AppSetting, _DB_ALERT_STATE_KEY)
if row and row.value:
parsed = json.loads(row.value)
if isinstance(parsed, dict):
return parsed, True
return None, True
except Exception:
logger.exception("[rpa-heartbeat-alert] load state from db failed")
db.session.rollback()
return None, False
def _persist_alert_state_to_db(state: dict[str, Any]) -> None:
payload = json.dumps(state, ensure_ascii=False)
row = db.session.get(AppSetting, _DB_ALERT_STATE_KEY)
if row:
row.value = payload
else:
db.session.add(AppSetting(key=_DB_ALERT_STATE_KEY, value=payload))
db.session.commit()
def _normalize_alert_state(state: dict[str, Any]) -> dict[str, Any]:
"""写入前补齐 updated_at,供跨存储源比较版本。"""
normalized = dict(state)
normalized["updated_at"] = time.time()
return normalized
def _try_load_alert_state_from_redis() -> dict[str, Any] | None:
client = _redis_client()
if client is None:
return None
try:
raw = client.get(_REDIS_ALERT_STATE_KEY)
if raw:
parsed = json.loads(raw)
if isinstance(parsed, dict):
return parsed
except Exception:
logger.exception("[rpa-heartbeat-alert] load state from redis failed")
return None
def _sync_redis_cache_from_db(state: dict[str, Any]) -> None:
"""DB 为权威源时,无条件用 DB 状态覆盖 Redis 缓存。"""
_persist_alert_state_to_redis(state)
def _persist_alert_state_to_redis(state: dict[str, Any]) -> None:
client = _redis_client()
if client is None:
return
try:
client.set(_REDIS_ALERT_STATE_KEY, json.dumps(state, ensure_ascii=False), ex=86400 * 7)
except Exception:
logger.exception("[rpa-heartbeat-alert] save state to redis failed")
def _delete_redis_alert_state_if_possible() -> None:
"""DB 无状态时清理 Redis 残留缓存。"""
client = _redis_client()
if client is None:
return
try:
client.delete(_REDIS_ALERT_STATE_KEY)
except Exception:
logger.exception("[rpa-heartbeat-alert] delete state from redis failed")
def reset_rpa_worker_alert_state_for_tests() -> None:
"""单测隔离:清空进程内告警冷却状态与 DB 行。"""
global _LAST_CHECK_MONO, _RECIPIENT_GAP_LOGGED
_LAST_CHECK_MONO = 0.0
_RECIPIENT_GAP_LOGGED = False
with _MEMORY_ALERT_LOCK:
_MEMORY_ALERT_STATE.clear()
try:
from flask import has_app_context
if has_app_context():
row = db.session.get(AppSetting, _DB_ALERT_STATE_KEY)
if row:
db.session.delete(row)
db.session.commit()
except Exception:
db.session.rollback()
def _load_alert_state() -> dict[str, Any]:
"""
加载告警冷却状态;DB 为权威源,Redis 仅作缓存,仅 DB 不可读时才回退 Redis/内存。
"""
db_state, db_ok = _try_read_alert_state_from_db()
if db_ok:
if db_state is not None:
_memory_save_alert_state(db_state)
_sync_redis_cache_from_db(db_state)
return db_state
_memory_save_alert_state({})
_delete_redis_alert_state_if_possible()
return {}
redis_state = _try_load_alert_state_from_redis()
if redis_state is not None:
_memory_save_alert_state(redis_state)
return redis_state
return _memory_load_alert_state()
def _save_alert_state(state: dict[str, Any]) -> None:
"""保存告警冷却状态;写内存 + DB + Redis(可用时)。"""
payload = _normalize_alert_state(state) if state else {}
_memory_save_alert_state(payload)
if not payload:
return
try:
_persist_alert_state_to_db(payload)
except Exception:
db.session.rollback()
logger.exception("[rpa-heartbeat-alert] save state to db failed")
_persist_alert_state_to_redis(payload)
def _claim_alert_send_lock_db(
*,
lock_state: dict[str, Any],
should_send_fn: Callable[[dict[str, Any]], bool],
) -> tuple[bool, dict[str, Any]]:
row = (
db.session.query(AppSetting)
.filter(AppSetting.key == _DB_ALERT_STATE_KEY)
.with_for_update()
.one_or_none()
)
existing: dict[str, Any] = {}
if row and row.value:
parsed = json.loads(row.value)
if isinstance(parsed, dict):
existing = parsed
if not should_send_fn(existing):
db.session.rollback()
return False, existing
previous_state = dict(existing)
lock_state = _normalize_alert_state(lock_state)
payload = json.dumps(lock_state, ensure_ascii=False)
if row:
row.value = payload
else:
db.session.add(AppSetting(key=_DB_ALERT_STATE_KEY, value=payload))
db.session.commit()
_memory_save_alert_state(lock_state)
_persist_alert_state_to_redis(lock_state)
return True, previous_state
def _claim_alert_send_lock_memory_only(
*,
lock_state: dict[str, Any],
should_send_fn: Callable[[dict[str, Any]], bool],
) -> tuple[bool, dict[str, Any]]:
"""仅当 DB 不可读/不可写时使用的进程内 claim 兜底。"""
mem = _memory_load_alert_state()
if not should_send_fn(mem):
return False, mem
previous_state = dict(mem)
_memory_save_alert_state(lock_state)
return True, previous_state
def _claim_alert_send_lock(
*,
lock_state: dict[str, Any],
should_send_fn: Callable[[dict[str, Any]], bool],
) -> tuple[bool, dict[str, Any]]:
"""
跨进程发送锁:仅写入 sending 状态,不更新 last_sent_at 冷却。
Returns:
(claimed, previous_state):claimed 为 True 时 previous_state 供发送失败回滚。
"""
try:
return _claim_alert_send_lock_db(lock_state=lock_state, should_send_fn=should_send_fn)
except IntegrityError:
db.session.rollback()
existing, db_ok = _try_read_alert_state_from_db()
if existing:
_memory_save_alert_state(existing)
elif db_ok:
_memory_save_alert_state({})
return False, existing or {}
except Exception:
db.session.rollback()
logger.exception("[rpa-heartbeat-alert] claim send lock in db failed")
existing, db_ok = _try_read_alert_state_from_db()
if db_ok:
if existing:
_memory_save_alert_state(existing)
return False, existing or {}
return _claim_alert_send_lock_memory_only(
lock_state=lock_state,
should_send_fn=should_send_fn,
)
def _commit_alert_sent(*, final_state: dict[str, Any]) -> None:
"""企微发送成功后写入最终状态与 last_sent_at(进入长冷却)。"""
_save_alert_state(final_state)
def _release_alert_send_lock(*, previous_state: dict[str, Any]) -> None:
"""企微发送失败:回滚 sending 锁,不推进 last_sent_at。"""
if previous_state:
_save_alert_state(previous_state)
return
_memory_save_alert_state({})
try:
row = db.session.get(AppSetting, _DB_ALERT_STATE_KEY)
if row:
db.session.delete(row)
db.session.commit()
except Exception:
db.session.rollback()
logger.exception("[rpa-heartbeat-alert] release send lock in db failed")
_delete_redis_alert_state_if_possible()
def _send_alert_to_recipients(*, title: str, content: str) -> bool:
from app.services.integrations.wecom.notify import send_wecom_event_message
recipients = _alert_recipients()
if not recipients:
_log_recipient_gap_once()
logger.warning("[rpa-heartbeat-alert] no recipients available, title=%s", title)
return False
sent_any = False
for user in recipients:
result = send_wecom_event_message(
event_type="schedule_completed",
user=user,
title=title,
content=content,
jump_path="/admin/schedules",
)
if result.get("ok"):
sent_any = True
else:
logger.warning(
"[rpa-heartbeat-alert] notify failed user=%s reason=%s",
user.username,
result.get("reason"),
)
return sent_any
def _is_active_send_lock(existing: dict[str, Any], *, now_ts: float) -> bool:
if str(existing.get("status") or "").strip() != _STATUS_SENDING:
return False
started = float(existing.get("sending_started_at") or 0)
return started > 0 and (now_ts - started) < _send_lock_seconds()
def _effective_last_status(existing: dict[str, Any]) -> str:
status = str(existing.get("status") or "").strip()
if status == _STATUS_SENDING:
return str(existing.get("sending_target") or "").strip()
return status
def _should_send_storage_or_offline(
*,
existing: dict[str, Any],
target_status: str,
now_ts: float,
cooldown: int,
) -> bool:
if _is_active_send_lock(existing, now_ts=now_ts):
return False
last_status = _effective_last_status(existing)
last_sent_at = float(existing.get("last_sent_at") or 0)
return last_status != target_status or (now_ts - last_sent_at) >= cooldown
def _try_send_with_claim(
*,
target_status: str,
state: dict[str, Any],
now_ts: float,
cooldown: int,
title: str,
content: str,
) -> bool:
def should_send_fn(existing: dict[str, Any]) -> bool:
if _is_active_send_lock(existing, now_ts=now_ts):
return False
if target_status == "ready":
return _effective_last_status(existing) in {"offline", "storage_unavailable"}
return _should_send_storage_or_offline(
existing=existing,
target_status=target_status,
now_ts=now_ts,
cooldown=cooldown,
)
lock_state = {
"status": _STATUS_SENDING,
"sending_target": target_status,
"sending_started_at": now_ts,
"last_sent_at": float(state.get("last_sent_at") or 0),
"reasons": state.get("reasons", []),
}
claimed, previous_state = _claim_alert_send_lock(lock_state=lock_state, should_send_fn=should_send_fn)
if not claimed:
return False
if _send_alert_to_recipients(title=title, content=content):
final_state = {
"status": target_status,
"last_sent_at": now_ts,
"reasons": state.get("reasons", []),
}
_commit_alert_sent(final_state=final_state)
return True
_release_alert_send_lock(previous_state=previous_state)
return False
def maybe_alert_rpa_worker_status(*, force: bool = False) -> dict[str, Any]:
"""
周期检查 RPA Worker 就绪状态并按冷却时间发送离线/恢复告警。
Returns:
dict: 本次检查结果摘要(供运维日志)。
"""
global _LAST_CHECK_MONO
if not _alert_enabled():
return {"skipped": True, "reason": "alert_disabled"}
now_mono = time.monotonic()
if not force and _LAST_CHECK_MONO and (now_mono - _LAST_CHECK_MONO) < 60:
return {"skipped": True, "reason": "throttled"}
_LAST_CHECK_MONO = now_mono
readiness = check_inventory_rpa_worker_ready()
state = _load_alert_state()
effective_status = _effective_last_status(state)
last_sent_at = float(state.get("last_sent_at") or 0)
cooldown = _alert_cooldown_seconds()
now_ts = time.time()
storage_unavailable = "heartbeat_storage_unavailable" in readiness.reasons
summary = {
"ready": readiness.ready,
"status": "storage_unavailable" if storage_unavailable else ("ready" if readiness.ready else "offline"),
"reasons": readiness.reasons,
"detail_message": readiness.detail_message,
}
if storage_unavailable:
should_send = _should_send_storage_or_offline(
existing=state,
target_status="storage_unavailable",
now_ts=now_ts,
cooldown=cooldown,
)
if should_send:
title = "货代库存 RPA 心跳存储异常"
content = (
f"{RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE}\n\n"
f"原因:{'; '.join(readiness.reasons[:8]) or 'unknown'}"
)
new_state = {
"status": "storage_unavailable",
"last_sent_at": last_sent_at,
"reasons": readiness.reasons,
}
if _try_send_with_claim(
target_status="storage_unavailable",
state=new_state,
now_ts=now_ts,
cooldown=cooldown,
title=title,
content=content,
):
summary["storage_alert_sent"] = True
return summary
if not readiness.ready:
should_send = _should_send_storage_or_offline(
existing=state,
target_status="offline",
now_ts=now_ts,
cooldown=cooldown,
)
if should_send:
detail = readiness.detail_message or RPA_WORKER_OFFLINE_MESSAGE
title = "货代库存 RPA Worker 离线"
content = f"{detail}\n\n原因:{'; '.join(readiness.reasons[:8]) or 'unknown'}"
new_state = {"status": "offline", "last_sent_at": last_sent_at, "reasons": readiness.reasons}
if _try_send_with_claim(
target_status="offline",
state=new_state,
now_ts=now_ts,
cooldown=cooldown,
title=title,
content=content,
):
summary["alert_sent"] = True
return summary
if effective_status in {"offline", "storage_unavailable"}:
title = "货代库存 RPA Worker 已恢复"
content = "库存 RPA Worker 心跳已恢复,可正常触发库存导出。"
new_state = {"status": "ready", "last_sent_at": last_sent_at, "reasons": []}
if _try_send_with_claim(
target_status="ready",
state=new_state,
now_ts=now_ts,
cooldown=cooldown,
title=title,
content=content,
):
summary["recovery_sent"] = True
return summary
@@ -0,0 +1 @@
"""inbound:入站 RPA。"""
@@ -0,0 +1,275 @@
"""
services/freight_rpa/inbound/report_archive.py
用途:inbound(入站,原收料)RPA 产物事实能力——Worker 回调的原样归档(xlsx 落 MinIO、
三年保留期、不写库存快照表)、到期对象清理(retention)、单文件企微投递与管理员
强制重发(resend)。批次 R Task 10 自 shipping_notice.receipt_report_storage /
schedule.freight_inbound_rpa_retention / shipping_notice.receipt_report_notification
平移而来(函数名 receipt 词根→inbound;模型 ShippingReceiptReport* 引用不变——批次 S 才改表)。
依赖:models(ShippingReceiptReportFile / ShippingReceiptRpaUnitRun / ShippingReceiptNotificationDelivery /
User / ScheduleRun 相关模型经行对象访问)、file_assets.storage、integrations.wecom.notify、
freight_rpa.inbound.trigger_io(回调 SCHEMA 与 drop 根)、
shipping_notice.audit_service(适应度测试白名单内,本模块唯一 shipping_notice 业务依赖,
见 tests/services/freight_rpa/test_import_boundary.py)。
逻辑:Worker 回调进入 /api/freight-rpa/inbound-batch-ready 后由组合根注册的业务 sink
(shipping_notice.rpa_sinks.register_inbound_sinks)调 ingest_inbound_callback 完成原样归档,
empty/success/failed 三个终态分支各自 commit;终态落库后的业务桥(推进在途调拨来源任务、
调拨证据同步)与排程终态归集(finalize)经 on_terminal 钩子回调 shipping_notice 侧实现,
本模块不 import 任何桥与 finalize——依赖方向保持 shipping_notice → freight_rpa,
与拆分前「归档 commit 后立刻推桥」的调用顺序逐点一致。
"""
from __future__ import annotations
import hashlib
from datetime import datetime, timedelta
from pathlib import Path
from typing import Any, Callable
from flask import current_app
from app import db
from app.core.errors import NotFoundError, ValidationError
from app.models import (
ShippingReceiptNotificationDelivery,
ShippingReceiptReportFile,
ShippingReceiptRpaUnitRun,
User,
)
from app.services.file_assets.storage import file_asset_storage
from app.services.freight_rpa.inbound.trigger_io import SCHEMA as INBOUND_TRIGGER_SCHEMA, inbound_drop_dir
from app.services.integrations.wecom.notify import send_wecom_file_message, upload_wecom_temp_media
from app.services.shipping_notice.audit_service import append_shipping_audit_event
# 终态落库后的业务收尾钩子:由 shipping_notice 域注入(推进在途调拨来源任务 + 调拨证据同步
# + 排程终态归集),契约 = 原 storage.ingest_receipt_callback 中「commit 之后的桥/finalize 尾巴」。
InboundTerminalHook = Callable[..., None]
def _read_inbound_callback_file(file_path: str) -> bytes:
"""只读取 inbound 专用 drop 根内的 xlsx,拒绝 callback 任意本机文件读取。
路径契约为「drop 根内文件名」:Worker(Windows RPA 主机)与后端(Linux 容器)分属
两机,各自看到的根路径不同(C:\\HxopsRpaTest\\... vs /mnt/hxops-rpa-*-data/...),
Worker 只上报文件名,后端用自身挂载的 drop 根拼接定位;携带本机绝对路径的历史
载荷亦按末段文件名解析(2026-10-08 修复跨机成功回调全程 400 的事故)。
"""
configured_root = str(inbound_drop_dir() or '').strip()
if not configured_root:
raise ValidationError('receipt callback file root is unavailable', code='SHIPPING.RECEIPT_CALLBACK_FILE_INVALID')
root = Path(configured_root).resolve()
# 容忍历史载荷携带 Windows 绝对路径:先归一分隔符再取末段文件名(防遍历,单一分段)。
name = Path(str(file_path).replace('\\', '/')).name
path = (root / name).resolve()
try:
path.relative_to(root)
except ValueError as exc:
raise ValidationError('receipt callback file is outside receipt drop root', code='SHIPPING.RECEIPT_CALLBACK_FILE_INVALID') from exc
if path.suffix.lower() != '.xlsx' or not path.is_file():
raise ValidationError('receipt callback file must be an existing xlsx', code='SHIPPING.RECEIPT_CALLBACK_FILE_INVALID')
max_size = max(int(current_app.config.get('FILE_ASSET_MAX_SIZE_MB', 30) or 30), 1) * 1024 * 1024
if path.stat().st_size > max_size:
raise ValidationError('receipt callback file exceeds configured size limit', code='SHIPPING.RECEIPT_CALLBACK_FILE_INVALID')
return path.read_bytes()
def ingest_inbound_callback(payload: dict[str, Any], *, on_terminal: InboundTerminalHook) -> dict[str, Any]:
"""幂等接收单个 inbound 单元回调,原样归档三年且不写库存快照表。
Args:
payload: Worker 回调载荷(schema_version/callback_id/status/file_path/...)。
on_terminal: 必填业务收尾钩子(shipping_notice 域注入,见模块 docstring);在每个终态
分支 commit 之后、以与拆分前完全一致的实参被调用——
empty/failed: on_terminal(unit, ok=False, error_code=..., error_message=...);
success: on_terminal(unit, ok=True, file_no=..., file_sha256=...)。
业务约束:钩子内部异常只记日志,绝不回滚归档终态(契约由实现方保持)。
"""
if payload.get('schema_version') != INBOUND_TRIGGER_SCHEMA:
raise ValidationError('receipt callback schema_version is invalid', code='SHIPPING.RECEIPT_CALLBACK_INVALID')
callback_id = str(payload.get('callback_id') or '').strip()
unit = ShippingReceiptRpaUnitRun.query.filter_by(callback_id=callback_id).one_or_none()
if unit is None:
raise NotFoundError('Receipt RPA unit not found', code='SHIPPING.RECEIPT_UNIT_NOT_FOUND')
status = str(payload.get('status') or '').strip().lower()
before = {'status': unit.status, 'error_code': unit.error_code, 'error_message': unit.error_message}
if status in {'empty', 'no_data'}:
# [STEP] 与库存 no_inventory_data 对齐:empty 是合法业务结果,落 error_code=no_receipt_data。
unit.status = 'empty'
unit.error_code = str(payload.get('error_code') or 'no_receipt_data')[:64]
unit.error_message = str(payload.get('error_message') or 'no_receipt_data')[:2000]
unit.finished_at = datetime.utcnow()
append_shipping_audit_event(
event_type='shipping_receipt_rpa_callback_received', aggregate_type='shipping_receipt_unit',
aggregate_id=str(unit.id), run_no=unit.schedule_run.run_no if unit.schedule_run else None,
actor_type='rpa', actor_id='receipt-worker', unit_id=unit.id, result='success',
before=before,
after={
'status': 'empty',
'callback_id': unit.callback_id,
'error_code': unit.error_code,
'error_message': unit.error_message,
},
metadata={'callback_status': status, 'skip_reason': unit.error_code},
)
db.session.commit()
on_terminal(
unit, ok=False, error_code=unit.error_code or 'no_receipt_data',
error_message=unit.error_message or 'no_receipt_data',
)
return {'unit_run_id': unit.id, 'status': 'empty'}
if status != 'success':
unit.status = 'failed'; unit.error_code = str(payload.get('error_code') or 'RPA.RECEIPT_EXPORT_FAILED')[:64]; unit.error_message = str(payload.get('error_message') or 'receipt export failed')[:2000]; unit.finished_at = datetime.utcnow()
append_shipping_audit_event(
event_type='shipping_receipt_rpa_callback_received', aggregate_type='shipping_receipt_unit',
aggregate_id=str(unit.id), run_no=unit.schedule_run.run_no if unit.schedule_run else None,
actor_type='rpa', actor_id='receipt-worker', unit_id=unit.id, result='failure',
before=before, after={'status': 'failed', 'error_code': unit.error_code, 'error_message': unit.error_message},
metadata={'callback_status': status},
)
db.session.commit()
on_terminal(unit, ok=False, error_code=unit.error_code, error_message=unit.error_message)
return {'unit_run_id': unit.id, 'status': 'failed'}
data = _read_inbound_callback_file(str(payload.get('file_path') or ''))
sha256 = hashlib.sha256(data).hexdigest()
claimed = str(payload.get('sha256') or '').lower()
if claimed and claimed != sha256:
raise ValidationError('receipt callback sha256 mismatch', code='SHIPPING.RECEIPT_CALLBACK_SHA_MISMATCH')
existing = ShippingReceiptReportFile.query.filter_by(unit_run_id=unit.id, sha256=sha256).one_or_none()
if existing:
return {'unit_run_id': unit.id, 'status': unit.status, 'file_id': existing.id, 'idempotent': True}
filename = Path(str(payload.get('original_filename') or payload.get('file_path') or 'receipt.xlsx')).name
storage_key = f'shipping/receipt-reports/{datetime.utcnow():%Y/%m}/{unit.id}/{sha256}.xlsx'
file_asset_storage.upload_bytes(storage_key=storage_key, data=data, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
record = ShippingReceiptReportFile(unit_run_id=unit.id, storage_provider='minio', storage_bucket=file_asset_storage.bucket_name, storage_key=storage_key, original_filename=filename, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', file_size=len(data), sha256=sha256, archive_expires_at=datetime.utcnow() + timedelta(days=365 * 3))
db.session.add(record)
unit.status = 'success'; unit.finished_at = datetime.utcnow()
db.session.flush()
append_shipping_audit_event(event_type='shipping_receipt_report_archived', aggregate_type='shipping_receipt_unit', aggregate_id=str(unit.id), run_no=unit.schedule_run.run_no if unit.schedule_run else None, actor_type='rpa', actor_id='receipt-worker', unit_id=unit.id, result='success', before=before, after={'status': 'success', 'source_run_no': unit.callback_id, 'file_id': record.id, 'sha256': sha256, 'file_size': len(data)}, artifact_refs=[{'kind': 'receipt_report', 'id': str(record.id), 'sha256': sha256}], metadata={'file_size': len(data), 'retention_days': 365 * 3})
db.session.commit()
on_terminal(unit, ok=True, file_no=str(record.id), file_sha256=sha256)
return {'unit_run_id': unit.id, 'status': 'success', 'file_id': record.id, 'idempotent': False}
def run_freight_inbound_rpa_retention_schedule(task: Any, run: Any) -> tuple[int, int, int, int, list[dict], list[str], list[dict]]:
"""仅删除已到三年保留期的 MinIO 对象,永不删除文件事实、运行或审计。
Args:
task: 排程任务行(job_params.limit 提供单批上限,1..1000)。
run: 排程执行记录(本函数不改写 run,仅按排程协议返回计数/明细/日志)。
Returns:
排程平台 Job 协议七元组(总查得数、成功、失败、跳过 0、明细、错误、step_logs)。
"""
limit = max(1, min(int((getattr(task, 'job_params', {}) or {}).get('limit', 100)), 1000))
now = datetime.utcnow()
rows = ShippingReceiptReportFile.query.filter(
ShippingReceiptReportFile.archive_expires_at.is_not(None),
ShippingReceiptReportFile.archive_expires_at <= now,
ShippingReceiptReportFile.archive_deleted_at.is_(None),
).order_by(ShippingReceiptReportFile.id).limit(limit).all()
success = failed = 0
errors: list[str] = []
for report_file in rows:
try:
file_asset_storage.delete_object(report_file.storage_key)
report_file.archive_deleted_at = now
report_file.archive_delete_result_json = {'status': 'deleted', 'deleted_at': now.isoformat()}
append_shipping_audit_event(
event_type='shipping_receipt_report_archive_deleted', aggregate_type='shipping_receipt_file',
aggregate_id=str(report_file.id), actor_type='worker', actor_id='receipt-retention',
unit_id=report_file.unit_run_id, result='success',
before={'status': 'archived'}, after={'status': 'archive_deleted'},
artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}],
)
success += 1
except Exception as exc:
errors.append(f'{report_file.id}: {exc}')
append_shipping_audit_event(
event_type='shipping_receipt_report_archive_delete_attempted', aggregate_type='shipping_receipt_file',
aggregate_id=str(report_file.id), actor_type='worker', actor_id='receipt-retention',
unit_id=report_file.unit_run_id, result='failure',
before={'status': 'archived'}, after={'status': 'archived', 'delete_error': str(exc)[:2000]},
artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}],
)
failed += 1
db.session.commit()
return len(rows), success, failed, 0, [{'file_id': row.id} for row in rows], errors, [{'step': 'receipt_retention', 'status': 'completed'}]
def _recipient_ids(report_file: ShippingReceiptReportFile) -> list[int]:
"""从所属排程冻结的接收人列表取目标用户;停用通知时返回空。"""
run = report_file.unit_run.schedule_run
task = run.task if run else None
if task is None or not task.notify_enabled:
return []
return sorted({int(user_id) for user_id in (task.notify_user_ids_json or []) if str(user_id).isdigit()})
def deliver_inbound_file(file_id: int, *, force: bool = False) -> dict:
"""向排程接收人逐一投递原样收料文件;同文件用户的成功投递可幂等重放。
Args:
file_id: 已归档收料文件主键(ShippingReceiptReportFile.id)。
force: 管理员补偿重发(resend 端点传 True),绕过成功幂等但仍受通知开关约束。
Returns:
dict: success_count / failed_count(file_not_found 时附 reason)。
"""
report_file = db.session.get(ShippingReceiptReportFile, file_id)
if report_file is None:
return {'success_count': 0, 'failed_count': 0, 'reason': 'file_not_found'}
success_count = failed_count = 0
for user_id in _recipient_ids(report_file):
key = f'receipt:file:{report_file.id}:user:{user_id}'
delivery = ShippingReceiptNotificationDelivery.query.filter_by(idempotency_key=key).one_or_none()
if delivery and delivery.status == 'success' and not force:
success_count += 1
continue
if delivery is None:
delivery = ShippingReceiptNotificationDelivery(
unit_run_id=report_file.unit_run_id, report_file_id=report_file.id, recipient_user_id=user_id,
message_type='file', idempotency_key=key, status='pending',
)
db.session.add(delivery)
db.session.flush()
user = db.session.get(User, user_id)
if user is None or not user.wecom_userid:
delivery.status = 'failed'; delivery.error_code = 'WECOM_USER_UNBOUND'; delivery.error_message = 'recipient has no wecom binding'
failed_count += 1
append_shipping_audit_event(
event_type='shipping_receipt_file_notification_attempted', aggregate_type='shipping_receipt_file',
aggregate_id=str(report_file.id), actor_type='system', owner_user_id=user_id,
unit_id=report_file.unit_run_id, result='failure',
before={'delivery_status': 'pending'},
after={'delivery_status': delivery.status, 'error_code': delivery.error_code},
artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}],
metadata={'delivery_id': delivery.id, 'message_type': 'file'},
)
continue
try:
media_id = upload_wecom_temp_media(file_asset_storage.get_bytes(report_file.storage_key), report_file.original_filename)
result = send_wecom_file_message(user.wecom_userid, media_id)
if int(result.get('errcode', -1)) != 0:
raise RuntimeError(str(result.get('errmsg') or result.get('errcode')))
delivery.status = 'success'; delivery.sent_at = datetime.utcnow(); delivery.error_code = None; delivery.error_message = None
delivery.response_summary_json = {'media_uploaded': True, 'errcode': 0}
success_count += 1
append_shipping_audit_event(
event_type='shipping_receipt_file_notification_attempted', aggregate_type='shipping_receipt_file', aggregate_id=str(report_file.id),
actor_type='system', owner_user_id=user_id, unit_id=report_file.unit_run_id, result='success',
before={'delivery_status': 'pending'}, after={'delivery_status': delivery.status, 'sent_at': delivery.sent_at.isoformat() if delivery.sent_at else None},
artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}],
metadata={'delivery_id': delivery.id, 'message_type': 'file'},
)
except Exception as exc:
delivery.status = 'failed'; delivery.error_code = 'WECOM_SEND_FAILED'; delivery.error_message = str(exc)[:2000]
failed_count += 1
append_shipping_audit_event(
event_type='shipping_receipt_file_notification_attempted', aggregate_type='shipping_receipt_file',
aggregate_id=str(report_file.id), actor_type='system', owner_user_id=user_id,
unit_id=report_file.unit_run_id, result='failure',
before={'delivery_status': 'pending'},
after={'delivery_status': delivery.status, 'error_code': delivery.error_code, 'error_message': delivery.error_message},
artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}],
metadata={'delivery_id': delivery.id, 'message_type': 'file'},
)
db.session.commit()
return {'success_count': success_count, 'failed_count': failed_count}
@@ -0,0 +1,93 @@
"""
services/freight_rpa/inbound/trigger_io.py
用途:inbound(入站,原收料)RPA 的纯文件 IO——trigger/落盘目录解析、批量 trigger JSON
原子写入,以及 Worker 触发/回调契约常量(SCHEMA/ACTION_*)。
依赖:Flask current_app 配置、Path/JSON/文件系统工具;不 import 任何业务编排模块
(import 边界由 tests/services/freight_rpa/test_import_boundary.py 锁死)。
逻辑:由 schedule.freight_inbound_rpa_job(排程写 trigger)、api.schedule.runs(admin 单元重试)、
in_transit_transfer.inbound_trigger_service(调拨按需/批量触发)、
freight_rpa.common.worker_heartbeat(inbound trigger 目录探测/就绪检查)、
freight_rpa.inbound.report_archive(drop 目录定位与回调 SCHEMA 校验,Task 10 下沉)等调用,
与外部 RPA Worker 的文件投递目录交互;schema/action 新值以本文件常量为单一真相
(Worker 侧 Task 12 对表:freight_rpa.inbound.v1 / inbound_export_batch)。
"""
from __future__ import annotations
import json
import os
from datetime import datetime
from pathlib import Path
from typing import Any
from flask import current_app
# Worker 触发/回调契约常量:后端写入侧与校验侧共用单一真相,禁止再写字面量。
# [PROMPT_UPDATE] 2026-10-16 freight_rpa 解耦批次 R:schema/action 切换为下述新值
# (旧 receipt 时代字面量已从 backend/app 与 Worker 双侧清零,历史对照见 cutover runbook),
# 旧字符串已在 backend/app 内清零;Worker 侧由 Task 12 对齐。
SCHEMA = "freight_rpa.inbound.v1"
ACTION_INBOUND_EXPORT_BATCH = "inbound_export_batch"
def _path(key: str) -> Path | None:
value = str(current_app.config.get(key) or "").strip()
if not value:
return None
return Path(value)
def inbound_trigger_dir() -> Path | None:
"""RPA inbound 批量导出触发 JSON 目录(FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR);
绝不回落到 onhand trigger 目录。"""
return _path("FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR")
def inbound_drop_dir() -> Path | None:
"""RPA inbound 导出文件落盘目录(FREIGHT_RPA_SHARED_INBOUND_DROP_DIR)。"""
return _path("FREIGHT_RPA_SHARED_INBOUND_DROP_DIR")
def _write_trigger_json_atomic(path: Path, body: dict[str, Any]) -> None:
"""原子发布 trigger,避免 Worker 读取到写入中的半截 JSON。"""
temp_path = path.with_name(f'.{path.name}.{os.getpid()}.tmp')
try:
with open(temp_path, 'w', encoding='utf-8') as handle:
json.dump(body, handle, ensure_ascii=False, indent=2)
handle.flush()
os.fsync(handle.fileno())
os.replace(temp_path, path)
finally:
if temp_path.exists():
temp_path.unlink(missing_ok=True)
def write_inbound_export_batch_trigger(run_no: str, units: list[dict[str, Any]], payload: dict[str, Any] | None = None) -> str | None:
"""
写入 inbound 批量 trigger 文件 inbound_export_batch_{run_no}.json
([PROMPT_UPDATE] 2026-10-16 批次 R:文件名前缀随 Worker 侧 Task 12 一起由
receipt_export_batch_* 切换为 inbound_export_batch_*;Worker 轮询 <root>/*.json
按内容消费,schema/action 取本文件常量新值)。
Args:
run_no: 批次运行号;进 body.batch_run_no 并参与文件名(安全化仅保留字母数字-_)。
units: 触发单元载荷列表;业务约束——空列表直接返回 None(无单元不落盘)。
payload: 调用方附加字段,合并覆盖 body 顶层键(schema_version/action 缺省取常量)。
Returns:
str | None: 触发文件绝对路径;目录未配置或 units 为空时返回 None。
"""
trigger_dir = inbound_trigger_dir()
if not trigger_dir or not units:
return None
trigger_dir.mkdir(parents=True, exist_ok=True)
safe_run_no = ''.join(char for char in run_no if char.isalnum() or char in {'-', '_'}) or 'inbound'
body = {
'schema_version': SCHEMA, 'action': ACTION_INBOUND_EXPORT_BATCH,
'batch_run_no': run_no, 'requested_at': datetime.utcnow().isoformat(), 'units': units,
**(payload or {}),
}
path = trigger_dir / f'inbound_export_batch_{safe_run_no}.json'
_write_trigger_json_atomic(path, body)
return str(path)
@@ -0,0 +1 @@
"""onhand:在手库存 RPA。"""
@@ -0,0 +1,99 @@
"""
services/freight_rpa/onhand/attempts.py
用途:统计任务的 onhand(库存)RPA 导出与货代上传重试次数,并返回统一上限。
依赖:ShippingNotice、ShippingTaskEvent 模型与事件查询逻辑(仅 models,无业务编排 import)。
逻辑:由 shipping_notice 的 inventory_rpa_workflow、fulfillment_workflow 等模块调用本文件,
决定是否还能继续触发 RPA 重试;事件类型字符串(inventory_rpa_* 等)是落库数据值,
随 models 命名一并留待批次 S 处理,本模块只改包归属与标识符词根。
"""
from __future__ import annotations
import os
from datetime import datetime
from app.models import ShippingNotice, ShippingTaskEvent
DEFAULT_RPA_UPLOAD_MAX_ATTEMPTS = 3
_ONHAND_SUCCESS_EVENTS = {
"inventory_uploaded",
"inventory_parsed",
"inventory_rpa_drop_ingested",
"inventory_rpa_ready",
"inventory_template_mapping_used",
}
_ONHAND_ATTEMPT_RESET_EVENTS = _ONHAND_SUCCESS_EVENTS | {
"decision_retry_rpa",
}
_UPLOAD_SUCCESS_EVENTS = {
"upload_rpa_success",
"upload_manual_confirmed",
}
def onhand_rpa_attempts(task: ShippingNotice | None) -> int:
"""统计自上次库存成功事件以来的 RPA 库存导出触发/失败次数。"""
if not task or task.id is None:
return 0
last_reset = (
ShippingTaskEvent.query.filter_by(task_id=task.id)
.filter(ShippingTaskEvent.event_type.in_(_ONHAND_ATTEMPT_RESET_EVENTS))
.order_by(ShippingTaskEvent.id.desc())
.first()
)
since: datetime | None = last_reset.created_at if last_reset else None
triggered = ShippingTaskEvent.query.filter_by(task_id=task.id).filter(
ShippingTaskEvent.event_type == "inventory_rpa_triggered"
)
failed = ShippingTaskEvent.query.filter_by(task_id=task.id).filter(
ShippingTaskEvent.event_type == "inventory_rpa_failed"
)
if since:
triggered = triggered.filter(ShippingTaskEvent.created_at >= since)
failed = failed.filter(ShippingTaskEvent.created_at >= since)
return max(triggered.count(), failed.count())
def upload_rpa_attempts(task: ShippingNotice | None) -> int:
"""统计自上次上传成功事件以来的 RPA 货代上传触发/失败次数。"""
if not task or task.id is None:
return 0
last_success = (
ShippingTaskEvent.query.filter_by(task_id=task.id)
.filter(ShippingTaskEvent.event_type.in_(_UPLOAD_SUCCESS_EVENTS))
.order_by(ShippingTaskEvent.id.desc())
.first()
)
since: datetime | None = last_success.created_at if last_success else None
triggered = ShippingTaskEvent.query.filter_by(task_id=task.id).filter(
ShippingTaskEvent.event_type == "upload_rpa_triggered"
)
failed = ShippingTaskEvent.query.filter_by(task_id=task.id).filter(
ShippingTaskEvent.event_type == "upload_rpa_failed"
)
if since:
triggered = triggered.filter(ShippingTaskEvent.created_at >= since)
failed = failed.filter(ShippingTaskEvent.created_at >= since)
return max(triggered.count(), failed.count())
def max_rpa_upload_attempts() -> int:
"""RPA 货代上传最大重试次数(环境变量 FREIGHT_RPA_UPLOAD_MAX_ATTEMPTS)。"""
value = os.getenv("FREIGHT_RPA_UPLOAD_MAX_ATTEMPTS")
if value is None or not str(value).strip():
return DEFAULT_RPA_UPLOAD_MAX_ATTEMPTS
try:
parsed = int(value)
except (TypeError, ValueError):
return DEFAULT_RPA_UPLOAD_MAX_ATTEMPTS
return max(parsed, 1)
@@ -0,0 +1,302 @@
"""
services/freight_rpa/onhand/callback_cleanup.py
用途:RPA callback drop 区文件归档失败后的持久化重试队列、隔离与消费标记
(Task 9 自 shipping_notice.inventory_rpa_callback_cleanup 整体平移,纯协议文件 IO、零业务落盘)。
依赖:freight_rpa.onhand.trigger_io(onhand_drop_dir / onhand_processed_dir)、json、uuid、Flask current_app。
逻辑:commit 后由 shipping_notice 业务 sink 调用尝试归档;失败则移入 .hxops_quarantine 并入队;
scheduler/worker 启动时定期消费队列。
"""
from __future__ import annotations
import json
import logging
import shutil
import uuid
from datetime import datetime
from pathlib import Path
from typing import Any
from flask import current_app
from app.services.freight_rpa.onhand.trigger_io import onhand_drop_dir, onhand_processed_dir
_CALLBACK_CONSUMED_SUFFIX = ".hxops_consumed"
_CLEANUP_QUEUE_DIRNAME = ".cleanup_queue"
_CLEANUP_FAILED_DIRNAME = ".cleanup_failed"
_QUARANTINE_DIRNAME = ".hxops_quarantine"
_DEFAULT_MAX_CLEANUP_ATTEMPTS = 16
_LOGGER = logging.getLogger(__name__)
def callback_cleanup_queue_dir() -> Path | None:
"""drop 目录下 callback 归档重试队列路径。"""
drop = onhand_drop_dir()
if not drop:
return None
return drop / _CLEANUP_QUEUE_DIRNAME
def callback_cleanup_failed_dir() -> Path | None:
"""超过最大重试次数的 cleanup job 隔离目录。"""
drop = onhand_drop_dir()
if not drop:
return None
return drop / _CLEANUP_FAILED_DIRNAME
def callback_quarantine_dir() -> Path | None:
"""
Worker 不应扫描的 callback 隔离目录(drop 根目录外的子目录)。
归档失败时 HXOPS 将文件原子移入此处,避免重复上报。
"""
drop = onhand_drop_dir()
if not drop:
return None
return drop / _QUARANTINE_DIRNAME
def callback_cleanup_max_attempts() -> int:
"""cleanup job 最大重试次数(FREIGHT_RPA_CALLBACK_CLEANUP_MAX_ATTEMPTS)。"""
try:
return max(
1,
int(current_app.config.get("FREIGHT_RPA_CALLBACK_CLEANUP_MAX_ATTEMPTS") or _DEFAULT_MAX_CLEANUP_ATTEMPTS),
)
except (TypeError, ValueError):
return _DEFAULT_MAX_CLEANUP_ATTEMPTS
def is_callback_drop_file_consumed(callback_path: Path) -> bool:
"""判断 drop 文件是否已被 HXOPS 消费(sidecar 或已位于 quarantine)。"""
path = Path(callback_path)
if not path.name:
return False
quarantine = callback_quarantine_dir()
if quarantine and quarantine in path.parents:
return True
sidecar = Path(f"{path}{_CALLBACK_CONSUMED_SUFFIX}")
return sidecar.is_file()
def mark_callback_drop_file_consumed(
callback_path: Path,
*,
run_no: str | None = None,
task_no: str | None = None,
schedule_run_id: int | None = None,
inventory_file_no: str | None = None,
) -> None:
"""
标记 drop 区 callback 文件已被系统消费。
核心逻辑:写 sidecar JSON;配合 quarantine 供 Worker 跳过重复扫描(Worker 须忽略 .hxops_* 子目录)。
"""
if not callback_path.is_file():
return
sidecar = Path(f"{callback_path}{_CALLBACK_CONSUMED_SUFFIX}")
payload = {
"callback_path": str(callback_path),
"consumed_at": datetime.utcnow().isoformat(),
"run_no": str(run_no or "").strip() or None,
"task_no": str(task_no or "").strip() or None,
"schedule_run_id": schedule_run_id,
"inventory_file_no": str(inventory_file_no or "").strip() or None,
}
try:
sidecar.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8")
except OSError as exc:
_LOGGER.warning("failed to write callback consumed marker %s: %s", sidecar, exc)
def quarantine_callback_drop_file(callback_path: Path) -> Path | None:
"""
将归档失败的 callback 原子移入隔离目录,避免 Worker 扫描 drop 根目录时重复上报。
Returns:
隔离后的路径;不可用时返回 None。
"""
path = Path(callback_path)
if not path.is_file():
return None
quarantine = callback_quarantine_dir()
if quarantine is None:
return None
quarantine.mkdir(parents=True, exist_ok=True)
target = quarantine / path.name
if target.exists():
target = quarantine / (
f"{path.stem}_{datetime.utcnow().strftime('%Y%m%d%H%M%S')}{path.suffix}"
)
shutil.move(str(path), str(target))
consumed = Path(f"{path}{_CALLBACK_CONSUMED_SUFFIX}")
if consumed.is_file():
try:
consumed.unlink()
except OSError:
pass
return target
def enqueue_callback_file_move(
callback_path: Path,
*,
processed_dir: Path,
run_no: str | None = None,
task_no: str | None = None,
schedule_run_id: int | None = None,
error: str | None = None,
) -> Path | None:
"""
将失败的 callback 归档操作写入持久化队列,供后续重试。
Returns:
队列 job 文件路径;队列不可用时返回 None。
"""
queue = callback_cleanup_queue_dir()
if queue is None:
return None
queue.mkdir(parents=True, exist_ok=True)
job_id = uuid.uuid4().hex
job_path = queue / f"move_{job_id}.json"
payload: dict[str, Any] = {
"job_id": job_id,
"callback_path": str(callback_path),
"processed_dir": str(processed_dir),
"run_no": str(run_no or "").strip() or None,
"task_no": str(task_no or "").strip() or None,
"schedule_run_id": schedule_run_id,
"last_error": str(error or "").strip() or None,
"enqueued_at": datetime.utcnow().isoformat(),
"attempts": 0,
}
tmp = job_path.with_suffix(".json.tmp")
try:
tmp.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8")
tmp.replace(job_path)
except OSError as exc:
_LOGGER.warning("failed to enqueue callback move job for %s: %s", callback_path, exc)
return None
return job_path
def move_callback_drop_file_to_processed(callback_path: Path, processed_dir: Path) -> None:
"""将 callback 文件移入 processed 目录(公开给 workflow 直接调用)。"""
_move_callback_file_to_processed(callback_path, processed_dir)
def _move_callback_file_to_processed(callback_path: Path, processed_dir: Path) -> None:
"""将 callback 文件移入 processed 目录。"""
if not callback_path.is_file():
return
processed_dir.mkdir(parents=True, exist_ok=True)
target = processed_dir / callback_path.name
if target.exists():
target = processed_dir / (
f"{callback_path.stem}_{datetime.utcnow().strftime('%H%M%S')}{callback_path.suffix}"
)
shutil.move(str(callback_path), str(target))
consumed = Path(f"{callback_path}{_CALLBACK_CONSUMED_SUFFIX}")
if consumed.is_file():
try:
consumed.unlink()
except OSError:
pass
def _archive_failed_cleanup_job(job_path: Path, payload: dict[str, Any]) -> None:
"""超过最大重试次数后将 job 移入 failed 目录。"""
failed_dir = callback_cleanup_failed_dir()
if failed_dir is None:
try:
job_path.unlink()
except OSError:
pass
return
failed_dir.mkdir(parents=True, exist_ok=True)
target = failed_dir / job_path.name
payload["archived_at"] = datetime.utcnow().isoformat()
try:
target.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8")
job_path.unlink()
except OSError as exc:
_LOGGER.warning("failed to archive cleanup job %s: %s", job_path, exc)
def flush_callback_cleanup_queue(*, max_jobs: int = 32) -> list[str]:
"""
重试持久化 callback 归档队列。
核心逻辑:源文件已不存在视为完成;超限 job 移入 failed;仍失败则累加 attempts。
"""
queue = callback_cleanup_queue_dir()
if queue is None or not queue.is_dir():
return []
warnings: list[str] = []
max_attempts = callback_cleanup_max_attempts()
jobs = sorted(queue.glob("move_*.json"))[: max(max_jobs, 1)]
for job_path in jobs:
try:
payload = json.loads(job_path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError, TypeError, ValueError) as exc:
warnings.append(f"{job_path.name}:invalid_job:{str(exc)[:80]}")
try:
job_path.unlink()
except OSError:
pass
continue
callback_raw = str(payload.get("callback_path") or "").strip()
processed_raw = str(payload.get("processed_dir") or "").strip()
callback_path = Path(callback_raw) if callback_raw else None
processed_dir = Path(processed_raw) if processed_raw else onhand_processed_dir()
if callback_path is None or processed_dir is None:
try:
job_path.unlink()
except OSError:
pass
continue
if not callback_path.is_file():
try:
job_path.unlink()
except OSError:
pass
continue
if int(payload.get("attempts") or 0) >= max_attempts:
warnings.append(f"{callback_path}:max_attempts_exceeded")
_archive_failed_cleanup_job(job_path, payload)
continue
try:
_move_callback_file_to_processed(callback_path, processed_dir)
try:
job_path.unlink()
except OSError:
pass
except Exception as exc:
payload["attempts"] = int(payload.get("attempts") or 0) + 1
payload["last_error"] = str(exc)[:240]
payload["last_attempt_at"] = datetime.utcnow().isoformat()
warnings.append(f"{callback_path}:{str(exc)[:120]}")
if int(payload["attempts"]) >= max_attempts:
_archive_failed_cleanup_job(job_path, payload)
else:
try:
job_path.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8")
except OSError:
pass
_LOGGER.warning(
"callback cleanup retry failed for %s (attempt=%s)",
callback_path,
payload["attempts"],
exc_info=exc,
)
return warnings
def recover_pending_rpa_callback_cleanup_jobs(*, max_jobs: int = 64) -> tuple[int, list[str]]:
"""
启动或调度恢复时消费 callback cleanup 队列。
Returns:
tuple: (成功消化或移除的 job 数, 告警列表)。
"""
queue = callback_cleanup_queue_dir()
before = len(list(queue.glob("move_*.json"))) if queue and queue.is_dir() else 0
warnings = flush_callback_cleanup_queue(max_jobs=max_jobs)
after = len(list(queue.glob("move_*.json"))) if queue and queue.is_dir() else 0
return max(0, before - after), warnings
@@ -0,0 +1,108 @@
"""
services/freight_rpa/onhand/trigger_io.py
用途:onhand(在手库存)RPA 的纯文件 IO——trigger/落盘目录解析、trigger JSON 原子写、
单任务导出 trigger 写入,以及 Worker 触发/回调契约常量(SCHEMA/ACTION_*)。
依赖:Flask current_app 配置、Path/JSON/文件系统工具;不 import 任何业务编排模块
(import 边界由 tests/services/freight_rpa/test_import_boundary.py 锁死)。
逻辑:由 shipping_notice.onhand_trigger_batch(批量/按需编排)、inventory_rpa_workflow(回调 schema 校验)、
per_source_rpa_service(回调 schema 校验)、freight_rpa.common.worker_heartbeat(目录探测)等调用,
与外部 RPA Worker 的文件投递目录交互;schema/action 新值以本文件常量为单一真相
(Worker 侧 Task 12 对表:freight_rpa.onhand.v1 / onhand_export / onhand_export_batch)。
"""
from __future__ import annotations
import json
import os
from datetime import datetime
from pathlib import Path
from typing import Any
from flask import current_app
# Worker 触发/回调契约常量:后端写入侧与校验侧共用单一真相,禁止再写字面量。
# [PROMPT_UPDATE] 2026-10-16 freight_rpa 解耦批次 R:schema/action 切换为下述新值
# (旧 inventory 时代字面量已从 backend/app 与 Worker 双侧清零,历史对照见 cutover runbook),
# 旧字符串已在 backend/app 内清零;Worker 侧由 Task 12 对齐。
SCHEMA = "freight_rpa.onhand.v1"
ACTION_ONHAND_EXPORT = "onhand_export"
ACTION_ONHAND_EXPORT_BATCH = "onhand_export_batch"
def _path(key: str) -> Path | None:
value = str(current_app.config.get(key) or "").strip()
if not value:
return None
return Path(value)
def onhand_drop_dir() -> Path | None:
"""RPA onhand 库存 Excel 落盘目录(FREIGHT_RPA_SHARED_ONHAND_DROP_DIR)。"""
return _path("FREIGHT_RPA_SHARED_ONHAND_DROP_DIR")
def onhand_processed_dir() -> Path | None:
"""已处理 onhand 文件归档子目录(drop_dir/processed)。"""
base = onhand_drop_dir()
if not base:
return None
return base / "processed"
def onhand_trigger_dir() -> Path | None:
"""RPA onhand 导出触发 JSON 目录(FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR)。"""
return _path("FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR")
def _write_trigger_json_atomic(path: Path, body: dict[str, Any]) -> None:
"""原子发布 trigger,避免 Worker 读取到写入中的半截 JSON。"""
temp_path = path.with_name(f'.{path.name}.{os.getpid()}.tmp')
try:
with open(temp_path, 'w', encoding='utf-8') as handle:
json.dump(body, handle, ensure_ascii=False, indent=2)
handle.flush()
os.fsync(handle.fileno())
os.replace(temp_path, path)
finally:
if temp_path.exists():
temp_path.unlink(missing_ok=True)
def write_onhand_export_trigger(task_no: str, payload: dict[str, Any] | None = None) -> str | None:
"""
写入 RPA onhand 导出触发文件 inventory_export_{task_no}.json
(文件名沿用既有 Worker 契约,仅 action 取新值 ACTION_ONHAND_EXPORT)。
Returns:
str | None: 触发文件绝对路径;目录未配置时返回 None。
"""
trigger_dir = onhand_trigger_dir()
if not trigger_dir:
return None
trigger_dir.mkdir(parents=True, exist_ok=True)
body = {
"action": ACTION_ONHAND_EXPORT,
"task_no": task_no,
"run_no": f"LEGACY-{task_no}-{datetime.utcnow().strftime('%Y%m%d%H%M%S%f')}",
"requested_at": datetime.utcnow().isoformat(),
**(payload or {}),
}
path = trigger_dir / f"inventory_export_{task_no}.json"
_write_trigger_json_atomic(path, body)
return str(path)
# TODO(批次S): 全仓零调用,死代码候选,收敛时删除
def find_latest_inventory_file() -> Path | None:
"""在 drop 目录中查找最新修改的 xlsx/xls/csv 库存文件。"""
drop = onhand_drop_dir()
if not drop or not drop.is_dir():
return None
candidates = [
p for p in drop.iterdir()
if p.is_file() and p.suffix.lower() in {".xlsx", ".xls", ".csv"}
]
if not candidates:
return None
return max(candidates, key=lambda p: p.stat().st_mtime)
@@ -0,0 +1,336 @@
"""
services/freight_rpa/onhand/workflow_protocol.py
用途:onhand(在手库存)RPA 回调协议态——attempt 行记账、run_no 幂等键、轮次校验、
排程进度记账与超时窗口判定的纯协议层。
依赖:app.models(ShippingTaskEvent / ShippingTaskInventoryRpaAttempt / ScheduleRun)、
app.extensions.db、freight_rpa.onhand 包内模块;**禁止 import 任何
shipping_notice 业务模块**(import 边界由 tests/services/freight_rpa/test_import_boundary.py
AST 全包扫描锁死,含函数内延迟 import)。
逻辑:Task 9 拆分自 shipping_notice.inventory_rpa_workflow——回调进入
/api/freight-rpa/* 蓝图后,业务 sink(shipping_notice.rpa_sinks 注册)在原事务内
调用本模块完成协议记账(不改变 commit 时机),再由域内业务函数做快照落盘/
门禁推进/审计投影;快照、Gate、状态机等业务终态一律留在 shipping_notice。
"""
from __future__ import annotations
import json
from datetime import datetime
from pathlib import Path
from typing import Any
from app.extensions import db
from app.models import ScheduleRun, ShippingTaskEvent, ShippingTaskInventoryRpaAttempt
def latest_task_event(task: Any, event_type: str) -> ShippingTaskEvent | None:
"""返回任务最近一条指定类型的 ShippingTaskEvent(RPA 超时/重试/轮次校验用)。"""
if task.id is None:
return None
return (
ShippingTaskEvent.query.filter_by(task_id=task.id, event_type=event_type)
.order_by(ShippingTaskEvent.id.desc())
.first()
)
def extract_run_no_from_trigger(trigger_path: str | None) -> str:
"""从 trigger 文件路径或 JSON 内容提取 run_no(batch / legacy 单票均支持)。"""
path = Path(str(trigger_path or ""))
name = path.name
prefix = "inventory_export_batch_"
if name.startswith(prefix) and name.endswith(".json"):
return name[len(prefix) : -len(".json")]
if name.startswith("inventory_export_") and name.endswith(".json") and path.is_file():
try:
payload = json.loads(path.read_text(encoding="utf-8"))
if isinstance(payload, dict):
run_no = str(payload.get("run_no") or "").strip()
if run_no:
return run_no
except (OSError, json.JSONDecodeError, TypeError, ValueError):
pass
return ""
def is_legacy_trigger_run_no(run_no: str) -> bool:
"""判断 run_no 是否来自 legacy 单任务 trigger(worker 可能不回传 run_no)。"""
return str(run_no or "").strip().upper().startswith("LEGACY-")
def expected_rpa_callback_run_no(task: Any) -> str:
"""读取任务最近一次 RPA 触发记录的 run_no(事件 detail 优先,缺失回退 trigger 文件)。"""
last_trigger = latest_task_event(task, "inventory_rpa_triggered")
if not last_trigger:
return ""
detail = last_trigger.detail_json if isinstance(last_trigger.detail_json, dict) else {}
run_no = str(detail.get("run_no") or "").strip()
if run_no:
return run_no
return extract_run_no_from_trigger(str(detail.get("trigger") or ""))
def validate_rpa_callback_run_no(task: Any, callback_run_no: str) -> str | None:
"""校验回调 run_no 属于当前任务最近一次有效触发轮次。
Returns:
None 校验通过;否则返回拒绝原因码(no_active_trigger / run_no_missing / run_no_mismatch)。
"""
provided = str(callback_run_no or "").strip()
expected = expected_rpa_callback_run_no(task)
if not expected:
return "no_active_trigger"
if not provided:
if is_legacy_trigger_run_no(expected):
return None
return "run_no_missing"
if provided != expected:
return "run_no_mismatch"
return None
def resolve_effective_callback_run_no(task: Any, payload: dict[str, Any]) -> str:
"""解析回调实际归属的 run_no(显式传入优先,否则回退当前触发轮次)。"""
provided = str(payload.get("run_no") or "").strip()
if provided:
return provided
return expected_rpa_callback_run_no(task)
def get_consumed_inventory_rpa_run_no(task: Any) -> str:
"""读取已消费(处理完成)的 RPA 轮次 run_no。"""
attempt = (
ShippingTaskInventoryRpaAttempt.query
.filter_by(task_no=str(task.task_no or ''), status='consumed')
.order_by(ShippingTaskInventoryRpaAttempt.consumed_at.desc(), ShippingTaskInventoryRpaAttempt.id.desc())
.first()
)
return str(getattr(attempt, 'source_run_no', '') or '').strip()
def mark_inventory_rpa_run_no_consumed(task: Any, run_no: str) -> None:
"""[协议记账] 标记当前 RPA 轮次已被回调消费,防止同一 run_no 重放重复入库。
核心逻辑:只改 Attempt 行(status/consumed_at),不 commit——commit 时机由调用方
业务事务决定,与拆分前行为一致。
"""
effective = str(run_no or "").strip()
if not effective:
return
attempt = (
ShippingTaskInventoryRpaAttempt.query
.filter_by(task_no=str(task.task_no or ''), source_run_no=effective)
.one_or_none()
)
if attempt is not None:
attempt.status = 'consumed'
attempt.consumed_at = datetime.utcnow()
def validate_rpa_callback_not_replayed(task: Any, run_no: str) -> str | None:
"""拒绝同一 run_no 的重复成功/失败/跳过回调。
Returns:
None 允许处理;"run_no_already_consumed" 表示重放,应拒绝。
"""
effective = str(run_no or "").strip()
consumed = get_consumed_inventory_rpa_run_no(task)
if effective and consumed and effective == consumed:
return "run_no_already_consumed"
return None
def validate_schedule_batch_callback_run_no(schedule_run_id: int | None, callback_run_no: str) -> str | None:
"""校验定时 batch 回调 run_no 与排程 run 记录一致,防止错绑终态。
Returns:
None 校验通过;否则返回拒绝原因码(schedule_run_not_found / schedule_run_no_missing /
schedule_run_no_mismatch / schedule_run_not_awaiting)。
"""
if schedule_run_id is None:
return None
run = db.session.get(ScheduleRun, schedule_run_id)
if not run:
return "schedule_run_not_found"
expected = str(run.run_no or "").strip()
provided = str(callback_run_no or "").strip()
if not expected:
return "schedule_run_no_missing"
if provided != expected:
return "schedule_run_no_mismatch"
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
if run.status != "running" or not summary.get("awaiting_rpa"):
return "schedule_run_not_awaiting"
return None
def record_onhand_batch_progress(
run: ScheduleRun,
run_no: str,
*,
success_count: int,
skipped_count: int,
failed_count: int,
) -> dict[str, Any]:
"""[协议记账] 排程批量导出进度回写:max(现有, 上报) 防乱序回退,写后即 commit。
【AI 触发时机】:onhand-batch-progress 业务 sink 已完成 schema/run 校验后调用;
非终态记账(不修改 status/started_at/finished_at,终态仍以 batch-ready 为准)。
Args:
run: 已确认存在且处于 awaiting_rpa 的 ScheduleRun 行。
run_no: 批次 run_no,写入 response_summary_json.progress 供审计。
success_count / skipped_count / failed_count: 已按 max(0, int(x)) 归一的非负计数。
Returns:
dict: 提交后的最终计数 {'success_count','skipped_count','failed_count','run_no'};
供业务层拼装响应,键值与拆分前响应逐字一致。
"""
run.success_count = max(int(run.success_count or 0), success_count)
run.skipped_count = max(int(run.skipped_count or 0), skipped_count)
run.failed_count = max(int(run.failed_count or 0), failed_count)
summary = dict(run.response_summary_json or {})
summary['progress'] = {
'success_count': int(run.success_count or 0),
'skipped_count': int(run.skipped_count or 0),
'failed_count': int(run.failed_count or 0),
'batch_run_no': run_no,
'updated_at': datetime.utcnow().isoformat(),
}
run.response_summary_json = summary
# commit 时机与拆分前 inventory_rpa_workflow.report_inventory_batch_progress 完全一致:
# 校验通过、计数写完后立即提交,再由业务层构造响应。
db.session.commit()
return {
'run_no': run_no,
'success_count': int(run.success_count or 0),
'skipped_count': int(run.skipped_count or 0),
'failed_count': int(run.failed_count or 0),
}
def compute_rpa_wait_window(
triggered_at: datetime,
timeout_seconds: int,
*,
now: datetime | None = None,
) -> tuple[int, int, int]:
"""计算库存 RPA 等待窗口(elapsed / timeout / remaining 秒)。
【AI 触发时机】:业务层已确认任务处于 RPA 等待态、需要判断是否超时或调度复查时调用。
Args:
triggered_at: 最近一次 inventory_rpa_triggered 事件的 created_at。
timeout_seconds: 超时阈值秒数(由业务层 tool_common 读取配置)。
now: 可注入当前时间(测试用);缺省 utcnow。
Returns:
tuple[int, int, int]: (elapsed_seconds, timeout_seconds, remaining_seconds);
elapsed 向下取整且不为负,remaining 不为负。
"""
current = now or datetime.utcnow()
elapsed = max(int((current - triggered_at).total_seconds()), 0)
remaining = max(int(timeout_seconds) - elapsed, 0)
return elapsed, int(timeout_seconds), remaining
def resolve_shared_inventory_drop_file(raw_path: str, *, allowed_root: Path) -> Path | None:
"""将 Worker 回调中的 file_path 解析为 Linux 侧共享 drop 内的真实文件。
Windows Worker 上报 ``C:\\HxopsRpaTest\\data\\inventory_drop\\file.xlsx``,
Ubuntu 后端通过 ``/mnt/hxops-rpa-*-data/inventory_drop/file.xlsx`` 读同一 SMB 文件。
安全约束:仅允许 ``allowed_root`` 下按文件名映射,拒绝路径穿越。
Returns:
Path | None: 解析成功且确为 allowed_root 下存在文件时返回绝对路径;否则 None。
"""
text = str(raw_path or '').strip()
if not text:
return None
try:
root = allowed_root.resolve()
except OSError:
return None
candidate = Path(text)
try:
resolved = candidate.resolve()
if resolved.is_file():
resolved.relative_to(root)
return resolved
except (OSError, ValueError, RuntimeError):
pass
name = Path(text.replace('\\', '/')).name.strip()
if not name or name in {'.', '..'} or '/' in name or '\\' in name:
return None
mapped = (root / name).resolve()
try:
mapped.relative_to(root)
except ValueError:
return None
if mapped.is_file():
return mapped
return None
def normalize_inventory_result_status(payload: dict[str, Any]) -> str:
"""归一化单任务 RPA 库存回调结果。
核心逻辑:优先读取 worker 上报的 status;兼容旧回调仅含 success/skipped 布尔字段;
缺省 success 视为 true(历史单任务回调兼容)。
Returns:
str: success | skipped | failed
"""
raw_status = str(payload.get("status") or "").strip().lower()
if raw_status in {"success", "skipped", "failed"}:
return raw_status
if payload.get("skipped"):
return "skipped"
if bool(payload.get("success", True)):
return "success"
return "failed"
def normalize_inventory_batch_item_status(item: dict[str, Any]) -> str:
"""归一化 batch results 单条明细(比单任务更严格:缺字段不算 success)。
核心逻辑:与 worker `_normalize_inventory_batch_item_status` 对齐;空 dict 或
缺 status/success/skipped 直接归为 failed,避免误走 success→file_missing 分支。
Returns:
str: success | skipped | failed
"""
raw_status = str(item.get("status") or "").strip().lower()
if raw_status in {"success", "skipped", "failed"}:
return raw_status
if item.get("skipped"):
return "skipped"
if item.get("success") is True:
return "success"
return "failed"
def merge_batch_callback_item(payload: dict[str, Any], item: dict[str, Any]) -> dict[str, Any]:
"""合并 batch 顶层契约字段到 result item。
核心逻辑:合并 batch 已认证的 schema_version / run_no / task_no;其余身份字段必须由
Worker item 显式返回,禁止后端从任务或数据库补齐。
Returns:
dict: 合并后的 item 副本(不修改入参)。
"""
merged = dict(item)
top_schema_version = str(payload.get('schema_version') or '').strip()
if top_schema_version and not str(merged.get('schema_version') or '').strip():
merged['schema_version'] = top_schema_version
top_run_no = str(payload.get("run_no") or "").strip()
if top_run_no and not str(merged.get("run_no") or "").strip():
merged["run_no"] = top_run_no
task_no = str(merged.get("task_no") or payload.get("task_no") or "").strip()
if task_no and not str(merged.get("task_no") or "").strip():
merged["task_no"] = task_no
return merged
@@ -0,0 +1 @@
"""upload:货代上传 RPA。"""
@@ -0,0 +1,144 @@
"""
services/freight_rpa/upload/trigger_io.py
用途:upload(货代上传)RPA 的纯文件 IO——上传队列/trigger 目录解析、Excel 复制入队、
上传 trigger JSON 原子写入(含凭据信封固化)。
依赖:Flask current_app 配置、Path/shutil/uuid/JSON/文件系统工具;不 import 任何业务编排模块
(import 边界由 tests/services/freight_rpa/test_import_boundary.py 锁死)。
逻辑:由 shipping_notice.fulfillment_workflow(upload_to_freight 触发上传)、
freight_rpa.common.worker_heartbeat(上传目录就绪探测)调用,
与外部 RPA Worker 的文件投递目录交互;trigger 契约串以本文件常量为单一真相
([PROMPT_UPDATE] 2026-10-16 批次 R 新裁定:upload 契约随发布窗口一次切换——
action 由 shipment_upload 改为 outbound_upload、schema 由 shipping_notice_upload_rpa.v1
改为 freight_rpa.upload.v1,Worker 侧 Task 12 同窗口对齐,旧串全仓清零)。
"""
from __future__ import annotations
import json
import os
import shutil
import uuid
from datetime import datetime
from pathlib import Path
from typing import Any
from flask import current_app
# Worker 触发契约常量:后端写入侧单一真相,禁止再写字面量(Worker 侧常量见
# scripts/freight_rpa/common/rpa_callbacks.py 邻域的 inbound/onhand 对齐方式)。
SCHEMA = "freight_rpa.upload.v1"
ACTION_OUTBOUND_UPLOAD = "outbound_upload"
def _path(key: str) -> Path | None:
value = str(current_app.config.get(key) or "").strip()
if not value:
return None
return Path(value)
def _write_trigger_json_atomic(path: Path, body: dict[str, Any]) -> None:
"""原子发布 trigger,避免 Worker 读取到写入中的半截 JSON。"""
temp_path = path.with_name(f'.{path.name}.{os.getpid()}.tmp')
try:
with open(temp_path, 'w', encoding='utf-8') as handle:
json.dump(body, handle, ensure_ascii=False, indent=2)
handle.flush()
os.fsync(handle.fileno())
os.replace(temp_path, path)
finally:
if temp_path.exists():
temp_path.unlink(missing_ok=True)
def upload_queue_dir() -> Path | None:
"""货代上传 Excel 队列目录(RPA 从此处读取待上传文件)。"""
return _path("FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR")
def upload_trigger_dir() -> Path | None:
"""RPA 货代上传触发 JSON 目录。"""
return _path("FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR")
def write_upload_trigger(
task_no: str,
export_file_path: str,
payload: dict[str, Any] | None = None,
*,
attempt_id: int | None = None,
artifact_id: int | None = None,
connector_type: str | None = None,
upload_config: dict[str, Any] | None = None,
upload_config_hash: str | None = None,
login_url: str | None = None,
credential_envelope: dict[str, Any] | None = None,
callback_id: str | None = None,
business_no: str | None = None,
) -> tuple[str | None, str | None, str | None]:
"""
复制发货 Excel 至共享上传队列,并以原子发布方式写入 RPA 上传触发 JSON。
【AI 触发时机】:upload_to_freight(mode=auto|retry_upload) 触发货代上传时调用。
触发文件固化本次上传契约快照,Worker 据此进入 DSV/Crane 受控流程:
schema_version / task_no / attempt_id / artifact_id / callback_id(非空)/
connector_type / upload_config(本次快照 + upload_config_hash)/ login_url / credential_envelope / file_path。
平台差异(文件选择器、提交与结果判定)由 Worker 的受控 Adapter 按 upload_config 执行。
写入复用“临时文件 + fsync + os.replace”原子方式,避免 Worker 读取半写 JSON。
Args:
task_no: 发货任务号。
export_file_path: 待上传发货 Excel 的服务端路径。
payload: 附加字段(如 mode),与下列具名参数合并。
attempt_id: 本次 Upload Attempt 主键。
artifact_id: 当前上传目标 Artifact 主键。
connector_type: 业务连接类型(dbs / crane)。
upload_config: 本次上传使用的连接级受控配置快照(enabled/entry_url/selector 等)。
upload_config_hash: 该快照的 sha256,用于审计关联。
login_url: 该连接登录地址(先登录,再访问 upload_config.entry_url 进入上传页)。
credential_envelope: 连接凭据密文信封(Worker 据此登录)。
callback_id: 回调幂等 ID;为空时自动生成,保证非空。
business_no: 发货通知对外业务编号(业务单号),用于精简上传文件名;为空时回退 task_no。
Returns:
tuple[str | None, str | None, str | None]: (queue 文件路径, trigger 文件路径, callback_id);
失败时 (None, None, None)。
"""
queue = upload_queue_dir()
trigger_dir = upload_trigger_dir()
if not queue or not trigger_dir:
return None, None, None
queue.mkdir(parents=True, exist_ok=True)
trigger_dir.mkdir(parents=True, exist_ok=True)
src = Path(export_file_path)
if not src.is_file():
return None, None, None
# [STEP] 精简上传文件名:仅用业务编号(业务单号),避免 task_no 与导出文件名重复拼接过长;
# 业务编号为空时回退到内部任务号,扩展名沿用源文件(无扩展名时按 xlsx 兜底)。
emit_no = str(business_no or '').strip() or task_no
suffix = str(src.suffix or '.xlsx').lower()
dest = queue / f"{emit_no}{suffix}"
shutil.copy2(src, dest)
resolved_callback_id = str(callback_id or '').strip() or f'upload:{task_no}:{uuid.uuid4().hex[:12]}'
body = {
"action": ACTION_OUTBOUND_UPLOAD,
"schema_version": SCHEMA,
"task_no": task_no,
"attempt_id": attempt_id,
"artifact_id": artifact_id,
"callback_id": resolved_callback_id,
"connector_type": str(connector_type or '').strip() or None,
"upload_config": upload_config,
"upload_config_hash": upload_config_hash,
"login_url": login_url,
"credential_envelope": credential_envelope,
"file_path": str(dest),
"requested_at": datetime.utcnow().isoformat(),
**(payload or {}),
}
trigger_path = trigger_dir / f"upload_{task_no}.json"
_write_trigger_json_atomic(trigger_path, body)
return str(dest), str(trigger_path), resolved_callback_id