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

@@ -49,3 +49,22 @@ def test_receipt_worker_uses_common_trigger_consumer():
assert 'claim_trigger' in text
assert 'archive_trigger' in text
assert "path.replace(claimed)" not in text # 领取逻辑收敛到公共模块
def test_receipt_worker_logs_full_lifecycle_and_banner():
"""收料 Worker 必须启用文件日志、完整启动 banner,且成功/失败单元都留痕。"""
text = (Path(__file__).resolve().parents[2] / 'scripts' / 'rpa' / 'receipt' / 'receipt_rpa_worker.py').read_text(encoding='utf-8')
assert 'configure_file_logging' in text
assert 'maybe_rotate_open_log' in text
assert 'mock=' in text and 'api_base=' in text and 'auth_key=' in text # banner 对齐库存字段
assert '[receipt-unit] success' in text # 成功单元留痕(此前成功路径零输出)
assert '[receipt-unit] failed' in text
assert '[receipt-trigger] claimed' in text and '[receipt-trigger] archived' in text
def test_receipt_worker_reports_heartbeat_with_dedicated_identity():
"""收料 Worker 必须接心跳(对齐库存),且 ps1 以独立 WORKER_ID 上报避免监控身份抖动。"""
text = (Path(__file__).resolve().parents[2] / 'scripts' / 'rpa' / 'receipt' / 'receipt_rpa_worker.py').read_text(encoding='utf-8')
assert 'start_heartbeat_loop' in text and 'maybe_send_heartbeat' in text
ps1 = (Path(__file__).resolve().parents[2] / 'scripts' / 'rpa' / 'receipt' / 'start_receipt_worker.ps1').read_text(encoding='utf-8')
assert 'SHIPPING_NOTICE_RPA_WORKER_ID' in ps1 and '-receipt' in ps1
+64 -6
View File
@@ -609,7 +609,8 @@ def test_worker_reads_legacy_rpa_env_during_migration(monkeypatch):
def test_configure_file_logging_tees_stdout_and_stderr(monkeypatch, tmp_path, capsys):
"""配置 SHIPPING_NOTICE_RPA_WORKER_LOG_FILE 后,stdout/stderr 应同时写入日志文件并带行首时间戳。"""
worker = _load_freight_rpa_worker()
# 等价迁移:文件日志实现已提取至公共 worker_logging 模块,本用例改测公共接口。
worker_logging = _load_worker_logging()
log_path = tmp_path / "logs" / "worker.log"
timestamp_pattern = re.compile(r"^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} ")
@@ -618,7 +619,7 @@ def test_configure_file_logging_tees_stdout_and_stderr(monkeypatch, tmp_path, ca
original_stderr = sys.stderr
try:
resolved = worker._configure_file_logging()
resolved = worker_logging.configure_file_logging()
print("hello stdout")
print("hello stderr", file=sys.stderr)
finally:
@@ -645,7 +646,8 @@ def test_configure_file_logging_tees_stdout_and_stderr(monkeypatch, tmp_path, ca
def test_rotate_log_file_when_size_reaches_limit(monkeypatch, tmp_path):
"""日志超过 SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES 时,应滚动为 .1 并保留旧备份序列。"""
worker = _load_freight_rpa_worker()
# 等价迁移:轮转实现已提取至公共 worker_logging 模块,本用例改测公共接口。
worker_logging = _load_worker_logging()
log_path = tmp_path / "worker.log"
log_path.write_text("current-log", encoding="utf-8")
Path(f"{log_path}.1").write_text("old-1", encoding="utf-8")
@@ -653,7 +655,7 @@ def test_rotate_log_file_when_size_reaches_limit(monkeypatch, tmp_path):
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES", "1")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT", "2")
worker._rotate_log_file_if_needed(log_path)
worker_logging.rotate_log_file_if_needed(log_path)
assert not log_path.exists()
assert Path(f"{log_path}.1").read_text(encoding="utf-8") == "current-log"
@@ -662,18 +664,41 @@ def test_rotate_log_file_when_size_reaches_limit(monkeypatch, tmp_path):
def test_rotate_log_file_deletes_current_when_backup_count_zero(monkeypatch, tmp_path):
"""备份数量为 0 时,超过大小的当前日志应直接删除。"""
worker = _load_freight_rpa_worker()
# 等价迁移:轮转实现已提取至公共 worker_logging 模块,本用例改测公共接口。
worker_logging = _load_worker_logging()
log_path = tmp_path / "worker.log"
log_path.write_text("current-log", encoding="utf-8")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES", "1")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT", "0")
worker._rotate_log_file_if_needed(log_path)
worker_logging.rotate_log_file_if_needed(log_path)
assert not log_path.exists()
def _load_worker_logging():
"""加载 scripts/rpa/common/worker_logging.py 供单测直接断言。
历史背景:文件日志实现(tee/轮转/时间戳)原内置于 inventory_rpa_worker.py,
已提取为公共模块;Worker 内部私有名(_configure_file_logging 等)已删除,
日志行为用例统一改测公共接口,行为断言保持等价。
"""
common_dir = _repo_root() / "scripts" / "rpa" / "common"
if str(common_dir) not in sys.path:
sys.path.insert(0, str(common_dir))
module_path = common_dir / "worker_logging.py"
spec = importlib.util.spec_from_file_location("worker_logging_under_test", module_path)
assert spec is not None
assert spec.loader is not None
module = importlib.util.module_from_spec(spec)
# 模块顶层 `from rpa_common import _env` 依赖 sys.path,须先登记再执行;
# _ACTIVE_* 运行态按用例独立加载实例,避免跨用例状态串扰。
sys.modules[spec.name] = module
spec.loader.exec_module(module)
return module
def _load_worker_disk_cleanup():
"""加载 scripts/rpa/common/worker_disk_cleanup.py 供单测直接断言。"""
module_path = _repo_root() / "scripts" / "rpa" / "common" / "worker_disk_cleanup.py"
@@ -823,6 +848,39 @@ def test_worker_disk_cleanup_skips_when_retention_disabled(monkeypatch, tmp_path
assert not orphan_run.exists()
def test_cleanup_orphan_runtime_profiles_removes_receipt_prefix(tmp_path):
"""
崩溃残留的 receipt_* 临时 Profile 超期必须被清理;_session 目录保留。
断言意图:收料 Worker 的一次性 Profile 以 receipt_ 前缀创建,异常中断后
残留目录同样按孤儿 Profile 规则清理;会话复用目录按名豁免(与年龄无关);
未超期的 receipt_* Profile 正在使用中,前缀匹配不得误删。
"""
cleanup = _load_worker_disk_cleanup()
root = tmp_path / "browser_profile"
stale_receipt = root / "receipt_abcd1234"
stale_receipt.mkdir(parents=True)
(stale_receipt / "Cookies").write_text("drop", encoding="utf-8")
young_receipt = root / "receipt_fresh5678"
young_receipt.mkdir()
session_dir = root / "dsv_session"
session_dir.mkdir()
now = time.time()
old = now - 10 * 24 * 3600
os.utime(stale_receipt, (old, old))
os.utime(young_receipt, (now - 3600, now - 3600))
os.utime(session_dir, (old, old))
stats = cleanup.DiskCleanupStats()
# cutoff 对齐真实调用语义:run_worker_disk_cleanup 传入 now - 孤儿最大存活(默认 24h)
cleanup.cleanup_orphan_runtime_profiles(root, cutoff_unix=now - 24 * 3600, stats=stats)
# 过期 receipt_* 目录树删除;未过期 receipt_* 与 _session 结尾目录即使过期也保留
assert not stale_receipt.exists() and session_dir.exists()
assert young_receipt.exists()
assert stats.deleted_dirs == 1
def test_open_browser_uses_shipping_notice_profile_fallback(monkeypatch):
"""未配置 profile 根目录时,应回退到 shipping_notice/freight_rpa/browser_profile。"""
worker = _load_freight_rpa_worker()
@@ -69,3 +69,11 @@ def test_inventory_worker_scans_with_claim(tmp_path):
assert "claim_trigger" in text
# 三处 handler 的 failed 目录推导必须基于 processed_dir(根目录),不得再用 trigger_path.parent
assert text.count('trigger_path.parent / "failed"') == 0
def test_receipt_worker_runs_periodic_disk_cleanup():
"""收料 Worker 必须周期执行保留清理(对齐库存),孤儿 receipt_* Profile 必须纳入清理。"""
receipt = (Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "receipt" / "receipt_rpa_worker.py").read_text(encoding="utf-8")
assert "run_worker_disk_cleanup" in receipt and "cleanup_interval_seconds" in receipt
cleanup = (Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "common" / "worker_disk_cleanup.py").read_text(encoding="utf-8")
assert '"receipt_"' in cleanup or "'receipt_'" in cleanup
+84
View File
@@ -0,0 +1,84 @@
"""worker_logging 公共文件日志模块测试。
用途:锁定 Worker 文件日志行为——tee 落盘带时间戳、stdout 同时可见、
按大小轮转滚动备份、shutdown 恢复标准流。
依赖:标准库 + scripts/rpa/common/worker_logging。
逻辑:直接驱动公共函数,monkeypatch 环境变量与恢复标准流,不启动真实 Worker。
"""
from __future__ import annotations
import sys
from pathlib import Path
import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "common"))
from worker_logging import ( # noqa: E402
WorkerLogTee,
configure_file_logging,
log_line_timestamp,
rotate_log_file_if_needed,
shutdown_logging,
)
@pytest.fixture(autouse=True)
def _restore_streams():
"""每用例后强制恢复标准流并关闭日志,避免污染其他测试。"""
yield
shutdown_logging()
def test_tee_writes_timestamped_lines_to_both_streams(tmp_path, capsys):
"""tee 应把带时间戳的行同时写入控制台与日志文件。"""
log_file = (tmp_path / "worker.log").open("w", encoding="utf-8", buffering=1)
tee = WorkerLogTee(sys.stdout, log_file)
original_stdout = sys.stdout
sys.stdout = tee
try:
print("hello-worker")
finally:
sys.stdout = original_stdout
log_file.close()
content = (tmp_path / "worker.log").read_text(encoding="utf-8")
assert "hello-worker" in content
assert content.startswith(log_line_timestamp()[:10]) # 日期前缀存在
assert "hello-worker" in capsys.readouterr().out
def test_rotate_rolls_backups_and_drops_oldest(tmp_path, monkeypatch):
"""超过 max_bytes 时按 .1/.2 滚动,超过 backup_count 的最旧备份删除。"""
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES", "10")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT", "2")
path = tmp_path / "worker.log"
for round_no in range(3):
path.write_text(f"round-{round_no}-padding", encoding="utf-8")
rotate_log_file_if_needed(path)
# [断言意图] 滚动语义:最新内容滚入 .1,次新在 .2,最旧(round-0)被删,主文件位空缺待新写入
assert Path(f"{path}.1").read_text(encoding="utf-8") == "round-2-padding"
assert Path(f"{path}.2").read_text(encoding="utf-8") == "round-1-padding"
assert not Path(f"{path}.3").exists()
assert not path.exists() # 轮转后主文件位腾空,由调用方以追加模式重建
def test_configure_file_logging_enables_tee_and_shutdown_restores(tmp_path, monkeypatch, capsys):
"""configure 启用落盘、print 双写;shutdown 恢复标准流且不再写文件。"""
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_FILE", str(tmp_path / "logs" / "worker.log"))
enabled = configure_file_logging()
assert enabled == tmp_path / "logs" / "worker.log"
assert enabled.parent.is_dir() # 日志目录自动创建
print("banner-line")
shutdown_logging()
content = (tmp_path / "logs" / "worker.log").read_text(encoding="utf-8")
assert "banner-line" in content
assert "[logging] tee enabled" in content
out = capsys.readouterr().out
assert "banner-line" in out
def test_configure_without_env_is_noop(monkeypatch):
"""未配置 LOG_FILE 时 configure 返回 None 且不改标准流。"""
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_LOG_FILE", raising=False)
assert configure_file_logging() is None