Files
syops/scripts/freight_rpa/common/download_artifact_fallback.py
T
hugo c3eef5cf20 feat(rpa): 恢复FREIGHT_RPA命名空间统一运行目录并完成收料部署对齐与readiness加固
- AGENTS.md §8.1 红线改写:env 命名空间恢复 FREIGHT_RPA_*,SHIPPING_NOTICE_RPA_* 一刀切废弃、不设兼容层
- 全仓机械前缀替换(70 文件)并删除兼容层;4 个既有基线测试失败一并清零(过期桩/存储隔离/排程 fail-fast 接线)
- 运行期数据目录统一 freight_rpa/{inventory,receipt,common}:settings 默认、4 个 env、2 个 ps1 三侧一致
- 代码目录 scripts/rpa 更名 scripts/freight_rpa 与数据根对齐;全仓路径引用同步,README 部署走查与升级小节
- 收料部署对齐库存:计划任务注册脚本(独立任务名)、可选 -SessionReuse 会话复用、DSV 老别名链移除
- readiness 加固:排程离线立即 failed(不挂 awaiting);无 Redis 时追加进程内存储原因码与本地测试指引
- DSV 会话准备遇 SSO 重定向中止时改走自动登录,首源不再因未登录判死
2026-09-19 09:49:25 +08:00

77 lines
2.7 KiB
Python

"""
scripts/freight_rpa/download_artifact_fallback.py
用途:在浏览器实际已落盘但 Playwright Download 句柄不可用时,按下载目录中的新文件构造兼容适配器。
依赖:pathlib、shutil、time。
逻辑:DSV/Crane 在 expect_download 超时后调用;库存 worker 在 Download.save_as 因浏览器关闭失败时同样调用。
"""
from __future__ import annotations
import shutil
import time
from pathlib import Path
class FilesystemDownloadArtifact:
"""兼容 Playwright Download 的最小适配器,仅提供 `suggested_filename` 与 `save_as()`。"""
def __init__(self, path: Path) -> None:
self._path = Path(path)
self.suggested_filename = self._path.name
def save_as(self, dest: str) -> None:
target = Path(dest)
target.parent.mkdir(parents=True, exist_ok=True)
if self._path.resolve() == target.resolve():
return
shutil.move(str(self._path), str(target))
def wait_for_new_download_file(
*,
download_dir: str | Path,
baseline_names: set[str],
timeout_seconds: float = 12.0,
poll_seconds: float = 0.5,
) -> FilesystemDownloadArtifact | None:
"""
等待下载目录里出现本次新生成且大小稳定的文件。
核心逻辑:忽略 `.crdownload/.tmp` 等临时文件;优先接受 Excel/CSV 类产物,
同时兼容 Chromium 在 `downloads_path` 中落下的无扩展名原始文件;
连续两次观察到大小不变后,认为浏览器已完成落盘。
"""
root = Path(download_dir)
if not root.is_dir():
return None
deadline = time.monotonic() + max(1.0, timeout_seconds)
stable_sizes: dict[Path, int] = {}
allowed_suffixes = {".xlsx", ".xls", ".xlsm", ".xltx", ".xltm", ".csv", ""}
transient_suffixes = {".crdownload", ".tmp", ".part"}
while time.monotonic() < deadline:
candidates = []
for path in root.iterdir():
if not path.is_file():
continue
if path.name in baseline_names:
continue
suffix = path.suffix.lower()
if suffix in transient_suffixes or suffix not in allowed_suffixes:
continue
candidates.append(path)
candidates.sort(key=lambda item: item.stat().st_mtime, reverse=True)
for path in candidates:
try:
size = path.stat().st_size
except OSError:
continue
last_size = stable_sizes.get(path)
if last_size is not None and last_size == size and size > 0:
return FilesystemDownloadArtifact(path)
stable_sizes[path] = size
time.sleep(max(0.1, poll_seconds))
return None