按 common/connectors/inventory/receipt 分层并重命名
- common/: rpa_common, rpa_heartbeat, download_artifact_fallback,
new_rpa_worker_secret
- connectors/dsv|crane/: 登录网站连接器,库存与收料共用
- inventory/: inventory_rpa_worker, run_inventory_batch_trigger,
start_inventory_worker, register_inventory_worker_tasks
- receipt/: receipt_rpa_worker, receipt_crane/dbs_export,
start_receipt_worker
保留裸 import + sys.path 引导;修正懒加载路径;
按范围命名 register_rpa_background_tasks -> register_inventory_worker_tasks;
同步 backend 测试、start_local.ps1、.env 注释、docs 与 README 路径。
(cherry picked from commit f3050164d0)
365 lines
15 KiB
Python
365 lines
15 KiB
Python
"""
|
|
scripts/rpa/dsv_debug.py
|
|
|
|
用途:DSV 360 RPA 调试探针与链路阶段日志。
|
|
依赖:rpa_common。
|
|
逻辑:供 dsv_session、dsv_navigation、dsv_report_export 调用。
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import sys as _sys
|
|
from pathlib import Path as _Path
|
|
|
|
_RPA_ROOT = next(
|
|
(_c for _c in _Path(__file__).resolve().parents
|
|
if (_c / "connectors").is_dir() and (_c / "common").is_dir()
|
|
and (_c / "inventory").is_dir() and (_c / "receipt").is_dir()),
|
|
None,
|
|
)
|
|
if _RPA_ROOT is not None:
|
|
for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "inventory", "receipt"):
|
|
_dir = str(_RPA_ROOT) if not _rel else str(_RPA_ROOT / _rel)
|
|
if _dir not in _sys.path:
|
|
_sys.path.insert(0, _dir)
|
|
|
|
import json
|
|
import sys
|
|
import time
|
|
import urllib.request
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
from rpa_common import browser_timeout_ms as _browser_timeout_ms
|
|
from rpa_common import env as _env
|
|
|
|
def _emit_debug_event(run_id: str, hypothesis_id: str, location: str, msg: str, data: dict[str, Any] | None = None) -> None:
|
|
_payload = {
|
|
"sessionId": "dsv-export-stall",
|
|
"runId": run_id,
|
|
"hypothesisId": hypothesis_id,
|
|
"location": location,
|
|
"msg": msg,
|
|
"data": data or {},
|
|
"ts": int(time.time() * 1000),
|
|
}
|
|
_url = "http://127.0.0.1:7778/event"
|
|
_env_file = Path(".dbg/dsv-export-stall.env")
|
|
try:
|
|
if _env_file.is_file():
|
|
_content = _env_file.read_text(encoding="utf-8")
|
|
_url = next((line.split("=", 1)[1] for line in _content.splitlines() if line.startswith("DEBUG_SERVER_URL=")), _url)
|
|
_payload["sessionId"] = next((line.split("=", 1)[1] for line in _content.splitlines() if line.startswith("DEBUG_SESSION_ID=")), _payload["sessionId"])
|
|
urllib.request.urlopen(
|
|
urllib.request.Request(
|
|
_url,
|
|
data=json.dumps(_payload, ensure_ascii=False).encode("utf-8"),
|
|
headers={"Content-Type": "application/json"},
|
|
),
|
|
timeout=1.5,
|
|
).read()
|
|
except Exception:
|
|
pass
|
|
def _debug_dsv_page_snapshot(page: Any, *, target_text: str = "") -> str:
|
|
"""
|
|
汇总 DSV 当前页面与各 frame 的可见文本快照,便于定位菜单/报表文案漂移。
|
|
|
|
核心逻辑:采集 page.url、顶层 body 文本、关键菜单容器是否存在,以及各 frame 中
|
|
可见的链接/按钮/菜单项候选文本;当目标文案找不到时,日志里直接输出“页面上实际看到了什么”。
|
|
|
|
Args:
|
|
page: Playwright Page 对象。
|
|
target_text: 当前正在寻找的菜单/报表文案,可为空。
|
|
|
|
Returns:
|
|
str: 截断后的页面快照字符串,适合直接输出到 worker 日志。
|
|
"""
|
|
focus = str(target_text or "").strip()
|
|
try:
|
|
page_url = page.url
|
|
except Exception:
|
|
page_url = ""
|
|
snippets = [f"url={page_url!r}"]
|
|
try:
|
|
body = page.locator("body").inner_text(timeout=1_000).replace("\n", " ")[:500]
|
|
except Exception:
|
|
body = ""
|
|
if body:
|
|
snippets.append(f"page_body={body!r}")
|
|
try:
|
|
from dsv_session import has_dsv_report_nav_attached as _has_dsv_report_nav_attached
|
|
|
|
report_nav_exists = _has_dsv_report_nav_attached(page)
|
|
except Exception:
|
|
report_nav_exists = False
|
|
snippets.append(f"report_nav_exists={report_nav_exists}")
|
|
|
|
candidate_script = """
|
|
(focusText) => {
|
|
const normalize = (value) => ((value || '') + '').replace(/\\s+/g, ' ').trim();
|
|
const isVisible = (node) => {
|
|
const rect = node.getBoundingClientRect();
|
|
const style = window.getComputedStyle(node);
|
|
return style.display !== 'none' && style.visibility !== 'hidden' && rect.width > 0 && rect.height > 0;
|
|
};
|
|
const selectors = [
|
|
'#report-mega-legacy',
|
|
'#report-mega-legacy *',
|
|
'.mega-dropdown-menu *',
|
|
'.dropdown-menu *',
|
|
'a',
|
|
'button',
|
|
'[role="button"]',
|
|
'li',
|
|
'.nav-link',
|
|
'.dropdown-item',
|
|
];
|
|
const focus = normalize(focusText).toLowerCase();
|
|
const values = Array.from(document.querySelectorAll(selectors.join(',')))
|
|
.filter((node) => isVisible(node))
|
|
.map((node) => normalize(node.innerText || node.textContent || node.value))
|
|
.filter(Boolean);
|
|
const deduped = Array.from(new Set(values));
|
|
const matched = focus
|
|
? deduped.filter((text) => text.toLowerCase().includes(focus)).slice(0, 20)
|
|
: [];
|
|
return {
|
|
matched,
|
|
candidates: deduped.slice(0, 40),
|
|
};
|
|
}
|
|
"""
|
|
for idx, frame in enumerate(page.frames):
|
|
try:
|
|
frame_url = frame.url
|
|
except Exception:
|
|
frame_url = ""
|
|
try:
|
|
frame_name = frame.name
|
|
except Exception:
|
|
frame_name = ""
|
|
try:
|
|
frame_body = frame.locator("body").inner_text(timeout=1_000).replace("\n", " ")[:400]
|
|
except Exception:
|
|
frame_body = ""
|
|
try:
|
|
frame_data = frame.evaluate(candidate_script, focus, timeout=1_500)
|
|
except Exception:
|
|
frame_data = {"matched": [], "candidates": []}
|
|
matched = list((frame_data or {}).get("matched") or [])
|
|
candidates = list((frame_data or {}).get("candidates") or [])
|
|
if frame_body or candidates or matched:
|
|
snippets.append(
|
|
f"frame[{idx}] name={frame_name!r} url={frame_url!r} body={frame_body!r} matched={matched!r} candidates={candidates!r}"
|
|
)
|
|
return " | ".join(snippets)[:5000]
|
|
|
|
|
|
def _debug_dsv_stage(page: Any, stage: str, *, target_text: str = "") -> None:
|
|
"""
|
|
输出 DSV 关键阶段的运行时快照,用于排查“短暂到页后又跳走”或 DOM 未就绪的问题。
|
|
|
|
核心逻辑:在登录后等待首页、展开 Reports、选择 Program 等关键节点打印统一格式日志,
|
|
让失败复现时可以按时间顺序观察 URL、标题、body、frame 候选文本是否发生变化。
|
|
|
|
Args:
|
|
page: Playwright Page 对象。
|
|
stage: 当前阶段名,例如 `after-login-click`、`wait-app-3s`。
|
|
target_text: 当前关注的菜单或文案目标。
|
|
"""
|
|
try:
|
|
title = page.title()
|
|
except Exception:
|
|
title = ""
|
|
snapshot = _debug_dsv_page_snapshot(page, target_text=target_text)
|
|
print(f"[dsv-stage] stage={stage} title={title!r} {snapshot}")
|
|
|
|
|
|
# #region debug-point A:reports-debug-server
|
|
def _debug_server_config() -> tuple[str, str]:
|
|
"""读取 reports-menu-stuck 调试会话配置,未命中时回退默认本地地址。"""
|
|
env_path = _RPA_ROOT.parents[1] / ".dbg" / "reports-menu-stuck.env"
|
|
url = "http://127.0.0.1:7778/event"
|
|
session_id = "reports-menu-stuck"
|
|
try:
|
|
content = env_path.read_text(encoding="utf-8")
|
|
for line in content.splitlines():
|
|
if line.startswith("DEBUG_SERVER_URL="):
|
|
url = line.split("=", 1)[1].strip() or url
|
|
elif line.startswith("DEBUG_SESSION_ID="):
|
|
session_id = line.split("=", 1)[1].strip() or session_id
|
|
except Exception:
|
|
pass
|
|
return url, session_id
|
|
|
|
|
|
def _report_debug_event(hypothesis_id: str, location: str, msg: str, data: dict[str, Any] | None = None) -> None:
|
|
"""向 Debug Server 上报结构化运行时证据;失败时静默,不影响业务流程。"""
|
|
try:
|
|
url, session_id = _debug_server_config()
|
|
payload = {
|
|
"sessionId": session_id,
|
|
"runId": "pre-fix",
|
|
"hypothesisId": hypothesis_id,
|
|
"location": location,
|
|
"msg": msg,
|
|
"data": data or {},
|
|
"ts": int(time.time() * 1000),
|
|
}
|
|
req = urllib.request.Request(
|
|
url,
|
|
data=json.dumps(payload, ensure_ascii=False).encode("utf-8"),
|
|
headers={"Content-Type": "application/json"},
|
|
method="POST",
|
|
)
|
|
with urllib.request.urlopen(req, timeout=2):
|
|
pass
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
def _report_dsv_chain_stage(stage: str, status: str, *, started_at: float | None = None, extra: dict[str, Any] | None = None) -> None:
|
|
"""
|
|
统一记录 DSV 主链路各阶段耗时。
|
|
|
|
核心逻辑:只在主编排链路输出 `start/end/error` 三类探针,不参与任何业务判断,
|
|
让一次真实运行即可回放从登录到导出的完整阶段耗时分布。
|
|
"""
|
|
payload = dict(extra or {})
|
|
if started_at is not None:
|
|
payload["elapsedMs"] = int((time.monotonic() - started_at) * 1000)
|
|
print(
|
|
"[dsv-chain] "
|
|
f"stage={stage} "
|
|
f"status={status} "
|
|
+ (
|
|
" ".join(f"{key}={payload[key]!r}" for key in sorted(payload))
|
|
if payload
|
|
else ""
|
|
)
|
|
)
|
|
_report_debug_event(
|
|
"T",
|
|
f"freight_rpa_worker.py:_download_dsv360_inventory:{stage}:{status}",
|
|
"[DEBUG] dsv chain stage probe",
|
|
{"stage": stage, "status": status, **payload},
|
|
)
|
|
|
|
|
|
def _collect_dsv_reports_probe(page: Any) -> dict[str, Any]:
|
|
"""采集 Reports 导航的最小 DOM 证据,帮助判断是否点早、点错或被遮挡。"""
|
|
try:
|
|
probe = page.evaluate(
|
|
"""
|
|
() => {
|
|
const nav = document.querySelector('#report-mega-legacy');
|
|
const link = nav?.querySelector('a.dropdown-toggle, a.nav-link, a');
|
|
const textOf = (node) => ((node && (node.innerText || node.textContent || node.value)) || '').replace(/\\s+/g, ' ').trim();
|
|
const rectOf = (node) => {
|
|
if (!node || !node.getBoundingClientRect) return null;
|
|
const r = node.getBoundingClientRect();
|
|
return { x: Math.round(r.x), y: Math.round(r.y), width: Math.round(r.width), height: Math.round(r.height) };
|
|
};
|
|
const centerNode = (() => {
|
|
const rect = rectOf(link);
|
|
if (!rect || rect.width <= 0 || rect.height <= 0) return null;
|
|
return document.elementFromPoint(rect.x + Math.max(Math.floor(rect.width / 2), 1), rect.y + Math.max(Math.floor(rect.height / 2), 1));
|
|
})();
|
|
return {
|
|
navExists: !!nav,
|
|
navClass: nav?.className || '',
|
|
navAriaExpanded: nav?.getAttribute('aria-expanded') || '',
|
|
linkText: textOf(link),
|
|
linkClass: link?.className || '',
|
|
linkAriaExpanded: link?.getAttribute('aria-expanded') || '',
|
|
linkRect: rectOf(link),
|
|
centerTag: centerNode?.tagName || '',
|
|
centerText: textOf(centerNode).slice(0, 120),
|
|
activeTag: document.activeElement?.tagName || '',
|
|
activeText: textOf(document.activeElement).slice(0, 120),
|
|
};
|
|
}
|
|
""",
|
|
)
|
|
except Exception as exc:
|
|
probe = {"probe_error": str(exc)[:200]}
|
|
try:
|
|
probe["url"] = page.url
|
|
except Exception:
|
|
probe["url"] = ""
|
|
try:
|
|
from dsv_navigation import is_dsv_reports_menu_open as _is_dsv_reports_menu_open
|
|
|
|
probe["menuOpen"] = _is_dsv_reports_menu_open(page)
|
|
except Exception as exc:
|
|
probe["menuOpen"] = False
|
|
probe["menuOpenError"] = str(exc)[:120]
|
|
return probe
|
|
# #endregion
|
|
|
|
|
|
def _collect_dsv_menu_probe(page: Any, target_text: str = "") -> dict[str, Any]:
|
|
"""采集 Reports 级联菜单当前可见层级,帮助判断下拉是否真的推进到了下一层。"""
|
|
target_text = str(target_text or "").strip()
|
|
target_literal = json.dumps(target_text)
|
|
try:
|
|
probe = page.evaluate(
|
|
f"""
|
|
() => {{
|
|
const textOf = (node) => ((node && (node.innerText || node.textContent || node.value)) || '').replace(/\\s+/g, ' ').trim();
|
|
const nodes = Array.from(document.querySelectorAll(
|
|
'#report-mega-legacy a, #report-mega-legacy button, #report-mega-legacy [role="menuitem"], #report-mega-legacy [data-program], #report-mega-legacy [data-report], #report-mega-legacy .dropdown-item, #report-mega-legacy .menu-item, #report-mega-legacy div, #report-mega-legacy span, .mega-dropdown-menu a, .mega-dropdown-menu button, .mega-dropdown-menu [role="menuitem"], .mega-dropdown-menu [data-program], .mega-dropdown-menu [data-report], .mega-dropdown-menu .dropdown-item, .mega-dropdown-menu .menu-item, .mega-dropdown-menu div, .mega-dropdown-menu span, .dropdown-menu a, .dropdown-menu button, .dropdown-menu [role="menuitem"], .dropdown-menu [data-program], .dropdown-menu [data-report], .dropdown-menu .dropdown-item, .dropdown-menu .menu-item, .dropdown-menu div, .dropdown-menu span'
|
|
));
|
|
const visible = nodes
|
|
.filter((node) => {{
|
|
const rect = node.getBoundingClientRect ? node.getBoundingClientRect() : null;
|
|
const style = window.getComputedStyle ? window.getComputedStyle(node) : null;
|
|
return rect && rect.width > 0 && rect.height > 0 && style && style.visibility !== 'hidden' && style.display !== 'none';
|
|
}})
|
|
.map((node) => {{
|
|
const rect = node.getBoundingClientRect();
|
|
return {{
|
|
text: textOf(node),
|
|
className: node.className || '',
|
|
ariaExpanded: node.getAttribute('aria-expanded') || '',
|
|
tagName: node.tagName || '',
|
|
dataProgram: node.getAttribute('data-program') || '',
|
|
dataReport: node.getAttribute('data-report') || '',
|
|
x: Math.round(rect.x),
|
|
y: Math.round(rect.y),
|
|
}};
|
|
}})
|
|
.filter((item) => item.text)
|
|
.slice(0, 40);
|
|
const target = {target_literal};
|
|
const matched = target
|
|
? visible.filter((item) => item.text.toLowerCase().includes(target.toLowerCase())).slice(0, 10)
|
|
: [];
|
|
return {{
|
|
visibleItems: visible,
|
|
matchedItems: matched,
|
|
bodySnippet: textOf(document.body).slice(0, 600),
|
|
activeText: textOf(document.activeElement).slice(0, 120),
|
|
}};
|
|
}}
|
|
""",
|
|
)
|
|
except Exception as exc:
|
|
probe = {"probe_error": str(exc)[:200]}
|
|
try:
|
|
probe["url"] = page.url
|
|
except Exception:
|
|
probe["url"] = ""
|
|
return probe
|
|
|
|
|
|
# 公开 API
|
|
emit_debug_event = _emit_debug_event
|
|
debug_dsv_page_snapshot = _debug_dsv_page_snapshot
|
|
debug_dsv_stage = _debug_dsv_stage
|
|
debug_server_config = _debug_server_config
|
|
report_debug_event = _report_debug_event
|
|
report_dsv_chain_stage = _report_dsv_chain_stage
|
|
collect_dsv_reports_probe = _collect_dsv_reports_probe
|
|
collect_dsv_menu_probe = _collect_dsv_menu_probe
|