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
@@ -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