feat(rpa): 收料Worker能力对齐库存Worker并提取公共文件日志模块

- 新增 common/worker_logging:tee+时间戳+按大小轮转,库存 Worker 同步委托切换(纯等价重构)
- 收料 Worker 接入文件日志+完整 banner+领取/归档/单元成败全路径留痕
- 心跳对齐:独立身份 <主机名>-receipt(ps1 注入 WORKER_ID/HEARTBEAT_SECONDS),busy/idle 运行态
- 磁盘保留清理启动+周期,孤儿 Profile 覆盖 receipt_* 前缀;清理失败不中断主循环
- README 能力对齐表与禁止共写日志规则;technical.md §1.9 收料部署事实同步(含身份口径修正)
This commit is contained in:
hugo committed 2026-09-18 11:30:30 +08:00
1 parent 051f80e1e9
commit 4d879dd8ea
11 files changed
+554 -235

No files matched your search

+9 -5
View File
@@ -48,6 +48,9 @@ _PROTECTED_DROP_DIRNAMES = frozenset(
)
_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
@@ -108,7 +111,7 @@ def cleanup_interval_seconds() -> int:
def orphan_profile_max_age_seconds() -> int:
"""
读取孤儿临时 Profile(run_*)最大存活秒数。
读取孤儿临时 Profile(run_* / receipt_*)最大存活秒数。
核心逻辑:`SHIPPING_NOTICE_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS`,默认 24;
`<=0` 禁用孤儿 Profile 清理。会话复用目录(*_session)永不删除。
@@ -332,10 +335,11 @@ def cleanup_orphan_runtime_profiles(
stats: DiskCleanupStats,
) -> None:
"""
清理浏览器 Profile 根下过期的一次性 `run_*` 目录。
清理浏览器 Profile 根下过期的一次性 `run_*` / `receipt_*` 目录。
核心逻辑:会话复用目录名以 `_session` 结尾或历史 `dsv360_session`,一律保留;
仅删除 `run_*` 临时目录,避免异常中断后残留撑盘。
仅删除 `run_*` / `receipt_*` 临时目录,避免异常中断后残留撑盘。
收料 Worker 一次性 Profile 以 receipt_ 前缀创建,同属清理对象。
"""
if profile_root is None or not profile_root.is_dir():
return
@@ -350,7 +354,7 @@ def cleanup_orphan_runtime_profiles(
if name.endswith("_session") or name == "dsv360_session":
stats.skipped += 1
continue
if not name.startswith("run_"):
if not name.startswith(_RUNTIME_PROFILE_TEMP_PREFIXES):
stats.skipped += 1
continue
if not _is_older_than(path, cutoff_unix=cutoff_unix):
@@ -375,7 +379,7 @@ def run_worker_disk_cleanup(
【AI 触发时机】:Worker 启动后及主循环按 `DISK_CLEANUP_INTERVAL_SECONDS` 周期调用。
核心逻辑:按 `DISK_RETENTION_DAYS` 清理归档/日志备份/队列残留;按
`ORPHAN_PROFILE_MAX_AGE_HOURS` 清理孤儿 `run_*` Profile。全部 best-effort。
`ORPHAN_PROFILE_MAX_AGE_HOURS` 清理孤儿 `run_*` / `receipt_*` Profile。全部 best-effort。
Args:
inventory_trigger_dir: 库存 trigger 根目录。
+249
View File
@@ -0,0 +1,249 @@
"""scripts/rpa/common/worker_logging.py
用途:RPA Worker 通用文件日志——stdout/stderr tee 落盘、行级本地时间戳、
按大小轮转(启动前 + 运行中),供库存/收料等所有 Worker 复用。
依赖:rpa_common._env(环境变量读取与历史名兼容)、标准库。
逻辑:configure_file_logging 读 SHIPPING_NOTICE_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/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:
"""
按 SHIPPING_NOTICE_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("SHIPPING_NOTICE_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("SHIPPING_NOTICE_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 单个日志无限增长。
核心逻辑:当 `SHIPPING_NOTICE_RPA_WORKER_LOG_FILE` 已存在且大小达到 `SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES`
时,按 `.1`、`.2` ... 备份后缀向后滚动;超过 `SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT`
的旧文件会被删除。`SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES<=0` 时禁用轮转。
"""
max_bytes = _log_int_env("SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES", 10 * 1024 * 1024, min_value=0)
backup_count = _log_int_env("SHIPPING_NOTICE_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"))