feat(rpa): 完善库存与吊车报表自动化运行配置
This commit is contained in:
1 parent
70dd0051b8
commit
7a9fac2f8a
8 files changed
+364
-55
No files matched your search
@@ -77,6 +77,8 @@ Hxops 与货代系统之间通过 **目录 + JSON 触发文件** 解耦,RPA
|
||||
| `SHIPPING_NOTICE_RPA_WORKER_ENVIRONMENT` | `test` / `prod`,须与后端 `ENV_NAME` 一致 |
|
||||
| `SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS` | 心跳间隔(默认 20s),test/prod 触发前检查依赖在线心跳 |
|
||||
| `SHIPPING_NOTICE_RPA_CREDENTIAL_KEY` | Profile 凭据 Fernet 主密钥;必须与对应环境后端一致,只能由 Secret 渠道或部署脚本安全注入 |
|
||||
| `SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE` | 库存导出是否复用浏览器登录 Profile,默认 `true`;上传任务不受影响 |
|
||||
| `SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE_TTL_HOURS` | 持久 Profile 最长保留小时数,默认 `24`;超时后清空目录并重新登录 |
|
||||
|
||||
|
||||
新部署只使用 `new_rpa_worker_secret.ps1` + `start_rpa_worker.ps1`:Secret 由 DPAPI 保护,环境变量只注入对应 Worker 子进程。
|
||||
@@ -85,10 +87,11 @@ Hxops 与货代系统之间通过 **目录 + JSON 触发文件** 解耦,RPA
|
||||
运行参数使用 `SHIPPING_NOTICE_RPA_WORKER_*`,Profile 凭据主密钥使用
|
||||
`SHIPPING_NOTICE_RPA_CREDENTIAL_KEY`。部署文档和启动脚本只使用上述规范命名。
|
||||
|
||||
DSV 库存导出默认每次使用一次性浏览器 Profile。确认只运行单个对应环境 Worker 后,可在
|
||||
`start_rpa_worker.ps1` 启动命令末尾增加 `-ReuseDsvSession`,使 DSV 专用
|
||||
`dsv360_session` Profile 跨任务保留登录态;Crane 与上传任务仍不复用。不要同时启动两个
|
||||
使用同一 WorkerRoot 的 Worker,浏览器会拒绝并发打开同一持久 Profile。
|
||||
DSV/Crane 库存导出默认复用浏览器 Profile(按 `connector + rpa_profile_code` 隔离目录,
|
||||
默认保留 24 小时)。同一 WorkerRoot 只跑一个 Worker,任务串行消费;会话过期或站点踢登
|
||||
仍回落现有登录流程。上传任务保持一次性 Profile。若需强制每次全新登录,启动时加
|
||||
`-NoSessionReuse`。旧参数 `-ReuseDsvSession` / `SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE`
|
||||
仍兼容,但请改用 `SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE`。
|
||||
|
||||
### DSV WMS Upload Tool
|
||||
|
||||
@@ -1592,7 +1595,7 @@ $env:SHIPPING_NOTICE_RPA_WORKER_CRANE_PASSWORD = "<Crane密码>"
|
||||
python scripts/rpa/inventory/inventory_rpa_worker.py
|
||||
```
|
||||
|
||||
说明:`SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR` 现在仅作为“运行时 profile 根目录”。每次库存导出都会在该目录下自动创建一个全新的临时子目录,并在任务结束后清理,不会复用任何已有 profile。
|
||||
说明:`SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR` 是浏览器 Profile 根目录。库存导出默认开启会话复用:目录形如 `{connector}__{rpa_profile_code}_session`,跨任务保留登录态,默认 TTL 24 小时(`SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE_TTL_HOURS`);关闭复用或上传任务仍使用 `run_*` 一次性子目录并在结束后清理。同一 WorkerRoot 不要并发启动第二个库存 Worker。
|
||||
|
||||
如果登录框默认识别不稳定,可覆盖登录 selector:
|
||||
|
||||
|
||||
@@ -2,18 +2,42 @@
|
||||
scripts/rpa/crane_report_export.py
|
||||
|
||||
用途:Crane On Hand Details Query 异步报表导出(Run Report → Schedule Report → Scheduled Reports 下载)。
|
||||
依赖:Playwright Page;由 freight_rpa_worker._export_crane_inventory_source 委托调用。
|
||||
逻辑:必须先 Run Report 产出查询结果,再 Schedule 异步导出;轮询仅在 scheduled-reports 路由进行。
|
||||
依赖:Playwright Page、download_artifact_fallback;由 inventory_rpa_worker._export_crane_inventory_source 委托调用。
|
||||
逻辑:必须先 Run Report 产出查询结果,再 Schedule 异步导出;轮询仅在 scheduled-reports 路由进行;
|
||||
expect_download 超时时按下载目录新文件做短窗口兜底(与 DSV 同模块,窗口更短)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys as _sys
|
||||
from pathlib import Path as _Path
|
||||
|
||||
_RPA_ROOT = next(
|
||||
(
|
||||
_c
|
||||
for _c in _Path(__file__).resolve().parents
|
||||
if (_c / "connectors").is_dir()
|
||||
and (_c / "common").is_dir()
|
||||
and (_c / "inventory").is_dir()
|
||||
and (_c / "receipt").is_dir()
|
||||
),
|
||||
None,
|
||||
)
|
||||
if _RPA_ROOT is not None:
|
||||
for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "inventory", "receipt"):
|
||||
_dir = str(_RPA_ROOT) if not _rel else str(_RPA_ROOT / _rel)
|
||||
if _dir not in _sys.path:
|
||||
_sys.path.insert(0, _dir)
|
||||
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from download_artifact_fallback import wait_for_new_download_file as _wait_for_new_download_file
|
||||
|
||||
# Schedule Report Description 默认取 UUID 前 12 位十六进制(无连字符)。
|
||||
# 48 bit ≈ 2.8e14 种组合,单租户 RPA 导出场景碰撞可忽略;页面示例多为 6~8 位人工填写。
|
||||
_CRANE_SCHEDULE_DESCRIPTION_HEX_LEN_DEFAULT = 12
|
||||
@@ -71,6 +95,8 @@ _CRANE_SCHEDULED_COL_DESCRIPTION = 2
|
||||
_CRANE_SCHEDULED_COL_DOWNLOAD = 3
|
||||
_CRANE_SCHEDULED_REPORT_NAME_DEFAULT = "OnHandDetails.xlsx"
|
||||
_CRANE_SCHEDULED_SCAN_MAX_ROWS_DEFAULT = 20
|
||||
# Playwright download 事件偶发丢失时,目录兜底窗口(人工下载约 2s;不必拉到 DSV 的 60s)。
|
||||
_CRANE_DOWNLOAD_DIR_FALLBACK_SECONDS = 15.0
|
||||
_CRANE_SESSION_MODULE: Any | None = None
|
||||
|
||||
|
||||
@@ -930,10 +956,24 @@ def _wait_and_click_scheduled_download(
|
||||
description: str = "",
|
||||
expected_report_name: str = _CRANE_SCHEDULED_REPORT_NAME_DEFAULT,
|
||||
entry_url: str = "",
|
||||
download_dir: str = "",
|
||||
) -> Any:
|
||||
"""
|
||||
轮询 Scheduled Reports 直至目标行 Download 列由 Submitted 变为 Download 并点击。
|
||||
核心逻辑:每 2s 读一次状态;每 10s goto 刷新列表;表格可见时不重登,避免闪回登录页。
|
||||
核心逻辑:每 2s 探测一次状态;每 10s goto 刷新列表;表格可见时不重登,避免闪回登录页;
|
||||
expect_download 超时且已配置 download_dir 时,短窗口扫描目录新文件兜底。
|
||||
|
||||
Args:
|
||||
page: Playwright 页面。
|
||||
env: 环境变量读取函数。
|
||||
browser_timeout_ms: 浏览器操作超时(亦用于 expect_download)。
|
||||
description: Schedule 时写入的 Description,用于定位行。
|
||||
expected_report_name: 期望的 Name 列文件名。
|
||||
entry_url: Crane 入口 URL,用于会话恢复。
|
||||
download_dir: worker 注入的浏览器 downloads_path;空则不做目录兜底。
|
||||
|
||||
Returns:
|
||||
Playwright Download 或 FilesystemDownloadArtifact。
|
||||
"""
|
||||
entry = entry_url or _default_crane_entry_url(None)
|
||||
wait_ms = int(env("SHIPPING_NOTICE_RPA_WORKER_CRANE_SCHEDULED_REPORT_WAIT_MS", "300000") or "300000")
|
||||
@@ -950,6 +990,7 @@ def _wait_and_click_scheduled_download(
|
||||
last_list_refresh = time.monotonic()
|
||||
poll_index = 0
|
||||
last_status = "not_found"
|
||||
drop_dir = str(download_dir or "").strip()
|
||||
|
||||
while time.monotonic() < deadline:
|
||||
poll_index += 1
|
||||
@@ -1005,15 +1046,44 @@ def _wait_and_click_scheduled_download(
|
||||
f"description={description!r} status={last_status!r} after~{elapsed}s polls={poll_index}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
with page.expect_download(timeout=click_timeout) as download_info:
|
||||
if not _click_locator(locator, browser_timeout_ms=click_timeout):
|
||||
raise RuntimeError(
|
||||
f"Crane scheduled report Download link click failed for description={description!r}"
|
||||
)
|
||||
print(
|
||||
f"[crane-export] download started name={expected_report_name!r} description={description!r}"
|
||||
)
|
||||
return download_info.value
|
||||
baseline_names: set[str] = set()
|
||||
if drop_dir:
|
||||
try:
|
||||
baseline_names = {path.name for path in Path(drop_dir).iterdir() if path.is_file()}
|
||||
except OSError:
|
||||
baseline_names = set()
|
||||
try:
|
||||
# [STEP] 主路径:Playwright download 事件
|
||||
with page.expect_download(timeout=click_timeout) as download_info:
|
||||
if not _click_locator(locator, browser_timeout_ms=click_timeout):
|
||||
raise RuntimeError(
|
||||
f"Crane scheduled report Download link click failed for description={description!r}"
|
||||
)
|
||||
print(
|
||||
f"[crane-export] download started name={expected_report_name!r} description={description!r}"
|
||||
)
|
||||
return download_info.value
|
||||
except RuntimeError:
|
||||
# 点击失败不走目录兜底,避免空等
|
||||
raise
|
||||
except Exception:
|
||||
# [STEP] 事件丢失/晚到:短窗口扫 downloads_path(与 DSV 同模块)
|
||||
if not drop_dir:
|
||||
raise
|
||||
fallback = _wait_for_new_download_file(
|
||||
download_dir=drop_dir,
|
||||
baseline_names=baseline_names,
|
||||
timeout_seconds=_CRANE_DOWNLOAD_DIR_FALLBACK_SECONDS,
|
||||
)
|
||||
if fallback is None:
|
||||
raise
|
||||
print(
|
||||
"[crane-download-fallback] "
|
||||
f"using downloaded file from directory because Playwright download event timed out: "
|
||||
f"{fallback.suggested_filename}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return fallback
|
||||
|
||||
loop_elapsed_ms = int((time.monotonic() - loop_started) * 1000)
|
||||
remaining = int(deadline - time.monotonic())
|
||||
@@ -1091,11 +1161,12 @@ def export_crane_inventory_report(
|
||||
) -> Any:
|
||||
"""
|
||||
导出 Crane 库存报表。
|
||||
核心逻辑:Run Report(等待结果)→ Schedule Report(填 Description)→ Scheduled Reports 按 Description 下载。
|
||||
核心逻辑:Run Report(等待结果)→ Schedule Report(填 Description)→ Scheduled Reports 按 Description 下载;
|
||||
下载时 expect_download 失败则按 source.__download_dir 短窗口目录兜底。
|
||||
|
||||
Args:
|
||||
page: Playwright 页面。
|
||||
source: rpa_inventory_source 配置。
|
||||
source: rpa_inventory_source 配置(可含 worker 注入的 __download_dir)。
|
||||
env: 环境变量读取函数。
|
||||
browser_timeout_ms: 浏览器操作超时。
|
||||
select_or_fill: worker 提供的下拉/输入填充函数。
|
||||
@@ -1103,7 +1174,7 @@ def export_crane_inventory_report(
|
||||
trigger: inventory_export / batch trigger,用于生成唯一 Description。
|
||||
|
||||
Returns:
|
||||
Playwright Download 对象。
|
||||
Playwright Download 或 FilesystemDownloadArtifact。
|
||||
"""
|
||||
download_mode = _resolve_download_mode(source, env=env)
|
||||
entry_url = _default_crane_entry_url(source)
|
||||
@@ -1150,7 +1221,6 @@ def export_crane_inventory_report(
|
||||
browser_timeout_ms=browser_timeout_ms,
|
||||
entry_url=entry_url,
|
||||
)
|
||||
wait_ms = int(env("SHIPPING_NOTICE_RPA_WORKER_CRANE_SCHEDULED_REPORT_WAIT_MS", "300000") or "300000")
|
||||
return _wait_and_click_scheduled_download(
|
||||
page,
|
||||
env=env,
|
||||
@@ -1158,6 +1228,7 @@ def export_crane_inventory_report(
|
||||
description=schedule_description,
|
||||
expected_report_name=scheduled_report_name,
|
||||
entry_url=entry_url,
|
||||
download_dir=str(source.get("__download_dir") or ""),
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -19,7 +19,9 @@ Optional:
|
||||
SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS=3
|
||||
SHIPPING_NOTICE_RPA_WORKER_SAMPLE_INVENTORY=path/to/sample.xlsx
|
||||
SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR=data/shipping_notice/freight_rpa/browser_profile
|
||||
SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE=false
|
||||
SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE=true
|
||||
SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE_TTL_HOURS=24
|
||||
# legacy alias: SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE
|
||||
SHIPPING_NOTICE_RPA_WORKER_HEADLESS=false
|
||||
SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL=msedge
|
||||
SHIPPING_NOTICE_RPA_WORKER_BROWSER_EXECUTABLE_PATH=C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe
|
||||
@@ -852,22 +854,209 @@ def _export_crane_inventory_source(page: Any, trigger: dict[str, Any], source: d
|
||||
)
|
||||
|
||||
|
||||
_SESSION_META_FILENAME = ".hxops_rpa_session_meta.json"
|
||||
|
||||
|
||||
def _session_reuse_enabled() -> bool:
|
||||
"""
|
||||
返回库存导出是否复用持久浏览器 Profile。
|
||||
|
||||
核心逻辑:优先读 `SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE`;未设置时回落旧名
|
||||
`SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE`;两者皆未设置时默认开启,避免同账号
|
||||
重复 RPA 每次重新登录。上传任务仍由调用方传 `reuse_session=False` 强制一次性目录。
|
||||
"""
|
||||
raw = os.getenv("SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE")
|
||||
if raw is None:
|
||||
legacy = os.getenv("SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE")
|
||||
if legacy is not None:
|
||||
return str(legacy).strip().strip("\"'").lower() == "true"
|
||||
return True
|
||||
return str(raw).strip().strip("\"'").lower() == "true"
|
||||
|
||||
|
||||
def _dsv_session_reuse_enabled() -> bool:
|
||||
"""返回是否显式允许 DSV 库存导出复用受控浏览器会话。"""
|
||||
return _env("SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE", "false").lower() == "true"
|
||||
"""兼容旧测试/调用名;语义同 `_session_reuse_enabled`。"""
|
||||
return _session_reuse_enabled()
|
||||
|
||||
|
||||
def _session_reuse_ttl_seconds() -> int:
|
||||
"""
|
||||
返回持久 Profile 最长保留秒数。
|
||||
|
||||
核心逻辑:读取 `SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE_TTL_HOURS`,默认 24 小时;
|
||||
下限 1 小时,避免误配成 0 导致每次都重建。
|
||||
"""
|
||||
raw = _env("SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE_TTL_HOURS", "24") or "24"
|
||||
try:
|
||||
hours = int(raw)
|
||||
except ValueError:
|
||||
hours = 24
|
||||
return max(1, hours) * 3600
|
||||
|
||||
|
||||
def _sanitize_profile_dir_segment(value: str) -> str:
|
||||
"""
|
||||
将 connector / RPA Profile 编码成可作目录名的安全片段。
|
||||
|
||||
Args:
|
||||
value: 原始 connector_type 或 rpa_profile_code。
|
||||
|
||||
Returns:
|
||||
str: 仅保留字母数字与 `-_`,空值回落 `default`,最长 96 字符。
|
||||
"""
|
||||
text = str(value or "").strip()
|
||||
cleaned = "".join(ch if (ch.isalnum() or ch in "-_") else "_" for ch in text)
|
||||
return (cleaned[:96] or "default")
|
||||
|
||||
|
||||
def _session_profile_dir(connector_type: str, profile_code: str = "") -> Path:
|
||||
"""
|
||||
返回按连接器与 RPA 账号隔离的持久 Profile 目录。
|
||||
|
||||
核心逻辑:目录形如 `{connector}__{profile_code}_session`,不同货代账号绝不共用;
|
||||
若仍存在历史 `dsv360_session` 且目标目录尚未创建、profile 为 default,则沿用旧目录
|
||||
以保留已有登录态,待 TTL 过期后自然重建到新命名。
|
||||
|
||||
Args:
|
||||
connector_type: Worker 连接器名(如 dsv360 / crane_footprint)。
|
||||
profile_code: 平台 RPA Profile 编码;缺省时用 default。
|
||||
|
||||
Returns:
|
||||
Path: 持久 profile 目录路径(未必已存在)。
|
||||
"""
|
||||
connector = _sanitize_profile_dir_segment(connector_type or "unknown")
|
||||
code = _sanitize_profile_dir_segment(profile_code)
|
||||
target = _browser_profile_root() / f"{connector}__{code}_session"
|
||||
legacy = _browser_profile_root() / "dsv360_session"
|
||||
if (
|
||||
connector == "dsv360"
|
||||
and code == "default"
|
||||
and not target.exists()
|
||||
and legacy.exists()
|
||||
):
|
||||
return legacy
|
||||
return target
|
||||
|
||||
|
||||
def _dsv_session_profile_dir() -> Path:
|
||||
"""返回 DSV 专用持久 profile;该目录不得与其他货代任务共用。"""
|
||||
return _browser_profile_root() / "dsv360_session"
|
||||
"""兼容旧调用:返回 default DSV 持久 profile 路径。"""
|
||||
return _session_profile_dir("dsv360", "default")
|
||||
|
||||
|
||||
def _read_session_meta(profile_dir: Path) -> dict[str, Any]:
|
||||
"""读取持久 Profile 元数据;损坏或缺失时返回空 dict。"""
|
||||
meta_path = profile_dir / _SESSION_META_FILENAME
|
||||
if not meta_path.is_file():
|
||||
return {}
|
||||
try:
|
||||
payload = json.loads(meta_path.read_text(encoding="utf-8"))
|
||||
except (OSError, json.JSONDecodeError):
|
||||
return {}
|
||||
return payload if isinstance(payload, dict) else {}
|
||||
|
||||
|
||||
def _write_session_meta(
|
||||
profile_dir: Path,
|
||||
*,
|
||||
connector_type: str,
|
||||
profile_code: str,
|
||||
created_at_unix: float | None = None,
|
||||
) -> None:
|
||||
"""写入或刷新持久 Profile 元数据(创建时间保留,刷新 last_used)。"""
|
||||
now = time.time()
|
||||
created = float(created_at_unix) if created_at_unix is not None else now
|
||||
payload = {
|
||||
"created_at_unix": created,
|
||||
"created_at": datetime.fromtimestamp(created, tz=UTC).isoformat(),
|
||||
"last_used_at_unix": now,
|
||||
"last_used_at": datetime.fromtimestamp(now, tz=UTC).isoformat(),
|
||||
"connector_type": connector_type,
|
||||
"profile_code": profile_code,
|
||||
"ttl_hours": max(1, _session_reuse_ttl_seconds() // 3600),
|
||||
}
|
||||
meta_path = profile_dir / _SESSION_META_FILENAME
|
||||
meta_path.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
|
||||
|
||||
def _prepare_reusable_session_profile(
|
||||
profile_dir: Path,
|
||||
*,
|
||||
connector_type: str,
|
||||
profile_code: str,
|
||||
) -> Path:
|
||||
"""
|
||||
准备可复用 Profile 目录:超 TTL 则清空重建,否则刷新 last_used。
|
||||
|
||||
核心逻辑:以 meta 的 `created_at_unix` 起算;无 meta 时用目录 mtime。超过
|
||||
`SESSION_REUSE_TTL_HOURS`(默认 24h)则整目录删除后重建,迫使重新登录。
|
||||
|
||||
Args:
|
||||
profile_dir: 目标持久目录。
|
||||
connector_type: 连接器名,写入 meta。
|
||||
profile_code: RPA Profile 编码,写入 meta。
|
||||
|
||||
Returns:
|
||||
Path: 已确保存在且未过期的 profile 目录。
|
||||
"""
|
||||
ttl_seconds = _session_reuse_ttl_seconds()
|
||||
now = time.time()
|
||||
if profile_dir.exists():
|
||||
meta = _read_session_meta(profile_dir)
|
||||
created_at = meta.get("created_at_unix")
|
||||
try:
|
||||
created_ts = float(created_at) if created_at is not None else profile_dir.stat().st_mtime
|
||||
except (TypeError, ValueError, OSError):
|
||||
created_ts = now
|
||||
age_seconds = max(0.0, now - created_ts)
|
||||
if age_seconds >= ttl_seconds:
|
||||
print(
|
||||
"[browser] session_reuse expired "
|
||||
f"ageHours={age_seconds / 3600:.1f} ttlHours={ttl_seconds / 3600:.0f} "
|
||||
f"dir={profile_dir.name!r}; recreating"
|
||||
)
|
||||
shutil.rmtree(profile_dir, ignore_errors=True)
|
||||
profile_dir.mkdir(parents=True, exist_ok=True)
|
||||
_write_session_meta(
|
||||
profile_dir,
|
||||
connector_type=connector_type,
|
||||
profile_code=profile_code,
|
||||
created_at_unix=now,
|
||||
)
|
||||
return profile_dir
|
||||
profile_dir.mkdir(parents=True, exist_ok=True)
|
||||
_write_session_meta(
|
||||
profile_dir,
|
||||
connector_type=connector_type,
|
||||
profile_code=profile_code,
|
||||
created_at_unix=created_ts,
|
||||
)
|
||||
return profile_dir
|
||||
profile_dir.mkdir(parents=True, exist_ok=True)
|
||||
_write_session_meta(
|
||||
profile_dir,
|
||||
connector_type=connector_type,
|
||||
profile_code=profile_code,
|
||||
created_at_unix=now,
|
||||
)
|
||||
return profile_dir
|
||||
|
||||
|
||||
def _is_reusable_session_profile_dir(profile_dir: Path) -> bool:
|
||||
"""判断目录是否为应跨任务保留的持久 Profile(非 run_* 临时目录)。"""
|
||||
name = profile_dir.name
|
||||
if name.startswith("run_"):
|
||||
return False
|
||||
if name.endswith("_session"):
|
||||
return True
|
||||
return (profile_dir / _SESSION_META_FILENAME).is_file()
|
||||
|
||||
|
||||
def _should_cleanup_browser_profile(profile_dir: Path) -> bool:
|
||||
"""
|
||||
判断关闭浏览器后是否可删除本次 profile。
|
||||
|
||||
核心逻辑:仅显式开启的 DSV 固定会话目录需要跨任务保留;其余目录都是
|
||||
`_open_browser` 创建的一次性运行目录,应由调用方清理。
|
||||
核心逻辑:持久会话目录(`*_session` 或含 meta)跨任务保留;`run_*` 一次性目录
|
||||
由调用方清理。
|
||||
|
||||
Args:
|
||||
profile_dir: 已传给 Playwright persistent context 的 profile 目录。
|
||||
@@ -875,40 +1064,64 @@ def _should_cleanup_browser_profile(profile_dir: Path) -> bool:
|
||||
Returns:
|
||||
bool: 为 True 时调用方可安全删除该目录。
|
||||
"""
|
||||
return profile_dir.resolve() != _dsv_session_profile_dir().resolve()
|
||||
return not _is_reusable_session_profile_dir(profile_dir)
|
||||
|
||||
|
||||
def _open_browser(download_dir: Path, *, reuse_dsv_session: bool = False):
|
||||
def _source_rpa_profile_code(source: dict[str, Any] | None) -> str:
|
||||
"""从库存 source 提取 RPA Profile 编码,缺省回落 source_code。"""
|
||||
if not isinstance(source, dict):
|
||||
return ""
|
||||
return str(source.get("rpa_profile_code") or source.get("source_code") or "").strip()
|
||||
|
||||
|
||||
def _open_browser(
|
||||
download_dir: Path,
|
||||
*,
|
||||
reuse_session: bool = False,
|
||||
connector_type: str = "",
|
||||
profile_code: str = "",
|
||||
reuse_dsv_session: bool | None = None,
|
||||
):
|
||||
"""
|
||||
打开用于库存 RPA 导出的浏览器上下文。
|
||||
打开用于库存 / 上传 RPA 的浏览器上下文。
|
||||
|
||||
核心逻辑:默认创建一次性的运行时 profile 子目录。仅当调用方明确为 DSV
|
||||
库存导出请求会话复用,且 `SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE=true` 时,
|
||||
才使用独立的固定 `dsv360_session` 目录;其他货代任务绝不复用该会话。
|
||||
核心逻辑:库存导出在 `reuse_session=True` 且 `SESSION_REUSE` 开启时,使用
|
||||
`{connector}__{profile_code}_session` 持久目录并按 TTL 失效重建;关闭复用或上传
|
||||
任务则创建 `run_*` 一次性目录。会话失效仍由各 connector 登录流程兜底。
|
||||
|
||||
Args:
|
||||
download_dir: 当前导出任务的下载目录,浏览器下载结果会先落到这里。
|
||||
reuse_dsv_session: 仅 DSV 库存调用可传 True;环境开关关闭时仍使用临时目录。
|
||||
download_dir: 当前任务下载目录,浏览器 downloads_path 指向此处。
|
||||
reuse_session: 调用方是否请求复用(库存 True,上传 False)。
|
||||
connector_type: 连接器名,用于隔离持久目录。
|
||||
profile_code: RPA 账号编码,用于隔离持久目录。
|
||||
reuse_dsv_session: 旧参数别名;若传入则覆盖 `reuse_session`。
|
||||
|
||||
Returns:
|
||||
tuple: `(playwright, context, page, runtime_profile_dir)`,其中 `runtime_profile_dir`
|
||||
为本次执行使用的 profile 目录。调用方必须用
|
||||
tuple: `(playwright, context, page, runtime_profile_dir)`。调用方须用
|
||||
`_should_cleanup_browser_profile` 决定是否清理。
|
||||
"""
|
||||
if reuse_dsv_session is not None:
|
||||
reuse_session = bool(reuse_dsv_session)
|
||||
sync_playwright, _timeout = _require_playwright()
|
||||
playwright = sync_playwright().start()
|
||||
profile_root = _browser_profile_root()
|
||||
profile_root.mkdir(parents=True, exist_ok=True)
|
||||
use_reused_dsv_session = reuse_dsv_session and _dsv_session_reuse_enabled()
|
||||
runtime_profile_dir = (
|
||||
_dsv_session_profile_dir()
|
||||
if use_reused_dsv_session
|
||||
else Path(tempfile.mkdtemp(prefix="run_", dir=str(profile_root)))
|
||||
)
|
||||
use_reused_session = bool(reuse_session) and _session_reuse_enabled() and bool(connector_type)
|
||||
if use_reused_session:
|
||||
runtime_profile_dir = _prepare_reusable_session_profile(
|
||||
_session_profile_dir(connector_type, profile_code),
|
||||
connector_type=connector_type,
|
||||
profile_code=profile_code or "default",
|
||||
)
|
||||
profile_mode = "session_reuse"
|
||||
else:
|
||||
runtime_profile_dir = Path(tempfile.mkdtemp(prefix="run_", dir=str(profile_root)))
|
||||
profile_mode = "temporary"
|
||||
runtime_profile_dir.mkdir(parents=True, exist_ok=True)
|
||||
print(
|
||||
"[browser] profile_mode="
|
||||
f"{'dsv_session_reuse' if use_reused_dsv_session else 'temporary'}"
|
||||
f"{profile_mode} connector={connector_type or '-'} profile={profile_code or '-'} "
|
||||
f"dir={runtime_profile_dir.name!r}"
|
||||
)
|
||||
headless = _env("SHIPPING_NOTICE_RPA_WORKER_HEADLESS", "false").lower() == "true"
|
||||
channel = _env("SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL")
|
||||
@@ -962,7 +1175,9 @@ def _download_inventory_with_browser(trigger: dict[str, Any], drop_dir: Path) ->
|
||||
try:
|
||||
playwright, context, page, runtime_profile_dir = _open_browser(
|
||||
drop_dir,
|
||||
reuse_dsv_session=connector_type == "dsv360",
|
||||
reuse_session=True,
|
||||
connector_type=connector_type,
|
||||
profile_code=_source_rpa_profile_code(source),
|
||||
)
|
||||
with _profile_credentials(source):
|
||||
if connector_type == "dsv360":
|
||||
@@ -1278,7 +1493,9 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
|
||||
try:
|
||||
playwright, context, page, runtime_profile_dir = _open_browser(
|
||||
drop_dir,
|
||||
reuse_dsv_session=site == "dsv360",
|
||||
reuse_session=True,
|
||||
connector_type=site,
|
||||
profile_code=_profile_code,
|
||||
)
|
||||
if site not in {"dsv360", "crane_footprint"}:
|
||||
raise RuntimeError(f"unsupported connector_type: {site}")
|
||||
@@ -2136,7 +2353,11 @@ def _upload_shipment_with_browser(
|
||||
playwright = context = runtime_profile_dir = None
|
||||
failed = False
|
||||
try:
|
||||
playwright, context, page, runtime_profile_dir = _open_browser(file_path.parent)
|
||||
# 上传保持一次性 Profile,避免与库存持久登录态互相污染。
|
||||
playwright, context, page, runtime_profile_dir = _open_browser(
|
||||
file_path.parent,
|
||||
reuse_session=False,
|
||||
)
|
||||
with _profile_credentials(upload_source):
|
||||
return adapter.run(page, login_url=login_url)
|
||||
except Exception:
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
每个环境必须有独立 root、scope、共享目录、browser profile、日志和 DPAPI Secret 文件。
|
||||
DSV/Crane 登录地址、账号和密码来自 HXOPS trigger 的 credential_envelope,
|
||||
不从本机 Secret 文件读取。
|
||||
默认开启库存会话复用(SESSION_REUSE + 24h TTL);需要每次全新登录时传 -NoSessionReuse。
|
||||
#>
|
||||
param(
|
||||
[Parameter(Mandatory = $true)]
|
||||
@@ -26,6 +27,10 @@ param(
|
||||
[string]$PythonExe = "python.exe",
|
||||
[switch]$Mock,
|
||||
[switch]$Headless,
|
||||
# 默认开启库存会话复用;仅在需要强制每次全新登录时传 -NoSessionReuse。
|
||||
[switch]$NoSessionReuse,
|
||||
# 兼容旧文档:等价于开启复用(现在默认已开启)。
|
||||
[switch]$ReuseSession,
|
||||
[switch]$ReuseDsvSession
|
||||
)
|
||||
|
||||
@@ -60,6 +65,12 @@ foreach ($required in @("ToolApiKey", "CredentialKey")) {
|
||||
}
|
||||
}
|
||||
|
||||
# 库存 Profile 默认按 connector+rpa_profile 复用,TTL 24h;-NoSessionReuse 可关闭。
|
||||
$sessionReuse = if ($NoSessionReuse) { "false" } else { "true" }
|
||||
if ($ReuseSession -or $ReuseDsvSession) {
|
||||
$sessionReuse = "true"
|
||||
}
|
||||
|
||||
# 只设置当前 launcher 及其 Worker 子进程可见的环境变量;不写 User/Machine 持久配置。
|
||||
$processVars = [ordered]@{
|
||||
HXOPS_API_BASE = $ApiBase
|
||||
@@ -70,8 +81,8 @@ $processVars = [ordered]@{
|
||||
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS = "20"
|
||||
SHIPPING_NOTICE_RPA_WORKER_MOCK = $(if ($Mock) { "true" } else { "false" })
|
||||
SHIPPING_NOTICE_RPA_WORKER_HEADLESS = $(if ($Headless) { "true" } else { "false" })
|
||||
# 仅显式启用时让 DSV 库存任务复用专属 profile;默认继续使用一次性会话。
|
||||
SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE = $(if ($ReuseDsvSession) { "true" } else { "false" })
|
||||
SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE = $sessionReuse
|
||||
SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE_TTL_HOURS = "24"
|
||||
SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL = "msedge"
|
||||
SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS = "3"
|
||||
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR = Join-Path $dataRoot "inventory_triggers"
|
||||
|
||||
Reference in new issue
Block a user