feat(shipping-notice): 收料RPA接入调拨全链路并统一Worker触发目录消费
- 新增 common/trigger_consumer 领取/归档原语,库存与收料 Worker 统一四态目录契约,README 载明契约 - 触发先落单元行再原子写 trigger;假触发器委托真实服务;触发目录不可用单元标 failed - 回调终态桥接推进调拨来源任务,有推进即 commit 保证持久 - 预检接真实异动文件仓库与 parse_movement_rows,行合成 sheet/row_no 溯源 - 等待回调来源任务超时回收挂每轮排程领取,绝不自动重试 - 三环境补收料共享目录 env,值对齐 §1.9.3 挂载约定
This commit is contained in:
1 parent
80d78130f8
commit
65f751daf4
23 files changed
+607
-91
No files matched your search
@@ -119,6 +119,20 @@ DSV Worker 默认使用 `#file2`,也可用 `SHIPPING_NOTICE_RPA_WORKER_UPLOAD_
|
||||
`em.fa.fa-circle.success-color.status-icon` 和非空 `Reference #` 时回调成功,Reference
|
||||
作为货代回执号。CRANE 上传路径尚未确认,Worker 会显式失败,绝不会误用 DSV 页面。
|
||||
|
||||
## Trigger 目录四态契约(所有 Worker 强制)
|
||||
|
||||
| 目录 | 含义 | 进入方式 |
|
||||
| --- | --- | --- |
|
||||
| `<root>/*.json` | 待领取 | 后端经临时文件+`os.replace` 原子写入 |
|
||||
| `<root>/processing/` | 已领取、处理中 | Worker 经 `common/trigger_consumer.claim_trigger` 原子 rename |
|
||||
| `<root>/processed/` | 处理并回调成功 | `archive_trigger(claimed, 'processed')` |
|
||||
| `<root>/failed/` | 处理或回调失败,需人工 | `archive_trigger(claimed, 'failed')` |
|
||||
|
||||
- 领取失败(返回 None)= 已被其他消费者处理,跳过,禁止原地读取根目录文件。
|
||||
- Worker 崩溃可能留下 `processing/` 残留:重启不会自动重跑(防重复导出/重复回调);
|
||||
人工确认导出未完成则移回根目录重跑,已完成则人工补回调后归档。
|
||||
- 新增 Worker 一律复用 `common/trigger_consumer.py`,禁止再自建目录搬移逻辑。
|
||||
|
||||
## 部署、启动与停止手册
|
||||
|
||||
本节说明库存 RPA 测试导出的三种运行方式:
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
"""RPA trigger 文件统一消费契约:领取(claim)与归档(archive)原语。
|
||||
|
||||
用途:为库存/收料/上传等所有 Windows Worker 提供一致的 trigger 目录生命周期,
|
||||
替代各 Worker 各自实现"原地处理/领取归档"两套逻辑(重复轮子收敛点)。
|
||||
依赖:仅标准库 pathlib;禁止引入 playwright 或后端 app 依赖(Worker 独立运行)。
|
||||
逻辑:目录四态契约——
|
||||
<root>/*.json 待领取(后端临时文件+os.replace 原子写入)
|
||||
<root>/processing/ 已领取处理中(崩溃残留人工可见,不会被重扫重复导出)
|
||||
<root>/processed/ 处理并回调成功
|
||||
<root>/failed/ 处理或回调失败,需人工排查
|
||||
领取 = 同盘 rename 到 processing/(原子);被第二个消费者抢走时返回 None。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
_PROCESSING = "processing"
|
||||
_OUTCOMES = ("processed", "failed")
|
||||
|
||||
|
||||
def claim_trigger(path: Path) -> Path | None:
|
||||
"""原子领取一个 trigger 文件到同根 processing/ 目录。
|
||||
|
||||
Args:
|
||||
path: 根目录下的 trigger json 路径。
|
||||
Returns:
|
||||
领取后的 processing/ 内路径;文件不存在或已被他人领取时返回 None。
|
||||
"""
|
||||
processing_dir = path.parent / _PROCESSING
|
||||
try:
|
||||
processing_dir.mkdir(parents=True, exist_ok=True)
|
||||
claimed = processing_dir / path.name
|
||||
path.replace(claimed)
|
||||
return claimed
|
||||
except OSError:
|
||||
# Windows 下目标已存在(被另一 Worker 先领取)或文件已消失:放弃本个。
|
||||
return None
|
||||
|
||||
|
||||
def archive_trigger(claimed: Path, outcome: str) -> Path:
|
||||
"""把 processing/ 中已处理完的 trigger 归档到终态目录。
|
||||
|
||||
Args:
|
||||
claimed: claim_trigger 返回的 processing/ 内路径。
|
||||
outcome: 仅允许 'processed'(回调成功)或 'failed'(需人工排查)。
|
||||
Returns:
|
||||
归档后的完整路径。
|
||||
Raises:
|
||||
ValueError: outcome 非法,或 claimed 不在 processing/ 目录下。
|
||||
"""
|
||||
if outcome not in _OUTCOMES:
|
||||
raise ValueError(f"invalid trigger outcome: {outcome}")
|
||||
if claimed.parent.name != _PROCESSING:
|
||||
raise ValueError("trigger must be claimed into processing/ before archive")
|
||||
target_dir = claimed.parent.parent / outcome
|
||||
target_dir.mkdir(parents=True, exist_ok=True)
|
||||
target = target_dir / claimed.name
|
||||
claimed.replace(target)
|
||||
return target
|
||||
@@ -90,6 +90,7 @@ import worker_disk_cleanup # noqa: E402
|
||||
from download_artifact_fallback import ( # noqa: E402
|
||||
wait_for_new_download_file as _wait_for_new_download_file,
|
||||
)
|
||||
from trigger_consumer import claim_trigger # noqa: E402
|
||||
|
||||
# 测试与 smoke 向后兼容 re-export
|
||||
_maybe_auto_login_dsv = dsv_session.maybe_auto_login_dsv
|
||||
@@ -1550,7 +1551,7 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
|
||||
run_no = str(body.get("batch_run_no") or body.get("run_no") or trigger_path.stem).strip()
|
||||
task_no = str(body.get("task_no") or "").strip()
|
||||
sources = body.get("inventory_sources") or []
|
||||
failed_dir = trigger_path.parent / "failed"
|
||||
failed_dir = processed_dir.parent / "failed"
|
||||
# [DEBUG-TIMING] 批处理整体耗时基线:从进入 handler 到回调完成。
|
||||
batch_started_at = time.monotonic()
|
||||
print(f"[inventory-batch-timing] handler start run={run_no}")
|
||||
@@ -1862,7 +1863,7 @@ def _handle_inventory_trigger(trigger_path: Path, drop_dir: Path, processed_dir:
|
||||
_handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir)
|
||||
return
|
||||
task_no = str(body.get("task_no") or "").strip()
|
||||
failed_dir = trigger_path.parent / "failed"
|
||||
failed_dir = processed_dir.parent / "failed"
|
||||
if not task_no:
|
||||
print(f"[skip] invalid inventory trigger: {trigger_path.name}")
|
||||
trigger_path.unlink(missing_ok=True)
|
||||
@@ -2598,7 +2599,7 @@ def _handle_upload_trigger(trigger_path: Path, processed_dir: Path) -> None:
|
||||
file_path = str(body.get("file_path") or "").strip()
|
||||
attempt_id = body.get("attempt_id")
|
||||
callback_id = str(body.get("callback_id") or "").strip()
|
||||
failed_dir = trigger_path.parent / "failed"
|
||||
failed_dir = processed_dir.parent / "failed"
|
||||
if not task_no:
|
||||
trigger_path.unlink(missing_ok=True)
|
||||
return
|
||||
@@ -2686,11 +2687,16 @@ def _scan_triggers(trigger_dir: Path, handler, extra_args: tuple = ()) -> None:
|
||||
for path in sorted(trigger_dir.glob("*.json")):
|
||||
if not path.is_file():
|
||||
continue
|
||||
# 统一四态契约:先原子领取到 processing/ 再处理;被抢走/已消失则跳过,
|
||||
# 防止 Worker 重启或多实例部署时同一批 trigger 被重复导出、重复回调。
|
||||
claimed = claim_trigger(path)
|
||||
if claimed is None:
|
||||
continue
|
||||
rpa_heartbeat.set_worker_runtime_status("busy")
|
||||
try:
|
||||
handler(path, *extra_args)
|
||||
handler(claimed, *extra_args)
|
||||
except Exception as exc:
|
||||
print(f"[error] {path.name}: {exc}", file=sys.stderr)
|
||||
print(f"[error] {claimed.name}: {exc}", file=sys.stderr)
|
||||
finally:
|
||||
rpa_heartbeat.set_worker_runtime_status("idle")
|
||||
|
||||
|
||||
@@ -32,6 +32,7 @@ if _RPA_ROOT is not None:
|
||||
_sys.path.insert(0, _dir)
|
||||
|
||||
from rpa_common import browser_timeout_ms, click_text, env, select_or_fill # noqa: E402
|
||||
from trigger_consumer import archive_trigger, claim_trigger # noqa: E402
|
||||
import receipt_crane_export # noqa: E402
|
||||
import receipt_dbs_export # noqa: E402
|
||||
|
||||
@@ -200,24 +201,22 @@ def _process_units(body: dict[str, Any], drop_dir: Path) -> None:
|
||||
shutil.rmtree(profile_dir, ignore_errors=True)
|
||||
|
||||
|
||||
def _claim_and_process(path: Path, drop_dir: Path, processed_dir: Path, failed_dir: Path) -> None:
|
||||
"""原子领取一个 receipt trigger;成功归档 processed,callback 异常归档 failed。"""
|
||||
claimed_dir = path.parent / 'processing'
|
||||
claimed_dir.mkdir(parents=True, exist_ok=True)
|
||||
claimed = claimed_dir / path.name
|
||||
try:
|
||||
path.replace(claimed)
|
||||
except OSError:
|
||||
def _claim_and_process(path: Path, drop_dir: Path) -> None:
|
||||
"""原子领取一个 receipt trigger;成功归档 processed,异常归档 failed。
|
||||
|
||||
领取与归档统一走 common/trigger_consumer(四态目录契约),
|
||||
本函数只保留收料批次处理与 SystemExit 兜底。
|
||||
"""
|
||||
claimed = claim_trigger(path)
|
||||
if claimed is None:
|
||||
return
|
||||
try:
|
||||
_process_units(json.loads(claimed.read_text(encoding='utf-8')), drop_dir)
|
||||
processed_dir.mkdir(parents=True, exist_ok=True)
|
||||
claimed.replace(processed_dir / claimed.name)
|
||||
archive_trigger(claimed, 'processed')
|
||||
except (Exception, SystemExit):
|
||||
# SystemExit 也一并捕获:_require_dir 缺 env 会抛 SystemExit(非 Exception),
|
||||
# 若不捕获会静默退出进程、trigger 卡死在 processing/,无法归档到 failed/。
|
||||
failed_dir.mkdir(parents=True, exist_ok=True)
|
||||
claimed.replace(failed_dir / claimed.name)
|
||||
archive_trigger(claimed, 'failed')
|
||||
raise
|
||||
|
||||
|
||||
@@ -226,12 +225,11 @@ def main() -> None:
|
||||
drop_dir = _require_dir('SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR')
|
||||
trigger_dir = _require_dir('SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR')
|
||||
poll = max(1, int(env('SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS', '3') or '3'))
|
||||
processed_dir, failed_dir = trigger_dir / 'processed', trigger_dir / 'failed'
|
||||
print(f'[freight_receipt_rpa_worker] started trigger_dir={trigger_dir} drop_dir={drop_dir}')
|
||||
while True:
|
||||
for path in sorted(trigger_dir.glob('*.json')):
|
||||
try:
|
||||
_claim_and_process(path, drop_dir, processed_dir, failed_dir)
|
||||
_claim_and_process(path, drop_dir)
|
||||
except Exception as exc:
|
||||
print(f'[receipt-trigger] failed {path.name}: {exc}')
|
||||
time.sleep(poll)
|
||||
|
||||
Reference in new issue
Block a user