feat(rpa): 完善库存与吊车报表自动化运行配置
This commit is contained in:
1 parent
70dd0051b8
commit
7a9fac2f8a
8 files changed
+364
-55
No files matched your search
@@ -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