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 重定向中止时改走自动登录,首源不再因未登录判死
This commit is contained in:
1 parent
95488db656
commit
c3eef5cf20
90 files changed
+2022
-1463
No files matched your search
@@ -0,0 +1,76 @@
|
||||
"""
|
||||
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
|
||||
@@ -0,0 +1,43 @@
|
||||
<#
|
||||
.SYNOPSIS
|
||||
为同一 Windows 用户下的 RPA Worker 创建当前用户可解密的 Secret 文件。
|
||||
|
||||
.DESCRIPTION
|
||||
Secret 文件使用 PowerShell SecureString/Windows DPAPI 保存,不能被其他用户直接解密。
|
||||
启动脚本只在 Worker 子进程中设置 Process 级环境变量,不写入 User/Machine 环境变量。
|
||||
Secret 文件应保存在仓库之外,例如 C:\HxopsRpaSecrets\test.xml。
|
||||
DSV/Crane 登录地址、账号和密码不在本文件中保存;它们由 HXOPS RPA Profile
|
||||
配置并随加密 credential_envelope 进入 trigger,Worker 使用 CredentialKey 解密。
|
||||
#>
|
||||
param(
|
||||
[Parameter(Mandatory = $true)]
|
||||
[ValidateSet("test", "prod")]
|
||||
[string]$Environment,
|
||||
|
||||
[string]$OutputRoot = "C:\HxopsRpaSecrets"
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
$secretPath = Join-Path $OutputRoot ("{0}.xml" -f $Environment)
|
||||
New-Item -ItemType Directory -Force -Path $OutputRoot | Out-Null
|
||||
|
||||
function Read-RequiredSecret {
|
||||
param([Parameter(Mandatory = $true)][string]$Prompt)
|
||||
$value = Read-Host $Prompt -AsSecureString
|
||||
if (-not $value -or $value.Length -eq 0) {
|
||||
throw "$Prompt 不能为空"
|
||||
}
|
||||
return $value
|
||||
}
|
||||
|
||||
$record = [pscustomobject]@{
|
||||
ToolApiKey = Read-RequiredSecret "请输入 $Environment 环境 SHIPPING_NOTICE_TOOL_API_KEY"
|
||||
CredentialKey = Read-RequiredSecret "请输入 $Environment 环境 FREIGHT_RPA_CREDENTIAL_KEY"
|
||||
}
|
||||
|
||||
$record | Export-Clixml -LiteralPath $secretPath
|
||||
$currentUser = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
|
||||
icacls $secretPath /inheritance:r /grant:r "${currentUser}:F" | Out-Null
|
||||
|
||||
Write-Host "Secret 文件已创建:$secretPath"
|
||||
Write-Host "仅当前 Windows 用户可解密;不要复制到其他账号、提交 Git 或写入日志。"
|
||||
@@ -0,0 +1,481 @@
|
||||
"""
|
||||
scripts/freight_rpa/rpa_common.py
|
||||
|
||||
用途:RPA worker 与 DSV/Crane driver 共用的浏览器与环境变量工具。
|
||||
依赖:标准库、Playwright(运行时)。
|
||||
逻辑:由 freight_rpa_worker、dsv_*、crane_* 导入。
|
||||
"""
|
||||
|
||||
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 json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
from typing import Any, TextIO
|
||||
|
||||
|
||||
def _emit_debug_event(run_id: str, hypothesis_id: str, location: str, msg: str, data: dict[str, Any] | None = None) -> None:
|
||||
"""惰性委托 dsv_debug.emit_debug_event,避免 rpa_common ↔ dsv_debug 循环导入。"""
|
||||
try:
|
||||
from dsv_debug import emit_debug_event
|
||||
|
||||
emit_debug_event(run_id, hypothesis_id, location, msg, data)
|
||||
except Exception:
|
||||
return
|
||||
|
||||
|
||||
def _env(name: str, default: str = "") -> str:
|
||||
"""
|
||||
读取 RPA 环境变量,并去除首尾空白与最外层成对引号。
|
||||
|
||||
核心逻辑:直接读取规范名称;历史 SHIPPING_NOTICE_RPA_* 前缀已于
|
||||
2026-09-18 一刀切废弃,不再提供任何别名兼容。
|
||||
|
||||
Args:
|
||||
name: 规范环境变量名(FREIGHT_RPA_*)。
|
||||
default: 未设置时的默认值。
|
||||
|
||||
Returns:
|
||||
str: 去除空白与外层成对引号后的环境变量值。
|
||||
"""
|
||||
value = str(os.getenv(name, default) or default).strip()
|
||||
if len(value) >= 2 and (
|
||||
(value.startswith('"') and value.endswith('"'))
|
||||
or (value.startswith("'") and value.endswith("'"))
|
||||
):
|
||||
return value[1:-1]
|
||||
return value
|
||||
|
||||
|
||||
def _browser_timeout_ms() -> int:
|
||||
return max(5_000, int(_env("FREIGHT_RPA_WORKER_BROWSER_TIMEOUT_MS", "60000") or "60000"))
|
||||
|
||||
def _click_text(page: Any, text: str, *, exact: bool = True, timeout_ms: int | None = None) -> None:
|
||||
timeout = timeout_ms if timeout_ms is not None else _browser_timeout_ms()
|
||||
text_literal = json.dumps(text)
|
||||
for selector in (
|
||||
f"a.dropdown-item:has-text({text_literal})",
|
||||
f".dropdown-item:has-text({text_literal})",
|
||||
f"button:has-text({text_literal})",
|
||||
f'[role="button"]:has-text({text_literal})',
|
||||
f"a:has-text({text_literal})",
|
||||
f"li:has-text({text_literal})",
|
||||
f"div.device-type:has-text({text_literal})",
|
||||
):
|
||||
locator = page.locator(selector).first
|
||||
try:
|
||||
locator.click(timeout=3_000)
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
locator.click(timeout=3_000, force=True)
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
for role in ("button", "link"):
|
||||
try:
|
||||
page.get_by_role(role, name=text, exact=exact).first.click(timeout=3_000)
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
locator = page.get_by_text(text, exact=False).first
|
||||
try:
|
||||
locator.click(timeout=min(timeout, 3_000))
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
locator.click(timeout=min(timeout, 3_000), force=True)
|
||||
|
||||
|
||||
def _click_selector_or_text(page: Any, selector_env: str, fallback_text: str | None = None) -> None:
|
||||
selector = _env(selector_env)
|
||||
if selector:
|
||||
page.locator(selector).first.click(timeout=_browser_timeout_ms())
|
||||
return
|
||||
if selector_env == "FREIGHT_RPA_WORKER_DSV_VIEW_REPORT_SELECTOR":
|
||||
for view_selector in (
|
||||
'input[type="submit"][value="View Report"]',
|
||||
'button:has-text("View Report")',
|
||||
'.btn:has-text("View Report")',
|
||||
'input[value="View Report"]',
|
||||
'[role="button"]:has-text("View Report")',
|
||||
):
|
||||
try:
|
||||
locator = page.locator(view_selector).first
|
||||
locator.wait_for(state="visible", timeout=30_000)
|
||||
locator.evaluate("(node) => node.click()")
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
if fallback_text:
|
||||
_click_text(page, fallback_text, exact=True)
|
||||
return
|
||||
raise RuntimeError(f"Missing selector env: {selector_env}")
|
||||
|
||||
|
||||
def _fill_selector_or_label(page: Any, selector_env: str, label: str, value: str | None) -> None:
|
||||
text = str(value or "").strip()
|
||||
if not text:
|
||||
return
|
||||
selector = _env(selector_env)
|
||||
locator = page.locator(selector).first if selector else page.get_by_label(label).first
|
||||
try:
|
||||
current = str(locator.input_value(timeout=3_000) or "").strip()
|
||||
if current == text:
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
locator.fill(text, timeout=_browser_timeout_ms())
|
||||
|
||||
|
||||
def _fill_dsv_filter_if_needed(page: Any, selector_env: str, label: str, value: str | None) -> None:
|
||||
"""委托 dsv_report_parameters 按 SSRS 控件类型填充报表参数。"""
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
|
||||
module_path = _RPA_ROOT / "connectors" / "dsv" / "dsv_report_parameters.py"
|
||||
spec = importlib.util.spec_from_file_location("dsv_report_parameters_runtime", module_path)
|
||||
assert spec and spec.loader
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
module.fill_dsv_filter_if_needed(
|
||||
page,
|
||||
selector_env,
|
||||
label,
|
||||
value,
|
||||
env=_env,
|
||||
browser_timeout_ms=_browser_timeout_ms,
|
||||
debug_stage=_debug_dsv_stage,
|
||||
)
|
||||
|
||||
|
||||
def _select_or_fill(page: Any, selector_env: str, label: str, value: str | None) -> None:
|
||||
text = str(value or "").strip()
|
||||
if not text:
|
||||
return
|
||||
selector = _env(selector_env)
|
||||
locator = page.locator(selector).first if selector else page.get_by_label(label)
|
||||
try:
|
||||
locator.select_option(label=text, timeout=_browser_timeout_ms())
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
locator.select_option(value=text, timeout=_browser_timeout_ms())
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
locator.fill(text, timeout=_browser_timeout_ms())
|
||||
|
||||
|
||||
def _visible_locator(page: Any, selector: str | None):
|
||||
if not selector:
|
||||
return None
|
||||
for frame in page.frames:
|
||||
locator = frame.locator(selector).first
|
||||
try:
|
||||
return locator if locator.is_visible(timeout=1_000) else None
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
def _visible_locator_in_root(root: Any, selector: str | None):
|
||||
if not selector:
|
||||
return None
|
||||
try:
|
||||
locator = root.locator(selector).first
|
||||
return locator if locator.is_visible(timeout=1_000) else None
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _click_text_in_root(root: Any, text: str, *, exact: bool = True, timeout_ms: int | None = None) -> bool:
|
||||
timeout = timeout_ms if timeout_ms is not None else _browser_timeout_ms()
|
||||
text_literal = json.dumps(text)
|
||||
for selector in (
|
||||
f'a.dropdown-item:has-text({text_literal})',
|
||||
f'.dropdown-item:has-text({text_literal})',
|
||||
f'button:has-text({text_literal})',
|
||||
f'[role="button"]:has-text({text_literal})',
|
||||
f'a:has-text({text_literal})',
|
||||
f'li:has-text({text_literal})',
|
||||
f'span:has-text({text_literal})',
|
||||
):
|
||||
try:
|
||||
locator = root.locator(selector).first
|
||||
locator.click(timeout=min(timeout, 3_000))
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
locator = root.locator(selector).first
|
||||
locator.click(timeout=min(timeout, 3_000), force=True)
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
for role in ("button", "link"):
|
||||
try:
|
||||
root.get_by_role(role, name=text, exact=exact).first.click(timeout=min(timeout, 3_000))
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
root.get_by_text(text, exact=False).first.click(timeout=min(timeout, 3_000))
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
root.get_by_text(text, exact=False).first.click(timeout=min(timeout, 3_000), force=True)
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _click_visible_selector_or_text_in_root(root: Any, selector: str | None, fallback_texts: tuple[str, ...]) -> bool:
|
||||
locator = _visible_locator_in_root(root, selector)
|
||||
if locator is not None:
|
||||
# #region debug-point H4:root-selector-click-attempt
|
||||
_emit_debug_event(
|
||||
"pre-fix",
|
||||
"H4",
|
||||
"freight_rpa_worker.py:_click_visible_selector_or_text_in_root:selector-attempt",
|
||||
"[DEBUG] attempting selector click in selected root",
|
||||
{"selector": selector or "", "fallbackTexts": list(fallback_texts)},
|
||||
)
|
||||
# #endregion
|
||||
try:
|
||||
locator.click(timeout=_browser_timeout_ms())
|
||||
# #region debug-point H4:root-selector-click-success
|
||||
_emit_debug_event(
|
||||
"pre-fix",
|
||||
"H4",
|
||||
"freight_rpa_worker.py:_click_visible_selector_or_text_in_root:selector-success",
|
||||
"[DEBUG] selector click succeeded in selected root",
|
||||
{"selector": selector or ""},
|
||||
)
|
||||
# #endregion
|
||||
return True
|
||||
except Exception as exc:
|
||||
# #region debug-point H4:root-selector-click-error
|
||||
_emit_debug_event(
|
||||
"pre-fix",
|
||||
"H4",
|
||||
"freight_rpa_worker.py:_click_visible_selector_or_text_in_root:selector-error",
|
||||
"[DEBUG] selector click failed in selected root",
|
||||
{"selector": selector or "", "error": str(exc)[:300]},
|
||||
)
|
||||
# #endregion
|
||||
for text in fallback_texts:
|
||||
# #region debug-point H4:root-text-click-attempt
|
||||
_emit_debug_event(
|
||||
"pre-fix",
|
||||
"H4",
|
||||
"freight_rpa_worker.py:_click_visible_selector_or_text_in_root:text-attempt",
|
||||
"[DEBUG] attempting text click in selected root",
|
||||
{"text": text, "selector": selector or ""},
|
||||
)
|
||||
# #endregion
|
||||
clicked = _click_text_in_root(root, text, exact=True, timeout_ms=3_000)
|
||||
# #region debug-point H4:root-text-click-result
|
||||
_emit_debug_event(
|
||||
"pre-fix",
|
||||
"H4",
|
||||
"freight_rpa_worker.py:_click_visible_selector_or_text_in_root:text-result",
|
||||
"[DEBUG] text click result in selected root",
|
||||
{"text": text, "clicked": clicked, "selector": selector or ""},
|
||||
)
|
||||
# #endregion
|
||||
if clicked:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _fill_login_field(page: Any, selector_env: str, value_env: str, fallback_selectors: tuple[str, ...]) -> bool:
|
||||
value = _env(value_env)
|
||||
if not value:
|
||||
return False
|
||||
selectors = tuple(item for item in (_env(selector_env), *fallback_selectors) if item)
|
||||
for selector in selectors:
|
||||
locator = _visible_locator(page, selector)
|
||||
if locator is None:
|
||||
continue
|
||||
locator.fill(value, timeout=_browser_timeout_ms())
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _fill_first_visible_text_input(page: Any, value: str) -> bool:
|
||||
for selector in (
|
||||
'input:not([type])',
|
||||
'input[type="text"]',
|
||||
'input[type="email"]',
|
||||
'input',
|
||||
):
|
||||
for frame in page.frames:
|
||||
try:
|
||||
inputs = frame.locator(selector).all()
|
||||
except Exception:
|
||||
inputs = []
|
||||
for locator in inputs:
|
||||
try:
|
||||
if not locator.is_visible(timeout=500) or not _dsv_locator_can_edit(locator):
|
||||
continue
|
||||
locator.fill(value, timeout=2_000)
|
||||
if locator.input_value(timeout=1_000).strip():
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
def _click_login_submit(page: Any, selector_env: str, fallback_texts: tuple[str, ...]) -> bool:
|
||||
selector = _env(selector_env)
|
||||
locator = _visible_locator(page, selector)
|
||||
if locator is not None:
|
||||
locator.click(timeout=_browser_timeout_ms())
|
||||
return True
|
||||
for text in fallback_texts:
|
||||
try:
|
||||
page.get_by_role("button", name=text).click(timeout=3_000)
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
page.get_by_text(text, exact=True).click(timeout=3_000)
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
def _click_visible_selector_or_text(page: Any, selector_env: str, fallback_texts: tuple[str, ...]) -> bool:
|
||||
selector = _env(selector_env)
|
||||
locator = _visible_locator(page, selector)
|
||||
if locator is not None:
|
||||
locator.click(timeout=_browser_timeout_ms())
|
||||
return True
|
||||
if any(text in {"登录", "Login", "Log in", "Sign in"} for text in fallback_texts):
|
||||
for submit_selector in (
|
||||
'button[type="submit"]',
|
||||
'input[type="submit"]',
|
||||
"#signOnButton",
|
||||
".btn-primary",
|
||||
):
|
||||
locator = _visible_locator(page, submit_selector)
|
||||
if locator is None:
|
||||
continue
|
||||
locator.click(timeout=3_000, force=True)
|
||||
return True
|
||||
for text in fallback_texts:
|
||||
try:
|
||||
_click_text(page, text, exact=True, timeout_ms=3_000)
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
def _wait_for_visible_selector(
|
||||
page: Any,
|
||||
selector_env: str,
|
||||
fallback_selectors: tuple[str, ...],
|
||||
*,
|
||||
timeout_ms: int | None = None,
|
||||
):
|
||||
selectors = tuple(item for item in (_env(selector_env), *fallback_selectors) if item)
|
||||
wait_ms = timeout_ms if timeout_ms is not None else _browser_timeout_ms()
|
||||
deadline = time.monotonic() + (wait_ms / 1000)
|
||||
while time.monotonic() < deadline:
|
||||
for selector in selectors:
|
||||
for frame in page.frames:
|
||||
locator = frame.locator(selector).first
|
||||
try:
|
||||
if locator.is_visible(timeout=1_000):
|
||||
return locator
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
return None
|
||||
|
||||
|
||||
def _maybe_auto_login(page: Any, prefix: str) -> None:
|
||||
"""
|
||||
如页面出现登录框,则用 RPA 机器环境变量自动登录;未出现登录框则复用现有浏览器登录态。
|
||||
"""
|
||||
username_env = f"FREIGHT_RPA_WORKER_{prefix}_USERNAME"
|
||||
password_env = f"FREIGHT_RPA_WORKER_{prefix}_PASSWORD"
|
||||
if not _env(username_env) or not _env(password_env):
|
||||
return
|
||||
|
||||
user_filled = _fill_login_field(
|
||||
page,
|
||||
f"FREIGHT_RPA_WORKER_{prefix}_USERNAME_SELECTOR",
|
||||
username_env,
|
||||
(
|
||||
'input[name="username"]',
|
||||
'input[name="userName"]',
|
||||
'input[name="email"]',
|
||||
'input[type="email"]',
|
||||
'input[type="text"]',
|
||||
),
|
||||
)
|
||||
password_filled = _fill_login_field(
|
||||
page,
|
||||
f"FREIGHT_RPA_WORKER_{prefix}_PASSWORD_SELECTOR",
|
||||
password_env,
|
||||
('input[name="password"]', 'input[type="password"]'),
|
||||
)
|
||||
if not user_filled and not password_filled:
|
||||
return
|
||||
if user_filled != password_filled:
|
||||
raise RuntimeError(f"{prefix} login form partially detected; please configure login selectors")
|
||||
|
||||
if not _click_login_submit(
|
||||
page,
|
||||
f"FREIGHT_RPA_WORKER_{prefix}_LOGIN_BUTTON_SELECTOR",
|
||||
("Sign in", "Login", "Log in", "登录"),
|
||||
):
|
||||
raise RuntimeError(f"{prefix} login fields detected but submit button was not found")
|
||||
|
||||
page.wait_for_load_state("domcontentloaded", timeout=_browser_timeout_ms())
|
||||
if page.locator('input[type="password"]').first.is_visible(timeout=3_000):
|
||||
raise RuntimeError(f"{prefix} login did not complete; MFA/SSO/manual verification may be required")
|
||||
|
||||
|
||||
|
||||
# 公开 API
|
||||
env = _env
|
||||
browser_timeout_ms = _browser_timeout_ms
|
||||
click_text = _click_text
|
||||
click_selector_or_text = _click_selector_or_text
|
||||
fill_selector_or_label = _fill_selector_or_label
|
||||
fill_dsv_filter_if_needed = _fill_dsv_filter_if_needed
|
||||
select_or_fill = _select_or_fill
|
||||
visible_locator = _visible_locator
|
||||
visible_locator_in_root = _visible_locator_in_root
|
||||
click_text_in_root = _click_text_in_root
|
||||
click_visible_selector_or_text_in_root = _click_visible_selector_or_text_in_root
|
||||
fill_login_field = _fill_login_field
|
||||
fill_first_visible_text_input = _fill_first_visible_text_input
|
||||
click_login_submit = _click_login_submit
|
||||
click_visible_selector_or_text = _click_visible_selector_or_text
|
||||
wait_for_visible_selector = _wait_for_visible_selector
|
||||
maybe_auto_login = _maybe_auto_login
|
||||
@@ -0,0 +1,291 @@
|
||||
"""
|
||||
scripts/freight_rpa/common/rpa_heartbeat.py
|
||||
|
||||
用途:货代 RPA Worker 向后端上报心跳(POST /api/shipping-notice/rpa/heartbeat)。
|
||||
依赖:rpa_common.env、urllib、socket。
|
||||
逻辑:由 freight_rpa_worker 主循环按 FREIGHT_RPA_WORKER_HEARTBEAT_SECONDS 周期调用;同步写入共享目录哨兵文件。
|
||||
"""
|
||||
|
||||
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 json
|
||||
import os
|
||||
import socket
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from rpa_common import env as _env
|
||||
|
||||
_RUNTIME_STATUS = "idle"
|
||||
_LAST_HEARTBEAT_MONO = 0.0
|
||||
_DEFAULT_SENTINEL_NAME = ".hxops_rpa_shared_mount"
|
||||
_HEARTBEAT_THREAD: threading.Thread | None = None
|
||||
_HEARTBEAT_THREAD_LOCK = threading.Lock()
|
||||
|
||||
|
||||
def set_worker_runtime_status(status: str) -> None:
|
||||
"""更新 worker 运行态(idle / busy),供心跳上报。"""
|
||||
global _RUNTIME_STATUS
|
||||
normalized = str(status or "idle").strip().lower()
|
||||
_RUNTIME_STATUS = normalized if normalized in {"idle", "busy"} else "idle"
|
||||
|
||||
|
||||
def get_worker_runtime_status() -> str:
|
||||
return _RUNTIME_STATUS
|
||||
|
||||
|
||||
def _resolve_worker_environment() -> str:
|
||||
raw = (
|
||||
_env("FREIGHT_RPA_WORKER_ENVIRONMENT")
|
||||
or _env("ENV_NAME")
|
||||
or _env("HXOPS_ENV")
|
||||
or "dev"
|
||||
)
|
||||
value = str(raw or "dev").strip().lower()
|
||||
if value in {"development", ""}:
|
||||
return "dev"
|
||||
if value in {"testing"}:
|
||||
return "test"
|
||||
if value in {"production"}:
|
||||
return "prod"
|
||||
return value
|
||||
|
||||
|
||||
def _resolve_shared_scope_id() -> str:
|
||||
raw = (
|
||||
_env("FREIGHT_RPA_SHARED_SCOPE_ID")
|
||||
or _env("FREIGHT_RPA_SHARED_SCOPE_ID")
|
||||
or ""
|
||||
)
|
||||
value = str(raw or "").strip()
|
||||
if value:
|
||||
return value
|
||||
trigger = str(_env("FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR") or "").replace("\\", "/").lower()
|
||||
for token in ("hxops-rpa-test-data", "hxops-rpa-prod-data"):
|
||||
if token in trigger:
|
||||
return token
|
||||
return ""
|
||||
|
||||
|
||||
def _resolve_sentinel_name() -> str:
|
||||
return str(
|
||||
_env("FREIGHT_RPA_SHARED_SENTINEL_NAME")
|
||||
or _env("FREIGHT_RPA_SHARED_SENTINEL_NAME")
|
||||
or _DEFAULT_SENTINEL_NAME
|
||||
).strip() or _DEFAULT_SENTINEL_NAME
|
||||
|
||||
|
||||
def _resolve_worker_id(hostname: str) -> str:
|
||||
explicit = str(_env("FREIGHT_RPA_WORKER_ID") or "").strip()
|
||||
if explicit:
|
||||
return explicit
|
||||
pid = os.getpid()
|
||||
return f"{hostname}-{pid}"
|
||||
|
||||
|
||||
def write_shared_mount_sentinel(*, trigger_dir: str | Path, hostname: str | None = None) -> None:
|
||||
"""
|
||||
在 trigger 共享目录写入哨兵文件,供 Ubuntu 后端校验 CIFS 挂载与 scope 一致。
|
||||
核心逻辑:不创建 trigger 根目录,仅更新已存在目录下的哨兵文件。
|
||||
"""
|
||||
scope_id = _resolve_shared_scope_id()
|
||||
if not scope_id:
|
||||
return
|
||||
root = Path(trigger_dir)
|
||||
if not root.is_dir():
|
||||
return
|
||||
host = hostname or socket.gethostname()
|
||||
body = "\n".join([
|
||||
f"scope_id={scope_id}",
|
||||
f"updated_at={datetime.now(UTC).replace(tzinfo=None).isoformat()}",
|
||||
f"host={host}",
|
||||
f"worker_id={_resolve_worker_id(host)}",
|
||||
])
|
||||
sentinel_path = root / _resolve_sentinel_name()
|
||||
sentinel_path.write_text(body + "\n", encoding="utf-8")
|
||||
|
||||
|
||||
def build_heartbeat_payload(
|
||||
*,
|
||||
trigger_dir: str | Path,
|
||||
drop_dir: str | Path,
|
||||
status: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
组装心跳 payload。
|
||||
核心逻辑:capabilities 含 inventory_export;Worker 开启上传时附加 freight_upload;
|
||||
shared_scope_id 用于跨平台路径对齐与环境隔离。
|
||||
"""
|
||||
hostname = socket.gethostname()
|
||||
capabilities = ["inventory_export"]
|
||||
upload_enabled = str(_env("FREIGHT_RPA_WORKER_UPLOAD_ENABLED", "false") or "false").strip().lower() in {
|
||||
"1", "true", "yes", "on",
|
||||
}
|
||||
if upload_enabled:
|
||||
capabilities.append("freight_upload")
|
||||
return {
|
||||
"worker_id": _resolve_worker_id(hostname),
|
||||
"hostname": hostname,
|
||||
"environment": _resolve_worker_environment(),
|
||||
"capabilities": capabilities,
|
||||
"status": status or get_worker_runtime_status(),
|
||||
"trigger_dir": str(trigger_dir),
|
||||
"drop_dir": str(drop_dir),
|
||||
"shared_scope_id": _resolve_shared_scope_id(),
|
||||
"version": str(_env("FREIGHT_RPA_WORKER_VERSION", "rpa-poc") or "rpa-poc"),
|
||||
"timestamp": datetime.now(UTC).replace(tzinfo=None).isoformat(),
|
||||
}
|
||||
|
||||
|
||||
def post_heartbeat(payload: dict[str, Any]) -> bool:
|
||||
"""
|
||||
向后端上报心跳。
|
||||
Returns:
|
||||
bool: HTTP 2xx 时 True,否则 False(不中断 worker 主循环)。
|
||||
"""
|
||||
base = str(_env("HXOPS_API_BASE", "http://127.0.0.1:5052") or "http://127.0.0.1:5052").rstrip("/")
|
||||
key = (
|
||||
_env("SHIPPING_NOTICE_TOOL_API_KEY")
|
||||
or _env("INTEGRATION_API_KEY")
|
||||
or _env("HXOPS_TOOLS_API_KEY")
|
||||
)
|
||||
if not key:
|
||||
print("[heartbeat] skipped: missing SHIPPING_NOTICE_TOOL_API_KEY", file=sys.stderr)
|
||||
return False
|
||||
|
||||
url = f"{base}/api/shipping-notice/rpa/heartbeat"
|
||||
data = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
||||
req = urllib.request.Request(
|
||||
url,
|
||||
data=data,
|
||||
headers={
|
||||
"Content-Type": "application/json",
|
||||
"X-Integration-Key": key,
|
||||
"X-Shipping-Tool-Key": key,
|
||||
},
|
||||
method="POST",
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=8) as resp:
|
||||
return 200 <= int(resp.status) < 300
|
||||
except urllib.error.HTTPError as exc:
|
||||
body = ""
|
||||
try:
|
||||
body = exc.read().decode("utf-8", errors="replace")[:500]
|
||||
except Exception:
|
||||
body = ""
|
||||
print(f"[heartbeat] HTTP {exc.code} {body}", file=sys.stderr)
|
||||
return False
|
||||
except Exception as exc:
|
||||
print(f"[heartbeat] failed: {exc}", file=sys.stderr)
|
||||
return False
|
||||
|
||||
|
||||
def _start_heartbeat_request(payload: dict[str, Any]) -> bool:
|
||||
"""
|
||||
非阻塞地提交一次心跳 HTTP 请求。
|
||||
|
||||
核心逻辑:心跳仅用于 Worker 就绪观测,不能阻塞库存 Trigger 扫描;同一时刻最多
|
||||
保留一条后台请求。若网络库在底层超时后仍未返回,后续周期跳过新请求而主循环照常继续。
|
||||
|
||||
Returns:
|
||||
bool: 已启动新请求时为 True;已有未完成请求时为 False。
|
||||
"""
|
||||
global _HEARTBEAT_THREAD
|
||||
with _HEARTBEAT_THREAD_LOCK:
|
||||
if _HEARTBEAT_THREAD is not None and _HEARTBEAT_THREAD.is_alive():
|
||||
print("[heartbeat] skipped: previous request still in progress", file=sys.stderr)
|
||||
return False
|
||||
thread = threading.Thread(
|
||||
target=post_heartbeat,
|
||||
args=(payload,),
|
||||
name="shipping-rpa-heartbeat",
|
||||
daemon=True,
|
||||
)
|
||||
_HEARTBEAT_THREAD = thread
|
||||
thread.start()
|
||||
return True
|
||||
|
||||
|
||||
def maybe_send_heartbeat(
|
||||
*,
|
||||
trigger_dir: str | Path,
|
||||
drop_dir: str | Path,
|
||||
last_sent_mono: float,
|
||||
force: bool = False,
|
||||
) -> float:
|
||||
"""
|
||||
按 FREIGHT_RPA_WORKER_HEARTBEAT_SECONDS 节流发送心跳。
|
||||
Returns:
|
||||
float: 最近一次尝试后的 monotonic 时间戳(成功或失败均更新节流时钟)。
|
||||
"""
|
||||
global _LAST_HEARTBEAT_MONO
|
||||
interval = max(15, int(_env("FREIGHT_RPA_WORKER_HEARTBEAT_SECONDS", "20") or "20"))
|
||||
now = time.monotonic()
|
||||
if not force and last_sent_mono and (now - last_sent_mono) < interval:
|
||||
return last_sent_mono
|
||||
write_shared_mount_sentinel(trigger_dir=trigger_dir)
|
||||
payload = build_heartbeat_payload(trigger_dir=trigger_dir, drop_dir=drop_dir)
|
||||
_start_heartbeat_request(payload)
|
||||
_LAST_HEARTBEAT_MONO = now
|
||||
return now
|
||||
|
||||
|
||||
def start_heartbeat_loop(
|
||||
*,
|
||||
trigger_dir: str | Path,
|
||||
drop_dir: str | Path,
|
||||
interval_seconds: float,
|
||||
) -> threading.Thread:
|
||||
"""
|
||||
启动独立守护心跳线程,使心跳节奏与业务主循环解耦。
|
||||
|
||||
核心逻辑:批量站点导出(浏览器登录+下载)会长时间阻塞 worker 主循环;若心跳由
|
||||
主循环发送,执行期间会停发,后端按心跳 TTL 误判 Worker 离线。本线程按固定间隔
|
||||
持续上报,主循环只负责业务扫描;线程内异常仅打印,绝不退出。
|
||||
|
||||
Args:
|
||||
trigger_dir: 触发目录(哨兵写入与心跳 payload 使用)。
|
||||
drop_dir: 库存落盘目录(心跳 payload 使用)。
|
||||
interval_seconds: 心跳间隔;实际以环境变量最小 15s 为准。
|
||||
|
||||
Returns:
|
||||
已启动的守护线程(daemon,随进程退出)。
|
||||
"""
|
||||
def _loop() -> None:
|
||||
while True:
|
||||
time.sleep(max(5.0, float(interval_seconds)))
|
||||
try:
|
||||
maybe_send_heartbeat(
|
||||
trigger_dir=trigger_dir,
|
||||
drop_dir=drop_dir,
|
||||
last_sent_mono=0.0,
|
||||
force=True,
|
||||
)
|
||||
except Exception:
|
||||
print("[heartbeat] loop tick failed", file=sys.stderr)
|
||||
|
||||
thread = threading.Thread(target=_loop, name="shipping-rpa-heartbeat-loop", daemon=True)
|
||||
thread.start()
|
||||
return thread
|
||||
@@ -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
|
||||
@@ -0,0 +1,430 @@
|
||||
"""
|
||||
scripts/freight_rpa/common/worker_disk_cleanup.py
|
||||
|
||||
用途:RPA Worker 本机磁盘保留清理,防止 logs / 归档 trigger / drop 归档 / 孤儿临时 Profile 长期堆积撑爆盘符。
|
||||
依赖:rpa_common.env、pathlib、shutil、time。
|
||||
逻辑:由 inventory(及可复用的 receipt)Worker 主循环周期调用;只删超过保留期的归档与临时物,
|
||||
绝不删除进行中的 trigger 根目录 JSON、可复用会话 Profile(*_session)、以及活跃 cleanup 队列。
|
||||
"""
|
||||
|
||||
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 shutil
|
||||
import time
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
from rpa_common import env as _env
|
||||
|
||||
_PROTECTED_DROP_DIRNAMES = frozenset(
|
||||
{
|
||||
"processed",
|
||||
".hxops_quarantine",
|
||||
".cleanup_queue",
|
||||
".cleanup_failed",
|
||||
".hxops_rpa_shared_mount",
|
||||
}
|
||||
)
|
||||
_DROP_ROOT_SUFFIXES = frozenset({".xlsx", ".xls", ".csv", ".hxops_consumed"})
|
||||
_TRIGGER_ARCHIVE_DIRNAMES = ("processed", "failed")
|
||||
# 一次性运行 Profile 前缀:库存 Worker 用 run_*,收料 Worker 用 receipt_*,
|
||||
# 两者均为浏览器崩溃/异常中断后可能残留的临时目录,超期统一清理。
|
||||
_RUNTIME_PROFILE_TEMP_PREFIXES = ("run_", "receipt_")
|
||||
_DEFAULT_RETENTION_DAYS = 7
|
||||
_DEFAULT_INTERVAL_SECONDS = 3600
|
||||
_DEFAULT_ORPHAN_PROFILE_HOURS = 24
|
||||
|
||||
|
||||
class DiskCleanupStats:
|
||||
"""单次清理统计,便于日志汇总与单测断言。"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.deleted_files = 0
|
||||
self.deleted_dirs = 0
|
||||
self.skipped = 0
|
||||
self.errors = 0
|
||||
self.details: list[str] = []
|
||||
|
||||
def record_file(self, path: Path) -> None:
|
||||
self.deleted_files += 1
|
||||
self.details.append(f"file:{path}")
|
||||
|
||||
def record_dir(self, path: Path) -> None:
|
||||
self.deleted_dirs += 1
|
||||
self.details.append(f"dir:{path}")
|
||||
|
||||
def record_error(self, path: Path, exc: BaseException) -> None:
|
||||
self.errors += 1
|
||||
self.details.append(f"error:{path}:{type(exc).__name__}")
|
||||
|
||||
|
||||
def retention_days() -> int:
|
||||
"""
|
||||
读取归档保留天数。
|
||||
|
||||
核心逻辑:`FREIGHT_RPA_WORKER_DISK_RETENTION_DAYS`,默认 7;
|
||||
`<=0` 表示禁用按天清理(仍可单独清理孤儿临时 Profile,见 orphan 配置)。
|
||||
|
||||
Returns:
|
||||
int: 保留天数;禁用时为 0。
|
||||
"""
|
||||
return _int_env("FREIGHT_RPA_WORKER_DISK_RETENTION_DAYS", _DEFAULT_RETENTION_DAYS, min_value=0)
|
||||
|
||||
|
||||
def cleanup_interval_seconds() -> int:
|
||||
"""
|
||||
读取清理周期秒数。
|
||||
|
||||
核心逻辑:`FREIGHT_RPA_WORKER_DISK_CLEANUP_INTERVAL_SECONDS`,默认 3600;
|
||||
最小值 60,避免主循环过于频繁扫盘。
|
||||
|
||||
Returns:
|
||||
int: 清理间隔秒数。
|
||||
"""
|
||||
return _int_env(
|
||||
"FREIGHT_RPA_WORKER_DISK_CLEANUP_INTERVAL_SECONDS",
|
||||
_DEFAULT_INTERVAL_SECONDS,
|
||||
min_value=60,
|
||||
)
|
||||
|
||||
|
||||
def orphan_profile_max_age_seconds() -> int:
|
||||
"""
|
||||
读取孤儿临时 Profile(run_* / receipt_*)最大存活秒数。
|
||||
|
||||
核心逻辑:`FREIGHT_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS`,默认 24;
|
||||
`<=0` 禁用孤儿 Profile 清理。会话复用目录(*_session)永不删除。
|
||||
|
||||
Returns:
|
||||
int: 最大存活秒数;禁用时为 0。
|
||||
"""
|
||||
hours = _int_env(
|
||||
"FREIGHT_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS",
|
||||
_DEFAULT_ORPHAN_PROFILE_HOURS,
|
||||
min_value=0,
|
||||
)
|
||||
return hours * 3600
|
||||
|
||||
|
||||
def _int_env(name: str, default: int, *, min_value: int = 0) -> int:
|
||||
"""读取整数环境变量;非法值回退默认,并钳制下限。"""
|
||||
try:
|
||||
value = int(_env(name, str(default)) or str(default))
|
||||
except ValueError:
|
||||
return default
|
||||
return max(value, min_value)
|
||||
|
||||
|
||||
def _mtime_unix(path: Path) -> float | None:
|
||||
"""读取 mtime;失败返回 None。"""
|
||||
try:
|
||||
return path.stat().st_mtime
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
|
||||
def _is_older_than(path: Path, *, cutoff_unix: float) -> bool:
|
||||
"""路径 mtime 早于 cutoff 时视为过期。"""
|
||||
mtime = _mtime_unix(path)
|
||||
if mtime is None:
|
||||
return False
|
||||
return mtime < cutoff_unix
|
||||
|
||||
|
||||
def _safe_unlink(path: Path, stats: DiskCleanupStats) -> None:
|
||||
"""best-effort 删除文件。"""
|
||||
try:
|
||||
if path.is_file() or path.is_symlink():
|
||||
path.unlink(missing_ok=True)
|
||||
stats.record_file(path)
|
||||
else:
|
||||
stats.skipped += 1
|
||||
except OSError as exc:
|
||||
stats.record_error(path, exc)
|
||||
|
||||
|
||||
def _safe_rmtree(path: Path, stats: DiskCleanupStats) -> None:
|
||||
"""best-effort 删除目录树。"""
|
||||
try:
|
||||
if path.is_dir():
|
||||
shutil.rmtree(path, ignore_errors=False)
|
||||
stats.record_dir(path)
|
||||
else:
|
||||
stats.skipped += 1
|
||||
except OSError as exc:
|
||||
stats.record_error(path, exc)
|
||||
|
||||
|
||||
def cleanup_files_older_than(
|
||||
directory: Path,
|
||||
*,
|
||||
cutoff_unix: float,
|
||||
stats: DiskCleanupStats,
|
||||
recursive: bool = False,
|
||||
name_predicate: Callable[[Path], bool] | None = None,
|
||||
suffix_allowlist: frozenset[str] | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
删除目录中超过 cutoff 的文件(可选递归、文件名/后缀过滤)。
|
||||
|
||||
核心逻辑:只处理普通文件;目录本身不删(由调用方决定是否 rmtree)。
|
||||
匹配失败或权限错误计入 stats,不中断整轮清理。
|
||||
|
||||
Args:
|
||||
directory: 目标目录;不存在则跳过。
|
||||
cutoff_unix: 早于此 Unix 时间戳的文件可删。
|
||||
stats: 累计统计。
|
||||
recursive: 是否递归子目录。
|
||||
name_predicate: 可选文件名过滤;返回 False 则跳过。
|
||||
suffix_allowlist: 可选后缀白名单(小写,含点);None 表示不限制。
|
||||
"""
|
||||
if not directory.is_dir():
|
||||
return
|
||||
iterator = directory.rglob("*") if recursive else directory.iterdir()
|
||||
for path in iterator:
|
||||
try:
|
||||
if not path.is_file():
|
||||
continue
|
||||
except OSError as exc:
|
||||
stats.record_error(path, exc)
|
||||
continue
|
||||
if name_predicate is not None and not name_predicate(path):
|
||||
stats.skipped += 1
|
||||
continue
|
||||
if suffix_allowlist is not None and path.suffix.lower() not in suffix_allowlist:
|
||||
# 兼容 sidecar:`.xlsx.hxops_consumed` 的 suffix 是 `.hxops_consumed`
|
||||
if path.name.endswith(".hxops_consumed") and ".hxops_consumed" in suffix_allowlist:
|
||||
pass
|
||||
else:
|
||||
stats.skipped += 1
|
||||
continue
|
||||
if not _is_older_than(path, cutoff_unix=cutoff_unix):
|
||||
stats.skipped += 1
|
||||
continue
|
||||
_safe_unlink(path, stats)
|
||||
|
||||
|
||||
def cleanup_trigger_archives(trigger_dir: Path | None, *, cutoff_unix: float, stats: DiskCleanupStats) -> None:
|
||||
"""
|
||||
清理 trigger 下 processed/failed 归档 JSON。
|
||||
|
||||
核心逻辑:绝不触碰 trigger 根目录进行中的 `*.json`。
|
||||
"""
|
||||
if trigger_dir is None or not trigger_dir.is_dir():
|
||||
return
|
||||
for dirname in _TRIGGER_ARCHIVE_DIRNAMES:
|
||||
cleanup_files_older_than(
|
||||
trigger_dir / dirname,
|
||||
cutoff_unix=cutoff_unix,
|
||||
stats=stats,
|
||||
recursive=False,
|
||||
suffix_allowlist=frozenset({".json"}),
|
||||
)
|
||||
|
||||
|
||||
def cleanup_drop_archives(drop_dir: Path | None, *, cutoff_unix: float, stats: DiskCleanupStats) -> None:
|
||||
"""
|
||||
清理 drop 区归档与隔离目录,以及根目录过期导出文件。
|
||||
|
||||
核心逻辑:
|
||||
- 清理 `processed` / `.hxops_quarantine` / `.cleanup_failed` 中过期文件;
|
||||
- 清理 drop 根目录过期的 Excel/CSV 与 `.hxops_consumed` sidecar;
|
||||
- 不碰 `.cleanup_queue`(活跃重试队列)。
|
||||
"""
|
||||
if drop_dir is None or not drop_dir.is_dir():
|
||||
return
|
||||
for dirname in ("processed", ".hxops_quarantine", ".cleanup_failed"):
|
||||
cleanup_files_older_than(
|
||||
drop_dir / dirname,
|
||||
cutoff_unix=cutoff_unix,
|
||||
stats=stats,
|
||||
recursive=False,
|
||||
)
|
||||
# [STEP 1] drop 根:仅清理导出产物与消费标记,跳过受保护子目录与其它文件
|
||||
for path in drop_dir.iterdir():
|
||||
try:
|
||||
if path.is_dir():
|
||||
if path.name in _PROTECTED_DROP_DIRNAMES or path.name.startswith("."):
|
||||
stats.skipped += 1
|
||||
continue
|
||||
if not path.is_file():
|
||||
continue
|
||||
except OSError as exc:
|
||||
stats.record_error(path, exc)
|
||||
continue
|
||||
suffix = path.suffix.lower()
|
||||
is_consumed_sidecar = path.name.endswith(".hxops_consumed")
|
||||
if suffix not in _DROP_ROOT_SUFFIXES and not is_consumed_sidecar:
|
||||
stats.skipped += 1
|
||||
continue
|
||||
if not _is_older_than(path, cutoff_unix=cutoff_unix):
|
||||
stats.skipped += 1
|
||||
continue
|
||||
_safe_unlink(path, stats)
|
||||
|
||||
|
||||
def cleanup_upload_queue(queue_dir: Path | None, *, cutoff_unix: float, stats: DiskCleanupStats) -> None:
|
||||
"""
|
||||
清理 upload_queue 中过期文件。
|
||||
|
||||
核心逻辑:待上传文件正常应在数分钟内被消费;超过保留期视为残留,可删。
|
||||
"""
|
||||
if queue_dir is None or not queue_dir.is_dir():
|
||||
return
|
||||
cleanup_files_older_than(queue_dir, cutoff_unix=cutoff_unix, stats=stats, recursive=False)
|
||||
|
||||
|
||||
def cleanup_log_backups(log_file: Path | None, *, cutoff_unix: float, stats: DiskCleanupStats) -> None:
|
||||
"""
|
||||
清理 worker 日志轮转备份(worker.log.1 / .2 ...)。
|
||||
|
||||
核心逻辑:不删当前 `worker.log`(由大小轮转负责);只删过期备份。
|
||||
"""
|
||||
if log_file is None:
|
||||
return
|
||||
parent = log_file.parent
|
||||
if not parent.is_dir():
|
||||
return
|
||||
prefix = f"{log_file.name}."
|
||||
for path in parent.iterdir():
|
||||
try:
|
||||
if not path.is_file():
|
||||
continue
|
||||
except OSError as exc:
|
||||
stats.record_error(path, exc)
|
||||
continue
|
||||
if path.name == log_file.name:
|
||||
stats.skipped += 1
|
||||
continue
|
||||
if not path.name.startswith(prefix):
|
||||
continue
|
||||
suffix = path.name[len(prefix) :]
|
||||
if not suffix.isdigit():
|
||||
continue
|
||||
if not _is_older_than(path, cutoff_unix=cutoff_unix):
|
||||
stats.skipped += 1
|
||||
continue
|
||||
_safe_unlink(path, stats)
|
||||
|
||||
|
||||
def cleanup_orphan_runtime_profiles(
|
||||
profile_root: Path | None,
|
||||
*,
|
||||
cutoff_unix: float,
|
||||
stats: DiskCleanupStats,
|
||||
) -> None:
|
||||
"""
|
||||
清理浏览器 Profile 根下过期的一次性 `run_*` / `receipt_*` 目录。
|
||||
|
||||
核心逻辑:会话复用目录名以 `_session` 结尾或历史 `dsv360_session`,一律保留;
|
||||
仅删除 `run_*` / `receipt_*` 临时目录,避免异常中断后残留撑盘。
|
||||
收料 Worker 一次性 Profile 以 receipt_ 前缀创建,同属清理对象。
|
||||
"""
|
||||
if profile_root is None or not profile_root.is_dir():
|
||||
return
|
||||
for path in profile_root.iterdir():
|
||||
try:
|
||||
if not path.is_dir():
|
||||
continue
|
||||
except OSError as exc:
|
||||
stats.record_error(path, exc)
|
||||
continue
|
||||
name = path.name
|
||||
if name.endswith("_session") or name == "dsv360_session":
|
||||
stats.skipped += 1
|
||||
continue
|
||||
if not name.startswith(_RUNTIME_PROFILE_TEMP_PREFIXES):
|
||||
stats.skipped += 1
|
||||
continue
|
||||
if not _is_older_than(path, cutoff_unix=cutoff_unix):
|
||||
stats.skipped += 1
|
||||
continue
|
||||
_safe_rmtree(path, stats)
|
||||
|
||||
|
||||
def run_worker_disk_cleanup(
|
||||
*,
|
||||
inventory_trigger_dir: Path | None = None,
|
||||
upload_trigger_dir: Path | None = None,
|
||||
drop_dir: Path | None = None,
|
||||
upload_queue_dir: Path | None = None,
|
||||
browser_profile_dir: Path | None = None,
|
||||
log_file: Path | None = None,
|
||||
now_unix: float | None = None,
|
||||
) -> DiskCleanupStats:
|
||||
"""
|
||||
执行一轮 Worker 本机磁盘保留清理。
|
||||
|
||||
【AI 触发时机】:Worker 启动后及主循环按 `DISK_CLEANUP_INTERVAL_SECONDS` 周期调用。
|
||||
|
||||
核心逻辑:按 `DISK_RETENTION_DAYS` 清理归档/日志备份/队列残留;按
|
||||
`ORPHAN_PROFILE_MAX_AGE_HOURS` 清理孤儿 `run_*` / `receipt_*` Profile。全部 best-effort。
|
||||
|
||||
Args:
|
||||
inventory_trigger_dir: 库存 trigger 根目录。
|
||||
upload_trigger_dir: 上传 trigger 根目录。
|
||||
drop_dir: 库存 drop 根目录。
|
||||
upload_queue_dir: 上传队列目录。
|
||||
browser_profile_dir: 浏览器 Profile 根目录。
|
||||
log_file: 当前 worker 日志文件路径。
|
||||
now_unix: 可选当前时间(单测注入)。
|
||||
|
||||
Returns:
|
||||
DiskCleanupStats: 本轮删除/跳过/错误统计。
|
||||
"""
|
||||
stats = DiskCleanupStats()
|
||||
now = float(now_unix if now_unix is not None else time.time())
|
||||
days = retention_days()
|
||||
if days > 0:
|
||||
cutoff = now - (days * 86400)
|
||||
cleanup_trigger_archives(inventory_trigger_dir, cutoff_unix=cutoff, stats=stats)
|
||||
cleanup_trigger_archives(upload_trigger_dir, cutoff_unix=cutoff, stats=stats)
|
||||
cleanup_drop_archives(drop_dir, cutoff_unix=cutoff, stats=stats)
|
||||
cleanup_upload_queue(upload_queue_dir, cutoff_unix=cutoff, stats=stats)
|
||||
cleanup_log_backups(log_file, cutoff_unix=cutoff, stats=stats)
|
||||
orphan_age = orphan_profile_max_age_seconds()
|
||||
if orphan_age > 0:
|
||||
cleanup_orphan_runtime_profiles(
|
||||
browser_profile_dir,
|
||||
cutoff_unix=now - orphan_age,
|
||||
stats=stats,
|
||||
)
|
||||
return stats
|
||||
|
||||
|
||||
def format_cleanup_summary(stats: DiskCleanupStats) -> str:
|
||||
"""
|
||||
将清理统计格式化为单行日志。
|
||||
|
||||
Args:
|
||||
stats: 清理结果。
|
||||
|
||||
Returns:
|
||||
str: 适合 print 的摘要。
|
||||
"""
|
||||
stamp = datetime.now(UTC).astimezone().strftime("%Y-%m-%d %H:%M:%S")
|
||||
return (
|
||||
f"[disk-cleanup] at={stamp} deleted_files={stats.deleted_files} "
|
||||
f"deleted_dirs={stats.deleted_dirs} skipped={stats.skipped} errors={stats.errors}"
|
||||
)
|
||||
@@ -0,0 +1,249 @@
|
||||
"""scripts/freight_rpa/common/worker_logging.py
|
||||
|
||||
用途:RPA Worker 通用文件日志——stdout/stderr tee 落盘、行级本地时间戳、
|
||||
按大小轮转(启动前 + 运行中),供库存/收料等所有 Worker 复用。
|
||||
依赖:rpa_common._env(环境变量读取与历史名兼容)、标准库。
|
||||
逻辑:configure_file_logging 读 FREIGHT_RPA_WORKER_LOG_FILE 启用;
|
||||
maybe_rotate_open_log 在主循环周期调用做运行中轮转;shutdown_logging 恢复标准流。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import atexit
|
||||
import sys
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
from typing import TextIO
|
||||
|
||||
from rpa_common import _env
|
||||
|
||||
|
||||
def _backend_dir() -> Path:
|
||||
"""返回仓库内 backend 根目录(本模块位于 <repo>/scripts/freight_rpa/common/)。"""
|
||||
return Path(__file__).resolve().parents[3] / "backend"
|
||||
|
||||
|
||||
def log_line_timestamp() -> str:
|
||||
"""
|
||||
生成 worker 日志行首时间戳(本地时区)。
|
||||
|
||||
核心逻辑:RPA 批量导出常跨 1+ 小时,行级时间便于对照 DSV 页面卡顿与超时点。
|
||||
|
||||
Returns:
|
||||
str: `YYYY-MM-DD HH:MM:SS` 格式字符串。
|
||||
"""
|
||||
return datetime.now(UTC).astimezone().strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
|
||||
def _log_int_env(name: str, default: int, *, min_value: int = 0) -> int:
|
||||
"""读取日志相关整数环境变量;非法值回退默认值。"""
|
||||
try:
|
||||
value = int(_env(name, str(default)) or str(default))
|
||||
except ValueError:
|
||||
return default
|
||||
return max(value, min_value)
|
||||
|
||||
|
||||
class WorkerLogTee:
|
||||
"""
|
||||
同时写入控制台与日志文件的轻量 stream。
|
||||
|
||||
核心逻辑:保留原 stdout/stderr,避免计划任务改为日志模式后本地调试看不到输出;
|
||||
每行完整输出前自动前缀本地时间戳;文件 flush 采用行级同步,RPA 异常退出时尽量
|
||||
保留最后几行排障信息;支持运行中替换底层日志句柄以便按大小轮转。
|
||||
"""
|
||||
|
||||
def __init__(self, console: TextIO, log_file: TextIO) -> None:
|
||||
self._console = console
|
||||
self._log_file = log_file
|
||||
self._pending = ""
|
||||
self.encoding = getattr(console, "encoding", "utf-8")
|
||||
|
||||
def replace_log_file(self, log_file: TextIO) -> TextIO:
|
||||
"""
|
||||
替换底层日志文件句柄(用于运行中轮转)。
|
||||
|
||||
核心逻辑:先 flush 缓冲,再切换句柄;调用方负责关闭旧句柄与打开新文件。
|
||||
|
||||
Args:
|
||||
log_file: 新的追加写日志句柄。
|
||||
|
||||
Returns:
|
||||
TextIO: 被替换下来的旧日志句柄。
|
||||
"""
|
||||
self.flush()
|
||||
previous = self._log_file
|
||||
self._log_file = log_file
|
||||
return previous
|
||||
|
||||
def _emit_line(self, line: str, *, newline: bool) -> None:
|
||||
"""将单行(可含时间戳前缀)写入控制台与日志文件。"""
|
||||
if line:
|
||||
stamped = f"{log_line_timestamp()} {line}"
|
||||
self._console.write(stamped)
|
||||
self._log_file.write(stamped)
|
||||
if newline:
|
||||
self._console.write("\n")
|
||||
self._log_file.write("\n")
|
||||
|
||||
def write(self, text: str) -> int:
|
||||
self._pending += text
|
||||
while "\n" in self._pending:
|
||||
line, self._pending = self._pending.split("\n", 1)
|
||||
self._emit_line(line, newline=True)
|
||||
self.flush()
|
||||
return len(text)
|
||||
|
||||
def flush(self) -> None:
|
||||
if self._pending:
|
||||
self._emit_line(self._pending, newline=False)
|
||||
self._pending = ""
|
||||
self._console.flush()
|
||||
self._log_file.flush()
|
||||
|
||||
def isatty(self) -> bool:
|
||||
return bool(getattr(self._console, "isatty", lambda: False)())
|
||||
|
||||
|
||||
# 运行中日志轮转需要持有 Tee 与路径;仅由 configure_file_logging / maybe_rotate_open_log 维护。
|
||||
_ACTIVE_LOG_PATH: Path | None = None
|
||||
_ACTIVE_STDOUT_TEE: WorkerLogTee | None = None
|
||||
_ACTIVE_STDERR_TEE: WorkerLogTee | None = None
|
||||
_ACTIVE_LOG_HANDLE: TextIO | None = None
|
||||
|
||||
|
||||
def configure_file_logging() -> Path | None:
|
||||
"""
|
||||
按 FREIGHT_RPA_WORKER_LOG_FILE 启用 worker 文件日志。
|
||||
|
||||
【AI 触发时机】:Windows 任务计划程序后台运行 RPA worker 时配置本变量,
|
||||
让所有 print/stdout/stderr 同时落盘,并在每行前自动加本地时间戳,便于排查
|
||||
登录、下载、回调失败与长批次耗时。
|
||||
|
||||
Returns:
|
||||
Path | None: 已启用的日志路径;未配置时返回 None。
|
||||
"""
|
||||
global _ACTIVE_LOG_PATH, _ACTIVE_STDOUT_TEE, _ACTIVE_STDERR_TEE, _ACTIVE_LOG_HANDLE
|
||||
if _ACTIVE_LOG_PATH is not None:
|
||||
return _ACTIVE_LOG_PATH
|
||||
raw = _env("FREIGHT_RPA_WORKER_LOG_FILE")
|
||||
if not raw:
|
||||
return None
|
||||
path = Path(raw).expanduser()
|
||||
if not path.is_absolute():
|
||||
path = (_backend_dir() / path).resolve()
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
rotate_log_file_if_needed(path)
|
||||
log_file = path.open("a", encoding="utf-8", buffering=1)
|
||||
original_stdout = sys.stdout
|
||||
original_stderr = sys.stderr
|
||||
stdout_tee = WorkerLogTee(original_stdout, log_file)
|
||||
stderr_tee = WorkerLogTee(original_stderr, log_file)
|
||||
sys.stdout = stdout_tee # type: ignore[assignment]
|
||||
sys.stderr = stderr_tee # type: ignore[assignment]
|
||||
_ACTIVE_LOG_PATH = path
|
||||
_ACTIVE_STDOUT_TEE = stdout_tee
|
||||
_ACTIVE_STDERR_TEE = stderr_tee
|
||||
_ACTIVE_LOG_HANDLE = log_file
|
||||
atexit.register(shutdown_logging)
|
||||
print(f"[logging] tee enabled path={path}")
|
||||
return path
|
||||
|
||||
|
||||
def shutdown_logging() -> None:
|
||||
"""
|
||||
恢复 stdout/stderr 并关闭日志句柄(原 _configure_file_logging 内 _close_log 逻辑公开化)。
|
||||
|
||||
核心逻辑:把标准流还原为启用 tee 前的原流,关闭当前日志句柄并清空 _ACTIVE_* 状态;
|
||||
由 configure_file_logging 注册到 atexit 兜底,进程退出时保证日志落盘完整。
|
||||
未启用文件日志时 no-op。
|
||||
"""
|
||||
global _ACTIVE_LOG_PATH, _ACTIVE_STDOUT_TEE, _ACTIVE_STDERR_TEE, _ACTIVE_LOG_HANDLE
|
||||
stdout_tee = _ACTIVE_STDOUT_TEE
|
||||
stderr_tee = _ACTIVE_STDERR_TEE
|
||||
if stdout_tee is not None:
|
||||
sys.stdout = stdout_tee._console
|
||||
if stderr_tee is not None:
|
||||
sys.stderr = stderr_tee._console
|
||||
handle = _ACTIVE_LOG_HANDLE
|
||||
try:
|
||||
handle.close()
|
||||
except Exception:
|
||||
pass
|
||||
_ACTIVE_LOG_PATH = None
|
||||
_ACTIVE_STDOUT_TEE = None
|
||||
_ACTIVE_STDERR_TEE = None
|
||||
_ACTIVE_LOG_HANDLE = None
|
||||
|
||||
|
||||
def active_log_path() -> Path | None:
|
||||
"""返回当前已启用的日志文件路径;未启用文件日志时返回 None。"""
|
||||
return _ACTIVE_LOG_PATH
|
||||
|
||||
|
||||
def maybe_rotate_open_log() -> None:
|
||||
"""
|
||||
常驻 Worker 运行中按大小轮转当前日志。
|
||||
|
||||
核心逻辑:Windows 下无法对仍打开的文件 rename,须先关闭句柄 → 调用既有
|
||||
`rotate_log_file_if_needed` → 再以追加模式打开新文件并挂回 TeeStream。
|
||||
未启用文件日志或未超限时 no-op。
|
||||
"""
|
||||
global _ACTIVE_LOG_HANDLE
|
||||
path = _ACTIVE_LOG_PATH
|
||||
stdout_tee = _ACTIVE_STDOUT_TEE
|
||||
stderr_tee = _ACTIVE_STDERR_TEE
|
||||
handle = _ACTIVE_LOG_HANDLE
|
||||
if path is None or stdout_tee is None or stderr_tee is None or handle is None:
|
||||
return
|
||||
max_bytes = _log_int_env("FREIGHT_RPA_WORKER_LOG_MAX_BYTES", 10 * 1024 * 1024, min_value=0)
|
||||
if max_bytes <= 0:
|
||||
return
|
||||
try:
|
||||
handle.flush()
|
||||
if path.stat().st_size < max_bytes:
|
||||
return
|
||||
except OSError:
|
||||
return
|
||||
try:
|
||||
handle.close()
|
||||
except Exception:
|
||||
pass
|
||||
_ACTIVE_LOG_HANDLE = None
|
||||
rotate_log_file_if_needed(path)
|
||||
new_handle = path.open("a", encoding="utf-8", buffering=1)
|
||||
stdout_tee.replace_log_file(new_handle)
|
||||
stderr_tee.replace_log_file(new_handle)
|
||||
_ACTIVE_LOG_HANDLE = new_handle
|
||||
print(f"[logging] rotated open log path={path}")
|
||||
|
||||
|
||||
def rotate_log_file_if_needed(path: Path) -> None:
|
||||
"""
|
||||
在打开日志前做大小轮转,避免 Windows 常驻 worker 单个日志无限增长。
|
||||
|
||||
核心逻辑:当 `FREIGHT_RPA_WORKER_LOG_FILE` 已存在且大小达到 `FREIGHT_RPA_WORKER_LOG_MAX_BYTES`
|
||||
时,按 `.1`、`.2` ... 备份后缀向后滚动;超过 `FREIGHT_RPA_WORKER_LOG_BACKUP_COUNT`
|
||||
的旧文件会被删除。`FREIGHT_RPA_WORKER_LOG_MAX_BYTES<=0` 时禁用轮转。
|
||||
"""
|
||||
max_bytes = _log_int_env("FREIGHT_RPA_WORKER_LOG_MAX_BYTES", 10 * 1024 * 1024, min_value=0)
|
||||
backup_count = _log_int_env("FREIGHT_RPA_WORKER_LOG_BACKUP_COUNT", 5, min_value=0)
|
||||
if max_bytes <= 0 or not path.is_file():
|
||||
return
|
||||
try:
|
||||
if path.stat().st_size < max_bytes:
|
||||
return
|
||||
except OSError:
|
||||
return
|
||||
|
||||
if backup_count <= 0:
|
||||
path.unlink(missing_ok=True)
|
||||
return
|
||||
|
||||
oldest = Path(f"{path}.{backup_count}")
|
||||
oldest.unlink(missing_ok=True)
|
||||
for index in range(backup_count - 1, 0, -1):
|
||||
src = Path(f"{path}.{index}")
|
||||
if src.exists():
|
||||
src.replace(Path(f"{path}.{index + 1}"))
|
||||
path.replace(Path(f"{path}.1"))
|
||||
Reference in new issue
Block a user