feat(shipping-notice): 增加 RPA Worker 心跳上报与状态查询功能

This commit is contained in:
hugo committed 2026-07-12 12:52:01 +08:00
1 parent c3f05ba96b
commit 5a147c4d85
49 files changed
+4032 -1500

No files matched your search

+1
View File
@@ -12,5 +12,6 @@ import app.api.schedule.config # noqa: F401
import app.api.schedule.tasks # noqa: F401
import app.api.schedule.runs # noqa: F401
import app.api.schedule.platform_tasks # noqa: F401
import app.api.schedule.rpa_workers # noqa: F401
__all__ = ['schedule_admin_bp']
+24
View File
@@ -0,0 +1,24 @@
"""
backend/app/api/schedule/rpa_workers.py
用途:管理端查询货代库存 RPA Worker 在线状态与就绪摘要。
依赖:schedule.blueprint、rpa_worker_heartbeat.serialize_rpa_worker_status。
逻辑:ScheduleWorkbenchPanel 在库存 RPA 排程工作台展示 worker 心跳状态。
"""
from __future__ import annotations
from app.api.schedule.blueprint import schedule_admin_bp
from app.core.decorators import require_admin
from app.core.response import ok
from app.services.shipping_notice.rpa_worker_heartbeat import serialize_rpa_worker_status
@schedule_admin_bp.route('/rpa-workers/status', methods=['GET'])
@require_admin
def get_rpa_workers_status():
"""
返回库存 RPA Worker 心跳摘要(在线/离线、最后心跳时间、就绪原因)。
核心逻辑:读取 Redis/内存心跳并与当前环境、trigger 目录比对。
"""
return ok(serialize_rpa_worker_status())
+17
View File
@@ -21,6 +21,7 @@ from app.core.errors import ConflictError, NotFoundError
from app.models import ScheduleRun, ScheduleTask
from app.services.schedule.query_service import get_run, list_runs, serialize_run
from app.services.schedule.scheduler_service import _generate_run_no, run_task_now
from app.services.schedule.shipping_inventory_rpa_archive import resolve_inventory_raw_zip_download
from app.services.schedule.shipping_inventory_rpa_finalize import recover_stale_awaiting_rpa_schedule_runs
@@ -139,3 +140,19 @@ def get_schedule_run_excel(run_id: int):
download_name=run.excel_file_name or 'result.xlsx',
mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
)
@schedule_admin_bp.route('/schedule-runs/<int:run_id>/inventory-raw-zip', methods=['GET'])
@require_admin
def get_schedule_run_inventory_raw_zip(run_id: int):
"""下载库存 RPA 排程 run 的原始库存 Excel 打包(ZIP + manifest)。"""
run = get_run(run_id)
if not run:
raise NotFoundError('Not found')
zip_path, file_name = resolve_inventory_raw_zip_download(run)
return send_file(
zip_path,
as_attachment=True,
download_name=file_name,
mimetype='application/zip',
)
+21 -1
View File
@@ -34,6 +34,7 @@ from app.services.shipping_notice.query_service import (
task_export_error_message,
)
from app.services.shipping_notice.tool_common import switch_batch_focus
from app.services.shipping_notice.rpa_worker_heartbeat import record_rpa_worker_heartbeat
from app.services.shipping_notice.tool_api_url import resolve_tool_api_base_url
shipping_notice_bp = Blueprint("shipping_notice", __name__)
@@ -81,7 +82,10 @@ def _tool_error_code(exc: AppError) -> str:
@shipping_notice_bp.errorhandler(AppError)
def _handle_tool_app_error(exc: AppError):
"""把业务异常统一转成 Tool 侧约定的 JSON 结构。"""
return (jsonify({'ok': False, 'error_code': _tool_error_code(exc), 'message': exc.message}), exc.http_status)
body: dict[str, object] = {'ok': False, 'error_code': _tool_error_code(exc), 'message': exc.message}
if exc.details:
body['details'] = exc.details
return jsonify(body), exc.http_status
@shipping_notice_bp.before_request
def _verify_tool_access():
@@ -323,6 +327,22 @@ def tool_switch_focus_task():
db.session.commit()
return jsonify({'status': 'ok', 'batch_no': batch.batch_no, 'task_no': task.task_no, 'message': f'已切换当前任务到 {task.task_no}', 'data': {'batch': serialize_batch_summary(batch), 'focus_task': serialize_task_summary(task)}})
@shipping_notice_bp.route('/rpa/heartbeat', methods=['POST'])
def rpa_worker_heartbeat():
"""
RPA Worker 心跳上报。
核心逻辑:校验 payload 后写入 Redis/内存;供触发库存 RPA 前就绪检查使用。
"""
payload = _payload()
try:
worker = record_rpa_worker_heartbeat(payload)
except ValueError as exc:
raise ValidationError(str(exc))
except ServiceUnavailableError:
raise
return jsonify({'status': 'ok', 'message': 'heartbeat recorded', 'data': worker})
@shipping_notice_bp.route('/rpa/inventory-ready', methods=['POST'])
def rpa_inventory_ready():
"""RPA 回调入口:上报库存导出结果并回写任务状态。"""
+41
View File
@@ -161,6 +161,41 @@ class Config:
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS = int(
os.getenv('SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS') or '900'
)
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS = int(
os.getenv('SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS') or '90'
)
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED = (
os.getenv('SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED', 'true').lower() == 'true'
)
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS = (
os.getenv('SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS', '').strip().lower()
in {'1', 'true', 'yes', 'on'}
if os.getenv('SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS')
else _normalize_env_name(os.getenv('ENV_NAME')) in {'test', 'prod'}
)
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK = (
os.getenv('SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK', 'false').lower() == 'true'
)
SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID = os.getenv('SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID', '').strip()
SHIPPING_NOTICE_RPA_SHARED_SENTINEL_NAME = (
os.getenv('SHIPPING_NOTICE_RPA_SHARED_SENTINEL_NAME', '.hxops_rpa_shared_mount').strip()
or '.hxops_rpa_shared_mount'
)
SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED = (
os.getenv('SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED', 'true').lower() == 'true'
)
SHIPPING_NOTICE_RPA_WORKER_ALERT_COOLDOWN_SECONDS = int(
os.getenv('SHIPPING_NOTICE_RPA_WORKER_ALERT_COOLDOWN_SECONDS') or '1800'
)
SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES = os.getenv(
'SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES', ''
).strip()
SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN = (
os.getenv('SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN', 'true').lower() == 'true'
)
SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS = int(
os.getenv('SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS') or '120'
)
SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM = os.getenv('SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM', 'false').lower() == 'true'
SHIPPING_NOTICE_AUTO_MATCH_ENABLED = os.getenv('SHIPPING_NOTICE_AUTO_MATCH_ENABLED', 'true').lower() == 'true'
SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED = (
@@ -209,6 +244,9 @@ class Config:
FREIGHT_RPA_BROWSER_PROFILE_DIR = _data_path(
"FREIGHT_RPA_BROWSER_PROFILE_DIR", "shipping_notice", "freight_rpa", "browser_profile"
)
FREIGHT_RPA_INVENTORY_ARCHIVE_DIR = _data_path(
"FREIGHT_RPA_INVENTORY_ARCHIVE_DIR", "shipping_notice", "freight_rpa", "inventory_archives"
)
FREIGHT_SHIPMENT_TEMPLATE_PATH = _backend_path(
"FREIGHT_SHIPMENT_TEMPLATE_PATH", "templates", "freight_shipment_upload.xlsx"
)
@@ -349,6 +387,9 @@ class TestingConfig(Config):
SCHEDULE_WORKER_ENABLED = False
FIXED_ASSETS_SYNC_ENABLED = False
FIXED_ASSETS_EXPORT_TO_DOCS = False
ENV_NAME = 'dev'
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS = False
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK = True
config = {
+8 -2
View File
@@ -65,8 +65,14 @@ class ConflictError(AppError):
class ServiceUnavailableError(AppError):
def __init__(self, message: str = "Service unavailable", *, code: str = "SYSTEM.SERVICE_UNAVAILABLE"):
super().__init__(code=code, message=message, http_status=503, retryable=True)
def __init__(
self,
message: str = "Service unavailable",
*,
code: str = "SYSTEM.SERVICE_UNAVAILABLE",
details: dict[str, Any] | None = None,
):
super().__init__(code=code, message=message, http_status=503, details=details or {}, retryable=True)
class AgentHandlerNotConfiguredError(AppError):
@@ -9,6 +9,7 @@ from sqlalchemy.orm import joinedload
from app import db
from app.models import ScheduleRun, ScheduleTask
from app.core.response import utc_iso
from app.services.schedule.shipping_inventory_rpa_archive import inventory_raw_zip_available_from_summary
from app.services.schedule.timezone_util import (
DEFAULT_SCHEDULE_TIMEZONE,
compute_next_run_at,
@@ -59,6 +60,7 @@ def serialize_task(task: ScheduleTask, *, last_status: str | None = None) -> dic
def serialize_run(run: ScheduleRun) -> dict:
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
return {
'id': run.id,
'run_no': run.run_no,
@@ -82,6 +84,7 @@ def serialize_run(run: ScheduleRun) -> dict:
'error_message': run.error_message,
'excel_file_name': run.excel_file_name,
'excel_file_size': run.excel_file_size,
'inventory_raw_zip_available': inventory_raw_zip_available_from_summary(summary),
'kb_sync_status': run.kb_sync_status,
'kb_group_id': run.kb_group_id,
'kb_document_id': run.kb_document_id,
@@ -76,11 +76,30 @@ _WECOM_STATUS_LABEL = {
_WECOM_EVENT_TYPE = 'schedule_completed'
def _build_schedule_run_wecom_jump_params(task: ScheduleTask, run: ScheduleRun) -> dict[str, Any]:
"""
构造排程企微 textcard 跳转 query 参数。
核心逻辑:指向管理端 /admin/schedules;有原始库存归档时附加 raw_zip=1 供深链展示下载入口。
"""
from app.services.schedule.shipping_inventory_rpa_archive import inventory_raw_zip_available_from_summary
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
params: dict[str, Any] = {
'task_id': task.id,
'run_id': run.id,
}
if inventory_raw_zip_available_from_summary(summary):
params['raw_zip'] = '1'
return params
def _build_schedule_run_wecom_description(run: ScheduleRun) -> str:
"""
组装排程完成企微 textcard 正文。
核心逻辑:与管理端统计口径一致,展示 total/success/skipped/failed 四列计数。
核心逻辑:与管理端统计口径一致,展示 total/success/skipped/failed 四列计数;
有原始库存归档时提示点击卡片进入 HXOPS(URL 仅放 jump_url,不写进正文)。
"""
status_label = _WECOM_STATUS_LABEL.get(run.status, run.status)
skipped_count = int(run.skipped_count or 0)
@@ -93,6 +112,10 @@ def _build_schedule_run_wecom_description(run: ScheduleRun) -> str:
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
if summary.get('excel_failed') or summary.get('excel_export_status') == 'failed':
description += '\n备注: 库存源已成功,但排程 Excel 生成失败'
from app.services.schedule.shipping_inventory_rpa_archive import inventory_raw_zip_available_from_summary
if inventory_raw_zip_available_from_summary(summary):
description += '\n原始库存包:点击本通知进入 HXOPS 下载'
return description
@@ -125,7 +148,7 @@ def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None:
return
title = f'排程执行结果: {task.name}'
description = _build_schedule_run_wecom_description(run)
jump_params = _build_schedule_run_wecom_jump_params(task, run)
media_id = None
if run.excel_file_data and run.excel_file_name:
@@ -142,7 +165,8 @@ def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None:
for u in wecom_users:
trace_id = uuid.uuid4().hex
jump_url = _build_jump_url('/workspace', trace_id, {'tab': 'schedule-runs'})
jump_url = _build_jump_url('/admin/schedules', trace_id, jump_params)
description = _build_schedule_run_wecom_description(run)
try:
audit = _create_audit(_WECOM_EVENT_TYPE, u, title, description, trace_id)
@@ -617,8 +641,17 @@ def start_scheduler(app):
recovered_awaiting,
)
from app.services.shipping_notice.rpa_worker_heartbeat_alert import maybe_alert_rpa_worker_status
maybe_alert_rpa_worker_status(force=True)
while True:
try:
from app.services.shipping_notice.rpa_worker_heartbeat_alert import (
maybe_alert_rpa_worker_status,
)
maybe_alert_rpa_worker_status()
now = utc_now_naive()
due_tasks = db.session.query(ScheduleTask).filter(
ScheduleTask.enabled.is_(True),
@@ -0,0 +1,269 @@
"""
backend/app/services/schedule/shipping_inventory_rpa_archive.py
用途:货代库存 RPA 排程 run 的原始库存 ZIP 归档(finalize 预生成 + 下载直传)。
依赖:ScheduleRun、ShippingInventoryFile、shipping_inventory_rpa_finalize.is_shipping_inventory_rpa_task。
逻辑:finalize 调用 persist_inventory_rpa_raw_zip_archive 写入磁盘与 summary;
query_service 只读 summary;api/schedule/runs 按 raw_inventory_zip_path send_file。
"""
from __future__ import annotations
import json
import re
import zipfile
from pathlib import Path
from typing import Any
from flask import current_app
from app import db
from app.core.errors import NotFoundError
from app.models import ScheduleRun, ShippingInventoryFile
from app.services.schedule.shipping_inventory_rpa_finalize import is_shipping_inventory_rpa_task
_RAW_ZIP_NOT_FOUND_MESSAGE = "原始库存包不存在,请重新执行或联系管理员"
_EMPTY_ARCHIVE_SUMMARY: dict[str, Any] = {
"raw_inventory_zip_available": False,
"raw_inventory_zip_path": None,
"raw_inventory_file_count": 0,
"raw_inventory_file_nos": [],
"raw_inventory_zip_size": 0,
}
def get_inventory_archive_dir() -> str:
"""返回库存 RPA 原始 ZIP 归档根目录(自动创建)。"""
archive_dir = Path(
current_app.config.get("FREIGHT_RPA_INVENTORY_ARCHIVE_DIR")
if current_app
else ""
)
if not str(archive_dir):
from app.core.config.settings import Config
archive_dir = Path(Config.FREIGHT_RPA_INVENTORY_ARCHIVE_DIR)
archive_dir.mkdir(parents=True, exist_ok=True)
return str(archive_dir)
def inventory_raw_zip_download_name(run_no: str) -> str:
"""浏览器下载时使用的 ZIP 文件名。"""
return f"inventory-rpa-raw-{run_no}.zip"
def _inventory_raw_zip_archive_path(run_no: str) -> Path:
"""磁盘归档路径:<archive_dir>/<run_no>.zip。"""
return Path(get_inventory_archive_dir()) / f"{run_no}.zip"
def _api_response_created(run: ScheduleRun) -> list[dict[str, Any]]:
"""从 run.api_response_json 提取 created 列表。"""
api_resp = run.api_response_json if isinstance(run.api_response_json, dict) else {}
created = api_resp.get("created")
if not isinstance(created, list):
return []
return [item for item in created if isinstance(item, dict)]
def _normalize_created_items(created: list[dict[str, Any]] | None) -> list[dict[str, Any]]:
"""过滤并规范化 created 列表。"""
if not isinstance(created, list):
return []
return [item for item in created if isinstance(item, dict)]
def _iter_packable_inventory_files(
run: ScheduleRun,
*,
created: list[dict[str, Any]] | None = None,
):
"""
遍历可实际打包的库存快照。
核心逻辑:需存在 ShippingInventoryFile 且 storage_path 指向可读文件。
Yields:
tuple[dict, ShippingInventoryFile, Path]: created 项、快照记录、可读路径。
"""
if not is_shipping_inventory_rpa_task(getattr(run, "task", None)):
return
items = _normalize_created_items(created) if created is not None else _api_response_created(run)
for item in items:
inventory_file_no = str(item.get("inventory_file_no") or "").strip()
if not inventory_file_no:
continue
inv_file = (
db.session.query(ShippingInventoryFile)
.filter(ShippingInventoryFile.inventory_file_no == inventory_file_no)
.first()
)
if not inv_file:
continue
storage_path = Path(str(inv_file.storage_path or "").strip())
if not storage_path.is_file():
continue
yield item, inv_file, storage_path
def inventory_raw_zip_available_from_summary(summary: dict[str, Any] | None) -> bool:
"""
从 response_summary_json 读取原始库存 ZIP 是否可下载。
核心逻辑:列表序列化只读 summary,不查库、不访问磁盘。
"""
if not isinstance(summary, dict):
return False
return bool(summary.get("raw_inventory_zip_available"))
def persist_inventory_rpa_raw_zip_archive(
run: ScheduleRun,
*,
created: list[dict[str, Any]] | None = None,
) -> dict[str, Any]:
"""
finalize 阶段预生成原始库存 ZIP 归档并返回 summary 字段。
核心逻辑:收集可读快照 → 写入 <archive_dir>/<run_no>.zip(含 manifest.json);
无可用文件时返回 raw_inventory_zip_available=false。
Args:
run: 库存 RPA ScheduleRun。
created: 可选回调 created 列表;finalize 时传入避免依赖尚未落库的 api_response_json。
Returns:
dict: raw_inventory_zip_available / raw_inventory_zip_path / raw_inventory_file_count /
raw_inventory_file_nos / raw_inventory_zip_size。
"""
packable_files = list(_iter_packable_inventory_files(run, created=created))
if not packable_files:
return dict(_EMPTY_ARCHIVE_SUMMARY)
archive_path = _inventory_raw_zip_archive_path(run.run_no)
files_manifest: list[dict[str, str]] = []
with zipfile.ZipFile(archive_path, "w", compression=zipfile.ZIP_DEFLATED) as archive:
for zip_index, (item, inv_file, storage_path) in enumerate(packable_files, start=1):
inventory_file_no = str(item.get("inventory_file_no") or "").strip()
source_code = str(item.get("source_code") or inv_file.source_code or "").strip()
warehouse_id = str(item.get("warehouse_id") or inv_file.warehouse_id or "").strip()
entry_name = _build_zip_entry_name(
index=zip_index,
source_code=source_code,
warehouse_id=warehouse_id,
inventory_file_no=inventory_file_no,
original_suffix=storage_path.suffix or ".xlsx",
)
archive.write(storage_path, arcname=entry_name)
files_manifest.append({
"inventory_file_no": inventory_file_no,
"source_code": source_code,
"warehouse_id": warehouse_id,
"file_name": entry_name,
"original_file_name": inv_file.source_file_name or storage_path.name,
})
manifest = {
"run_no": run.run_no,
"total_count": int(run.total_count or 0),
"success_count": int(run.success_count or 0),
"skipped_count": int(run.skipped_count or 0),
"failed_count": int(run.failed_count or 0),
"files": files_manifest,
}
archive.writestr(
"manifest.json",
json.dumps(manifest, ensure_ascii=False, indent=2),
)
return {
"raw_inventory_zip_available": True,
"raw_inventory_zip_path": str(archive_path.resolve()),
"raw_inventory_file_count": len(files_manifest),
"raw_inventory_file_nos": [item["inventory_file_no"] for item in files_manifest],
"raw_inventory_zip_size": int(archive_path.stat().st_size),
}
def _is_allowed_inventory_archive_path(zip_path: Path) -> bool:
"""
校验归档 ZIP 路径是否安全可下载。
核心逻辑:文件存在、后缀为 .zip、真实路径必须在 FREIGHT_RPA_INVENTORY_ARCHIVE_DIR 内。
"""
resolved = zip_path.resolve()
if resolved.suffix.lower() != ".zip":
return False
if not resolved.is_file():
return False
archive_dir = Path(get_inventory_archive_dir()).resolve()
try:
resolved.relative_to(archive_dir)
except ValueError:
return False
return True
def resolve_inventory_raw_zip_download(run: ScheduleRun) -> tuple[Path, str]:
"""
解析 run 已归档的原始库存 ZIP 路径供下载接口 send_file。
核心逻辑:读取 summary.raw_inventory_zip_path,校验文件存在、后缀为 .zip、
且真实路径位于 FREIGHT_RPA_INVENTORY_ARCHIVE_DIR 内;任一不满足则 404。
Returns:
tuple[Path, str]: 归档 ZIP 绝对路径与建议下载文件名。
Raises:
NotFoundError: summary 未标记可用、路径非法或归档文件已丢失。
"""
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
if not inventory_raw_zip_available_from_summary(summary):
raise NotFoundError(_RAW_ZIP_NOT_FOUND_MESSAGE)
zip_path_raw = str(summary.get("raw_inventory_zip_path") or "").strip()
if not zip_path_raw:
raise NotFoundError(_RAW_ZIP_NOT_FOUND_MESSAGE)
zip_path = Path(zip_path_raw)
if not _is_allowed_inventory_archive_path(zip_path):
raise NotFoundError(_RAW_ZIP_NOT_FOUND_MESSAGE)
return zip_path.resolve(), inventory_raw_zip_download_name(run.run_no)
def _sanitize_zip_segment(value: str) -> str:
"""ZIP 内文件名片段安全化,避免路径穿越与非法字符。"""
cleaned = re.sub(r"[^\w\-.]+", "_", str(value or "").strip())
return cleaned or "unknown"
def _build_zip_entry_name(
*,
index: int,
source_code: str,
warehouse_id: str,
inventory_file_no: str,
original_suffix: str,
) -> str:
"""生成 ZIP 内单文件条目名(不含目录)。"""
base = "_".join(
filter(
None,
[
f"{index:03d}",
_sanitize_zip_segment(source_code),
_sanitize_zip_segment(warehouse_id),
_sanitize_zip_segment(inventory_file_no),
],
)
)
suffix = original_suffix if original_suffix.startswith(".") else f".{original_suffix}"
return f"{base}{suffix}"
@@ -529,6 +529,27 @@ def _finalize_shipping_inventory_schedule_run_impl(
"skipped": skipped,
"failed": failed,
}
archive_summary: dict[str, Any] = {
"raw_inventory_zip_available": False,
"raw_inventory_zip_path": None,
"raw_inventory_file_count": 0,
"raw_inventory_file_nos": [],
"raw_inventory_zip_size": 0,
}
try:
from app.services.schedule.shipping_inventory_rpa_archive import persist_inventory_rpa_raw_zip_archive
archive_summary = persist_inventory_rpa_raw_zip_archive(run, created=created)
except Exception as archive_exc:
if current_app:
current_app.logger.error(
"[schedule-run] inventory RPA raw zip archive failed run_no=%s: %s",
run.run_no,
archive_exc,
exc_info=True,
)
run.response_summary_json = {
"awaiting_rpa": False,
"total_count": total_count,
@@ -548,6 +569,7 @@ def _finalize_shipping_inventory_schedule_run_impl(
"failed_count": failed_count,
"excel_failed": not excel_export_ok,
},
**archive_summary,
}
run.error_message = "; ".join(errors[:3]) if errors else None
run.excel_file_data = file_data
@@ -14,10 +14,12 @@ from datetime import datetime
from typing import Any
from app import db
from app.core.errors import ServiceUnavailableError
from app.models import ScheduleRun, ScheduleTask
from app.services.schedule.shipping_inventory_rpa_finalize import AWAITING_RPA_CALLBACK_STATUS
from app.services.shipping_notice.inventory_sources import build_rpa_inventory_source, list_inventory_sources
from app.services.shipping_notice.rpa import write_inventory_export_batch_trigger
from app.services.shipping_notice.rpa_worker_heartbeat import RPA_WORKER_OFFLINE_MESSAGE
ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]]
@@ -137,19 +139,34 @@ def run_shipping_inventory_rpa_schedule(task: ScheduleTask, run: ScheduleRun) ->
return 0, 0, 0, 1, [], [message], step_logs
run_no = run.run_no or f"RUN{datetime.utcnow().strftime('%Y%m%d%H%M%S')}"
trigger_path = write_inventory_export_batch_trigger(
run_no,
sources,
payload={
"trigger_type": "scheduled",
"schedule_run_id": run.id,
"schedule_task_id": task.id,
},
)
try:
trigger_path = write_inventory_export_batch_trigger(
run_no,
sources,
payload={
"trigger_type": "scheduled",
"schedule_run_id": run.id,
"schedule_task_id": task.id,
},
)
except ServiceUnavailableError as exc:
message = str(exc.message or RPA_WORKER_OFFLINE_MESSAGE)
detail_message = str((exc.details or {}).get("detail_message") or message)
step_logs.append({
"step": "shipping_inventory_rpa",
"status": "failed",
"detail": {
"message": message,
"detail_message": detail_message,
"error_code": exc.code,
"reasons": (exc.details or {}).get("reasons") or [],
},
})
return len(sources), 0, len(sources), 0, [], [detail_message], step_logs
if not trigger_path:
message = "inventory RPA trigger dir not configured"
step_logs.append({"step": "shipping_inventory_rpa", "status": "failed", "detail": {"message": message}})
return len(sources), 0, 0, len(sources), [], [message], step_logs
return len(sources), 0, len(sources), 0, [], [message], step_logs
run.api_request_json = {
"run_no": run_no,
@@ -13,6 +13,7 @@ from pathlib import Path
from typing import Any
from app import db
from app.core.errors import ServiceUnavailableError
from app.models import ShippingTask, ShippingTaskEvent
from app.services.shipping_notice.constants import CP_INVENTORY_SOURCE_REVIEW, CP_UPLOAD_REQ, PH_RPA_PENDING
from app.services.shipping_notice.inventory_snapshot import ingest_inventory_file
@@ -38,6 +39,7 @@ from app.services.shipping_notice.rpa import (
inventory_processed_dir,
write_inventory_export_trigger_for_task,
)
from app.services.shipping_notice.rpa_worker_heartbeat import RPA_WORKER_OFFLINE_MESSAGE
from app.services.shipping_notice.rpa_attempts import (
inventory_rpa_attempts,
max_rpa_inventory_attempts,
@@ -475,14 +477,19 @@ def ensure_inventory_via_rpa(task: ShippingTask, *, mode: str) -> dict[str, Any]
# [STEP 3] 触发下一次 RPA 导出或给出人工兜底提示。
# 触发成功则推进到 pending;触发失败则明确要求用户改走手工上传。
attempt_no = attempts + 1
trigger = write_inventory_export_trigger_for_task(
task.task_no,
rpa_source,
payload={
"mode": mode,
"attempt": attempt_no,
},
)
try:
trigger = write_inventory_export_trigger_for_task(
task.task_no,
rpa_source,
payload={
"mode": mode,
"attempt": attempt_no,
},
)
except ServiceUnavailableError as exc:
trigger = None
detail_message = str((exc.details or {}).get("detail_message") or exc.message or RPA_WORKER_OFFLINE_MESSAGE)
task.error_message = detail_message[:500]
if trigger:
apply_task_transition(task, TaskTransition.RPA_PENDING)
task.error_message = None
@@ -534,24 +541,31 @@ def ensure_inventory_via_rpa(task: ShippingTask, *, mode: str) -> dict[str, Any]
)
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
task.error_message = "RPA 库存目录未配置或触发失败"
offline_message = (task.error_message or "").strip()
if offline_message == RPA_WORKER_OFFLINE_MESSAGE:
human_message = RPA_WORKER_OFFLINE_MESSAGE
detail = "请启动 Windows RPA 服务后重试,或手动上传货代库存 Excel。"
else:
human_message = "RPA 库存目录未配置或触发失败"
detail = "请重新获取库存,或手动上传货代库存 Excel。"
task.error_message = human_message[:500]
set_task_step_progress(
task,
step_key="step3_inventory_prepare",
step_title="获取库存",
status="needs_human",
message="RPA 库存触发失败",
message=human_message,
progress_percent=100,
current=0,
total=max_attempts,
detail="请重新获取库存,或手动上传货代库存 Excel。",
detail=detail,
)
log_task_event(task, "inventory_rpa_retry_requested", {"reason": "trigger_failed"})
db.session.commit()
return tool_response(
status="needs_human",
task=task,
message="RPA 库存目录未配置或触发失败。请上传货代库存 Excel。",
message=f"{human_message}。请上传货代库存 Excel。" if human_message != RPA_WORKER_OFFLINE_MESSAGE else human_message,
data=serialize_task_for_tool(task),
checkpoint=CP_UPLOAD_REQ,
)
+7 -1
View File
@@ -79,8 +79,11 @@ def write_inventory_export_trigger(task_no: str, payload: dict[str, Any] | None
写入 RPA 库存导出触发文件 inventory_export_{task_no}.json。
Returns:
str | None: 触发文件绝对路径;目录未配置时返回 None。
str | None: 触发文件绝对路径;目录未配置或 worker 未就绪时返回 None。
"""
from app.services.shipping_notice.rpa_worker_heartbeat import assert_inventory_rpa_worker_ready
assert_inventory_rpa_worker_ready()
trigger_dir = inventory_trigger_dir()
if not trigger_dir:
return None
@@ -114,6 +117,9 @@ def write_inventory_export_batch_trigger(
Returns:
str | None: 触发文件绝对路径。
"""
from app.services.shipping_notice.rpa_worker_heartbeat import assert_inventory_rpa_worker_ready
assert_inventory_rpa_worker_ready()
trigger_dir = inventory_trigger_dir()
if not trigger_dir or not sources:
return None
@@ -0,0 +1,575 @@
"""
services/shipping_notice/rpa_worker_heartbeat.py
用途:货代库存 RPA Worker 心跳存储、共享目录校验、就绪检查与状态查询。
依赖:Flask current_app、redis_client、shipping_notice.rpa(目录与 mock 模式)。
逻辑:freight_rpa_worker 调 POST /rpa/heartbeat;写 trigger 前由 rpa / inventory_rpa_workflow / shipping_inventory_rpa_job 调用就绪检查。
"""
from __future__ import annotations
import json
import logging
import os
import threading
import time
from dataclasses import dataclass, field
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
from flask import current_app
from app.core.config.settings import _normalize_env_name
from app.core.errors import ServiceUnavailableError
from app.services.shipping_notice.rpa import inventory_trigger_dir, rpa_runtime_mode
logger = logging.getLogger(__name__)
RPA_WORKER_OFFLINE_MESSAGE = "RPA Worker 未在线,请启动 Windows RPA 服务后重试"
RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE = "RPA Worker 心跳存储不可用,请检查 Redis 连接"
INVENTORY_EXPORT_CAPABILITY = "inventory_export"
_REDIS_INDEX_KEY = "shipping:rpa:heartbeat:index"
_REDIS_WORKER_KEY_PREFIX = "shipping:rpa:heartbeat:worker:"
_MEMORY_STORE: dict[str, dict[str, Any]] = {}
_MEMORY_LOCK = threading.Lock()
_REASON_USER_HINTS: dict[str, str] = {
"no_worker_heartbeat": "未收到任何 Worker 心跳",
"heartbeat_storage_unavailable": "心跳存储不可用(Redis)",
"trigger_dir_not_configured": "后端未配置库存 trigger 目录",
"trigger_dir_not_accessible": "trigger 目录不存在或不可访问",
"shared_sentinel_missing": "共享目录哨兵文件缺失,可能 CIFS 未挂载",
"shared_scope_mismatch": "共享目录 scope 与后端配置不一致",
"trigger_dir_not_writable": "trigger 目录不可写",
"environment_mismatch": "Worker 环境与后端环境不一致",
"missing_inventory_export_capability": "Worker 未声明 inventory_export 能力",
}
@dataclass
class RpaWorkerReadiness:
"""库存 RPA 触发前就绪检查结果。"""
ready: bool
message: str
workers: list[dict[str, Any]] = field(default_factory=list)
reasons: list[str] = field(default_factory=list)
checked_at: str = ""
detail_message: str = ""
def _utc_now_iso() -> str:
return datetime.now(timezone.utc).replace(tzinfo=None).isoformat()
def _config_bool(key: str, default: bool) -> bool:
if current_app:
raw = current_app.config.get(key, default)
else:
raw = os.getenv(key, str(default).lower())
return str(raw).strip().lower() in {"1", "true", "yes", "on"}
def _config_str(key: str, default: str = "") -> str:
if current_app:
raw = current_app.config.get(key, default)
else:
raw = os.getenv(key, default)
return str(raw or default).strip()
def _heartbeat_ttl_seconds() -> int:
raw = 90
if current_app:
raw = int(current_app.config.get("SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS") or 90)
else:
raw = int(os.getenv("SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS") or "90")
return max(60, raw)
def _heartbeat_check_required() -> bool:
"""Mock RPA 或显式关闭时跳过 worker 心跳就绪检查。"""
if rpa_runtime_mode().get("mock"):
return False
return _config_bool("SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED", True)
def _heartbeat_redis_required() -> bool:
"""test/prod 默认要求 Redis;dev 仅显式开启时要求。"""
explicit = os.getenv("SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS")
if explicit is not None and str(explicit).strip() != "":
return _config_bool("SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS", False)
if current_app:
configured = current_app.config.get("SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS")
if configured is not None:
return bool(configured)
env_name = resolve_backend_rpa_environment()
return env_name in {"test", "prod"}
def _heartbeat_allow_memory_fallback() -> bool:
return _config_bool("SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK", False)
def resolve_backend_rpa_environment() -> str:
"""将后端部署环境归一为 dev / test / prod。"""
env_name = os.getenv("ENV_NAME") or os.getenv("FLASK_ENV")
if current_app:
env_name = current_app.config.get("ENV_NAME") or env_name
return _normalize_env_name(env_name)
def shared_scope_id() -> str:
"""共享 SMB 目录逻辑标识(如 hxops-rpa-test-data),用于跨平台路径对齐。"""
explicit = _config_str("SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID", "")
if explicit:
return explicit
trigger_dir = inventory_trigger_dir()
if not trigger_dir:
return ""
for part in Path(trigger_dir).parts:
normalized = str(part).strip().lower()
if normalized.startswith("hxops-rpa-"):
return normalized
return ""
def shared_sentinel_name() -> str:
return _config_str("SHIPPING_NOTICE_RPA_SHARED_SENTINEL_NAME", ".hxops_rpa_shared_mount")
def _shared_mount_check_required() -> bool:
"""配置了 scope_id 或 test/prod 环境时强制校验共享哨兵。"""
if shared_scope_id():
return True
return resolve_backend_rpa_environment() in {"test", "prod"}
def _parse_capabilities(raw: Any) -> set[str]:
if isinstance(raw, str):
values = [part.strip().lower() for part in raw.split(",")]
elif isinstance(raw, list):
values = [str(part).strip().lower() for part in raw]
else:
values = []
return {value for value in values if value}
def _coerce_worker_payload(payload: dict[str, Any]) -> dict[str, Any]:
"""校验并规范化 worker 心跳 payload。"""
worker_id = str(payload.get("worker_id") or "").strip()
if not worker_id:
raise ValueError("worker_id is required")
timestamp = str(payload.get("timestamp") or "").strip() or _utc_now_iso()
environment = str(payload.get("environment") or "").strip().lower() or resolve_backend_rpa_environment()
status = str(payload.get("status") or "idle").strip().lower()
if status not in {"idle", "busy"}:
status = "idle"
scope = str(payload.get("shared_scope_id") or "").strip()
return {
"worker_id": worker_id,
"hostname": str(payload.get("hostname") or "").strip(),
"environment": environment,
"capabilities": sorted(_parse_capabilities(payload.get("capabilities"))),
"status": status,
"trigger_dir": str(payload.get("trigger_dir") or "").strip(),
"drop_dir": str(payload.get("drop_dir") or "").strip(),
"shared_scope_id": scope,
"version": str(payload.get("version") or "").strip(),
"timestamp": timestamp,
"received_at": _utc_now_iso(),
}
def _redis_client():
from app.services.redis_client import get_redis_client
return get_redis_client()
def _memory_store_worker(worker: dict[str, Any]) -> None:
with _MEMORY_LOCK:
_MEMORY_STORE[worker["worker_id"]] = dict(worker)
def _memory_list_workers() -> list[dict[str, Any]]:
with _MEMORY_LOCK:
return [dict(item) for item in _MEMORY_STORE.values()]
def reset_rpa_worker_heartbeat_state_for_tests() -> None:
"""单测隔离:清空进程内内存心跳缓存。"""
with _MEMORY_LOCK:
_MEMORY_STORE.clear()
def _redis_store_worker(worker: dict[str, Any]) -> bool:
client = _redis_client()
if client is None:
return False
ttl = _heartbeat_ttl_seconds() * 2
key = f"{_REDIS_WORKER_KEY_PREFIX}{worker['worker_id']}"
try:
client.set(key, json.dumps(worker, ensure_ascii=False), ex=ttl)
client.sadd(_REDIS_INDEX_KEY, worker["worker_id"])
client.expire(_REDIS_INDEX_KEY, ttl * 4)
return True
except Exception:
logger.exception("[rpa-heartbeat] redis store failed worker_id=%s", worker.get("worker_id"))
return False
def _redis_list_workers() -> tuple[list[dict[str, Any]], bool]:
"""
从 Redis 读取 worker 心跳列表。
Returns:
tuple[list, read_failed]: read_failed=True 表示 Redis 读取异常(非“无心跳”)。
"""
client = _redis_client()
if client is None:
return [], False
workers: list[dict[str, Any]] = []
try:
worker_ids = client.smembers(_REDIS_INDEX_KEY) or []
for worker_id in sorted(worker_ids):
raw = client.get(f"{_REDIS_WORKER_KEY_PREFIX}{worker_id}")
if not raw:
continue
parsed = json.loads(raw)
if isinstance(parsed, dict):
workers.append(parsed)
except Exception:
logger.exception("[rpa-heartbeat] redis list failed")
return [], True
return workers, False
def record_rpa_worker_heartbeat(payload: dict[str, Any]) -> dict[str, Any]:
"""
记录 RPA Worker 心跳。
核心逻辑:test/prod 必须写 Redis;仅 dev 且显式允许时才降级进程内存。
"""
worker = _coerce_worker_payload(payload)
stored_in_redis = _redis_store_worker(worker)
if stored_in_redis:
worker["storage"] = "redis"
return worker
if _heartbeat_redis_required():
raise ServiceUnavailableError(
RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE,
code="RPA.HEARTBEAT_STORAGE_UNAVAILABLE",
details={"reason": "redis_write_failed", "worker_id": worker.get("worker_id")},
)
if _heartbeat_allow_memory_fallback():
_memory_store_worker(worker)
worker["storage"] = "memory"
return worker
raise ServiceUnavailableError(
RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE,
code="RPA.HEARTBEAT_STORAGE_UNAVAILABLE",
details={"reason": "memory_fallback_disabled", "worker_id": worker.get("worker_id")},
)
def list_rpa_worker_heartbeats() -> tuple[list[dict[str, Any]], bool]:
"""
返回当前已知 worker 心跳列表。
Returns:
tuple[workers, storage_read_failed]
"""
workers, read_failed = _redis_list_workers()
if read_failed:
return [], True
if workers:
return workers, False
if _heartbeat_redis_required():
if _redis_client() is None:
return [], True
return [], False
if _heartbeat_allow_memory_fallback():
return _memory_list_workers(), False
return [], False
def _heartbeat_age_seconds(worker: dict[str, Any], *, now: float | None = None) -> float | None:
raw = str(worker.get("received_at") or worker.get("timestamp") or "").strip()
if not raw:
return None
try:
parsed = datetime.fromisoformat(raw.replace("Z", ""))
if parsed.tzinfo is None:
parsed = parsed.replace(tzinfo=timezone.utc)
except ValueError:
return None
current = now if now is not None else time.time()
return max(current - parsed.timestamp(), 0.0)
def _parse_sentinel_content(raw: str) -> dict[str, str]:
parsed: dict[str, str] = {}
for line in raw.splitlines():
if "=" not in line:
continue
key, value = line.split("=", 1)
parsed[key.strip().lower()] = value.strip()
return parsed
def _read_shared_sentinel(trigger_dir: Path) -> tuple[dict[str, str] | None, str | None]:
sentinel_path = trigger_dir / shared_sentinel_name()
if not sentinel_path.is_file():
return None, "shared_sentinel_missing"
try:
content = sentinel_path.read_text(encoding="utf-8")
parsed = _parse_sentinel_content(content)
if not parsed:
return None, "shared_sentinel_invalid"
return parsed, None
except Exception:
return None, "shared_sentinel_unreadable"
def _verify_shared_trigger_mount(trigger_dir: Path | None) -> tuple[bool, list[str]]:
"""
校验 trigger 目录为真实共享挂载,而非 Ubuntu 本地误创建目录。
核心逻辑:目录必须已存在;test/prod 或配置 scope_id 时要求哨兵文件且 scope 一致。
"""
reasons: list[str] = []
if trigger_dir is None:
return False, ["trigger_dir_not_configured"]
if not trigger_dir.exists():
return False, ["trigger_dir_not_accessible"]
if not trigger_dir.is_dir():
return False, ["trigger_dir_not_accessible"]
expected_scope = shared_scope_id()
if _shared_mount_check_required():
sentinel, sentinel_reason = _read_shared_sentinel(trigger_dir)
if sentinel_reason:
reasons.append(sentinel_reason)
elif expected_scope:
actual_scope = str(sentinel.get("scope_id") or "").strip()
if actual_scope != expected_scope:
reasons.append(f"shared_scope_mismatch:{actual_scope}!={expected_scope}")
elif not str(sentinel.get("scope_id") or "").strip():
reasons.append("shared_scope_mismatch:missing_scope_id")
if reasons:
return False, reasons
try:
probe = trigger_dir / ".hxops_rpa_write_probe"
probe.write_text("ok", encoding="utf-8")
probe.unlink(missing_ok=True)
except Exception:
reasons.append("trigger_dir_not_writable")
return not reasons, reasons
def _worker_scope_matches(worker: dict[str, Any]) -> tuple[bool, list[str]]:
expected_scope = shared_scope_id()
if not expected_scope:
return True, []
worker_scope = str(worker.get("shared_scope_id") or "").strip()
if worker_scope == expected_scope:
return True, []
return False, [f"shared_scope_mismatch:{worker_scope or '-'}!={expected_scope}"]
def _worker_is_eligible(
worker: dict[str, Any],
*,
backend_env: str,
ttl_seconds: int,
now: float,
) -> tuple[bool, list[str]]:
reasons: list[str] = []
age = _heartbeat_age_seconds(worker, now=now)
if age is None:
reasons.append("heartbeat_timestamp_invalid")
elif age > ttl_seconds:
reasons.append(f"heartbeat_stale:{int(age)}s")
capabilities = _parse_capabilities(worker.get("capabilities"))
if INVENTORY_EXPORT_CAPABILITY not in capabilities:
reasons.append("missing_inventory_export_capability")
worker_env = str(worker.get("environment") or "").strip().lower()
if worker_env and worker_env != backend_env:
reasons.append(f"environment_mismatch:{worker_env}!={backend_env}")
scope_ok, scope_reasons = _worker_scope_matches(worker)
if not scope_ok:
reasons.extend(scope_reasons)
return not reasons, reasons
def _summarize_reasons(reasons: list[str]) -> str:
hints: list[str] = []
for reason in reasons:
base = reason.split(":", 1)[0]
hint = _REASON_USER_HINTS.get(base)
if hint and hint not in hints:
hints.append(hint)
return ";".join(hints) if hints else ";".join(reasons[:5])
def _build_failure_message(result: RpaWorkerReadiness) -> tuple[str, str]:
"""返回 (用户可见 message, 运维 detail_message)。"""
if any(reason == "heartbeat_storage_unavailable" for reason in result.reasons):
return RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE, _summarize_reasons(result.reasons)
detail = _summarize_reasons(result.reasons)
if not detail:
return RPA_WORKER_OFFLINE_MESSAGE, RPA_WORKER_OFFLINE_MESSAGE
return RPA_WORKER_OFFLINE_MESSAGE, f"{RPA_WORKER_OFFLINE_MESSAGE}({detail})"
def check_inventory_rpa_worker_ready() -> RpaWorkerReadiness:
"""
检查库存 RPA 触发前 worker 是否就绪。
核心逻辑:Redis 可用、共享哨兵有效、最近心跳在 TTL 内、环境/scope 匹配。
"""
checked_at = _utc_now_iso()
if not _heartbeat_check_required():
return RpaWorkerReadiness(
ready=True,
message="heartbeat check skipped",
checked_at=checked_at,
)
reasons: list[str] = []
if _heartbeat_redis_required() and _redis_client() is None:
reasons.append("heartbeat_storage_unavailable")
trigger_dir = inventory_trigger_dir()
mount_ok, mount_reasons = _verify_shared_trigger_mount(trigger_dir)
reasons.extend(mount_reasons)
backend_env = resolve_backend_rpa_environment()
ttl_seconds = _heartbeat_ttl_seconds()
now = time.time()
workers, storage_read_failed = list_rpa_worker_heartbeats()
if storage_read_failed:
reasons.append("heartbeat_storage_unavailable")
eligible_workers: list[dict[str, Any]] = []
enriched_workers: list[dict[str, Any]] = []
for worker in workers:
eligible, worker_reasons = _worker_is_eligible(
worker,
backend_env=backend_env,
ttl_seconds=ttl_seconds,
now=now,
)
enriched = {
**worker,
"age_seconds": _heartbeat_age_seconds(worker, now=now),
"eligible": eligible,
"ineligible_reasons": worker_reasons,
}
enriched_workers.append(enriched)
if eligible:
eligible_workers.append(enriched)
else:
reasons.extend([f"{worker.get('worker_id')}:{reason}" for reason in worker_reasons])
if not workers and "heartbeat_storage_unavailable" not in reasons:
reasons.append("no_worker_heartbeat")
mount_block_tokens = {
"trigger_dir_not_configured",
"trigger_dir_not_accessible",
"shared_sentinel_missing",
"shared_sentinel_invalid",
"shared_sentinel_unreadable",
"trigger_dir_not_writable",
}
blocking_mount = any(reason in mount_block_tokens for reason in reasons) or any(
reason.startswith("shared_scope_mismatch") for reason in reasons
)
ready = bool(eligible_workers) and not blocking_mount and "heartbeat_storage_unavailable" not in reasons
message, detail_message = ("ready", "ready") if ready else _build_failure_message(
RpaWorkerReadiness(ready=False, message="", reasons=sorted(set(reasons)))
)
return RpaWorkerReadiness(
ready=ready,
message=message,
detail_message=detail_message,
workers=enriched_workers,
reasons=sorted(set(reasons)),
checked_at=checked_at,
)
def assert_inventory_rpa_worker_ready() -> None:
"""
写 trigger 前的强制就绪检查。
Raises:
ServiceUnavailableError: worker 未就绪、共享目录无效或心跳存储不可用。
"""
result = check_inventory_rpa_worker_ready()
if result.ready:
return
code = "RPA.WORKER_OFFLINE"
if "heartbeat_storage_unavailable" in result.reasons:
code = "RPA.HEARTBEAT_STORAGE_UNAVAILABLE"
logger.warning(
"[rpa-heartbeat] readiness blocked code=%s reasons=%s detail=%s",
code,
result.reasons,
result.detail_message,
)
raise ServiceUnavailableError(
result.message,
code=code,
details={
"reasons": result.reasons,
"detail_message": result.detail_message,
"checked_at": result.checked_at,
"shared_scope_id": shared_scope_id(),
"trigger_dir": str(inventory_trigger_dir() or ""),
},
)
def serialize_rpa_worker_status() -> dict[str, Any]:
"""管理端展示:在线 worker 列表与就绪摘要(含详细 reasons)。"""
readiness = check_inventory_rpa_worker_ready()
ttl_seconds = _heartbeat_ttl_seconds()
workers = []
now = time.time()
for worker in readiness.workers:
workers.append({
"worker_id": worker.get("worker_id"),
"hostname": worker.get("hostname"),
"environment": worker.get("environment"),
"status": worker.get("status"),
"capabilities": worker.get("capabilities") or [],
"trigger_dir": worker.get("trigger_dir"),
"drop_dir": worker.get("drop_dir"),
"shared_scope_id": worker.get("shared_scope_id"),
"version": worker.get("version"),
"timestamp": worker.get("timestamp"),
"received_at": worker.get("received_at"),
"age_seconds": _heartbeat_age_seconds(worker, now=now),
"online": (_heartbeat_age_seconds(worker, now=now) or 9999) <= ttl_seconds,
"eligible": worker.get("eligible"),
"ineligible_reasons": worker.get("ineligible_reasons") or [],
})
return {
"ready": readiness.ready,
"message": readiness.message,
"detail_message": readiness.detail_message,
"checked_at": readiness.checked_at,
"heartbeat_ttl_seconds": ttl_seconds,
"backend_environment": resolve_backend_rpa_environment(),
"shared_scope_id": shared_scope_id(),
"shared_sentinel_name": shared_sentinel_name(),
"trigger_dir": str(inventory_trigger_dir() or ""),
"reasons": readiness.reasons,
"workers": workers,
}
@@ -0,0 +1,563 @@
"""
services/shipping_notice/rpa_worker_heartbeat_alert.py
用途:库存 RPA Worker 离线/恢复主动告警(企微 textcard + 冷却去重)。
依赖:rpa_worker_heartbeat、redis_client、wecom_notify、models.User、models.AppSetting。
逻辑:由 schedule worker 每轮循环调用;DB 为告警状态权威源,Redis 仅作缓存同步。
"""
from __future__ import annotations
import json
import logging
import threading
import time
from collections.abc import Callable
from typing import Any
from flask import current_app
from sqlalchemy.exc import IntegrityError
from app import db
from app.models import AppSetting, User
from app.services.shipping_notice.rpa_worker_heartbeat import (
RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE,
RPA_WORKER_OFFLINE_MESSAGE,
_heartbeat_check_required,
check_inventory_rpa_worker_ready,
)
logger = logging.getLogger(__name__)
_REDIS_ALERT_STATE_KEY = "shipping:rpa:heartbeat:alert:state"
_DB_ALERT_STATE_KEY = "shipping:rpa:heartbeat:alert:state"
_STATUS_SENDING = "sending"
_LAST_CHECK_MONO = 0.0
_MEMORY_ALERT_STATE: dict[str, Any] = {}
_MEMORY_ALERT_LOCK = threading.Lock()
_RECIPIENT_GAP_LOGGED = False
def _config_bool(key: str, default: bool) -> bool:
raw = current_app.config.get(key, default)
return str(raw).strip().lower() in {"1", "true", "yes", "on"}
def _alert_enabled() -> bool:
if not _heartbeat_check_required():
return False
return _config_bool("SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED", True)
def _alert_cooldown_seconds() -> int:
return max(300, int(current_app.config.get("SHIPPING_NOTICE_RPA_WORKER_ALERT_COOLDOWN_SECONDS") or 1800))
def _send_lock_seconds() -> int:
"""企微发送中的短锁 TTL;发送失败过期后可重试,不进入长冷却。"""
return max(60, int(current_app.config.get("SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS") or 120))
def _alert_fallback_admin_enabled() -> bool:
return _config_bool("SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN", True)
def _alert_recipients() -> list[User]:
"""
解析告警接收人。
核心逻辑:优先 SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES;未配置时可选回退已绑企微的 admin。
"""
raw = str(current_app.config.get("SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES") or "").strip()
names = [part.strip() for part in raw.split(",") if part.strip()] if raw else []
if names:
users = (
db.session.query(User)
.filter(User.username.in_(names), User.wecom_userid.isnot(None))
.all()
)
if users:
return users
logger.warning(
"[rpa-heartbeat-alert] configured usernames have no bound wecom_userid: %s",
names,
)
if _alert_fallback_admin_enabled():
admins = (
db.session.query(User)
.filter(User.role == "admin", User.wecom_userid.isnot(None))
.order_by(User.id.asc())
.limit(20)
.all()
)
if admins:
logger.info(
"[rpa-heartbeat-alert] using admin fallback recipients count=%d",
len(admins),
)
return admins
return []
def _log_recipient_gap_once() -> None:
"""部署缺口:未配置接收人且无已绑企微 admin 时仅打一次明确 warning。"""
global _RECIPIENT_GAP_LOGGED
if _RECIPIENT_GAP_LOGGED:
return
_RECIPIENT_GAP_LOGGED = True
logger.warning(
"[rpa-heartbeat-alert] no wecom recipients: set SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES "
"or bind wecom_userid for at least one admin (FALLBACK_ADMIN=true)"
)
def _redis_client():
from app.services.redis_client import get_redis_client
return get_redis_client()
def _memory_load_alert_state() -> dict[str, Any]:
with _MEMORY_ALERT_LOCK:
return dict(_MEMORY_ALERT_STATE)
def _memory_save_alert_state(state: dict[str, Any]) -> None:
with _MEMORY_ALERT_LOCK:
_MEMORY_ALERT_STATE.clear()
_MEMORY_ALERT_STATE.update(state)
def _load_alert_state_from_db() -> dict[str, Any] | None:
state, _db_ok = _try_read_alert_state_from_db()
return state
def _try_read_alert_state_from_db() -> tuple[dict[str, Any] | None, bool]:
"""
读取 DB 告警状态。
Returns:
(state, db_available):无行时 state 为 None 但 db_available 仍为 True。
"""
try:
row = db.session.get(AppSetting, _DB_ALERT_STATE_KEY)
if row and row.value:
parsed = json.loads(row.value)
if isinstance(parsed, dict):
return parsed, True
return None, True
except Exception:
logger.exception("[rpa-heartbeat-alert] load state from db failed")
db.session.rollback()
return None, False
def _persist_alert_state_to_db(state: dict[str, Any]) -> None:
payload = json.dumps(state, ensure_ascii=False)
row = db.session.get(AppSetting, _DB_ALERT_STATE_KEY)
if row:
row.value = payload
else:
db.session.add(AppSetting(key=_DB_ALERT_STATE_KEY, value=payload))
db.session.commit()
def _normalize_alert_state(state: dict[str, Any]) -> dict[str, Any]:
"""写入前补齐 updated_at,供跨存储源比较版本。"""
normalized = dict(state)
normalized["updated_at"] = time.time()
return normalized
def _try_load_alert_state_from_redis() -> dict[str, Any] | None:
client = _redis_client()
if client is None:
return None
try:
raw = client.get(_REDIS_ALERT_STATE_KEY)
if raw:
parsed = json.loads(raw)
if isinstance(parsed, dict):
return parsed
except Exception:
logger.exception("[rpa-heartbeat-alert] load state from redis failed")
return None
def _sync_redis_cache_from_db(state: dict[str, Any]) -> None:
"""DB 为权威源时,无条件用 DB 状态覆盖 Redis 缓存。"""
_persist_alert_state_to_redis(state)
def _persist_alert_state_to_redis(state: dict[str, Any]) -> None:
client = _redis_client()
if client is None:
return
try:
client.set(_REDIS_ALERT_STATE_KEY, json.dumps(state, ensure_ascii=False), ex=86400 * 7)
except Exception:
logger.exception("[rpa-heartbeat-alert] save state to redis failed")
def _delete_redis_alert_state_if_possible() -> None:
"""DB 无状态时清理 Redis 残留缓存。"""
client = _redis_client()
if client is None:
return
try:
client.delete(_REDIS_ALERT_STATE_KEY)
except Exception:
logger.exception("[rpa-heartbeat-alert] delete state from redis failed")
def reset_rpa_worker_alert_state_for_tests() -> None:
"""单测隔离:清空进程内告警冷却状态与 DB 行。"""
global _LAST_CHECK_MONO, _RECIPIENT_GAP_LOGGED
_LAST_CHECK_MONO = 0.0
_RECIPIENT_GAP_LOGGED = False
with _MEMORY_ALERT_LOCK:
_MEMORY_ALERT_STATE.clear()
try:
from flask import has_app_context
if has_app_context():
row = db.session.get(AppSetting, _DB_ALERT_STATE_KEY)
if row:
db.session.delete(row)
db.session.commit()
except Exception:
db.session.rollback()
def _load_alert_state() -> dict[str, Any]:
"""
加载告警冷却状态;DB 为权威源,Redis 仅作缓存,仅 DB 不可读时才回退 Redis/内存。
"""
db_state, db_ok = _try_read_alert_state_from_db()
if db_ok:
if db_state is not None:
_memory_save_alert_state(db_state)
_sync_redis_cache_from_db(db_state)
return db_state
_memory_save_alert_state({})
_delete_redis_alert_state_if_possible()
return {}
redis_state = _try_load_alert_state_from_redis()
if redis_state is not None:
_memory_save_alert_state(redis_state)
return redis_state
return _memory_load_alert_state()
def _save_alert_state(state: dict[str, Any]) -> None:
"""保存告警冷却状态;写内存 + DB + Redis(可用时)。"""
payload = _normalize_alert_state(state) if state else {}
_memory_save_alert_state(payload)
if not payload:
return
try:
_persist_alert_state_to_db(payload)
except Exception:
db.session.rollback()
logger.exception("[rpa-heartbeat-alert] save state to db failed")
_persist_alert_state_to_redis(payload)
def _claim_alert_send_lock_db(
*,
lock_state: dict[str, Any],
should_send_fn: Callable[[dict[str, Any]], bool],
) -> tuple[bool, dict[str, Any]]:
row = (
db.session.query(AppSetting)
.filter(AppSetting.key == _DB_ALERT_STATE_KEY)
.with_for_update()
.one_or_none()
)
existing: dict[str, Any] = {}
if row and row.value:
parsed = json.loads(row.value)
if isinstance(parsed, dict):
existing = parsed
if not should_send_fn(existing):
db.session.rollback()
return False, existing
previous_state = dict(existing)
lock_state = _normalize_alert_state(lock_state)
payload = json.dumps(lock_state, ensure_ascii=False)
if row:
row.value = payload
else:
db.session.add(AppSetting(key=_DB_ALERT_STATE_KEY, value=payload))
db.session.commit()
_memory_save_alert_state(lock_state)
_persist_alert_state_to_redis(lock_state)
return True, previous_state
def _claim_alert_send_lock_memory_only(
*,
lock_state: dict[str, Any],
should_send_fn: Callable[[dict[str, Any]], bool],
) -> tuple[bool, dict[str, Any]]:
"""仅当 DB 不可读/不可写时使用的进程内 claim 兜底。"""
mem = _memory_load_alert_state()
if not should_send_fn(mem):
return False, mem
previous_state = dict(mem)
_memory_save_alert_state(lock_state)
return True, previous_state
def _claim_alert_send_lock(
*,
lock_state: dict[str, Any],
should_send_fn: Callable[[dict[str, Any]], bool],
) -> tuple[bool, dict[str, Any]]:
"""
跨进程发送锁:仅写入 sending 状态,不更新 last_sent_at 冷却。
Returns:
(claimed, previous_state):claimed 为 True 时 previous_state 供发送失败回滚。
"""
try:
return _claim_alert_send_lock_db(lock_state=lock_state, should_send_fn=should_send_fn)
except IntegrityError:
db.session.rollback()
existing, db_ok = _try_read_alert_state_from_db()
if existing:
_memory_save_alert_state(existing)
elif db_ok:
_memory_save_alert_state({})
return False, existing or {}
except Exception:
db.session.rollback()
logger.exception("[rpa-heartbeat-alert] claim send lock in db failed")
existing, db_ok = _try_read_alert_state_from_db()
if db_ok:
if existing:
_memory_save_alert_state(existing)
return False, existing or {}
return _claim_alert_send_lock_memory_only(
lock_state=lock_state,
should_send_fn=should_send_fn,
)
def _commit_alert_sent(*, final_state: dict[str, Any]) -> None:
"""企微发送成功后写入最终状态与 last_sent_at(进入长冷却)。"""
_save_alert_state(final_state)
def _release_alert_send_lock(*, previous_state: dict[str, Any]) -> None:
"""企微发送失败:回滚 sending 锁,不推进 last_sent_at。"""
if previous_state:
_save_alert_state(previous_state)
return
_memory_save_alert_state({})
try:
row = db.session.get(AppSetting, _DB_ALERT_STATE_KEY)
if row:
db.session.delete(row)
db.session.commit()
except Exception:
db.session.rollback()
logger.exception("[rpa-heartbeat-alert] release send lock in db failed")
_delete_redis_alert_state_if_possible()
def _send_alert_to_recipients(*, title: str, content: str) -> bool:
from app.services.wecom_notify import send_wecom_event_message
recipients = _alert_recipients()
if not recipients:
_log_recipient_gap_once()
logger.warning("[rpa-heartbeat-alert] no recipients available, title=%s", title)
return False
sent_any = False
for user in recipients:
result = send_wecom_event_message(
event_type="schedule_completed",
user=user,
title=title,
content=content,
jump_path="/admin/schedules",
)
if result.get("ok"):
sent_any = True
else:
logger.warning(
"[rpa-heartbeat-alert] notify failed user=%s reason=%s",
user.username,
result.get("reason"),
)
return sent_any
def _is_active_send_lock(existing: dict[str, Any], *, now_ts: float) -> bool:
if str(existing.get("status") or "").strip() != _STATUS_SENDING:
return False
started = float(existing.get("sending_started_at") or 0)
return started > 0 and (now_ts - started) < _send_lock_seconds()
def _effective_last_status(existing: dict[str, Any]) -> str:
status = str(existing.get("status") or "").strip()
if status == _STATUS_SENDING:
return str(existing.get("sending_target") or "").strip()
return status
def _should_send_storage_or_offline(
*,
existing: dict[str, Any],
target_status: str,
now_ts: float,
cooldown: int,
) -> bool:
if _is_active_send_lock(existing, now_ts=now_ts):
return False
last_status = _effective_last_status(existing)
last_sent_at = float(existing.get("last_sent_at") or 0)
return last_status != target_status or (now_ts - last_sent_at) >= cooldown
def _try_send_with_claim(
*,
target_status: str,
state: dict[str, Any],
now_ts: float,
cooldown: int,
title: str,
content: str,
) -> bool:
def should_send_fn(existing: dict[str, Any]) -> bool:
if _is_active_send_lock(existing, now_ts=now_ts):
return False
if target_status == "ready":
return _effective_last_status(existing) in {"offline", "storage_unavailable"}
return _should_send_storage_or_offline(
existing=existing,
target_status=target_status,
now_ts=now_ts,
cooldown=cooldown,
)
lock_state = {
"status": _STATUS_SENDING,
"sending_target": target_status,
"sending_started_at": now_ts,
"last_sent_at": float(state.get("last_sent_at") or 0),
"reasons": state.get("reasons", []),
}
claimed, previous_state = _claim_alert_send_lock(lock_state=lock_state, should_send_fn=should_send_fn)
if not claimed:
return False
if _send_alert_to_recipients(title=title, content=content):
final_state = {
"status": target_status,
"last_sent_at": now_ts,
"reasons": state.get("reasons", []),
}
_commit_alert_sent(final_state=final_state)
return True
_release_alert_send_lock(previous_state=previous_state)
return False
def maybe_alert_rpa_worker_status(*, force: bool = False) -> dict[str, Any]:
"""
周期检查 RPA Worker 就绪状态并按冷却时间发送离线/恢复告警。
Returns:
dict: 本次检查结果摘要(供运维日志)。
"""
global _LAST_CHECK_MONO
if not _alert_enabled():
return {"skipped": True, "reason": "alert_disabled"}
now_mono = time.monotonic()
if not force and _LAST_CHECK_MONO and (now_mono - _LAST_CHECK_MONO) < 60:
return {"skipped": True, "reason": "throttled"}
_LAST_CHECK_MONO = now_mono
readiness = check_inventory_rpa_worker_ready()
state = _load_alert_state()
effective_status = _effective_last_status(state)
last_sent_at = float(state.get("last_sent_at") or 0)
cooldown = _alert_cooldown_seconds()
now_ts = time.time()
storage_unavailable = "heartbeat_storage_unavailable" in readiness.reasons
summary = {
"ready": readiness.ready,
"status": "storage_unavailable" if storage_unavailable else ("ready" if readiness.ready else "offline"),
"reasons": readiness.reasons,
"detail_message": readiness.detail_message,
}
if storage_unavailable:
should_send = _should_send_storage_or_offline(
existing=state,
target_status="storage_unavailable",
now_ts=now_ts,
cooldown=cooldown,
)
if should_send:
title = "货代库存 RPA 心跳存储异常"
content = (
f"{RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE}\n\n"
f"原因:{'; '.join(readiness.reasons[:8]) or 'unknown'}"
)
new_state = {
"status": "storage_unavailable",
"last_sent_at": last_sent_at,
"reasons": readiness.reasons,
}
if _try_send_with_claim(
target_status="storage_unavailable",
state=new_state,
now_ts=now_ts,
cooldown=cooldown,
title=title,
content=content,
):
summary["storage_alert_sent"] = True
return summary
if not readiness.ready:
should_send = _should_send_storage_or_offline(
existing=state,
target_status="offline",
now_ts=now_ts,
cooldown=cooldown,
)
if should_send:
detail = readiness.detail_message or RPA_WORKER_OFFLINE_MESSAGE
title = "货代库存 RPA Worker 离线"
content = f"{detail}\n\n原因:{'; '.join(readiness.reasons[:8]) or 'unknown'}"
new_state = {"status": "offline", "last_sent_at": last_sent_at, "reasons": readiness.reasons}
if _try_send_with_claim(
target_status="offline",
state=new_state,
now_ts=now_ts,
cooldown=cooldown,
title=title,
content=content,
):
summary["alert_sent"] = True
return summary
if effective_status in {"offline", "storage_unavailable"}:
title = "货代库存 RPA Worker 已恢复"
content = "库存 RPA Worker 心跳已恢复,可正常触发库存导出。"
new_state = {"status": "ready", "last_sent_at": last_sent_at, "reasons": []}
if _try_send_with_claim(
target_status="ready",
state=new_state,
now_ts=now_ts,
cooldown=cooldown,
title=title,
content=content,
):
summary["recovery_sent"] = True
return summary
+4 -3
View File
@@ -29,12 +29,13 @@ def _get_enabled_events() -> set[str]:
def _get_notify_base_url() -> str:
"""
解析企微 textcard 跳转基地址。
核心逻辑:优先 WECOM_NOTIFY_BASE_URL,其次 WECOM_PUBLIC_BASE_URL。
解析企微 textcard 跳转基地址(用户点击入口,须为浏览器可访问的 HTTPS 公网域名)。
核心逻辑:优先 WECOM_PUBLIC_BASE_URL,其次 HXOPS_PUBLIC_BASE_URL;
WECOM_NOTIFY_BASE_URL 仅作历史内网/端口兼容兜底。
Returns:
去掉尾斜杠的基地址;均未配置时返回空字符串。
"""
for key in ('WECOM_NOTIFY_BASE_URL', 'WECOM_PUBLIC_BASE_URL'):
for key in ('WECOM_PUBLIC_BASE_URL', 'HXOPS_PUBLIC_BASE_URL', 'WECOM_NOTIFY_BASE_URL'):
raw = current_app.config.get(key)
if isinstance(raw, str) and raw.strip():
return raw.strip().rstrip('/')