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:
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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -2973,7 +2973,7 @@ pytest tests/test_shipping_notice_state_machine.py tests/test_shipping_notice_ui
|
||||
| trigger 目录 | `data\inventory_triggers` | `data\freight_receipt_rpa\receipt_triggers` |
|
||||
| drop 目录 | `data\inventory_drop` | `data\freight_receipt_rpa\receipt_drop` |
|
||||
| 回调端点 | `/api/shipping-notice/rpa/inventory-batch-ready` | `/api/shipping-notice/rpa/receipt-batch-ready` |
|
||||
| 心跳与哨兵 | 必需,触发前在线检查 fail-fast | **无**:收料 Worker 不发心跳、不写 `.hxops_rpa_shared_mount` |
|
||||
| 心跳与哨兵 | 必需,触发前在线检查 fail-fast | 心跳已接:以 `<主机名>-receipt` 独立身份周期上报(ps1 注入 `SHIPPING_NOTICE_RPA_WORKER_ID`);仍不写 `.hxops_rpa_shared_mount` 哨兵,触发前无 fail-fast 在线检查 |
|
||||
| 结果归属 | 库存快照/库存匹配 | MinIO 原样归档 + 企微投递,绝不进入库存链路 |
|
||||
|
||||
路径对应关系(测试环境;正式环境把 `Test` / `test-data` 换成 `Prod` / `prod-data`):
|
||||
@@ -3021,15 +3021,17 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File `
|
||||
-SecretFile "C:\HxopsRpaSecrets\test.xml"
|
||||
```
|
||||
|
||||
启动成功会输出 `[freight_receipt_rpa_worker] started trigger_dir=... drop_dir=...`,随后轮询 `receipt_triggers` 下完整的 `.json` 触发文件。执行策略拦截、`Unblock-File`、UTF-8 BOM 要求均与 `1.5.10` 相同(`start_receipt_worker.ps1` 同样必须保持 UTF-8 BOM,从仓库原样复制)。
|
||||
启动成功会输出 `[freight_receipt_rpa_worker] started` 独立行,后跟缩进字段块(` mock=...`、` api_base=...`、` trigger_dir=...`、` drop_dir=...`、` log=...` 等,完整字段以 `receipt_rpa_worker.py` 启动 banner 为准),随后轮询 `receipt_triggers` 下完整的 `.json` 触发文件。执行策略拦截、`Unblock-File`、UTF-8 BOM 要求均与 `1.5.10` 相同(`start_receipt_worker.ps1` 同样必须保持 UTF-8 BOM,从仓库原样复制)。
|
||||
|
||||
后台常驻沿用 `1.5.10` 的「`AtLogOn + Interactive`、每环境独立任务」模式,仅把动作换成收料启动脚本。收料 Worker 不写 `worker.log`,日志输出到控制台;计划任务建议用 `cmd.exe` 包装做文件重定向:
|
||||
启动脚本同时自动注入两个 Worker 运行变量:`SHIPPING_NOTICE_RPA_WORKER_LOG_FILE`(ps1 自动设为 `data\freight_receipt_rpa\logs\worker.log`,文件日志带时间戳并按大小轮转,无需手工配置)与 `SHIPPING_NOTICE_RPA_WORKER_ID=<主机名>-receipt`(独立心跳身份,监控端按此身份出独立收料卡片,不与库存 Worker 的 `<主机名>-<pid>` 混淆)。收料 Worker 的文件日志、启动 banner、心跳上报与周期磁盘保留清理(含共享 Profile 的孤儿 `receipt_*`)能力均已与库存 Worker 对齐;两个 Worker 禁止共写同一日志文件,各自由启动脚本指向各自根目录下的 `logs\worker.log`。
|
||||
|
||||
后台常驻沿用 `1.5.10` 的「`AtLogOn + Interactive`、每环境独立任务」模式,仅把动作换成收料启动脚本。收料 Worker 由启动脚本注入 `SHIPPING_NOTICE_RPA_WORKER_LOG_FILE`,文件日志写入 `data\freight_receipt_rpa\logs\worker.log`(tee 控制台、带时间戳、按大小轮转);计划任务仍可用 `cmd.exe` 包装对控制台输出做重定向留档:
|
||||
|
||||
```powershell
|
||||
$TestApiBase = "http://<test后端地址>:<端口>"
|
||||
$ReceiptAction = New-ScheduledTaskAction `
|
||||
-Execute "cmd.exe" `
|
||||
-Argument "/c powershell.exe -NoProfile -ExecutionPolicy Bypass -File ""C:\HxopsRpaTest\scripts\rpa\receipt\start_receipt_worker.ps1"" -Environment test -ApiBase ""$TestApiBase"" -WorkerRoot ""C:\HxopsRpaTest"" -SecretFile ""C:\HxopsRpaSecrets\test.xml"" >> ""C:\HxopsRpaTest\data\freight_receipt_rpa\logs\receipt_worker.log"" 2>&1" `
|
||||
-Argument "/c powershell.exe -NoProfile -ExecutionPolicy Bypass -File ""C:\HxopsRpaTest\scripts\rpa\receipt\start_receipt_worker.ps1"" -Environment test -ApiBase ""$TestApiBase"" -WorkerRoot ""C:\HxopsRpaTest"" -SecretFile ""C:\HxopsRpaSecrets\test.xml"" >> ""C:\HxopsRpaTest\data\freight_receipt_rpa\logs\receipt_console_output.log"" 2>&1" `
|
||||
-WorkingDirectory "C:\HxopsRpaTest"
|
||||
# $Trigger / $Principal / $Settings 与 1.5.10 的库存任务完全一致:
|
||||
# AtLogOn + Interactive;RestartCount 10、RestartInterval 1 分钟、ExecutionTimeLimit 0、MultipleInstances IgnoreNew。
|
||||
@@ -3060,7 +3062,7 @@ SHIPPING_NOTICE_RPA_RECEIPT_TIMEOUT_SECONDS=900
|
||||
- 到期对象由平台排程任务 **货代收料归档到期清理**(`freight-receipt-rpa-retention`)删除,建议在排程管理配置每日一次;它只删除过期对象,不删除运行、文件事实与审计记录。
|
||||
- 企微逐文件推送与汇总发给排程任务配置的接收人(`notify_user_ids` + `notify_enabled`),接收人必须已完成企微绑定,否则投递记 `WECOM_USER_UNBOUND` 失败。
|
||||
|
||||
排程创建:管理端「排程管理」新增平台任务 **货代收料 RPA**(`freight-receipt-rpa`),可选参数 `source_codes` 留空则执行全部已启用收料配置,按需配置 Cron 与接收人。收料排程与库存排程相互独立(站点、Cron、接收人分别选择)。收料触发前**没有**库存那套 Worker 在线 fail-fast 检查:Worker 停止只会让单元等待到 `SHIPPING_NOTICE_RPA_RECEIPT_TIMEOUT_SECONDS` 超时回收,因此上线后应按 `1.9.4` 验收并保留 `receipt_worker.log` 巡检。
|
||||
排程创建:管理端「排程管理」新增平台任务 **货代收料 RPA**(`freight-receipt-rpa`),可选参数 `source_codes` 留空则执行全部已启用收料配置,按需配置 Cron 与接收人。收料排程与库存排程相互独立(站点、Cron、接收人分别选择)。收料触发前**没有**库存那套 Worker 在线 fail-fast 检查:Worker 停止只会让单元等待到 `SHIPPING_NOTICE_RPA_RECEIPT_TIMEOUT_SECONDS` 超时回收,因此上线后应按 `1.9.4` 验收并保留 `data\freight_receipt_rpa\logs\worker.log` 巡检。
|
||||
|
||||
#### 1.9.4 端到端验证
|
||||
|
||||
@@ -3082,8 +3084,8 @@ SHIPPING_NOTICE_RPA_RECEIPT_TIMEOUT_SECONDS=900
|
||||
- 回调报 `SHIPPING.RECEIPT_CALLBACK_FILE_INVALID`:`file_path` 不在收料 drop 根内、非 `.xlsx`、空文件或超过 `FILE_ASSET_MAX_SIZE_MB`;多为收料/库存目录串用所致。
|
||||
- 单元长期 `awaiting_rpa`、排程停在 `awaiting_receipt_rpa_callback`:Worker 停止或崩溃;超过 `SHIPPING_NOTICE_RPA_RECEIPT_TIMEOUT_SECONDS` 由回收逻辑置 `RPA.RECEIPT_CALLBACK_TIMEOUT`,**不自动重试**,需管理员带原因重试或等下一轮 Cron。
|
||||
- DBS/Crane 登录或导出失败:先在 Windows 手工登录确认 MFA/SSO/代理;Crane 无论 Profile 首页保存为何,Worker 均强制进入 `#/inbound-details-query` 用页面默认条件执行;确认 Profile 已启用且 `SHIPPING_NOTICE_RPA_CREDENTIAL_KEY` 两端一致(否则无法解密凭据)。
|
||||
- `receipt_drop` 磁盘占用增长:归档完成后本地文件不再被后端读取,收料 Worker **不做本地清理**;按运维周期人工清理,建议保留最近几天便于排障。
|
||||
- 其余排障顺序与 `1.5.12` 一致:先看 Worker 控制台 / `receipt_worker.log`,再看两端目录与共享挂载,最后看后端日志与收料审计事件。
|
||||
- `receipt_drop` 磁盘占用增长:收料 Worker 已启用周期磁盘保留清理(启动 + 周期各一轮,清收料 processed/failed/drop 与共享 Profile 的孤儿 `run_*`/`receipt_*`);如需更早释放仍可人工清理,建议保留最近几天便于排障。
|
||||
- 其余排障顺序与 `1.5.12` 一致:先看 Worker 控制台 / `data\freight_receipt_rpa\logs\worker.log`,再看两端目录与共享挂载,最后看后端日志与收料审计事件。
|
||||
|
||||
#### 1.9.6 收料 RPA 三环境速查
|
||||
|
||||
|
||||
+15
-3
@@ -133,6 +133,18 @@ DSV Worker 默认使用 `#file2`,也可用 `SHIPPING_NOTICE_RPA_WORKER_UPLOAD_
|
||||
人工确认导出未完成则移回根目录重跑,已完成则人工补回调后归档。
|
||||
- 新增 Worker 一律复用 `common/trigger_consumer.py`,禁止再自建目录搬移逻辑。
|
||||
|
||||
## Worker 运行能力(库存 / 收料对齐)
|
||||
|
||||
| 能力 | 库存 Worker | 收料 Worker |
|
||||
| --- | --- | --- |
|
||||
| 文件日志(tee+时间戳+轮转) | `SHIPPING_NOTICE_RPA_WORKER_LOG_FILE` | 同左(ps1 默认 `data\freight_receipt_rpa\logs\worker.log`) |
|
||||
| 启动 banner / 运行中轮转 | ✅ | ✅(同一 `worker_logging` 模块) |
|
||||
| 心跳上报 | `<hostname>-<pid>`(随进程重启变化,ps1 未注入 `WORKER_ID`) | `<hostname>-receipt`(独立身份,ps1 注入) |
|
||||
| 磁盘保留清理 | 周期 + 启动一轮 | 同左(清收料 processed/failed/drop 与共享 Profile 的孤儿 `run_*`/`receipt_*`) |
|
||||
|
||||
规则:**两个 Worker 禁止共写同一日志文件**(多进程写同一文件会交错且 Windows 轮转竞争);
|
||||
每个 Worker 的 `LOG_FILE` 必须指向各自根目录下的 `logs/worker.log`。
|
||||
|
||||
## 部署、启动与停止手册
|
||||
|
||||
本节说明库存 RPA 测试导出的三种运行方式:
|
||||
@@ -184,9 +196,9 @@ Linux HXOPS 后端 Windows RPA Worker
|
||||
2. 程序:整目录复制 `scripts\rpa` 时已包含 `receipt\`;`receipt_rpa_worker.py` 要求同级存在 `connectors/`、`common/`、`inventory/`、`receipt/` 四个子目录,不能单拷 `receipt\`。
|
||||
3. 依赖:在库存 Worker 依赖之上补 `cryptography`:`python -m pip install playwright openpyxl pyyaml cryptography`。
|
||||
4. Secret:与库存共用 `new_rpa_worker_secret.ps1` 生成的 `C:\HxopsRpaSecrets\test.xml` / `prod.xml`,无需新建。
|
||||
5. 启动:`scripts\rpa\receipt\start_receipt_worker.ps1`,参数与库存启动脚本一致(`-Environment`、`-ApiBase`、`-WorkerRoot`、`-SecretFile`,可选 `-Mock` / `-Headless`);成功输出 `[freight_receipt_rpa_worker] started trigger_dir=... drop_dir=...`。
|
||||
6. 心跳/哨兵:收料 Worker **不发心跳、不写哨兵**,不参与「RPA Worker 在线」检查;收料触发前无 fail-fast,Worker 停止只会让单元等到 `SHIPPING_NOTICE_RPA_RECEIPT_TIMEOUT_SECONDS`(默认 900 秒)超时回收。
|
||||
7. 日志:收料 Worker 只输出到控制台;计划任务用 `cmd.exe` 包装 `>>` 重定向到 `data\freight_receipt_rpa\logs\receipt_worker.log`(完整任务计划示例见 technical.md §1.9.2)。
|
||||
5. 启动:`scripts\rpa\receipt\start_receipt_worker.ps1`,参数与库存启动脚本一致(`-Environment`、`-ApiBase`、`-WorkerRoot`、`-SecretFile`,可选 `-Mock` / `-Headless`);成功输出 `[freight_receipt_rpa_worker] started` 独立行,后跟缩进字段块(` mock=...`、` api_base=...`、` trigger_dir=...`、` drop_dir=...`、` log=...` 等,完整字段以 `receipt_rpa_worker.py` 启动 banner 为准)。
|
||||
6. 心跳/哨兵:心跳已接——以独立身份 `<主机名>-receipt`(ps1 注入 `SHIPPING_NOTICE_RPA_WORKER_ID`)按 `SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS`(默认 20 秒)周期上报 `/api/shipping-notice/rpa/heartbeat`;仍不写 `.hxops_rpa_shared_mount` 哨兵、触发前无 fail-fast 在线检查,Worker 停止只会让单元等到 `SHIPPING_NOTICE_RPA_RECEIPT_TIMEOUT_SECONDS`(默认 900 秒)超时回收。
|
||||
7. 日志:文件日志已接——ps1 注入 `SHIPPING_NOTICE_RPA_WORKER_LOG_FILE`,默认 `data\freight_receipt_rpa\logs\worker.log`(tee 控制台 + 时间戳 + 按大小轮转,与库存 Worker 同一 `worker_logging` 模块,两个 Worker 禁止共写同一日志文件);计划任务仍可用 `cmd.exe` 包装 `>>` 重定向控制台输出留档(完整任务计划示例见 technical.md §1.9.2)。
|
||||
8. 后端:`.env` 追加 `SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR` / `SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR` 两个共享子路径(漏配会写容器本地默认路径,Windows 看不到);容器 bind mount 无需新增。收料文件回调后原样归档 MinIO 保留三年,到期清理由平台任务「货代收料归档到期清理」负责。
|
||||
|
||||
|
||||
|
||||
@@ -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 根目录。
|
||||
|
||||
@@ -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"))
|
||||
@@ -40,7 +40,6 @@ Optional:
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import atexit
|
||||
from contextlib import contextmanager
|
||||
import json
|
||||
import os
|
||||
@@ -53,7 +52,7 @@ import urllib.error
|
||||
import urllib.request
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable, TextIO
|
||||
from typing import Any, Callable
|
||||
|
||||
from cryptography.fernet import Fernet, InvalidToken
|
||||
|
||||
@@ -91,6 +90,8 @@ from download_artifact_fallback import ( # noqa: E402
|
||||
wait_for_new_download_file as _wait_for_new_download_file,
|
||||
)
|
||||
from trigger_consumer import claim_trigger # noqa: E402
|
||||
# 日志实现已提取至公共模块(scripts/rpa/common/worker_logging.py),本 Worker 仅委托调用。
|
||||
from worker_logging import active_log_path, configure_file_logging, maybe_rotate_open_log # noqa: E402
|
||||
|
||||
# 测试与 smoke 向后兼容 re-export
|
||||
_maybe_auto_login_dsv = dsv_session.maybe_auto_login_dsv
|
||||
@@ -136,214 +137,6 @@ except ImportError:
|
||||
Workbook = None # type: ignore
|
||||
|
||||
|
||||
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")
|
||||
|
||||
|
||||
class _TeeStream:
|
||||
"""
|
||||
同时写入控制台与日志文件的轻量 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: _TeeStream | None = None
|
||||
_ACTIVE_STDERR_TEE: _TeeStream | 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
|
||||
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 = _TeeStream(original_stdout, log_file)
|
||||
stderr_tee = _TeeStream(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
|
||||
|
||||
def _close_log() -> None:
|
||||
global _ACTIVE_LOG_PATH, _ACTIVE_STDOUT_TEE, _ACTIVE_STDERR_TEE, _ACTIVE_LOG_HANDLE
|
||||
sys.stdout = original_stdout
|
||||
sys.stderr = original_stderr
|
||||
handle = _ACTIVE_LOG_HANDLE or log_file
|
||||
try:
|
||||
handle.close()
|
||||
except Exception:
|
||||
pass
|
||||
_ACTIVE_LOG_PATH = None
|
||||
_ACTIVE_STDOUT_TEE = None
|
||||
_ACTIVE_STDERR_TEE = None
|
||||
_ACTIVE_LOG_HANDLE = None
|
||||
|
||||
atexit.register(_close_log)
|
||||
print(f"[logging] tee enabled path={path}")
|
||||
return 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 _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)
|
||||
|
||||
|
||||
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"))
|
||||
|
||||
|
||||
def _backend_dir() -> Path:
|
||||
"""
|
||||
返回仓库内 backend 根目录。
|
||||
@@ -2732,14 +2525,14 @@ def _run_periodic_disk_cleanup(
|
||||
if not force and (now_mono - last_cleanup_mono) < interval:
|
||||
return last_cleanup_mono
|
||||
try:
|
||||
_maybe_rotate_open_log()
|
||||
maybe_rotate_open_log()
|
||||
stats = worker_disk_cleanup.run_worker_disk_cleanup(
|
||||
inventory_trigger_dir=inv_trigger_dir,
|
||||
upload_trigger_dir=upload_trigger_dir,
|
||||
drop_dir=drop_dir,
|
||||
upload_queue_dir=upload_queue_dir,
|
||||
browser_profile_dir=_browser_profile_root(),
|
||||
log_file=_ACTIVE_LOG_PATH,
|
||||
log_file=active_log_path(),
|
||||
)
|
||||
print(worker_disk_cleanup.format_cleanup_summary(stats))
|
||||
except Exception as exc:
|
||||
@@ -2754,7 +2547,7 @@ def main() -> None:
|
||||
核心逻辑:主循环扫描库存/上传 trigger;空闲时按间隔清理本机归档与临时文件,
|
||||
防止长期运行撑爆 RPA 主机盘符。
|
||||
"""
|
||||
log_path = _configure_file_logging()
|
||||
log_path = configure_file_logging()
|
||||
drop_dir = _require_path("SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR")
|
||||
inv_trigger_dir = _require_path("SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR")
|
||||
upload_queue_dir = _require_path("SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR")
|
||||
|
||||
@@ -33,6 +33,10 @@ if _RPA_ROOT is not None:
|
||||
|
||||
from rpa_common import browser_timeout_ms, click_text, env, select_or_fill # noqa: E402
|
||||
from trigger_consumer import archive_trigger, claim_trigger # noqa: E402
|
||||
import rpa_heartbeat # noqa: E402
|
||||
import worker_logging # noqa: E402
|
||||
import worker_disk_cleanup # noqa: E402
|
||||
from worker_disk_cleanup import cleanup_interval_seconds, format_cleanup_summary, run_worker_disk_cleanup # noqa: E402
|
||||
import receipt_crane_export # noqa: E402
|
||||
import receipt_dbs_export # noqa: E402
|
||||
|
||||
@@ -42,6 +46,14 @@ def _backend_dir() -> Path:
|
||||
return _RPA_ROOT.parents[1] / 'backend'
|
||||
|
||||
|
||||
def _mask_secret(value: str | None) -> str:
|
||||
"""掩码打印密钥:保留前 4 后 4,其余以 .... 代替;缺失或过短返回占位。"""
|
||||
value = str(value or '').strip()
|
||||
if len(value) <= 8:
|
||||
return '***' if value else 'missing'
|
||||
return f'{value[:4]}....{value[-4:]}'
|
||||
|
||||
|
||||
def _require_dir(variable: str) -> Path:
|
||||
"""读取 receipt 专用目录;不回退至库存共享路径。"""
|
||||
value = env(variable)
|
||||
@@ -150,6 +162,7 @@ def _validate_unit(unit: dict[str, Any]) -> None:
|
||||
|
||||
def _report_failure(unit: dict[str, Any], exc: Exception) -> None:
|
||||
"""失败单元单独回调;callback 本身失败则由 trigger failed 目录留待人工处理。"""
|
||||
print(f'[receipt-unit] failed source={unit.get("source_code")} callback={unit.get("callback_id")} error={str(exc)[:200]}')
|
||||
_post_callback({'schema_version': 'shipping_receipt_rpa.v1', 'callback_id': unit.get('callback_id'), 'status': 'failed', 'error_code': 'RPA.RECEIPT_EXPORT_FAILED', 'error_message': str(exc)[:2000]})
|
||||
|
||||
|
||||
@@ -165,6 +178,7 @@ def _process_units(body: dict[str, Any], drop_dir: Path) -> None:
|
||||
_validate_unit(item)
|
||||
grouped.setdefault((str(item['connector_type']).lower(), str(item['rpa_profile_code']), str(item['login_url'])), []).append(dict(item))
|
||||
for (connector, _profile, login_url), group in grouped.items():
|
||||
print(f'[receipt-batch] connector={connector} profile={_profile} units={len(group)}')
|
||||
mock = env('SHIPPING_NOTICE_RPA_WORKER_MOCK', 'false').lower() == 'true'
|
||||
resources = (None, None, None, None)
|
||||
try:
|
||||
@@ -188,6 +202,10 @@ def _process_units(body: dict[str, Any], drop_dir: Path) -> None:
|
||||
else:
|
||||
download = receipt_crane_export.export_receipt_report(page, unit, env=env, browser_timeout_ms=browser_timeout_ms(), select_or_fill=select_or_fill, click_text=click_text, first_in_profile=index == 0)
|
||||
output = _save_download(download, drop_dir, unit)
|
||||
print(
|
||||
f'[receipt-unit] success source={unit["source_code"]} '
|
||||
f'callback={unit["callback_id"]} file={output.name} size={output.stat().st_size}'
|
||||
)
|
||||
_post_callback({'schema_version': 'shipping_receipt_rpa.v1', 'callback_id': unit['callback_id'], 'status': 'success', 'file_path': str(output), 'original_filename': output.name, 'sha256': hashlib.sha256(output.read_bytes()).hexdigest()})
|
||||
except Exception as exc:
|
||||
_report_failure(unit, exc)
|
||||
@@ -210,28 +228,96 @@ def _claim_and_process(path: Path, drop_dir: Path) -> None:
|
||||
claimed = claim_trigger(path)
|
||||
if claimed is None:
|
||||
return
|
||||
print(f'[receipt-trigger] claimed {claimed.name}')
|
||||
# 心跳运行态对齐库存 Worker:领取成功即 busy,处理结束(含归档 failed 后 re-raise)
|
||||
# 由 finally 恢复 idle,保证 SystemExit 兜底路径也不会让监控长期挂 busy。
|
||||
rpa_heartbeat.set_worker_runtime_status('busy')
|
||||
try:
|
||||
_process_units(json.loads(claimed.read_text(encoding='utf-8')), drop_dir)
|
||||
archive_trigger(claimed, 'processed')
|
||||
print(f'[receipt-trigger] archived processed {claimed.name}')
|
||||
except (Exception, SystemExit):
|
||||
# SystemExit 也一并捕获:_require_dir 缺 env 会抛 SystemExit(非 Exception),
|
||||
# 若不捕获会静默退出进程、trigger 卡死在 processing/,无法归档到 failed/。
|
||||
archive_trigger(claimed, 'failed')
|
||||
print(f'[receipt-trigger] archived failed {claimed.name}')
|
||||
raise
|
||||
finally:
|
||||
rpa_heartbeat.set_worker_runtime_status('idle')
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""轮询收料专用 trigger 目录;不加载或扫描任何库存/upload 目录。"""
|
||||
worker_logging.configure_file_logging() # 未配置 LOG_FILE 时 no-op,仅 stdout
|
||||
drop_dir = _require_dir('SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR')
|
||||
trigger_dir = _require_dir('SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR')
|
||||
poll = max(1, int(env('SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS', '3') or '3'))
|
||||
print(f'[freight_receipt_rpa_worker] started trigger_dir={trigger_dir} drop_dir={drop_dir}')
|
||||
heartbeat_seconds = max(
|
||||
15,
|
||||
int(env('SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS', '20') or '20'),
|
||||
)
|
||||
last_cleanup_mono = 0.0
|
||||
cleanup_interval = cleanup_interval_seconds()
|
||||
# [STEP 1] 启动 banner:字段对齐库存 Worker,排查时一处看全运行配置。
|
||||
print(
|
||||
'[freight_receipt_rpa_worker] started\n'
|
||||
f' mock={env("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false")}\n'
|
||||
f' api_base={env("HXOPS_API_BASE", "http://127.0.0.1:5052").rstrip("/")}\n'
|
||||
f' poll_seconds={poll}\n'
|
||||
f' heartbeat_seconds={heartbeat_seconds}\n'
|
||||
f' headless={env("SHIPPING_NOTICE_RPA_WORKER_HEADLESS", "false")} '
|
||||
f'channel={env("SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL") or "default-chromium"}\n'
|
||||
f' auth_key={_mask_secret(env("SHIPPING_NOTICE_TOOL_API_KEY") or env("INTEGRATION_API_KEY"))}\n'
|
||||
f' credential_key={_mask_secret(env("SHIPPING_NOTICE_RPA_CREDENTIAL_KEY"))}\n'
|
||||
f' trigger_dir={trigger_dir}\n'
|
||||
f' drop_dir={drop_dir}\n'
|
||||
f' browser_profile_dir={env("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR") or "missing"}\n'
|
||||
f' log={worker_logging.active_log_path() or "stdout-only"}\n'
|
||||
f' disk_retention_days={worker_disk_cleanup.retention_days()} cleanup_interval_seconds={cleanup_interval}'
|
||||
)
|
||||
|
||||
def _run_cleanup_if_due(now_mono: float, *, force: bool = False) -> float:
|
||||
"""按间隔执行保留清理;启动时强制一轮。
|
||||
|
||||
best-effort 语义:清理失败仅打印告警,不中断主循环;且无论成败都推进
|
||||
上次清理时钟(返回 now_mono),避免持续性故障在每次 poll 后立刻重试刷屏。
|
||||
"""
|
||||
nonlocal last_cleanup_mono
|
||||
if not force and (now_mono - last_cleanup_mono) < cleanup_interval:
|
||||
return last_cleanup_mono
|
||||
profile_root_raw = str(env('SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR') or '').strip()
|
||||
try:
|
||||
stats = run_worker_disk_cleanup(
|
||||
inventory_trigger_dir=trigger_dir, # 该函数只清 processed/failed 归档,绝不碰根目录待领取 *.json
|
||||
drop_dir=drop_dir,
|
||||
browser_profile_dir=Path(profile_root_raw) if profile_root_raw else None,
|
||||
log_file=worker_logging.active_log_path(),
|
||||
)
|
||||
print(format_cleanup_summary(stats))
|
||||
except Exception as exc:
|
||||
print(f'[receipt-cleanup] failed: {exc}')
|
||||
return now_mono
|
||||
|
||||
# [STEP 2] 启动即清一轮(对齐库存节奏),避免重启前堆积的归档/孤儿 Profile 撑盘。
|
||||
last_cleanup_mono = _run_cleanup_if_due(time.monotonic(), force=True)
|
||||
# 启动时立即上报一次心跳(对齐库存 Worker),让监控端第一时间出现独立的
|
||||
# `<hostname>-receipt` 收料 Worker 卡片(WORKER_ID 由 ps1 注入,避免按 pid 抖动)。
|
||||
rpa_heartbeat.maybe_send_heartbeat(
|
||||
trigger_dir=str(trigger_dir), drop_dir=str(drop_dir), last_sent_mono=0.0, force=True,
|
||||
)
|
||||
# 心跳节奏交由独立守护线程承担:收料批量导出会长时间阻塞主循环,
|
||||
# 若由主循环发送心跳,执行期间会停发并被后端按 TTL 误判离线。
|
||||
rpa_heartbeat.start_heartbeat_loop(
|
||||
trigger_dir=str(trigger_dir), drop_dir=str(drop_dir), interval_seconds=heartbeat_seconds,
|
||||
)
|
||||
while True:
|
||||
for path in sorted(trigger_dir.glob('*.json')):
|
||||
worker_logging.maybe_rotate_open_log()
|
||||
try:
|
||||
_claim_and_process(path, drop_dir)
|
||||
except Exception as exc:
|
||||
print(f'[receipt-trigger] failed {path.name}: {exc}')
|
||||
last_cleanup_mono = _run_cleanup_if_due(time.monotonic())
|
||||
time.sleep(poll)
|
||||
|
||||
|
||||
|
||||
@@ -42,6 +42,10 @@ $processVars = [ordered]@{
|
||||
SHIPPING_NOTICE_RPA_WORKER_HEADLESS = $(if ($Headless) { 'true' } else { 'false' })
|
||||
# 不设 BROWSER_CHANNEL:默认 Playwright 捆绑 Chromium(禁止默认 msedge,见库存 Worker 同因)。
|
||||
SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS = '3'
|
||||
SHIPPING_NOTICE_RPA_WORKER_LOG_FILE = Join-Path $dataRoot 'logs\worker.log'
|
||||
# 独立 Worker 身份:监控端按 worker_id 出独立收料卡片,固定后缀避免与库存 Worker/按 pid 的身份抖动。
|
||||
SHIPPING_NOTICE_RPA_WORKER_ID = "${env:COMPUTERNAME}-receipt"
|
||||
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS = '20'
|
||||
SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR = Join-Path $dataRoot 'receipt_triggers'
|
||||
SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR = Join-Path $dataRoot 'receipt_drop'
|
||||
# 浏览器 Profile 目录复用既有标准变量(与库存 RPA Worker 一致),不另设 RECEIPT_* 冗余变量。
|
||||
|
||||
Reference in new issue
Block a user