fix: 给 soffice 加超时(120s)机制、worker 自动回收超时 running 任务,避免任务挂死阻塞队列

This commit is contained in:
sophie committed 2026-05-29 11:37:02 +08:00
1 parent 1d72018eb7
commit 0eb577df1a
11 files changed
+379 -88

No files matched your search

@@ -0,0 +1,92 @@
"""
backend/edkb_system/skills/soffice_util.py
文件用途:LibreOffice(soffice)转换统一封装
说明:
- 为 loader_docx / doc_to_pdf / loader_excel / loader_pptx 等技能提供带超时的 soffice 调用;
- 避免单个 Office 文档转换卡死导致 kb-worker 长期阻塞;
- 超时阈值通过环境变量 EDKB_SOFFICE_TIMEOUT_SEC 配置(默认 120 秒)。
"""
from __future__ import annotations
import os
import subprocess
from pathlib import Path
def soffice_timeout_sec() -> int:
"""读取 soffice 子进程超时秒数,最小 10 秒。"""
raw = str(os.environ.get("EDKB_SOFFICE_TIMEOUT_SEC", "120")).strip()
try:
value = int(raw)
except ValueError:
value = 120
return max(value, 10)
def soffice_candidates() -> list[str]:
"""返回 soffice 可执行文件候选路径(环境变量优先,其次 Windows 默认安装路径)。"""
return [
os.environ.get("EDKB_SOFFICE", "").strip(),
r"C:\Program Files\LibreOffice\program\soffice.exe",
r"C:\Program Files (x86)\LibreOffice\program\soffice.exe",
"soffice",
]
def find_soffice() -> str | None:
"""返回第一个可用的 soffice 路径;PATH 中的 `soffice` 不做存在性探测。"""
for candidate in soffice_candidates():
if not candidate:
continue
if candidate == "soffice":
return candidate
if Path(candidate).exists():
return candidate
return None
def run_soffice(cmd: list[str]) -> subprocess.CompletedProcess[str]:
"""
执行 soffice 命令并强制超时。
超时时抛出 RuntimeError,供上层清洗任务识别为失败而非无限等待。
"""
timeout = soffice_timeout_sec()
try:
return subprocess.run(
cmd,
capture_output=True,
text=True,
timeout=timeout,
)
except subprocess.TimeoutExpired as exc:
label = Path(cmd[-2]).name if len(cmd) >= 2 else "soffice"
raise RuntimeError(
f"soffice timed out after {timeout}s: {label}"
) from exc
def convert_with_soffice(
soffice: str,
*,
convert_to: str,
source_path: Path,
out_dir: Path,
) -> subprocess.CompletedProcess[str]:
"""
以 headless 模式调用 soffice 做格式转换。
:param convert_to: 目标格式,如 docx / pdf / xlsx / pptx
"""
out_dir.mkdir(parents=True, exist_ok=True)
cmd = [
soffice,
"--headless",
"--convert-to",
convert_to,
str(source_path),
"--outdir",
str(out_dir),
]
return run_soffice(cmd)