feat(freight-rpa): 批次R解耦编排层并切换 onhand/inbound 契约

将 RPA 编排收编至 freight_rpa,回调迁 /api/freight-rpa/*。
共享目录与 Worker 契约一次切换至 onhand/inbound/upload,
并补 outbound 骨架与 tt16 排程 job key 迁移。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
hugoandCursor committed 2026-10-17 23:18:48 +08:00
1 parent bf3154033b
commit ffc0d4a430
147 files changed
+4221 -2678

No files matched your search

@@ -0,0 +1 @@
"""onhand:在手库存 RPA。"""
@@ -0,0 +1,99 @@
"""
services/freight_rpa/onhand/attempts.py
用途:统计任务的 onhand(库存)RPA 导出与货代上传重试次数,并返回统一上限。
依赖:ShippingNotice、ShippingTaskEvent 模型与事件查询逻辑(仅 models,无业务编排 import)。
逻辑:由 shipping_notice 的 inventory_rpa_workflow、fulfillment_workflow 等模块调用本文件,
决定是否还能继续触发 RPA 重试;事件类型字符串(inventory_rpa_* 等)是落库数据值,
随 models 命名一并留待批次 S 处理,本模块只改包归属与标识符词根。
"""
from __future__ import annotations
import os
from datetime import datetime
from app.models import ShippingNotice, ShippingTaskEvent
DEFAULT_RPA_UPLOAD_MAX_ATTEMPTS = 3
_ONHAND_SUCCESS_EVENTS = {
"inventory_uploaded",
"inventory_parsed",
"inventory_rpa_drop_ingested",
"inventory_rpa_ready",
"inventory_template_mapping_used",
}
_ONHAND_ATTEMPT_RESET_EVENTS = _ONHAND_SUCCESS_EVENTS | {
"decision_retry_rpa",
}
_UPLOAD_SUCCESS_EVENTS = {
"upload_rpa_success",
"upload_manual_confirmed",
}
def onhand_rpa_attempts(task: ShippingNotice | None) -> int:
"""统计自上次库存成功事件以来的 RPA 库存导出触发/失败次数。"""
if not task or task.id is None:
return 0
last_reset = (
ShippingTaskEvent.query.filter_by(task_id=task.id)
.filter(ShippingTaskEvent.event_type.in_(_ONHAND_ATTEMPT_RESET_EVENTS))
.order_by(ShippingTaskEvent.id.desc())
.first()
)
since: datetime | None = last_reset.created_at if last_reset else None
triggered = ShippingTaskEvent.query.filter_by(task_id=task.id).filter(
ShippingTaskEvent.event_type == "inventory_rpa_triggered"
)
failed = ShippingTaskEvent.query.filter_by(task_id=task.id).filter(
ShippingTaskEvent.event_type == "inventory_rpa_failed"
)
if since:
triggered = triggered.filter(ShippingTaskEvent.created_at >= since)
failed = failed.filter(ShippingTaskEvent.created_at >= since)
return max(triggered.count(), failed.count())
def upload_rpa_attempts(task: ShippingNotice | None) -> int:
"""统计自上次上传成功事件以来的 RPA 货代上传触发/失败次数。"""
if not task or task.id is None:
return 0
last_success = (
ShippingTaskEvent.query.filter_by(task_id=task.id)
.filter(ShippingTaskEvent.event_type.in_(_UPLOAD_SUCCESS_EVENTS))
.order_by(ShippingTaskEvent.id.desc())
.first()
)
since: datetime | None = last_success.created_at if last_success else None
triggered = ShippingTaskEvent.query.filter_by(task_id=task.id).filter(
ShippingTaskEvent.event_type == "upload_rpa_triggered"
)
failed = ShippingTaskEvent.query.filter_by(task_id=task.id).filter(
ShippingTaskEvent.event_type == "upload_rpa_failed"
)
if since:
triggered = triggered.filter(ShippingTaskEvent.created_at >= since)
failed = failed.filter(ShippingTaskEvent.created_at >= since)
return max(triggered.count(), failed.count())
def max_rpa_upload_attempts() -> int:
"""RPA 货代上传最大重试次数(环境变量 FREIGHT_RPA_UPLOAD_MAX_ATTEMPTS)。"""
value = os.getenv("FREIGHT_RPA_UPLOAD_MAX_ATTEMPTS")
if value is None or not str(value).strip():
return DEFAULT_RPA_UPLOAD_MAX_ATTEMPTS
try:
parsed = int(value)
except (TypeError, ValueError):
return DEFAULT_RPA_UPLOAD_MAX_ATTEMPTS
return max(parsed, 1)
@@ -0,0 +1,302 @@
"""
services/freight_rpa/onhand/callback_cleanup.py
用途:RPA callback drop 区文件归档失败后的持久化重试队列、隔离与消费标记
(Task 9 自 shipping_notice.inventory_rpa_callback_cleanup 整体平移,纯协议文件 IO、零业务落盘)。
依赖:freight_rpa.onhand.trigger_io(onhand_drop_dir / onhand_processed_dir)、json、uuid、Flask current_app。
逻辑:commit 后由 shipping_notice 业务 sink 调用尝试归档;失败则移入 .hxops_quarantine 并入队;
scheduler/worker 启动时定期消费队列。
"""
from __future__ import annotations
import json
import logging
import shutil
import uuid
from datetime import datetime
from pathlib import Path
from typing import Any
from flask import current_app
from app.services.freight_rpa.onhand.trigger_io import onhand_drop_dir, onhand_processed_dir
_CALLBACK_CONSUMED_SUFFIX = ".hxops_consumed"
_CLEANUP_QUEUE_DIRNAME = ".cleanup_queue"
_CLEANUP_FAILED_DIRNAME = ".cleanup_failed"
_QUARANTINE_DIRNAME = ".hxops_quarantine"
_DEFAULT_MAX_CLEANUP_ATTEMPTS = 16
_LOGGER = logging.getLogger(__name__)
def callback_cleanup_queue_dir() -> Path | None:
"""drop 目录下 callback 归档重试队列路径。"""
drop = onhand_drop_dir()
if not drop:
return None
return drop / _CLEANUP_QUEUE_DIRNAME
def callback_cleanup_failed_dir() -> Path | None:
"""超过最大重试次数的 cleanup job 隔离目录。"""
drop = onhand_drop_dir()
if not drop:
return None
return drop / _CLEANUP_FAILED_DIRNAME
def callback_quarantine_dir() -> Path | None:
"""
Worker 不应扫描的 callback 隔离目录(drop 根目录外的子目录)。
归档失败时 HXOPS 将文件原子移入此处,避免重复上报。
"""
drop = onhand_drop_dir()
if not drop:
return None
return drop / _QUARANTINE_DIRNAME
def callback_cleanup_max_attempts() -> int:
"""cleanup job 最大重试次数(FREIGHT_RPA_CALLBACK_CLEANUP_MAX_ATTEMPTS)。"""
try:
return max(
1,
int(current_app.config.get("FREIGHT_RPA_CALLBACK_CLEANUP_MAX_ATTEMPTS") or _DEFAULT_MAX_CLEANUP_ATTEMPTS),
)
except (TypeError, ValueError):
return _DEFAULT_MAX_CLEANUP_ATTEMPTS
def is_callback_drop_file_consumed(callback_path: Path) -> bool:
"""判断 drop 文件是否已被 HXOPS 消费(sidecar 或已位于 quarantine)。"""
path = Path(callback_path)
if not path.name:
return False
quarantine = callback_quarantine_dir()
if quarantine and quarantine in path.parents:
return True
sidecar = Path(f"{path}{_CALLBACK_CONSUMED_SUFFIX}")
return sidecar.is_file()
def mark_callback_drop_file_consumed(
callback_path: Path,
*,
run_no: str | None = None,
task_no: str | None = None,
schedule_run_id: int | None = None,
inventory_file_no: str | None = None,
) -> None:
"""
标记 drop 区 callback 文件已被系统消费。
核心逻辑:写 sidecar JSON;配合 quarantine 供 Worker 跳过重复扫描(Worker 须忽略 .hxops_* 子目录)。
"""
if not callback_path.is_file():
return
sidecar = Path(f"{callback_path}{_CALLBACK_CONSUMED_SUFFIX}")
payload = {
"callback_path": str(callback_path),
"consumed_at": datetime.utcnow().isoformat(),
"run_no": str(run_no or "").strip() or None,
"task_no": str(task_no or "").strip() or None,
"schedule_run_id": schedule_run_id,
"inventory_file_no": str(inventory_file_no or "").strip() or None,
}
try:
sidecar.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8")
except OSError as exc:
_LOGGER.warning("failed to write callback consumed marker %s: %s", sidecar, exc)
def quarantine_callback_drop_file(callback_path: Path) -> Path | None:
"""
将归档失败的 callback 原子移入隔离目录,避免 Worker 扫描 drop 根目录时重复上报。
Returns:
隔离后的路径;不可用时返回 None。
"""
path = Path(callback_path)
if not path.is_file():
return None
quarantine = callback_quarantine_dir()
if quarantine is None:
return None
quarantine.mkdir(parents=True, exist_ok=True)
target = quarantine / path.name
if target.exists():
target = quarantine / (
f"{path.stem}_{datetime.utcnow().strftime('%Y%m%d%H%M%S')}{path.suffix}"
)
shutil.move(str(path), str(target))
consumed = Path(f"{path}{_CALLBACK_CONSUMED_SUFFIX}")
if consumed.is_file():
try:
consumed.unlink()
except OSError:
pass
return target
def enqueue_callback_file_move(
callback_path: Path,
*,
processed_dir: Path,
run_no: str | None = None,
task_no: str | None = None,
schedule_run_id: int | None = None,
error: str | None = None,
) -> Path | None:
"""
将失败的 callback 归档操作写入持久化队列,供后续重试。
Returns:
队列 job 文件路径;队列不可用时返回 None。
"""
queue = callback_cleanup_queue_dir()
if queue is None:
return None
queue.mkdir(parents=True, exist_ok=True)
job_id = uuid.uuid4().hex
job_path = queue / f"move_{job_id}.json"
payload: dict[str, Any] = {
"job_id": job_id,
"callback_path": str(callback_path),
"processed_dir": str(processed_dir),
"run_no": str(run_no or "").strip() or None,
"task_no": str(task_no or "").strip() or None,
"schedule_run_id": schedule_run_id,
"last_error": str(error or "").strip() or None,
"enqueued_at": datetime.utcnow().isoformat(),
"attempts": 0,
}
tmp = job_path.with_suffix(".json.tmp")
try:
tmp.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8")
tmp.replace(job_path)
except OSError as exc:
_LOGGER.warning("failed to enqueue callback move job for %s: %s", callback_path, exc)
return None
return job_path
def move_callback_drop_file_to_processed(callback_path: Path, processed_dir: Path) -> None:
"""将 callback 文件移入 processed 目录(公开给 workflow 直接调用)。"""
_move_callback_file_to_processed(callback_path, processed_dir)
def _move_callback_file_to_processed(callback_path: Path, processed_dir: Path) -> None:
"""将 callback 文件移入 processed 目录。"""
if not callback_path.is_file():
return
processed_dir.mkdir(parents=True, exist_ok=True)
target = processed_dir / callback_path.name
if target.exists():
target = processed_dir / (
f"{callback_path.stem}_{datetime.utcnow().strftime('%H%M%S')}{callback_path.suffix}"
)
shutil.move(str(callback_path), str(target))
consumed = Path(f"{callback_path}{_CALLBACK_CONSUMED_SUFFIX}")
if consumed.is_file():
try:
consumed.unlink()
except OSError:
pass
def _archive_failed_cleanup_job(job_path: Path, payload: dict[str, Any]) -> None:
"""超过最大重试次数后将 job 移入 failed 目录。"""
failed_dir = callback_cleanup_failed_dir()
if failed_dir is None:
try:
job_path.unlink()
except OSError:
pass
return
failed_dir.mkdir(parents=True, exist_ok=True)
target = failed_dir / job_path.name
payload["archived_at"] = datetime.utcnow().isoformat()
try:
target.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8")
job_path.unlink()
except OSError as exc:
_LOGGER.warning("failed to archive cleanup job %s: %s", job_path, exc)
def flush_callback_cleanup_queue(*, max_jobs: int = 32) -> list[str]:
"""
重试持久化 callback 归档队列。
核心逻辑:源文件已不存在视为完成;超限 job 移入 failed;仍失败则累加 attempts。
"""
queue = callback_cleanup_queue_dir()
if queue is None or not queue.is_dir():
return []
warnings: list[str] = []
max_attempts = callback_cleanup_max_attempts()
jobs = sorted(queue.glob("move_*.json"))[: max(max_jobs, 1)]
for job_path in jobs:
try:
payload = json.loads(job_path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError, TypeError, ValueError) as exc:
warnings.append(f"{job_path.name}:invalid_job:{str(exc)[:80]}")
try:
job_path.unlink()
except OSError:
pass
continue
callback_raw = str(payload.get("callback_path") or "").strip()
processed_raw = str(payload.get("processed_dir") or "").strip()
callback_path = Path(callback_raw) if callback_raw else None
processed_dir = Path(processed_raw) if processed_raw else onhand_processed_dir()
if callback_path is None or processed_dir is None:
try:
job_path.unlink()
except OSError:
pass
continue
if not callback_path.is_file():
try:
job_path.unlink()
except OSError:
pass
continue
if int(payload.get("attempts") or 0) >= max_attempts:
warnings.append(f"{callback_path}:max_attempts_exceeded")
_archive_failed_cleanup_job(job_path, payload)
continue
try:
_move_callback_file_to_processed(callback_path, processed_dir)
try:
job_path.unlink()
except OSError:
pass
except Exception as exc:
payload["attempts"] = int(payload.get("attempts") or 0) + 1
payload["last_error"] = str(exc)[:240]
payload["last_attempt_at"] = datetime.utcnow().isoformat()
warnings.append(f"{callback_path}:{str(exc)[:120]}")
if int(payload["attempts"]) >= max_attempts:
_archive_failed_cleanup_job(job_path, payload)
else:
try:
job_path.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8")
except OSError:
pass
_LOGGER.warning(
"callback cleanup retry failed for %s (attempt=%s)",
callback_path,
payload["attempts"],
exc_info=exc,
)
return warnings
def recover_pending_rpa_callback_cleanup_jobs(*, max_jobs: int = 64) -> tuple[int, list[str]]:
"""
启动或调度恢复时消费 callback cleanup 队列。
Returns:
tuple: (成功消化或移除的 job 数, 告警列表)。
"""
queue = callback_cleanup_queue_dir()
before = len(list(queue.glob("move_*.json"))) if queue and queue.is_dir() else 0
warnings = flush_callback_cleanup_queue(max_jobs=max_jobs)
after = len(list(queue.glob("move_*.json"))) if queue and queue.is_dir() else 0
return max(0, before - after), warnings
@@ -0,0 +1,108 @@
"""
services/freight_rpa/onhand/trigger_io.py
用途:onhand(在手库存)RPA 的纯文件 IO——trigger/落盘目录解析、trigger JSON 原子写、
单任务导出 trigger 写入,以及 Worker 触发/回调契约常量(SCHEMA/ACTION_*)。
依赖:Flask current_app 配置、Path/JSON/文件系统工具;不 import 任何业务编排模块
(import 边界由 tests/services/freight_rpa/test_import_boundary.py 锁死)。
逻辑:由 shipping_notice.onhand_trigger_batch(批量/按需编排)、inventory_rpa_workflow(回调 schema 校验)、
per_source_rpa_service(回调 schema 校验)、freight_rpa.common.worker_heartbeat(目录探测)等调用,
与外部 RPA Worker 的文件投递目录交互;schema/action 新值以本文件常量为单一真相
(Worker 侧 Task 12 对表:freight_rpa.onhand.v1 / onhand_export / onhand_export_batch)。
"""
from __future__ import annotations
import json
import os
from datetime import datetime
from pathlib import Path
from typing import Any
from flask import current_app
# Worker 触发/回调契约常量:后端写入侧与校验侧共用单一真相,禁止再写字面量。
# [PROMPT_UPDATE] 2026-10-16 freight_rpa 解耦批次 R:schema/action 切换为下述新值
# (旧 inventory 时代字面量已从 backend/app 与 Worker 双侧清零,历史对照见 cutover runbook),
# 旧字符串已在 backend/app 内清零;Worker 侧由 Task 12 对齐。
SCHEMA = "freight_rpa.onhand.v1"
ACTION_ONHAND_EXPORT = "onhand_export"
ACTION_ONHAND_EXPORT_BATCH = "onhand_export_batch"
def _path(key: str) -> Path | None:
value = str(current_app.config.get(key) or "").strip()
if not value:
return None
return Path(value)
def onhand_drop_dir() -> Path | None:
"""RPA onhand 库存 Excel 落盘目录(FREIGHT_RPA_SHARED_ONHAND_DROP_DIR)。"""
return _path("FREIGHT_RPA_SHARED_ONHAND_DROP_DIR")
def onhand_processed_dir() -> Path | None:
"""已处理 onhand 文件归档子目录(drop_dir/processed)。"""
base = onhand_drop_dir()
if not base:
return None
return base / "processed"
def onhand_trigger_dir() -> Path | None:
"""RPA onhand 导出触发 JSON 目录(FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR)。"""
return _path("FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR")
def _write_trigger_json_atomic(path: Path, body: dict[str, Any]) -> None:
"""原子发布 trigger,避免 Worker 读取到写入中的半截 JSON。"""
temp_path = path.with_name(f'.{path.name}.{os.getpid()}.tmp')
try:
with open(temp_path, 'w', encoding='utf-8') as handle:
json.dump(body, handle, ensure_ascii=False, indent=2)
handle.flush()
os.fsync(handle.fileno())
os.replace(temp_path, path)
finally:
if temp_path.exists():
temp_path.unlink(missing_ok=True)
def write_onhand_export_trigger(task_no: str, payload: dict[str, Any] | None = None) -> str | None:
"""
写入 RPA onhand 导出触发文件 inventory_export_{task_no}.json
(文件名沿用既有 Worker 契约,仅 action 取新值 ACTION_ONHAND_EXPORT)。
Returns:
str | None: 触发文件绝对路径;目录未配置时返回 None。
"""
trigger_dir = onhand_trigger_dir()
if not trigger_dir:
return None
trigger_dir.mkdir(parents=True, exist_ok=True)
body = {
"action": ACTION_ONHAND_EXPORT,
"task_no": task_no,
"run_no": f"LEGACY-{task_no}-{datetime.utcnow().strftime('%Y%m%d%H%M%S%f')}",
"requested_at": datetime.utcnow().isoformat(),
**(payload or {}),
}
path = trigger_dir / f"inventory_export_{task_no}.json"
_write_trigger_json_atomic(path, body)
return str(path)
# TODO(批次S): 全仓零调用,死代码候选,收敛时删除
def find_latest_inventory_file() -> Path | None:
"""在 drop 目录中查找最新修改的 xlsx/xls/csv 库存文件。"""
drop = onhand_drop_dir()
if not drop or not drop.is_dir():
return None
candidates = [
p for p in drop.iterdir()
if p.is_file() and p.suffix.lower() in {".xlsx", ".xls", ".csv"}
]
if not candidates:
return None
return max(candidates, key=lambda p: p.stat().st_mtime)
@@ -0,0 +1,336 @@
"""
services/freight_rpa/onhand/workflow_protocol.py
用途:onhand(在手库存)RPA 回调协议态——attempt 行记账、run_no 幂等键、轮次校验、
排程进度记账与超时窗口判定的纯协议层。
依赖:app.models(ShippingTaskEvent / ShippingTaskInventoryRpaAttempt / ScheduleRun)、
app.extensions.db、freight_rpa.onhand 包内模块;**禁止 import 任何
shipping_notice 业务模块**(import 边界由 tests/services/freight_rpa/test_import_boundary.py
AST 全包扫描锁死,含函数内延迟 import)。
逻辑:Task 9 拆分自 shipping_notice.inventory_rpa_workflow——回调进入
/api/freight-rpa/* 蓝图后,业务 sink(shipping_notice.rpa_sinks 注册)在原事务内
调用本模块完成协议记账(不改变 commit 时机),再由域内业务函数做快照落盘/
门禁推进/审计投影;快照、Gate、状态机等业务终态一律留在 shipping_notice。
"""
from __future__ import annotations
import json
from datetime import datetime
from pathlib import Path
from typing import Any
from app.extensions import db
from app.models import ScheduleRun, ShippingTaskEvent, ShippingTaskInventoryRpaAttempt
def latest_task_event(task: Any, event_type: str) -> ShippingTaskEvent | None:
"""返回任务最近一条指定类型的 ShippingTaskEvent(RPA 超时/重试/轮次校验用)。"""
if task.id is None:
return None
return (
ShippingTaskEvent.query.filter_by(task_id=task.id, event_type=event_type)
.order_by(ShippingTaskEvent.id.desc())
.first()
)
def extract_run_no_from_trigger(trigger_path: str | None) -> str:
"""从 trigger 文件路径或 JSON 内容提取 run_no(batch / legacy 单票均支持)。"""
path = Path(str(trigger_path or ""))
name = path.name
prefix = "inventory_export_batch_"
if name.startswith(prefix) and name.endswith(".json"):
return name[len(prefix) : -len(".json")]
if name.startswith("inventory_export_") and name.endswith(".json") and path.is_file():
try:
payload = json.loads(path.read_text(encoding="utf-8"))
if isinstance(payload, dict):
run_no = str(payload.get("run_no") or "").strip()
if run_no:
return run_no
except (OSError, json.JSONDecodeError, TypeError, ValueError):
pass
return ""
def is_legacy_trigger_run_no(run_no: str) -> bool:
"""判断 run_no 是否来自 legacy 单任务 trigger(worker 可能不回传 run_no)。"""
return str(run_no or "").strip().upper().startswith("LEGACY-")
def expected_rpa_callback_run_no(task: Any) -> str:
"""读取任务最近一次 RPA 触发记录的 run_no(事件 detail 优先,缺失回退 trigger 文件)。"""
last_trigger = latest_task_event(task, "inventory_rpa_triggered")
if not last_trigger:
return ""
detail = last_trigger.detail_json if isinstance(last_trigger.detail_json, dict) else {}
run_no = str(detail.get("run_no") or "").strip()
if run_no:
return run_no
return extract_run_no_from_trigger(str(detail.get("trigger") or ""))
def validate_rpa_callback_run_no(task: Any, callback_run_no: str) -> str | None:
"""校验回调 run_no 属于当前任务最近一次有效触发轮次。
Returns:
None 校验通过;否则返回拒绝原因码(no_active_trigger / run_no_missing / run_no_mismatch)。
"""
provided = str(callback_run_no or "").strip()
expected = expected_rpa_callback_run_no(task)
if not expected:
return "no_active_trigger"
if not provided:
if is_legacy_trigger_run_no(expected):
return None
return "run_no_missing"
if provided != expected:
return "run_no_mismatch"
return None
def resolve_effective_callback_run_no(task: Any, payload: dict[str, Any]) -> str:
"""解析回调实际归属的 run_no(显式传入优先,否则回退当前触发轮次)。"""
provided = str(payload.get("run_no") or "").strip()
if provided:
return provided
return expected_rpa_callback_run_no(task)
def get_consumed_inventory_rpa_run_no(task: Any) -> str:
"""读取已消费(处理完成)的 RPA 轮次 run_no。"""
attempt = (
ShippingTaskInventoryRpaAttempt.query
.filter_by(task_no=str(task.task_no or ''), status='consumed')
.order_by(ShippingTaskInventoryRpaAttempt.consumed_at.desc(), ShippingTaskInventoryRpaAttempt.id.desc())
.first()
)
return str(getattr(attempt, 'source_run_no', '') or '').strip()
def mark_inventory_rpa_run_no_consumed(task: Any, run_no: str) -> None:
"""[协议记账] 标记当前 RPA 轮次已被回调消费,防止同一 run_no 重放重复入库。
核心逻辑:只改 Attempt 行(status/consumed_at),不 commit——commit 时机由调用方
业务事务决定,与拆分前行为一致。
"""
effective = str(run_no or "").strip()
if not effective:
return
attempt = (
ShippingTaskInventoryRpaAttempt.query
.filter_by(task_no=str(task.task_no or ''), source_run_no=effective)
.one_or_none()
)
if attempt is not None:
attempt.status = 'consumed'
attempt.consumed_at = datetime.utcnow()
def validate_rpa_callback_not_replayed(task: Any, run_no: str) -> str | None:
"""拒绝同一 run_no 的重复成功/失败/跳过回调。
Returns:
None 允许处理;"run_no_already_consumed" 表示重放,应拒绝。
"""
effective = str(run_no or "").strip()
consumed = get_consumed_inventory_rpa_run_no(task)
if effective and consumed and effective == consumed:
return "run_no_already_consumed"
return None
def validate_schedule_batch_callback_run_no(schedule_run_id: int | None, callback_run_no: str) -> str | None:
"""校验定时 batch 回调 run_no 与排程 run 记录一致,防止错绑终态。
Returns:
None 校验通过;否则返回拒绝原因码(schedule_run_not_found / schedule_run_no_missing /
schedule_run_no_mismatch / schedule_run_not_awaiting)。
"""
if schedule_run_id is None:
return None
run = db.session.get(ScheduleRun, schedule_run_id)
if not run:
return "schedule_run_not_found"
expected = str(run.run_no or "").strip()
provided = str(callback_run_no or "").strip()
if not expected:
return "schedule_run_no_missing"
if provided != expected:
return "schedule_run_no_mismatch"
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
if run.status != "running" or not summary.get("awaiting_rpa"):
return "schedule_run_not_awaiting"
return None
def record_onhand_batch_progress(
run: ScheduleRun,
run_no: str,
*,
success_count: int,
skipped_count: int,
failed_count: int,
) -> dict[str, Any]:
"""[协议记账] 排程批量导出进度回写:max(现有, 上报) 防乱序回退,写后即 commit。
【AI 触发时机】:onhand-batch-progress 业务 sink 已完成 schema/run 校验后调用;
非终态记账(不修改 status/started_at/finished_at,终态仍以 batch-ready 为准)。
Args:
run: 已确认存在且处于 awaiting_rpa 的 ScheduleRun 行。
run_no: 批次 run_no,写入 response_summary_json.progress 供审计。
success_count / skipped_count / failed_count: 已按 max(0, int(x)) 归一的非负计数。
Returns:
dict: 提交后的最终计数 {'success_count','skipped_count','failed_count','run_no'};
供业务层拼装响应,键值与拆分前响应逐字一致。
"""
run.success_count = max(int(run.success_count or 0), success_count)
run.skipped_count = max(int(run.skipped_count or 0), skipped_count)
run.failed_count = max(int(run.failed_count or 0), failed_count)
summary = dict(run.response_summary_json or {})
summary['progress'] = {
'success_count': int(run.success_count or 0),
'skipped_count': int(run.skipped_count or 0),
'failed_count': int(run.failed_count or 0),
'batch_run_no': run_no,
'updated_at': datetime.utcnow().isoformat(),
}
run.response_summary_json = summary
# commit 时机与拆分前 inventory_rpa_workflow.report_inventory_batch_progress 完全一致:
# 校验通过、计数写完后立即提交,再由业务层构造响应。
db.session.commit()
return {
'run_no': run_no,
'success_count': int(run.success_count or 0),
'skipped_count': int(run.skipped_count or 0),
'failed_count': int(run.failed_count or 0),
}
def compute_rpa_wait_window(
triggered_at: datetime,
timeout_seconds: int,
*,
now: datetime | None = None,
) -> tuple[int, int, int]:
"""计算库存 RPA 等待窗口(elapsed / timeout / remaining 秒)。
【AI 触发时机】:业务层已确认任务处于 RPA 等待态、需要判断是否超时或调度复查时调用。
Args:
triggered_at: 最近一次 inventory_rpa_triggered 事件的 created_at。
timeout_seconds: 超时阈值秒数(由业务层 tool_common 读取配置)。
now: 可注入当前时间(测试用);缺省 utcnow。
Returns:
tuple[int, int, int]: (elapsed_seconds, timeout_seconds, remaining_seconds);
elapsed 向下取整且不为负,remaining 不为负。
"""
current = now or datetime.utcnow()
elapsed = max(int((current - triggered_at).total_seconds()), 0)
remaining = max(int(timeout_seconds) - elapsed, 0)
return elapsed, int(timeout_seconds), remaining
def resolve_shared_inventory_drop_file(raw_path: str, *, allowed_root: Path) -> Path | None:
"""将 Worker 回调中的 file_path 解析为 Linux 侧共享 drop 内的真实文件。
Windows Worker 上报 ``C:\\HxopsRpaTest\\data\\inventory_drop\\file.xlsx``,
Ubuntu 后端通过 ``/mnt/hxops-rpa-*-data/inventory_drop/file.xlsx`` 读同一 SMB 文件。
安全约束:仅允许 ``allowed_root`` 下按文件名映射,拒绝路径穿越。
Returns:
Path | None: 解析成功且确为 allowed_root 下存在文件时返回绝对路径;否则 None。
"""
text = str(raw_path or '').strip()
if not text:
return None
try:
root = allowed_root.resolve()
except OSError:
return None
candidate = Path(text)
try:
resolved = candidate.resolve()
if resolved.is_file():
resolved.relative_to(root)
return resolved
except (OSError, ValueError, RuntimeError):
pass
name = Path(text.replace('\\', '/')).name.strip()
if not name or name in {'.', '..'} or '/' in name or '\\' in name:
return None
mapped = (root / name).resolve()
try:
mapped.relative_to(root)
except ValueError:
return None
if mapped.is_file():
return mapped
return None
def normalize_inventory_result_status(payload: dict[str, Any]) -> str:
"""归一化单任务 RPA 库存回调结果。
核心逻辑:优先读取 worker 上报的 status;兼容旧回调仅含 success/skipped 布尔字段;
缺省 success 视为 true(历史单任务回调兼容)。
Returns:
str: success | skipped | failed
"""
raw_status = str(payload.get("status") or "").strip().lower()
if raw_status in {"success", "skipped", "failed"}:
return raw_status
if payload.get("skipped"):
return "skipped"
if bool(payload.get("success", True)):
return "success"
return "failed"
def normalize_inventory_batch_item_status(item: dict[str, Any]) -> str:
"""归一化 batch results 单条明细(比单任务更严格:缺字段不算 success)。
核心逻辑:与 worker `_normalize_inventory_batch_item_status` 对齐;空 dict 或
缺 status/success/skipped 直接归为 failed,避免误走 success→file_missing 分支。
Returns:
str: success | skipped | failed
"""
raw_status = str(item.get("status") or "").strip().lower()
if raw_status in {"success", "skipped", "failed"}:
return raw_status
if item.get("skipped"):
return "skipped"
if item.get("success") is True:
return "success"
return "failed"
def merge_batch_callback_item(payload: dict[str, Any], item: dict[str, Any]) -> dict[str, Any]:
"""合并 batch 顶层契约字段到 result item。
核心逻辑:合并 batch 已认证的 schema_version / run_no / task_no;其余身份字段必须由
Worker item 显式返回,禁止后端从任务或数据库补齐。
Returns:
dict: 合并后的 item 副本(不修改入参)。
"""
merged = dict(item)
top_schema_version = str(payload.get('schema_version') or '').strip()
if top_schema_version and not str(merged.get('schema_version') or '').strip():
merged['schema_version'] = top_schema_version
top_run_no = str(payload.get("run_no") or "").strip()
if top_run_no and not str(merged.get("run_no") or "").strip():
merged["run_no"] = top_run_no
task_no = str(merged.get("task_no") or payload.get("task_no") or "").strip()
if task_no and not str(merged.get("task_no") or "").strip():
merged["task_no"] = task_no
return merged