feat(freight-rpa): 批次R解耦编排层并切换 onhand/inbound 契约
将 RPA 编排收编至 freight_rpa,回调迁 /api/freight-rpa/*。 共享目录与 Worker 契约一次切换至 onhand/inbound/upload, 并补 outbound 骨架与 tt16 排程 job key 迁移。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
bf3154033b
commit
ffc0d4a430
147 files changed
+4221
-2678
No files matched your search
@@ -1,57 +0,0 @@
|
||||
"""
|
||||
services/shipping_notice/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)
|
||||
@@ -3,7 +3,7 @@ services/shipping_notice/fulfillment_workflow.py
|
||||
|
||||
用途:发货通知履约阶段 — 库存匹配、Excel 导出、货代上传(RPA/人工)与下游衔接入口。
|
||||
依赖:customer_identity_gate、reservation_gate、match、export、query_service、inventory_workflow、
|
||||
inventory_mapping_workflow、stp_line_inventory_match、upload_attempt_service、rpa.write_upload_trigger、
|
||||
inventory_mapping_workflow、stp_line_inventory_match、upload_attempt_service、freight_rpa.upload.trigger_io、
|
||||
tool_common、tool_response、fulfillment_audit、task_workflow(Excel 就绪清失效)、
|
||||
order_task_stage_machine。
|
||||
逻辑:tools.py 门面 re-export;匹配成功后 Gate 路径禁止 try_auto_chain 内嵌 generate/upload,
|
||||
@@ -65,11 +65,11 @@ from app.services.shipping_notice.upload_attempt_service import (
|
||||
record_manual_upload,
|
||||
start_rpa_attempt,
|
||||
)
|
||||
from app.services.shipping_notice.rpa import write_upload_trigger
|
||||
from app.services.shipping_notice.rpa_attempts import (
|
||||
from app.services.freight_rpa.onhand.attempts import (
|
||||
max_rpa_upload_attempts,
|
||||
upload_rpa_attempts,
|
||||
)
|
||||
from app.services.freight_rpa.upload.trigger_io import write_upload_trigger
|
||||
from app.services.shipping_notice.inventory_source_rules import task_rpa_inventory_source
|
||||
from app.services.shipping_notice.inventory_source_repository import get_rpa_trigger_inventory_source
|
||||
from app.services.shipping_notice.upload_config_validation import compute_upload_config_hash
|
||||
@@ -465,7 +465,7 @@ def _trigger_freight_upload_rpa(
|
||||
|
||||
# [STEP] 自动上传前强制系统级就绪:Worker / 凭据 / 共享目录 / 环境隔离 / 回调基址。
|
||||
try:
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat import assert_freight_upload_rpa_ready
|
||||
from app.services.freight_rpa.common.worker_heartbeat import assert_freight_upload_rpa_ready
|
||||
|
||||
assert_freight_upload_rpa_ready()
|
||||
except ServiceUnavailableError as exc:
|
||||
|
||||
@@ -122,7 +122,7 @@ def start_batch_test_export(source_ids: list[int], *, actor_id: int | None, retr
|
||||
"""创建批量验证并按连接配置分组投递 RPA;每站点保留独立运行与回调结果。"""
|
||||
sources = _validate_batch_sources(source_ids)
|
||||
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source
|
||||
from app.services.shipping_notice.rpa import write_inventory_export_batch_trigger
|
||||
from app.services.shipping_notice.onhand_trigger_batch import write_inventory_export_batch_trigger
|
||||
|
||||
stamp = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')
|
||||
batch = ShippingInventoryValidationBatch(
|
||||
@@ -219,7 +219,7 @@ def _expire_timed_out_runs(source: ShippingInventorySource) -> None:
|
||||
同一 RPA Profile 的批量站点由 Windows Worker 串行执行。每个站点沿用单站
|
||||
等待窗口会让排在后面的站点尚未被领取就超时,因此同组按站点数量线性扩展。
|
||||
"""
|
||||
timeout = max(1, int(current_app.config['FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS']))
|
||||
timeout = max(1, int(current_app.config['FREIGHT_RPA_ONHAND_TIMEOUT_SECONDS']))
|
||||
runs = ShippingInventoryConfigurationTestRun.query.filter(
|
||||
ShippingInventoryConfigurationTestRun.inventory_source_id == source.id,
|
||||
ShippingInventoryConfigurationTestRun.status.in_(['awaiting_rpa', 'processing']),
|
||||
@@ -274,7 +274,7 @@ def start_test_export(source_id: int, *, actor_id: int | None) -> dict[str, Any]
|
||||
).order_by(ShippingInventoryConfigurationTestRun.id.desc()).first()
|
||||
if active:
|
||||
return _payload(active)
|
||||
from app.services.shipping_notice.rpa import write_inventory_export_batch_trigger
|
||||
from app.services.shipping_notice.onhand_trigger_batch import write_inventory_export_batch_trigger
|
||||
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source
|
||||
|
||||
run_no = f'CONFIG-{source.source_code}-{datetime.utcnow().strftime("%Y%m%d%H%M%S%f")}'
|
||||
@@ -354,14 +354,14 @@ def report_test_export(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
db.session.commit()
|
||||
return _payload(run)
|
||||
# Windows Worker 回传 C:\HxopsRpa...\inventory_drop\file.xlsx;Linux 后端必须映射到
|
||||
# FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR 下同名文件,否则 Path(windows).is_file() 恒假。
|
||||
# FREIGHT_RPA_SHARED_ONHAND_DROP_DIR 下同名文件,否则 Path(windows).is_file() 恒假。
|
||||
raw_file_path = str(payload.get('file_path') or '').strip()
|
||||
path: Path | None = None
|
||||
from app.services.shipping_notice.rpa import inventory_drop_dir
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import _resolve_shared_inventory_drop_file
|
||||
drop_root = inventory_drop_dir()
|
||||
from app.services.freight_rpa.onhand.trigger_io import onhand_drop_dir
|
||||
from app.services.freight_rpa.onhand.workflow_protocol import resolve_shared_inventory_drop_file
|
||||
drop_root = onhand_drop_dir()
|
||||
if drop_root is not None:
|
||||
path = _resolve_shared_inventory_drop_file(raw_file_path, allowed_root=drop_root)
|
||||
path = resolve_shared_inventory_drop_file(raw_file_path, allowed_root=drop_root)
|
||||
if path is None:
|
||||
candidate = Path(raw_file_path)
|
||||
if candidate.is_file():
|
||||
|
||||
@@ -1,300 +0,0 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_rpa_callback_cleanup.py
|
||||
|
||||
用途:RPA callback drop 区文件归档失败后的持久化重试队列、隔离与消费标记。
|
||||
依赖:rpa.inventory_drop_dir / inventory_processed_dir、json、uuid、Flask current_app。
|
||||
逻辑:commit 后尝试归档;失败则移入 .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.shipping_notice.rpa import inventory_drop_dir, inventory_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 = inventory_drop_dir()
|
||||
if not drop:
|
||||
return None
|
||||
return drop / _CLEANUP_QUEUE_DIRNAME
|
||||
|
||||
|
||||
def callback_cleanup_failed_dir() -> Path | None:
|
||||
"""超过最大重试次数的 cleanup job 隔离目录。"""
|
||||
drop = inventory_drop_dir()
|
||||
if not drop:
|
||||
return None
|
||||
return drop / _CLEANUP_FAILED_DIRNAME
|
||||
|
||||
|
||||
def callback_quarantine_dir() -> Path | None:
|
||||
"""
|
||||
Worker 不应扫描的 callback 隔离目录(drop 根目录外的子目录)。
|
||||
归档失败时 HXOPS 将文件原子移入此处,避免重复上报。
|
||||
"""
|
||||
drop = inventory_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 inventory_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
|
||||
@@ -1,27 +1,32 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_rpa_workflow.py
|
||||
|
||||
用途:发货通知库存 RPA 编排(触发导出、等待/超时、回调落盘)。
|
||||
依赖:customer_identity_gate、reservation_gate、rpa、rpa_attempts、inventory_snapshot、
|
||||
inventory_mapping_workflow、query_service、动态订单字段、tool_common、state_machine、tool_response。
|
||||
用途:发货通知库存 RPA 业务编排(触发导出、等待/超时、回调落盘、快照与门禁推进)。
|
||||
依赖:customer_identity_gate、reservation_gate、freight_rpa.onhand(trigger_io 目录/attempts 计数/
|
||||
workflow_protocol 协议记账)、inventory_snapshot、inventory_mapping_workflow、query_service、
|
||||
动态订单字段、tool_common、state_machine、tool_response。
|
||||
逻辑:inventory_workflow.ensure_inventory 在 auto 时仅复用快照、在 retry_rpa 时委托本模块触发刷新;
|
||||
库存源始终由规则 Gate 自动裁决;Reservation 门禁从当前 Extraction 的动态 FieldValue 读取;
|
||||
复用 ready 快照走 link_snapshot_to_task_for_preparation(动态仓未决可 pending_matching)。
|
||||
Task 9 拆分:attempt 行记账/run_no 幂等键/轮次与排程校验/批量进度记账/超时窗口数学/
|
||||
回调契约归一化等纯协议态下沉 freight_rpa.onhand.workflow_protocol(零 shipping_notice
|
||||
import);快照落盘、ScheduleRun finalize、ProcessGate/Execution 推进、审计投影与状态机
|
||||
留守本文件(事务边界与 commit 时机与拆分前逐点等价)。下方旧私有名以模块别名 re-export,
|
||||
既有同包调用与测试 import(含 monkeypatch 接缝)不换名。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import shutil
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, ServiceUnavailableError
|
||||
from app.models import ShippingInventoryFile, ShippingNotice, ShippingOrderTask, ShippingTaskEvent
|
||||
from app.models import ShippingInventoryFile, ShippingNotice, ShippingOrderTask
|
||||
from app.services.shipping_notice.constants import POSITION_UPLOAD_REQ, PH_RPA_PENDING
|
||||
from app.services.shipping_notice.inventory_snapshot import ingest_inventory_file
|
||||
from app.services.shipping_notice.inventory_snapshot_store import (
|
||||
@@ -36,7 +41,7 @@ from app.services.shipping_notice.inventory_upload import (
|
||||
rebuild_task_inventory_attachment_from_snapshot,
|
||||
stage_task_inventory_callback_file,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_rpa_callback_cleanup import (
|
||||
from app.services.freight_rpa.onhand.callback_cleanup import (
|
||||
enqueue_callback_file_move,
|
||||
flush_callback_cleanup_queue,
|
||||
mark_callback_drop_file_consumed,
|
||||
@@ -60,15 +65,34 @@ from app.services.shipping_notice.query_service import (
|
||||
)
|
||||
from app.services.shipping_notice.reservation_gate import task_reservation_gate_issues
|
||||
from app.services.shipping_notice.task_field_gate import field_conflict_gate_response
|
||||
from app.services.shipping_notice.rpa import (
|
||||
inventory_drop_dir,
|
||||
inventory_processed_dir,
|
||||
from app.services.freight_rpa.onhand.attempts import onhand_rpa_attempts
|
||||
from app.services.freight_rpa.onhand.trigger_io import (
|
||||
SCHEMA,
|
||||
onhand_drop_dir,
|
||||
onhand_processed_dir,
|
||||
)
|
||||
from app.services.freight_rpa.onhand.workflow_protocol import (
|
||||
compute_rpa_wait_window,
|
||||
expected_rpa_callback_run_no,
|
||||
extract_run_no_from_trigger,
|
||||
get_consumed_inventory_rpa_run_no,
|
||||
is_legacy_trigger_run_no,
|
||||
latest_task_event,
|
||||
mark_inventory_rpa_run_no_consumed,
|
||||
merge_batch_callback_item,
|
||||
normalize_inventory_batch_item_status,
|
||||
normalize_inventory_result_status,
|
||||
record_onhand_batch_progress,
|
||||
resolve_effective_callback_run_no,
|
||||
resolve_shared_inventory_drop_file,
|
||||
validate_rpa_callback_not_replayed,
|
||||
validate_rpa_callback_run_no,
|
||||
validate_schedule_batch_callback_run_no,
|
||||
)
|
||||
from app.services.shipping_notice.onhand_trigger_batch import (
|
||||
write_inventory_export_trigger_for_task,
|
||||
)
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat import RPA_WORKER_OFFLINE_MESSAGE
|
||||
from app.services.shipping_notice.rpa_attempts import (
|
||||
inventory_rpa_attempts,
|
||||
)
|
||||
from app.services.freight_rpa.common.worker_heartbeat import RPA_WORKER_OFFLINE_MESSAGE
|
||||
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
|
||||
from app.services.shipping_notice.tool_common import (
|
||||
log_task_event,
|
||||
@@ -78,6 +102,23 @@ from app.services.shipping_notice.tool_common import (
|
||||
from app.services.shipping_notice.tool_response import tool_response
|
||||
from app.services.shipping_notice.task_disposition_service import task_execution_block_reason
|
||||
|
||||
# [协议态 re-export] Task 9 下沉 freight_rpa.onhand.workflow_protocol 的函数在本模块保留旧私有名
|
||||
# 别名:既有同包调用与测试(tests/test_shipping_process_recovery_plan 等直接 import 旧名)
|
||||
# 不换名;monkeypatch 接缝仍以本模块全局名为准。
|
||||
_extract_run_no_from_trigger = extract_run_no_from_trigger
|
||||
_is_legacy_trigger_run_no = is_legacy_trigger_run_no
|
||||
_expected_rpa_callback_run_no = expected_rpa_callback_run_no
|
||||
_validate_rpa_callback_run_no = validate_rpa_callback_run_no
|
||||
_resolve_effective_callback_run_no = resolve_effective_callback_run_no
|
||||
_get_consumed_inventory_rpa_run_no = get_consumed_inventory_rpa_run_no
|
||||
_mark_inventory_rpa_run_no_consumed = mark_inventory_rpa_run_no_consumed
|
||||
_validate_rpa_callback_not_replayed = validate_rpa_callback_not_replayed
|
||||
_validate_schedule_batch_callback_run_no = validate_schedule_batch_callback_run_no
|
||||
_resolve_shared_inventory_drop_file = resolve_shared_inventory_drop_file
|
||||
_normalize_rpa_inventory_result_status = normalize_inventory_result_status
|
||||
_normalize_rpa_inventory_batch_item_status = normalize_inventory_batch_item_status
|
||||
_merge_batch_callback_item = merge_batch_callback_item
|
||||
|
||||
|
||||
def _workflow_owner(task: ShippingNotice | ShippingOrderTask) -> ShippingNotice | ShippingOrderTask:
|
||||
"""将正式 Notice 输入解析为 OT owner;库存运行事实统一写入 OT。"""
|
||||
@@ -103,17 +144,6 @@ def _workflow_error(task: ShippingNotice | ShippingOrderTask) -> str | None:
|
||||
return getattr(_workflow_owner(task), 'error_message', None)
|
||||
|
||||
|
||||
def latest_task_event(task: ShippingNotice, 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 _inventory_rpa_attempt_label(*, attempt_no: int, max_attempts: int, manual_retry_round: bool) -> str:
|
||||
"""
|
||||
生成库存 RPA 尝试状态文案。
|
||||
@@ -276,10 +306,10 @@ def inventory_rpa_wait_seconds(task: ShippingNotice) -> tuple[int | None, int |
|
||||
last_trigger = latest_task_event(task, "inventory_rpa_triggered")
|
||||
if not last_trigger or not isinstance(last_trigger.created_at, datetime):
|
||||
return None, None, None
|
||||
# 超时窗口数学为协议态(workflow_protocol.compute_rpa_wait_window);
|
||||
# 业务门禁(blocking reason / ready 文件)与超时阈值配置(tool_common)留守本域。
|
||||
timeout_seconds = rpa_inventory_timeout_seconds()
|
||||
elapsed = max(int((datetime.utcnow() - last_trigger.created_at).total_seconds()), 0)
|
||||
remaining = max(timeout_seconds - elapsed, 0)
|
||||
return elapsed, timeout_seconds, remaining
|
||||
return compute_rpa_wait_window(last_trigger.created_at, timeout_seconds)
|
||||
|
||||
|
||||
def next_inventory_rpa_recheck_at(task: ShippingNotice) -> datetime | None:
|
||||
@@ -603,65 +633,6 @@ def _persist_post_commit_task_event(
|
||||
)
|
||||
|
||||
|
||||
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 可能不回传)。"""
|
||||
return str(run_no or "").strip().upper().startswith("LEGACY-")
|
||||
|
||||
|
||||
def _expected_rpa_callback_run_no(task: ShippingNotice) -> str:
|
||||
"""读取任务最近一次 RPA 触发记录的 run_no。"""
|
||||
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: ShippingNotice, callback_run_no: str) -> str | None:
|
||||
"""校验回调 run_no 属于当前任务最近一次有效触发轮次。"""
|
||||
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: ShippingNotice, 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 _lock_task_for_rpa_callback(task: ShippingOrderTask) -> ShippingOrderTask:
|
||||
"""对订单任务行加悲观锁,防止并发回调重复消费同一轮次。"""
|
||||
if task.id is None:
|
||||
@@ -674,45 +645,6 @@ def _lock_task_for_rpa_callback(task: ShippingOrderTask) -> ShippingOrderTask:
|
||||
)
|
||||
|
||||
|
||||
def _get_consumed_inventory_rpa_run_no(task: ShippingNotice) -> str:
|
||||
"""读取已消费(处理完成)的 RPA 轮次 run_no。"""
|
||||
from app.models import ShippingTaskInventoryRpaAttempt
|
||||
|
||||
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: ShippingNotice, run_no: str) -> None:
|
||||
"""标记当前 RPA 轮次已被回调消费,防止同一 run_no 重放重复入库。"""
|
||||
effective = str(run_no or "").strip()
|
||||
if not effective:
|
||||
return
|
||||
from app.models import ShippingTaskInventoryRpaAttempt
|
||||
|
||||
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: ShippingNotice, run_no: str) -> str | None:
|
||||
"""拒绝同一 run_no 的重复成功/失败/跳过回调。"""
|
||||
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_rpa_callback_round(task: ShippingNotice, payload: dict[str, Any]) -> dict[str, Any] | None:
|
||||
"""
|
||||
校验 RPA 回调轮次契约(run_no + 幂等)。
|
||||
@@ -918,7 +850,7 @@ def _validate_rpa_callback_success_identity(task: ShippingNotice, payload: dict[
|
||||
def _validate_single_source_v2_contract(task: ShippingNotice, payload: dict[str, Any]) -> dict[str, Any] | None:
|
||||
"""强制单源库存成功回调携带 v2 身份围栏,禁止旧 payload 写入库存事实。
|
||||
|
||||
单源 Worker 与批量 Worker 共用 ``shipping_inventory_rpa.v2``;缺少任一
|
||||
单源 Worker 与批量 Worker 共用 ``freight_rpa.onhand.v1``;缺少任一
|
||||
Attempt/Execution 身份时直接拒绝,避免回调按 Task 级旧 run_no 错绑轮次。
|
||||
"""
|
||||
if str(payload.get('status') or '').strip().lower() != 'success':
|
||||
@@ -935,7 +867,7 @@ def _validate_single_source_v2_contract(task: ShippingNotice, payload: dict[str,
|
||||
'gate_id': payload.get('gate_id'),
|
||||
}
|
||||
missing = [key for key, value in required.items() if value in (None, '')]
|
||||
if required['schema_version'] != 'shipping_inventory_rpa.v2' or missing:
|
||||
if required['schema_version'] != SCHEMA or missing:
|
||||
return tool_response(
|
||||
status='failed',
|
||||
task=task,
|
||||
@@ -949,47 +881,6 @@ def _validate_single_source_v2_contract(task: ShippingNotice, payload: dict[str,
|
||||
return None
|
||||
|
||||
|
||||
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 显式返回,禁止后端从任务或数据库补齐。
|
||||
"""
|
||||
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
|
||||
|
||||
|
||||
def _validate_schedule_batch_callback_run_no(schedule_run_id: int | None, callback_run_no: str) -> str | None:
|
||||
"""校验定时 batch 回调 run_no 与排程 run 记录一致,防止错绑终态。"""
|
||||
if schedule_run_id is None:
|
||||
return None
|
||||
from app.models import ScheduleRun
|
||||
|
||||
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 report_inventory_batch_progress(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
RPA 批量导出进度回调:实时回写排程 run 的成功/跳过/失败笔数(非终态)。
|
||||
@@ -998,13 +889,14 @@ def report_inventory_batch_progress(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
展示"执行中"run 的笔数;最终计数仍以 inventory-batch-ready 回调为准(终态化时重算覆盖)。
|
||||
|
||||
核心逻辑:校验 schema_version、schedule_run_id 与 run_no 匹配且 run 仍处于 awaiting_rpa;
|
||||
仅更新计数列与 response_summary_json.progress,不修改 status/started_at/finished_at,
|
||||
不影响超时回收与最终终态化。计数采用 max(现有, 上报) 防乱序回退。
|
||||
计数写入与提交下沉 freight_rpa.onhand.workflow_protocol.record_onhand_batch_progress
|
||||
(max(现有, 上报) 防乱序回退,commit 时机与拆分前一致:校验通过、计数写完后立即提交),
|
||||
本函数只保留业务响应 envelope(tool_response)。
|
||||
|
||||
Returns:
|
||||
tool_response: 进度已回写为 ok;无效/非等待态为 failed(不改变 run 状态)。
|
||||
"""
|
||||
if payload.get('schema_version') != 'shipping_inventory_rpa.v2':
|
||||
if payload.get('schema_version') != SCHEMA:
|
||||
return tool_response(status='failed', message='callback_schema_invalid', data={
|
||||
'progress_status': 'invalid', 'error_code': 'callback_schema_invalid',
|
||||
})
|
||||
@@ -1018,7 +910,7 @@ def report_inventory_batch_progress(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
return tool_response(status='failed', message='progress_schema_invalid', data={
|
||||
'progress_status': 'invalid', 'error_code': 'callback_schema_invalid',
|
||||
})
|
||||
schedule_run_error = _validate_schedule_batch_callback_run_no(schedule_run_id, run_no)
|
||||
schedule_run_error = validate_schedule_batch_callback_run_no(schedule_run_id, run_no)
|
||||
if schedule_run_error:
|
||||
return tool_response(status='failed', message=f'排程进度回调无效: {schedule_run_error}', data={
|
||||
'progress_status': 'rejected', 'schedule_run_error': schedule_run_error,
|
||||
@@ -1030,30 +922,16 @@ def report_inventory_batch_progress(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
return tool_response(status='failed', message='schedule_run_not_found', data={
|
||||
'progress_status': 'rejected', 'schedule_run_error': 'schedule_run_not_found',
|
||||
})
|
||||
incoming = {
|
||||
'success_count': max(0, int(payload.get('success_count') or 0)),
|
||||
'skipped_count': max(0, int(payload.get('skipped_count') or 0)),
|
||||
'failed_count': max(0, int(payload.get('failed_count') or 0)),
|
||||
}
|
||||
run.success_count = max(int(run.success_count or 0), incoming['success_count'])
|
||||
run.skipped_count = max(int(run.skipped_count or 0), incoming['skipped_count'])
|
||||
run.failed_count = max(int(run.failed_count or 0), incoming['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
|
||||
db.session.commit()
|
||||
counts = record_onhand_batch_progress(
|
||||
run,
|
||||
run_no,
|
||||
success_count=max(0, int(payload.get('success_count') or 0)),
|
||||
skipped_count=max(0, int(payload.get('skipped_count') or 0)),
|
||||
failed_count=max(0, int(payload.get('failed_count') or 0)),
|
||||
)
|
||||
return tool_response(status='ok', message='库存 RPA 导出进度已回写', data={
|
||||
'progress_status': 'updated',
|
||||
'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),
|
||||
**counts,
|
||||
})
|
||||
|
||||
|
||||
@@ -1295,7 +1173,7 @@ def ensure_inventory_via_rpa(
|
||||
if last_trigger and isinstance(last_trigger.created_at, datetime):
|
||||
elapsed = int((datetime.utcnow() - last_trigger.created_at).total_seconds())
|
||||
if elapsed < timeout_seconds:
|
||||
attempts = inventory_rpa_attempts(task)
|
||||
attempts = onhand_rpa_attempts(task)
|
||||
return tool_response(
|
||||
status="running",
|
||||
task_id=task.task_no,
|
||||
@@ -1338,7 +1216,7 @@ def ensure_inventory_via_rpa(
|
||||
|
||||
# [STEP 2] 仅本次用户或系统明确触发可创建一次 RPA 尝试。
|
||||
# 禁止消费全局 drop 目录未校验文件,必须等待 RPA 回调或复用正式快照。
|
||||
attempts = inventory_rpa_attempts(task)
|
||||
attempts = onhand_rpa_attempts(task)
|
||||
|
||||
# [STEP 3] 触发下一次 RPA 导出或给出人工兜底提示。
|
||||
# 触发成功则推进到 pending;触发失败则明确要求用户改走手工上传。
|
||||
@@ -1441,46 +1319,6 @@ def ensure_inventory_via_rpa(
|
||||
)
|
||||
|
||||
|
||||
def _normalize_rpa_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_rpa_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 _summarize_rpa_inventory_batch_outcome(
|
||||
*,
|
||||
created: list[Any],
|
||||
@@ -1865,7 +1703,7 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
if not path.is_file():
|
||||
return tool_response(status="failed", task_id=task.task_no, message="库存文件不存在")
|
||||
|
||||
processed = inventory_processed_dir()
|
||||
processed = onhand_processed_dir()
|
||||
rpa_source = task_rpa_inventory_source(task)
|
||||
if not rpa_source or not rpa_source.get("source_code"):
|
||||
return tool_response(
|
||||
@@ -2106,7 +1944,7 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
【AI 触发时机】:freight_rpa_worker 已完成库存文件导出、需要确认 HXOPS 已接收回调时调用。
|
||||
本函数只验证回调信封并持久化 Job;禁止在 HTTP 请求内解析 Excel、关联任务或推进 Gate。
|
||||
"""
|
||||
if payload.get('schema_version') != 'shipping_inventory_rpa.v2':
|
||||
if payload.get('schema_version') != SCHEMA:
|
||||
return tool_response(status='failed', message='callback_schema_invalid', data={
|
||||
'transport_status': 'invalid', 'business_status': 'rejected', 'error_code': 'callback_schema_invalid',
|
||||
})
|
||||
@@ -2179,43 +2017,6 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
)
|
||||
|
||||
|
||||
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`` 下按文件名映射,拒绝路径穿越。
|
||||
"""
|
||||
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 _persist_batch_callback_receipt(
|
||||
payload: dict[str, Any],
|
||||
*,
|
||||
@@ -2230,7 +2031,7 @@ def _persist_batch_callback_receipt(
|
||||
Returns:
|
||||
用受控副本路径替换成功项 ``file_path`` 后的 payload;无法安全收件时返回 None。
|
||||
"""
|
||||
allowed_root = inventory_drop_dir()
|
||||
allowed_root = onhand_drop_dir()
|
||||
if allowed_root is None:
|
||||
return None
|
||||
try:
|
||||
@@ -2296,7 +2097,7 @@ def _received_batch_callback_file_path(
|
||||
).strip('_') or 'unknown'
|
||||
receipt_root = (_storage_root() / 'rpa_callback_receipts' / safe_callback_id).resolve()
|
||||
|
||||
drop_dir = inventory_drop_dir()
|
||||
drop_dir = onhand_drop_dir()
|
||||
if drop_dir is not None:
|
||||
mapped = _resolve_shared_inventory_drop_file(file_path, allowed_root=drop_dir)
|
||||
if mapped is not None:
|
||||
@@ -2331,7 +2132,7 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any
|
||||
|
||||
cleanup_retry_warnings = flush_callback_cleanup_queue()
|
||||
|
||||
if payload.get('schema_version') != 'shipping_inventory_rpa.v2':
|
||||
if payload.get('schema_version') != SCHEMA:
|
||||
return tool_response(status='failed', message='callback_schema_invalid', data={
|
||||
'transport_status': 'invalid', 'business_status': 'rejected', 'error_code': 'callback_schema_invalid',
|
||||
})
|
||||
@@ -2790,7 +2591,7 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any
|
||||
f'per_source_callback_confirmation_failed:{final_code}'
|
||||
)
|
||||
|
||||
drop_dir = inventory_drop_dir()
|
||||
drop_dir = onhand_drop_dir()
|
||||
is_drop_file = False
|
||||
if drop_dir is not None:
|
||||
try:
|
||||
@@ -2875,7 +2676,7 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any
|
||||
|
||||
finalize_result: dict[str, Any] = {"ok": False, "schedule_finalize_status": "skipped"}
|
||||
if schedule_run_id is not None:
|
||||
from app.services.schedule.shipping_inventory_rpa_finalize import finalize_shipping_inventory_schedule_run
|
||||
from app.services.schedule.freight_onhand_rpa_finalize import finalize_shipping_inventory_schedule_run
|
||||
|
||||
finalize_result = finalize_shipping_inventory_schedule_run(
|
||||
schedule_run_id,
|
||||
@@ -2890,7 +2691,7 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any
|
||||
callback_move_warnings.extend(
|
||||
_flush_pending_callback_moves(
|
||||
pending_callback_moves,
|
||||
inventory_processed_dir(),
|
||||
onhand_processed_dir(),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
"""
|
||||
services/shipping_notice/onhand_trigger_batch.py
|
||||
|
||||
用途:onhand(在手库存)RPA 的批量/按需导出编排——组装逐源凭据与身份键、写批量 trigger、
|
||||
单票按需触发的 fail-closed 入口。
|
||||
依赖:Flask current_app 配置、freight_rpa.onhand.trigger_io(目录解析/原子写/SCHEMA/ACTION 常量)、
|
||||
shipping_notice.inventory_source_repository(按源补 Profile 密文,函数内延迟 import)。
|
||||
逻辑:由 schedule.freight_onhand_rpa_job(定时批量)、inventory_configuration_test(配置测试)、
|
||||
inventory_rpa_workflow / per_source_rpa_service(按需触发)调用,
|
||||
与 freight_rpa.onhand.trigger_io 的纯文件 IO 分层:本文件管业务编排,目录与 JSON 原子写下沉包内。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.freight_rpa.onhand.trigger_io import (
|
||||
ACTION_ONHAND_EXPORT_BATCH,
|
||||
SCHEMA,
|
||||
_write_trigger_json_atomic,
|
||||
onhand_trigger_dir,
|
||||
)
|
||||
|
||||
|
||||
def write_inventory_export_batch_trigger(
|
||||
run_no: str,
|
||||
sources: list[dict[str, Any]],
|
||||
*,
|
||||
payload: dict[str, Any] | None = None,
|
||||
) -> str | None:
|
||||
"""
|
||||
写入批量库存导出 trigger(DSV/Crane 一次登录多 Warehouse)。
|
||||
【AI 触发时机】:定时排程或后台批量预热库存快照时调用。
|
||||
|
||||
Args:
|
||||
run_no: RPA 批次号,写入回调 audit。
|
||||
sources: build_rpa_inventory_source 构造的源列表。
|
||||
payload: 额外字段(trigger_type、schedule_run_id 等)。
|
||||
|
||||
Returns:
|
||||
str | None: 触发文件绝对路径。
|
||||
"""
|
||||
trigger_dir = onhand_trigger_dir()
|
||||
if not trigger_dir or not sources:
|
||||
return None
|
||||
trigger_dir.mkdir(parents=True, exist_ok=True)
|
||||
inventory_sources = []
|
||||
for source in sources:
|
||||
if not isinstance(source, dict) or not source.get("source_code"):
|
||||
continue
|
||||
# 调用方只持有非敏感快照;写 trigger 前在服务端按 Source 补入 Profile 密文。
|
||||
from app.services.shipping_notice.inventory_source_repository import get_rpa_trigger_inventory_source
|
||||
configuration_test = str((payload or {}).get('trigger_type') or '') in {'configuration_test', 'configuration_test_batch'}
|
||||
trigger_source = get_rpa_trigger_inventory_source(
|
||||
str(source["source_code"]), enabled_only=not configuration_test,
|
||||
) or source
|
||||
source = {**source, **trigger_source}
|
||||
business_connector = str(source.get("connector_type") or "").strip().lower()
|
||||
worker_connector = {"dbs": "dsv360", "crane": "crane_footprint"}.get(business_connector, business_connector)
|
||||
item = {
|
||||
"source_code": source.get("source_code"),
|
||||
"connector_type": business_connector,
|
||||
"worker_connector_type": worker_connector,
|
||||
"rpa_profile_code": source.get("rpa_profile_code"),
|
||||
"warehouse_id": source.get("fixed_warehouse_id") or source.get("warehouse_id"),
|
||||
"login_url": source.get("login_url"),
|
||||
"entry_url": source.get("login_url"),
|
||||
"navigation": source.get("navigation") or {},
|
||||
"parameters": source.get("parameters") or [],
|
||||
"query": source.get("query") or {},
|
||||
"credential_envelope": source.get("credential_envelope") or {},
|
||||
# 配置测试回调据此将批次结果精确回写到各自站点运行。
|
||||
"validation_run_no": source.get("validation_run_no"),
|
||||
}
|
||||
# v2 逐源身份必须由后端显式写入,Worker 不得重新生成。
|
||||
for identity_key in (
|
||||
"callback_id", "task_no", "attempt_no", "source_run_no", "candidate_set_id", "candidate_set_version",
|
||||
"execution_id", "gate_id", "expected_warehouse_id", "lease_token",
|
||||
):
|
||||
if source.get(identity_key) is not None:
|
||||
item[identity_key] = source[identity_key]
|
||||
if not item.get('callback_id') and item.get('source_run_no'):
|
||||
item['callback_id'] = f"{item['source_run_no']}:C1"
|
||||
inventory_sources.append(item)
|
||||
if not inventory_sources:
|
||||
return None
|
||||
|
||||
body = {
|
||||
"action": ACTION_ONHAND_EXPORT_BATCH,
|
||||
"schema_version": SCHEMA,
|
||||
"callback_id": f"{run_no}:batch:C1",
|
||||
"batch_run_no": run_no,
|
||||
"run_no": run_no, # 旧排程读取兼容;新回调不得依赖该字段
|
||||
"trigger_type": "scheduled",
|
||||
"requested_at": datetime.utcnow().isoformat(),
|
||||
"inventory_sources": inventory_sources,
|
||||
**(payload or {}),
|
||||
}
|
||||
safe_run = "".join(ch for ch in run_no if ch.isalnum() or ch in {"-", "_"}) or "batch"
|
||||
path = trigger_dir / f"inventory_export_batch_{safe_run}.json"
|
||||
_write_trigger_json_atomic(path, body)
|
||||
return str(path)
|
||||
|
||||
|
||||
def inventory_rpa_batch_enabled() -> bool:
|
||||
"""是否启用按需单票走 batch trigger 统一路径(Flask config 优先于环境变量)。"""
|
||||
raw = current_app.config.get("SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED")
|
||||
if raw is None:
|
||||
raw = os.getenv("SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED", "true")
|
||||
return str(raw).strip().lower() in {"1", "true", "yes", "on"}
|
||||
|
||||
|
||||
def build_on_demand_inventory_trigger_source(
|
||||
task_no: str,
|
||||
rpa_source: dict[str, Any],
|
||||
*,
|
||||
body: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
构造按需库存导出批次触发内的单源条目(含 Profile 凭据与逐源身份键)。
|
||||
【AI 触发时机】:单源 on-demand 触发与多候选合并批次触发(per_source_rpa_service)共用本构造,
|
||||
保证两条路径投递给 Worker 的输入契约完全一致。
|
||||
|
||||
Args:
|
||||
task_no: 发货任务号。
|
||||
rpa_source: 调用方持有的非敏感源快照(含 source_code);DB 配置/Profile 存在时以其为准。
|
||||
body: 触发载荷,提供 callback_id/source_run_no/attempt_no/lease_token 等逐源身份键。
|
||||
|
||||
Returns:
|
||||
可直接传入 write_inventory_export_batch_trigger 的单源条目。
|
||||
"""
|
||||
from app.services.shipping_notice.inventory_source_repository import get_rpa_trigger_inventory_source
|
||||
|
||||
source_code = str(rpa_source.get('source_code') or '').strip()
|
||||
rpa_source = get_rpa_trigger_inventory_source(source_code) or rpa_source
|
||||
# Legacy 单票 trigger 与 batch trigger 必须共享 worker 输入契约。
|
||||
rpa_source = dict(rpa_source)
|
||||
business_connector = str(rpa_source.get('connector_type') or '').strip().lower()
|
||||
rpa_source.setdefault('worker_connector_type', {'dbs': 'dsv360', 'crane': 'crane_footprint'}.get(business_connector, business_connector))
|
||||
rpa_source.setdefault('entry_url', rpa_source.get('login_url'))
|
||||
rpa_source.setdefault('credential_envelope', {})
|
||||
source_item = dict(rpa_source)
|
||||
source_item.update({
|
||||
"source_code": source_code,
|
||||
"callback_id": body.get("callback_id") or (
|
||||
f"{body.get('source_run_no')}:C1" if body.get('source_run_no') else None
|
||||
),
|
||||
"task_no": task_no,
|
||||
# 按需逐源回调必须携带 Attempt 身份;仅写在 batch 顶层会导致
|
||||
# Worker 结果丢失 source_run_no,后端无法把 Excel 绑定到最新 Attempt。
|
||||
"attempt_no": body.get("attempt_no") or body.get("attempt"),
|
||||
"source_run_no": body.get("source_run_no"),
|
||||
"candidate_set_id": body.get("candidate_set_id"),
|
||||
"candidate_set_version": body.get("candidate_set_version"),
|
||||
"execution_id": body.get("execution_id"),
|
||||
"gate_id": body.get("gate_id"),
|
||||
"expected_warehouse_id": body.get("expected_warehouse_id"),
|
||||
"lease_token": body.get("lease_token"),
|
||||
})
|
||||
return source_item
|
||||
|
||||
|
||||
def write_inventory_export_trigger_for_task(
|
||||
task_no: str,
|
||||
rpa_source: dict[str, Any],
|
||||
*,
|
||||
payload: dict[str, Any] | None = None,
|
||||
) -> str | None:
|
||||
"""
|
||||
写入按需库存 RPA trigger;batch 开启时包装为单源 batch trigger,与定时导出共用 worker 路径。
|
||||
【AI 触发时机】:ensure_inventory_via_rpa 触发单票 RPA 导出时调用。
|
||||
|
||||
核心逻辑:仅允许 v2 batch 模式写 inventory_export_batch;关闭时 fail-closed,
|
||||
不再生成 legacy inventory_export trigger。
|
||||
"""
|
||||
body = dict(payload or {})
|
||||
if inventory_rpa_batch_enabled():
|
||||
run_no = str(body.get("batch_run_no") or f"BATCH-{task_no}-{datetime.utcnow().strftime('%Y%m%d%H%M%S%f')}")
|
||||
source_item = build_on_demand_inventory_trigger_source(task_no, rpa_source, body=body)
|
||||
return write_inventory_export_batch_trigger(
|
||||
run_no,
|
||||
[source_item],
|
||||
payload={
|
||||
"schema_version": SCHEMA,
|
||||
"trigger_type": "on_demand",
|
||||
"task_no": task_no,
|
||||
**body,
|
||||
},
|
||||
)
|
||||
raise ValidationError(
|
||||
'shipping inventory RPA v2 batch trigger is required',
|
||||
code='SHIPPING.INVENTORY_RPA_V2_REQUIRED',
|
||||
)
|
||||
@@ -38,10 +38,11 @@ from app.services.shipping_notice.inventory_snapshot_store import (
|
||||
find_latest_ready_snapshot,
|
||||
is_snapshot_fresh,
|
||||
)
|
||||
from app.services.shipping_notice.rpa import (
|
||||
from app.services.shipping_notice.onhand_trigger_batch import (
|
||||
build_on_demand_inventory_trigger_source,
|
||||
write_inventory_export_batch_trigger,
|
||||
)
|
||||
from app.services.freight_rpa.onhand.trigger_io import SCHEMA
|
||||
|
||||
|
||||
def _archive_unclaimed_trigger(attempt: ShippingTaskInventoryRpaAttempt) -> str | None:
|
||||
@@ -99,7 +100,7 @@ def _validate_callback_attempt_identity(
|
||||
"""校验回调身份与已冻结 Attempt/当前 CandidateSet/正式 Execution 一致。"""
|
||||
required = ('schema_version', 'callback_id', 'source_run_no', 'attempt_no', 'lease_token',
|
||||
'candidate_set_id', 'execution_id', 'gate_id')
|
||||
if str(callback_payload.get('schema_version') or '') != 'shipping_inventory_rpa.v2':
|
||||
if str(callback_payload.get('schema_version') or '') != SCHEMA:
|
||||
return False
|
||||
if any(callback_payload.get(key) in (None, '') for key in required):
|
||||
return False
|
||||
@@ -521,7 +522,7 @@ def ensure_all_required_sources_prepared(
|
||||
batch_run_no,
|
||||
pending_payloads,
|
||||
payload={
|
||||
'schema_version': 'shipping_inventory_rpa.v2',
|
||||
'schema_version': SCHEMA,
|
||||
'trigger_type': 'on_demand',
|
||||
'task_no': task_no,
|
||||
'mode': mode,
|
||||
@@ -771,7 +772,7 @@ def per_source_callback_handler(
|
||||
|
||||
def claim_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""记录 Worker 领取的逐源 Attempt,不推进 Snapshot、Link 或 Gate。"""
|
||||
if payload.get('schema_version') != 'shipping_inventory_rpa.v2' or not isinstance(payload.get('items'), list):
|
||||
if payload.get('schema_version') != SCHEMA or not isinstance(payload.get('items'), list):
|
||||
return {'transport_status': 'invalid', 'business_status': 'rejected', 'error_code': 'callback_schema_invalid'}
|
||||
worker_id = str(payload.get('worker_id') or '').strip() or None
|
||||
now = datetime.utcnow()
|
||||
|
||||
@@ -520,7 +520,7 @@ def _task_tool_payload(task: ShippingNotice) -> dict[str, Any]:
|
||||
'inventory_snapshot': _serialize_inventory_snapshot(task),
|
||||
}
|
||||
from app.services.shipping_notice.notice_upload import max_notice_chars
|
||||
from app.services.shipping_notice.rpa import rpa_runtime_mode
|
||||
from app.services.freight_rpa.common.rpa_runtime import rpa_runtime_mode
|
||||
|
||||
workflow_owner = (
|
||||
db.session.get(ShippingOrderTask, int(task.order_task_id))
|
||||
@@ -787,7 +787,7 @@ def _serialize_source_candidate_projection(task: ShippingNotice) -> dict[str, An
|
||||
|
||||
def serialize_task(task: ShippingNotice, projection: TaskProjection) -> dict[str, Any]:
|
||||
"""按投影类型序列化任务;TOOL 会剔除 Agent 不应复述的内部状态码。"""
|
||||
from app.services.shipping_notice.rpa import rpa_runtime_mode
|
||||
from app.services.freight_rpa.common.rpa_runtime import rpa_runtime_mode
|
||||
|
||||
workflow_owner = (
|
||||
db.session.get(ShippingOrderTask, int(task.order_task_id))
|
||||
|
||||
@@ -147,7 +147,7 @@ def recover_stale_shipping_notice_jobs() -> tuple[int, str]:
|
||||
from app.services.shipping_notice.intake_parse_workflow import (
|
||||
sync_intake_after_parse_job_recovery,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_rpa_callback_cleanup import (
|
||||
from app.services.freight_rpa.onhand.callback_cleanup import (
|
||||
recover_pending_rpa_callback_cleanup_jobs,
|
||||
)
|
||||
|
||||
|
||||
@@ -1,93 +0,0 @@
|
||||
"""收料报表企微通知的管理员重发通道。
|
||||
|
||||
用途:收料排程的正常通知已统一并入排程通用出口——run 终态后一次性发送
|
||||
textcard 汇总 + 原始收料 ZIP(scheduler_service._notify_schedule_run_wecom,
|
||||
与库存 RPA 同门禁同出口);本模块只保留管理员对单个已归档收料文件的
|
||||
强制重发能力(POST /receipt-report-files/<id>/resend),不触发 RPA。
|
||||
依赖:models、file_asset_storage、audit_service、integrations.wecom.notify。
|
||||
逻辑:deliver_receipt_file 幂等投递单文件并落 ShippingReceiptNotificationDelivery
|
||||
与 shipping 审计;force=True 供管理员补偿重发,绕过成功幂等但仍受通知开关约束。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingReceiptNotificationDelivery, ShippingReceiptReportFile, User
|
||||
from app.services.file_assets.storage import file_asset_storage
|
||||
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
|
||||
|
||||
|
||||
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_receipt_file(file_id: int, *, force: bool = False) -> dict:
|
||||
"""向排程接收人逐一投递原样收料文件;同文件用户的成功投递可幂等重放。"""
|
||||
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}
|
||||
@@ -1,58 +1,26 @@
|
||||
"""收料 RPA callback 的原样归档服务。
|
||||
"""收料 RPA callback 的域内业务桥与终态收尾(shipping_notice 留守侧)。
|
||||
|
||||
用途:接收收料 RPA 单元回调,原样归档文件三年且不写库存快照表;终态落库后
|
||||
通过收料回调桥推进在途调拨的 waiting_rpa_callback 来源任务(B3 接线);
|
||||
每笔终态回调回写 ScheduleRun 进度计数(对齐库存 inventory-batch-progress)。
|
||||
依赖:models(ShippingReceiptReportFile/ShippingReceiptRpaUnitRun)、file_asset_storage、
|
||||
audit_service、freight_receipt_rpa_finalize、in_transit_transfer.inbound_callback_bridge(惰性导入)、
|
||||
in_transit_transfer.evidence_sync(惰性导入,仅 success 终态)。
|
||||
逻辑:success/empty/failed 三个终态分支各自 commit 后调用 _advance_transfer_source_job;
|
||||
empty 落库 error_code=no_receipt_data(对齐库存 no_inventory_data);
|
||||
有 schedule_run_id 时 refresh 进度再 finalize;success 分支再触发调拨证据同步;
|
||||
两座桥都是记账不是收料链路的正确性依赖,桥内异常只记日志绝不回滚归档终态。
|
||||
用途:批次 R Task 10 拆分后,本模块只留守「业务桥」——收料终态落库后推进在途调拨的
|
||||
waiting_rpa_callback 来源任务(B3 接线)、success 终态的调拨证据同步,以及排程
|
||||
终态归集(finalize)调用;原样归档/三年保留/resend/通知投递等 RPA 产物事实能力
|
||||
已下沉 freight_rpa.inbound.report_archive(函数名 receipt 词根→inbound)。
|
||||
依赖:freight_rpa.inbound.report_archive(归档能力,经 ingest_receipt_callback 委托)、
|
||||
in_transit_transfer.inbound_callback_bridge / evidence_sync(惰性导入,仅桥),
|
||||
schedule.freight_inbound_rpa_finalize(惰性导入,仅 finalize)。
|
||||
逻辑:ingest_receipt_callback 仍是本域回调入口(rpa_sinks 以 {'success':True,'data':...}
|
||||
envelope 注册为 inbound-batch-ready sink):委托 report_archive.ingest_inbound_callback
|
||||
归档(各终态分支各自 commit),并以 _finish_inbound_callback_terminal 作为
|
||||
on_terminal 钩子——commit 之后按拆分前同一顺序执行「推桥 →(success)证据同步 →
|
||||
finalize」;两座桥都是记账不是收料链路的正确性依赖,桥内异常只记日志绝不回滚归档终态。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import ShippingReceiptReportFile, ShippingReceiptRpaUnitRun
|
||||
from app.services.file_assets.storage import file_asset_storage
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
|
||||
|
||||
def _read_receipt_callback_file(file_path: str) -> bytes:
|
||||
"""只读取收料专用 drop 根内的 xlsx,拒绝 callback 任意本机文件读取。
|
||||
|
||||
路径契约为「drop 根内文件名」:Worker(Windows RPA 主机)与后端(Linux 容器)分属
|
||||
两机,各自看到的根路径不同(C:\\HxopsRpaTest\\... vs /mnt/hxops-rpa-*-data/...),
|
||||
Worker 只上报文件名,后端用自身挂载的 drop 根拼接定位;携带本机绝对路径的历史
|
||||
载荷亦按末段文件名解析(2026-10-08 修复跨机成功回调全程 400 的事故)。
|
||||
"""
|
||||
configured_root = str(current_app.config.get('FREIGHT_RPA_SHARED_RECEIPT_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()
|
||||
from app.models import ShippingReceiptRpaUnitRun
|
||||
|
||||
|
||||
def _advance_transfer_source_job(
|
||||
@@ -84,107 +52,53 @@ def _advance_transfer_source_job(
|
||||
current_app.logger.warning('[receipt-callback] advance transfer source job failed: %s', exc)
|
||||
|
||||
|
||||
def ingest_receipt_callback(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""幂等接收单个收料单元回调,原样归档三年且不写库存快照表。"""
|
||||
if payload.get('schema_version') != 'shipping_receipt_rpa.v1':
|
||||
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()
|
||||
_advance_transfer_source_job(
|
||||
unit, ok=False, error_code=unit.error_code or 'no_receipt_data',
|
||||
error_message=unit.error_message or 'no_receipt_data',
|
||||
)
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import (
|
||||
finalize_receipt_schedule_run_if_complete,
|
||||
refresh_receipt_schedule_run_progress,
|
||||
)
|
||||
# 按需触发单元无排程 run(schedule_run_id 为 NULL),跳过排程终态归集。
|
||||
if unit.schedule_run_id:
|
||||
refresh_receipt_schedule_run_progress(unit.schedule_run_id)
|
||||
finalize_receipt_schedule_run_if_complete(unit.schedule_run_id)
|
||||
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()
|
||||
_advance_transfer_source_job(unit, ok=False, error_code=unit.error_code, error_message=unit.error_message)
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import (
|
||||
finalize_receipt_schedule_run_if_complete,
|
||||
refresh_receipt_schedule_run_progress,
|
||||
)
|
||||
# 按需触发单元无排程 run(schedule_run_id 为 NULL),跳过排程终态归集。
|
||||
if unit.schedule_run_id:
|
||||
refresh_receipt_schedule_run_progress(unit.schedule_run_id)
|
||||
finalize_receipt_schedule_run_if_complete(unit.schedule_run_id)
|
||||
return {'unit_run_id': unit.id, 'status': 'failed'}
|
||||
data = _read_receipt_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()
|
||||
_advance_transfer_source_job(unit, ok=True, file_no=str(record.id), file_sha256=sha256)
|
||||
# [调拨证据同步·主链路] success 终态文件落地即解析写调拨待办(本分支专属;
|
||||
# empty/failed 分支不触发同步)。桥模式失败仅日志,绝不影响收料归档主链路
|
||||
# (语义见 in_transit_transfer/evidence_sync.sync_and_commit_for_callback)。
|
||||
try:
|
||||
from datetime import datetime as _dt
|
||||
def _finish_inbound_callback_terminal(
|
||||
unit: 'ShippingReceiptRpaUnitRun', *, ok: bool,
|
||||
file_no: str | None = None, file_sha256: str | None = None,
|
||||
error_code: str | None = None, error_message: str | None = None,
|
||||
) -> None:
|
||||
"""终态归档 commit 之后的业务收尾(on_terminal 钩子实现),顺序与拆分前逐点一致。
|
||||
|
||||
from app.services.in_transit_transfer.evidence_sync import sync_and_commit_for_callback
|
||||
核心逻辑:[STEP 1] 推进在途调拨来源任务(_advance_transfer_source_job,原 B3 接线);
|
||||
[STEP 2] 仅 success 终态触发调拨证据同步(桥模式失败仅日志,绝不影响收料归档主链路,
|
||||
语义见 in_transit_transfer/evidence_sync.sync_and_commit_for_callback);[STEP 3] 有排程
|
||||
run 时回写进度并归集终态(按需触发单元 schedule_run_id 为 NULL,跳过排程终态归集;
|
||||
文件通知不在此逐文件发送:统一由排程终态归集后一次性推送,与库存 RPA 同构)。
|
||||
"""
|
||||
_advance_transfer_source_job(
|
||||
unit, ok=ok, file_no=file_no, file_sha256=file_sha256,
|
||||
error_code=error_code, error_message=error_message,
|
||||
)
|
||||
if ok:
|
||||
# [调拨证据同步·主链路] success 终态文件落地即解析写调拨待办(本分支专属;
|
||||
# empty/failed 分支不触发同步)。
|
||||
try:
|
||||
from datetime import datetime as _dt
|
||||
|
||||
sync_and_commit_for_callback(
|
||||
source_code=unit.source_code, business_date=str(_dt.utcnow().date()), now=_dt.utcnow(),
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001 —— 双保险:桥内部已吞异常
|
||||
current_app.logger.warning('[receipt-callback] transfer evidence sync failed: %s', exc)
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import (
|
||||
from app.services.in_transit_transfer.evidence_sync import sync_and_commit_for_callback
|
||||
|
||||
sync_and_commit_for_callback(
|
||||
source_code=unit.source_code, business_date=str(_dt.utcnow().date()), now=_dt.utcnow(),
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001 —— 双保险:桥内部已吞异常
|
||||
current_app.logger.warning('[receipt-callback] transfer evidence sync failed: %s', exc)
|
||||
from app.services.schedule.freight_inbound_rpa_finalize import (
|
||||
finalize_receipt_schedule_run_if_complete,
|
||||
refresh_receipt_schedule_run_progress,
|
||||
)
|
||||
# 按需触发单元无排程 run(schedule_run_id 为 NULL),跳过排程终态归集。
|
||||
# 文件通知不在此处逐文件发送:统一由排程终态归集后一次性推送(与库存 RPA 同构)。
|
||||
if unit.schedule_run_id:
|
||||
refresh_receipt_schedule_run_progress(unit.schedule_run_id)
|
||||
finalize_receipt_schedule_run_if_complete(unit.schedule_run_id)
|
||||
return {'unit_run_id': unit.id, 'status': 'success', 'file_id': record.id, 'idempotent': False}
|
||||
|
||||
|
||||
def ingest_receipt_callback(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""幂等接收单个收料单元回调:委托 report_archive 原样归档,终态后执行业务桥收尾。
|
||||
|
||||
Args:
|
||||
payload: Worker 回调载荷;schema_version 必须等于 freight_rpa.inbound.v1。
|
||||
Returns:
|
||||
dict: unit_run_id/status[/file_id/idempotent],与拆分前逐键一致(API envelope 契约)。
|
||||
"""
|
||||
from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback
|
||||
|
||||
return ingest_inbound_callback(payload, on_terminal=_finish_inbound_callback_terminal)
|
||||
@@ -1,56 +0,0 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/receipt_rpa.py
|
||||
|
||||
用途:独立收料 RPA trigger 的目录解析与批量载荷原子写入。
|
||||
依赖:Flask current_app 配置 FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR。
|
||||
逻辑:freight_receipt_rpa_job / receipt_trigger_service 调用写 trigger;
|
||||
Worker 仅消费 shipping_receipt_rpa.v1,绝不回落到库存 trigger 目录。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import tempfile
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
|
||||
|
||||
def receipt_trigger_dir() -> Path | None:
|
||||
"""返回收料专用 trigger 目录;绝不回落到库存 trigger 目录。"""
|
||||
value = str(current_app.config.get('FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR') or '').strip()
|
||||
return Path(value) if value else None
|
||||
|
||||
|
||||
def write_receipt_export_batch_trigger(run_no: str, units: list[dict[str, Any]], payload: dict[str, Any] | None = None) -> str | None:
|
||||
"""写入收料批量 trigger;worker 仅允许消费 shipping_receipt_rpa.v1。"""
|
||||
trigger_dir = receipt_trigger_dir()
|
||||
if trigger_dir is None 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 'receipt'
|
||||
body = {
|
||||
'schema_version': 'shipping_receipt_rpa.v1', 'action': 'receipt_export_batch',
|
||||
'batch_run_no': run_no, 'requested_at': datetime.utcnow().isoformat(), 'units': units,
|
||||
**(payload or {}),
|
||||
}
|
||||
path = trigger_dir / f'receipt_export_batch_{safe_run_no}.json'
|
||||
# Worker 轮询 *.json;必须先写入同目录临时文件后原子替换,不能让 Worker
|
||||
# 领取到半截 JSON 并误入 failed/,这不会影响库存 trigger 的既有实现。
|
||||
fd, temp_name = tempfile.mkstemp(prefix=f'.{path.stem}.', suffix='.tmp', dir=str(trigger_dir))
|
||||
try:
|
||||
with os.fdopen(fd, 'w', encoding='utf-8') as handle:
|
||||
handle.write(json.dumps(body, ensure_ascii=False, indent=2))
|
||||
handle.flush()
|
||||
os.fsync(handle.fileno())
|
||||
os.replace(temp_name, path)
|
||||
except Exception:
|
||||
try:
|
||||
Path(temp_name).unlink(missing_ok=True)
|
||||
except OSError:
|
||||
pass
|
||||
raise
|
||||
return str(path)
|
||||
@@ -1,380 +0,0 @@
|
||||
"""
|
||||
services/shipping_notice/rpa.py
|
||||
|
||||
用途:管理库存导出与货代上传相关的 RPA 目录、触发文件和落盘辅助逻辑。
|
||||
依赖:Flask current_app 配置、Path/JSON/文件系统工具。
|
||||
逻辑:由 inventory_rpa_workflow、fulfillment_workflow 等上游模块调用本文件,与外部 RPA 文件投递目录进行交互。
|
||||
"""
|
||||
|
||||
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
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
|
||||
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")
|
||||
|
||||
|
||||
def _path(key: str) -> Path | None:
|
||||
value = str(current_app.config.get(key) or "").strip()
|
||||
if not value:
|
||||
return None
|
||||
return Path(value)
|
||||
|
||||
|
||||
def inventory_drop_dir() -> Path | None:
|
||||
"""RPA 库存 Excel 落盘目录(FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR)。"""
|
||||
return _path("FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR")
|
||||
|
||||
|
||||
def inventory_processed_dir() -> Path | None:
|
||||
"""已处理库存文件归档子目录(drop_dir/processed)。"""
|
||||
base = inventory_drop_dir()
|
||||
if not base:
|
||||
return None
|
||||
return base / "processed"
|
||||
|
||||
|
||||
def inventory_trigger_dir() -> Path | None:
|
||||
"""RPA 库存导出触发 JSON 目录。"""
|
||||
return _path("FREIGHT_RPA_SHARED_INVENTORY_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 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_inventory_export_trigger(task_no: str, payload: dict[str, Any] | None = None) -> str | None:
|
||||
"""
|
||||
写入 RPA 库存导出触发文件 inventory_export_{task_no}.json。
|
||||
|
||||
Returns:
|
||||
str | None: 触发文件绝对路径;目录未配置时返回 None。
|
||||
"""
|
||||
trigger_dir = inventory_trigger_dir()
|
||||
if not trigger_dir:
|
||||
return None
|
||||
trigger_dir.mkdir(parents=True, exist_ok=True)
|
||||
body = {
|
||||
"action": "inventory_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)
|
||||
|
||||
|
||||
def write_inventory_export_batch_trigger(
|
||||
run_no: str,
|
||||
sources: list[dict[str, Any]],
|
||||
*,
|
||||
payload: dict[str, Any] | None = None,
|
||||
) -> str | None:
|
||||
"""
|
||||
写入批量库存导出 trigger(DSV/Crane 一次登录多 Warehouse)。
|
||||
【AI 触发时机】:定时排程或后台批量预热库存快照时调用。
|
||||
|
||||
Args:
|
||||
run_no: RPA 批次号,写入回调 audit。
|
||||
sources: build_rpa_inventory_source 构造的源列表。
|
||||
payload: 额外字段(trigger_type、schedule_run_id 等)。
|
||||
|
||||
Returns:
|
||||
str | None: 触发文件绝对路径。
|
||||
"""
|
||||
trigger_dir = inventory_trigger_dir()
|
||||
if not trigger_dir or not sources:
|
||||
return None
|
||||
trigger_dir.mkdir(parents=True, exist_ok=True)
|
||||
inventory_sources = []
|
||||
for source in sources:
|
||||
if not isinstance(source, dict) or not source.get("source_code"):
|
||||
continue
|
||||
# 调用方只持有非敏感快照;写 trigger 前在服务端按 Source 补入 Profile 密文。
|
||||
from app.services.shipping_notice.inventory_source_repository import get_rpa_trigger_inventory_source
|
||||
configuration_test = str((payload or {}).get('trigger_type') or '') in {'configuration_test', 'configuration_test_batch'}
|
||||
trigger_source = get_rpa_trigger_inventory_source(
|
||||
str(source["source_code"]), enabled_only=not configuration_test,
|
||||
) or source
|
||||
source = {**source, **trigger_source}
|
||||
business_connector = str(source.get("connector_type") or "").strip().lower()
|
||||
worker_connector = {"dbs": "dsv360", "crane": "crane_footprint"}.get(business_connector, business_connector)
|
||||
item = {
|
||||
"source_code": source.get("source_code"),
|
||||
"connector_type": business_connector,
|
||||
"worker_connector_type": worker_connector,
|
||||
"rpa_profile_code": source.get("rpa_profile_code"),
|
||||
"warehouse_id": source.get("fixed_warehouse_id") or source.get("warehouse_id"),
|
||||
"login_url": source.get("login_url"),
|
||||
"entry_url": source.get("login_url"),
|
||||
"navigation": source.get("navigation") or {},
|
||||
"parameters": source.get("parameters") or [],
|
||||
"query": source.get("query") or {},
|
||||
"credential_envelope": source.get("credential_envelope") or {},
|
||||
# 配置测试回调据此将批次结果精确回写到各自站点运行。
|
||||
"validation_run_no": source.get("validation_run_no"),
|
||||
}
|
||||
# v2 逐源身份必须由后端显式写入,Worker 不得重新生成。
|
||||
for identity_key in (
|
||||
"callback_id", "task_no", "attempt_no", "source_run_no", "candidate_set_id", "candidate_set_version",
|
||||
"execution_id", "gate_id", "expected_warehouse_id", "lease_token",
|
||||
):
|
||||
if source.get(identity_key) is not None:
|
||||
item[identity_key] = source[identity_key]
|
||||
if not item.get('callback_id') and item.get('source_run_no'):
|
||||
item['callback_id'] = f"{item['source_run_no']}:C1"
|
||||
inventory_sources.append(item)
|
||||
if not inventory_sources:
|
||||
return None
|
||||
|
||||
body = {
|
||||
"action": "inventory_export_batch",
|
||||
"schema_version": "shipping_inventory_rpa.v2",
|
||||
"callback_id": f"{run_no}:batch:C1",
|
||||
"batch_run_no": run_no,
|
||||
"run_no": run_no, # 旧排程读取兼容;新回调不得依赖该字段
|
||||
"trigger_type": "scheduled",
|
||||
"requested_at": datetime.utcnow().isoformat(),
|
||||
"inventory_sources": inventory_sources,
|
||||
**(payload or {}),
|
||||
}
|
||||
safe_run = "".join(ch for ch in run_no if ch.isalnum() or ch in {"-", "_"}) or "batch"
|
||||
path = trigger_dir / f"inventory_export_batch_{safe_run}.json"
|
||||
_write_trigger_json_atomic(path, body)
|
||||
return str(path)
|
||||
|
||||
|
||||
def inventory_rpa_batch_enabled() -> bool:
|
||||
"""是否启用按需单票走 batch trigger 统一路径(Flask config 优先于环境变量)。"""
|
||||
raw = current_app.config.get("SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED")
|
||||
if raw is None:
|
||||
raw = os.getenv("SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED", "true")
|
||||
return str(raw).strip().lower() in {"1", "true", "yes", "on"}
|
||||
|
||||
|
||||
def build_on_demand_inventory_trigger_source(
|
||||
task_no: str,
|
||||
rpa_source: dict[str, Any],
|
||||
*,
|
||||
body: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
构造按需库存导出批次触发内的单源条目(含 Profile 凭据与逐源身份键)。
|
||||
【AI 触发时机】:单源 on-demand 触发与多候选合并批次触发(per_source_rpa_service)共用本构造,
|
||||
保证两条路径投递给 Worker 的输入契约完全一致。
|
||||
|
||||
Args:
|
||||
task_no: 发货任务号。
|
||||
rpa_source: 调用方持有的非敏感源快照(含 source_code);DB 配置/Profile 存在时以其为准。
|
||||
body: 触发载荷,提供 callback_id/source_run_no/attempt_no/lease_token 等逐源身份键。
|
||||
|
||||
Returns:
|
||||
可直接传入 write_inventory_export_batch_trigger 的单源条目。
|
||||
"""
|
||||
from app.services.shipping_notice.inventory_source_repository import get_rpa_trigger_inventory_source
|
||||
|
||||
source_code = str(rpa_source.get('source_code') or '').strip()
|
||||
rpa_source = get_rpa_trigger_inventory_source(source_code) or rpa_source
|
||||
# Legacy 单票 trigger 与 batch trigger 必须共享 worker 输入契约。
|
||||
rpa_source = dict(rpa_source)
|
||||
business_connector = str(rpa_source.get('connector_type') or '').strip().lower()
|
||||
rpa_source.setdefault('worker_connector_type', {'dbs': 'dsv360', 'crane': 'crane_footprint'}.get(business_connector, business_connector))
|
||||
rpa_source.setdefault('entry_url', rpa_source.get('login_url'))
|
||||
rpa_source.setdefault('credential_envelope', {})
|
||||
source_item = dict(rpa_source)
|
||||
source_item.update({
|
||||
"source_code": source_code,
|
||||
"callback_id": body.get("callback_id") or (
|
||||
f"{body.get('source_run_no')}:C1" if body.get('source_run_no') else None
|
||||
),
|
||||
"task_no": task_no,
|
||||
# 按需逐源回调必须携带 Attempt 身份;仅写在 batch 顶层会导致
|
||||
# Worker 结果丢失 source_run_no,后端无法把 Excel 绑定到最新 Attempt。
|
||||
"attempt_no": body.get("attempt_no") or body.get("attempt"),
|
||||
"source_run_no": body.get("source_run_no"),
|
||||
"candidate_set_id": body.get("candidate_set_id"),
|
||||
"candidate_set_version": body.get("candidate_set_version"),
|
||||
"execution_id": body.get("execution_id"),
|
||||
"gate_id": body.get("gate_id"),
|
||||
"expected_warehouse_id": body.get("expected_warehouse_id"),
|
||||
"lease_token": body.get("lease_token"),
|
||||
})
|
||||
return source_item
|
||||
|
||||
|
||||
def write_inventory_export_trigger_for_task(
|
||||
task_no: str,
|
||||
rpa_source: dict[str, Any],
|
||||
*,
|
||||
payload: dict[str, Any] | None = None,
|
||||
) -> str | None:
|
||||
"""
|
||||
写入按需库存 RPA trigger;batch 开启时包装为单源 batch trigger,与定时导出共用 worker 路径。
|
||||
【AI 触发时机】:ensure_inventory_via_rpa 触发单票 RPA 导出时调用。
|
||||
|
||||
核心逻辑:仅允许 v2 batch 模式写 inventory_export_batch;关闭时 fail-closed,
|
||||
不再生成 legacy inventory_export trigger。
|
||||
"""
|
||||
body = dict(payload or {})
|
||||
if inventory_rpa_batch_enabled():
|
||||
run_no = str(body.get("batch_run_no") or f"BATCH-{task_no}-{datetime.utcnow().strftime('%Y%m%d%H%M%S%f')}")
|
||||
source_item = build_on_demand_inventory_trigger_source(task_no, rpa_source, body=body)
|
||||
return write_inventory_export_batch_trigger(
|
||||
run_no,
|
||||
[source_item],
|
||||
payload={
|
||||
"schema_version": "shipping_inventory_rpa.v2",
|
||||
"trigger_type": "on_demand",
|
||||
"task_no": task_no,
|
||||
**body,
|
||||
},
|
||||
)
|
||||
raise ValidationError(
|
||||
'shipping inventory RPA v2 batch trigger is required',
|
||||
code='SHIPPING.INVENTORY_RPA_V2_REQUIRED',
|
||||
)
|
||||
|
||||
|
||||
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": "shipment_upload",
|
||||
"schema_version": "shipping_notice_upload_rpa.v1",
|
||||
"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
|
||||
|
||||
|
||||
def find_latest_inventory_file() -> Path | None:
|
||||
"""在 drop 目录中查找最新修改的 xlsx/xls/csv 库存文件。"""
|
||||
drop = inventory_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)
|
||||
@@ -1,97 +0,0 @@
|
||||
"""
|
||||
services/shipping_notice/rpa_attempts.py
|
||||
|
||||
用途:统计任务的 RPA 库存导出与货代上传重试次数,并返回统一上限。
|
||||
依赖:ShippingNotice、ShippingTaskEvent 模型与事件查询逻辑。
|
||||
逻辑:由 inventory_rpa_workflow、fulfillment_workflow 等模块调用本文件,决定是否还能继续触发 RPA 重试。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from datetime import datetime
|
||||
|
||||
from app.models import ShippingNotice, ShippingTaskEvent
|
||||
|
||||
DEFAULT_RPA_UPLOAD_MAX_ATTEMPTS = 3
|
||||
|
||||
_INVENTORY_SUCCESS_EVENTS = {
|
||||
"inventory_uploaded",
|
||||
"inventory_parsed",
|
||||
"inventory_rpa_drop_ingested",
|
||||
"inventory_rpa_ready",
|
||||
"inventory_template_mapping_used",
|
||||
}
|
||||
|
||||
_INVENTORY_ATTEMPT_RESET_EVENTS = _INVENTORY_SUCCESS_EVENTS | {
|
||||
"decision_retry_rpa",
|
||||
}
|
||||
|
||||
_UPLOAD_SUCCESS_EVENTS = {
|
||||
"upload_rpa_success",
|
||||
"upload_manual_confirmed",
|
||||
}
|
||||
|
||||
|
||||
def inventory_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_(_INVENTORY_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,103 @@
|
||||
"""
|
||||
services/shipping_notice/rpa_sinks.py
|
||||
|
||||
用途:onhand(在手库存)与 inbound(入站,原收料)RPA 回调的业务 sink 注册适配层——把
|
||||
/api/freight-rpa/* 蓝图的 dispatch_sink kind 接到真实业务处理器。
|
||||
依赖:freight_rpa.common.callback_sinks(register_sink)、inventory_rpa_workflow(快照落盘/
|
||||
批量 ingest)、per_source_rpa_service(Attempt 认领)、inventory_configuration_test(配置测试)、
|
||||
receipt_report_storage(inbound 归档入口 + 业务桥留守)、schedule.freight_inbound_rpa_finalize
|
||||
(inbound 进度/领取处理器,Task 11 已随排程壳平移改名)。
|
||||
逻辑:由组合根(app.create_app)调用 register_onhand_sinks() / register_inbound_sinks() 完成
|
||||
注册(幂等,重复注册覆盖)。各 sink 仅做两件事:① 复刻旧 shipping-notice rpa 回调端点
|
||||
端点的响应 envelope(逐 kind 对齐,禁止统一 envelope);② 对 onhand-repair 注入旧路由
|
||||
等价的 payload['repair']=True。业务事务边界完全由被包装的域内函数保持,本层不碰 db。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Callable
|
||||
|
||||
|
||||
def _bare(handler: Callable[[dict[str, Any]], dict[str, Any]]) -> Callable[..., dict[str, Any]]:
|
||||
"""旧端点直接 jsonify(业务函数返回值)——裸业务 dict envelope(inventory-ready 同款)。"""
|
||||
|
||||
def _sink(**payload: Any) -> dict[str, Any]:
|
||||
return handler(payload)
|
||||
|
||||
return _sink
|
||||
|
||||
|
||||
def _ok_data_envelope(handler: Callable[[dict[str, Any]], dict[str, Any]]) -> Callable[..., dict[str, Any]]:
|
||||
"""旧 /rpa/inventory-configuration-test-* 的 envelope:{'status':'ok','data':业务结果}。"""
|
||||
|
||||
def _sink(**payload: Any) -> dict[str, Any]:
|
||||
return {'status': 'ok', 'data': handler(payload)}
|
||||
|
||||
return _sink
|
||||
|
||||
|
||||
def _success_data_envelope(handler: Callable[[dict[str, Any]], dict[str, Any]]) -> Callable[..., dict[str, Any]]:
|
||||
"""旧 /rpa/inventory-batch-claimed 的 envelope:{'success':True,'data':业务结果}。"""
|
||||
|
||||
def _sink(**payload: Any) -> dict[str, Any]:
|
||||
return {'success': True, 'data': handler(payload)}
|
||||
|
||||
return _sink
|
||||
|
||||
|
||||
def _onhand_repair_sink(**payload: Any) -> dict[str, Any]:
|
||||
"""受控库存回调修复:等价旧 /rpa/inventory-repair——payload['repair']=True 后走 batch-ready ingest。"""
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch
|
||||
|
||||
payload['repair'] = True
|
||||
return rpa_report_inventory_batch(payload)
|
||||
|
||||
|
||||
def register_onhand_sinks() -> None:
|
||||
"""组合根入口:注册全部 onhand 回调 sink(幂等;create_app 每次启动调用)。
|
||||
|
||||
核心逻辑:kind 命名 = /api/freight-rpa/* 回调路由名去前缀;被包装函数全部住在
|
||||
shipping_notice(业务落盘留守域),与 Task 4 裁定一致——认领(claim_inventory_batch)
|
||||
与批量编排留 per_source_rpa_service,本层只做 envelope 复刻与分发接线。
|
||||
"""
|
||||
from app.services.freight_rpa.common.callback_sinks import register_sink
|
||||
from app.services.shipping_notice import inventory_configuration_test, inventory_rpa_workflow
|
||||
from app.services.shipping_notice.per_source_rpa_service import claim_inventory_batch
|
||||
|
||||
register_sink('onhand-ready', _bare(inventory_rpa_workflow.rpa_report_inventory))
|
||||
register_sink('onhand-batch-ready', _bare(inventory_rpa_workflow.rpa_report_inventory_batch))
|
||||
register_sink('onhand-batch-claimed', _success_data_envelope(claim_inventory_batch))
|
||||
register_sink('onhand-batch-progress', _bare(inventory_rpa_workflow.report_inventory_batch_progress))
|
||||
register_sink(
|
||||
'onhand-configuration-test-start',
|
||||
_ok_data_envelope(inventory_configuration_test.report_batch_test_progress),
|
||||
)
|
||||
register_sink(
|
||||
'onhand-configuration-test-analyze',
|
||||
_ok_data_envelope(inventory_configuration_test.report_test_export),
|
||||
)
|
||||
register_sink(
|
||||
'onhand-configuration-test-complete',
|
||||
_ok_data_envelope(inventory_configuration_test.report_batch_test_exports),
|
||||
)
|
||||
register_sink('onhand-repair', _onhand_repair_sink)
|
||||
|
||||
|
||||
def register_inbound_sinks() -> None:
|
||||
"""组合根入口:注册全部 inbound(收料)回调 sink(幂等;create_app 每次启动调用)。
|
||||
|
||||
核心逻辑:kind 命名 = /api/freight-rpa/* 回调路由名去前缀。inbound-batch-ready 的
|
||||
业务处理器 = receipt_report_storage.ingest_receipt_callback(归档能力下沉
|
||||
freight_rpa.inbound.report_archive 后的域内入口,内部把「终态推进在途调拨来源任务
|
||||
+ 调拨证据同步 + 排程终态归集」业务桥作为 on_terminal 钩子注入——业务桥留守
|
||||
shipping_notice,与拆分前调用方向一致);unit/batch-progress 处理器仍住排程壳
|
||||
(Task 11 已平移改名为 schedule.freight_inbound_rpa_finalize),按「处理函数住在哪个包」
|
||||
由本层接注册表。三个 kind 旧端点 envelope 均为 {'success':True,'data':...},逐字复刻。
|
||||
"""
|
||||
from app.services.freight_rpa.common.callback_sinks import register_sink
|
||||
from app.services.schedule import freight_inbound_rpa_finalize
|
||||
from app.services.shipping_notice import receipt_report_storage
|
||||
|
||||
register_sink('inbound-batch-ready', _success_data_envelope(receipt_report_storage.ingest_receipt_callback))
|
||||
register_sink('inbound-unit-progress', _success_data_envelope(freight_inbound_rpa_finalize.mark_receipt_unit_processing))
|
||||
register_sink('inbound-batch-progress', _success_data_envelope(freight_inbound_rpa_finalize.report_receipt_batch_progress))
|
||||
@@ -1,907 +0,0 @@
|
||||
"""
|
||||
services/shipping_notice/rpa_worker_heartbeat.py
|
||||
|
||||
用途:货代 RPA Worker 心跳存储、共享目录校验、库存/上传/收料就绪检查与状态查询。
|
||||
依赖:Flask current_app、redis_client、shipping_notice.rpa(库存与上传目录、mock 模式)、
|
||||
shipping_notice.receipt_rpa(收料 trigger 目录)。
|
||||
逻辑:freight_rpa_worker 调 POST /rpa/heartbeat;写 inventory/upload/receipt trigger 前强制就绪检查;
|
||||
管理端 /rpa-workers/status?scope=inventory|receipt 展示对应 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.shipping_notice.rpa import inventory_trigger_dir, 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、凭据与共享目录后重试"
|
||||
INVENTORY_EXPORT_CAPABILITY = "inventory_export"
|
||||
FREIGHT_UPLOAD_CAPABILITY = "freight_upload"
|
||||
RECEIPT_EXPORT_CAPABILITY = "receipt_export"
|
||||
# 收料 Worker 由 start_receipt_worker.ps1 注入 FREIGHT_RPA_WORKER_ID=<主机名>-receipt。
|
||||
RECEIPT_WORKER_ID_SUFFIX = "-receipt"
|
||||
_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_inventory_export_capability": "Worker 未声明 inventory_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 = inventory_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:
|
||||
"""
|
||||
判断心跳是否来自收料 Worker。
|
||||
|
||||
优先认 <主机名>-receipt(ps1 注入);兼容未注入 FREIGHT_RPA_WORKER_ID、
|
||||
回退为 <主机名>-<pid> 的进程——用心跳 trigger_dir 与收料目录对齐判定。
|
||||
"""
|
||||
if str(worker.get("worker_id") or "").strip().lower().endswith(RECEIPT_WORKER_ID_SUFFIX):
|
||||
return True
|
||||
from app.services.shipping_notice.receipt_rpa import receipt_trigger_dir
|
||||
|
||||
expected = receipt_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 = INVENTORY_EXPORT_CAPABILITY,
|
||||
) -> tuple[bool, list[str]]:
|
||||
"""
|
||||
判断单 Worker 是否满足心跳新鲜度、能力声明与环境/scope 隔离。
|
||||
|
||||
Args:
|
||||
worker: 心跳记录。
|
||||
backend_env: 后端归一环境(dev/test/prod)。
|
||||
ttl_seconds: 心跳 TTL。
|
||||
now: 当前 epoch 秒。
|
||||
required_capability: 必选能力(inventory_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:
|
||||
if required_capability == FREIGHT_UPLOAD_CAPABILITY:
|
||||
reasons.append("missing_freight_upload_capability")
|
||||
else:
|
||||
reasons.append("missing_inventory_export_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 _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=inventory_trigger_dir(),
|
||||
required_capability=INVENTORY_EXPORT_CAPABILITY,
|
||||
)
|
||||
|
||||
|
||||
def check_receipt_rpa_worker_ready() -> RpaWorkerReadiness:
|
||||
"""
|
||||
检查收料 RPA Worker 是否在线(管理端徽标 + 写 trigger 前 fail-fast)。
|
||||
|
||||
核心逻辑:仅看收料 Worker 心跳(*-receipt 或 trigger_dir 对齐);要求
|
||||
receipt_export 能力;校验收料 trigger 目录可写;与库存同口径要求共享哨兵。
|
||||
"""
|
||||
from app.services.shipping_notice.receipt_rpa import receipt_trigger_dir
|
||||
|
||||
return _check_rpa_worker_ready_for_capability(
|
||||
trigger_dir=receipt_trigger_dir(),
|
||||
required_capability=RECEIPT_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.shipping_notice.receipt_rpa import receipt_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(receipt_trigger_dir() or ''),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def _freight_upload_config_reasons() -> list[str]:
|
||||
"""
|
||||
预检货代上传静态配置:凭据主密钥、上传队列目录、回调 API 基址。
|
||||
|
||||
Returns:
|
||||
不合规原因码列表(空表示静态配置通过)。
|
||||
"""
|
||||
from app.services.shipping_notice.rpa 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.shipping_notice.rpa 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.shipping_notice.rpa 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(inventory_trigger_dir() or ""),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def serialize_rpa_worker_status(*, scope: str = "inventory") -> dict[str, Any]:
|
||||
"""
|
||||
管理端展示:按 scope 返回库存或收料 Worker 心跳摘要。
|
||||
|
||||
Args:
|
||||
scope: inventory(默认)或 receipt。
|
||||
"""
|
||||
from app.services.shipping_notice.rpa import upload_trigger_dir
|
||||
from app.services.shipping_notice.receipt_rpa import receipt_trigger_dir
|
||||
|
||||
normalized = str(scope or "inventory").strip().lower()
|
||||
if normalized == "receipt":
|
||||
readiness = check_receipt_rpa_worker_ready()
|
||||
trigger_path = str(receipt_trigger_dir() or "")
|
||||
else:
|
||||
readiness = check_inventory_rpa_worker_ready()
|
||||
trigger_path = str(inventory_trigger_dir() or "")
|
||||
normalized = "inventory"
|
||||
|
||||
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),
|
||||
},
|
||||
}
|
||||
@@ -1,558 +0,0 @@
|
||||
"""
|
||||
services/shipping_notice/rpa_worker_heartbeat_alert.py
|
||||
|
||||
用途:库存 RPA Worker 离线/恢复主动告警(企微 textcard + 冷却去重)。
|
||||
依赖:rpa_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 app.services.shipping_notice.rpa_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
|
||||
@@ -36,7 +36,7 @@ def shipping_recovery_tick() -> int:
|
||||
# 根据最新 Attempt/Gate 状态刷新按钮与阻断原因。
|
||||
inventory_timeout_seconds = max(int(getattr(
|
||||
current_app.config,
|
||||
'FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS',
|
||||
'FREIGHT_RPA_ONHAND_TIMEOUT_SECONDS',
|
||||
900,
|
||||
) or 900), 1)
|
||||
inventory_scan_count = _scan_stale_inventory_attempts(
|
||||
|
||||
@@ -83,7 +83,7 @@ def auto_rpa_inventory_enabled() -> bool:
|
||||
|
||||
def rpa_inventory_timeout_seconds() -> int:
|
||||
"""RPA 库存导出等待超时秒数。"""
|
||||
return cfg_int("FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS", 900, min_value=5)
|
||||
return cfg_int("FREIGHT_RPA_ONHAND_TIMEOUT_SECONDS", 900, min_value=5)
|
||||
|
||||
|
||||
def auto_mapping_allow_llm() -> bool:
|
||||
|
||||
Reference in new issue
Block a user