unis-oa/backend/app/storage/convert.py

514 lines
21 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"""把"浏览器打不开的那几种格式"转成 PDF,让在线阅览和下载后打开长得一样。
为什么要这一层
==============
Word / Excel / PPT 原来走 :mod:`app.storage.preview`:后端把正文读出来,前端用模板画。
内容一个字不缺,版式全丢——合并单元格没了、颜色字体没了、图表没了、分页也没了,
审批人看到的其实是"另一份文件";浏览器自己又打不开 ``.docx``。于是"在线预览"和
"下载后打开"永远是两副样子。
这一层补的就是那一段:用 LibreOffice(``soffice --headless``)把文档转成 PDF。转出来的
就是下载后打开那个版式,而 PDF 浏览器自带阅读器直接能看,顺带白送缩放、选字、翻页、打印。
四条硬规矩
==========
1. **装不上也照常跑**:``soffice`` 是可选件(和 ``python-docx`` / MinIO SDK 一个套路)。
找不到、跑不动、超时,一律 :func:`available` 为假,预览自动退回
:mod:`app.storage.preview` 那份结构化正文——版式降级,内容不少,不报错、不卡审批链。
2. **原件一个字节都不动**:产物落在源文件所属后端的 ``preview/<kind>/`` 区里,位置由
"源位置 + 源文件字节数" 哈希算出来。源文件被替换(字节数变了)位置就跟着变,
旧产物自然没人认领,由 :func:`sweep` 收掉。
3. **一份文件只转一次**:后端上已经有产物就不再转。同一条附件十个人点开只转一次;
服务重启也不会把历史附件重转一遍(先问后端,再动手)。
4. **产物不算业务数据**:不进 :mod:`app.service.storage_gc` 的引用账,也不进"待补删"
那张表。它随时能凭原件重新生成,所以清点只按"源还在不在"判,删错了顶多再转一次。
安全边界
========
附件是别人传上来的,所以 ``soffice`` 只拿固定几个参数:无恢复、无锁检查、无默认文档,
``-env:UserInstallation`` 指向一个用完就删的临时目录。源文件先复制成 ``source.<ext>``
再交给它——文件名里那些空格、引号、``--`` 前缀没机会变成命令行参数;产物只认 ``.pdf``
这一个后缀,落盘位置完全由我们自己算。
"""
from __future__ import annotations
import hashlib
import logging
import os
import re
import shutil
import subprocess
import tempfile
import threading
import time
from dataclasses import dataclass
from datetime import datetime, timedelta
from pathlib import Path
from typing import Any
from .. import dbconfig
from .base import FileStore, StorageError, StorageUnreadableError, clean_name, extension_of
logger = logging.getLogger("unisoa.convert")
#: 产物统一放这个区:与原件同后端,但和业务字节分开,清点时一眼认得出哪些是派生的
ARTIFACT_PREFIX = "preview"
#: LibreOffice 吃得下去并能导出 PDF 的常见办公格式。
#: 留意 .doc/.xls/.ppt 这三兄弟——老格式以前"只能下载",有了这一层照样能在线看。
CONVERTIBLE = frozenset(
{
"doc", "docx", "dot", "dotx", "odt", "rtf", "wps", "wpd",
"xls", "xlsx", "xlsm", "xlsb", "ods", "et",
"ppt", "pptx", "pptm", "odp", "dps",
"vsd", "vsdx",
}
)
#: 一次转换最多等多久。LibreOffice 冷启动 1~2 秒,几十页的文档实测十几秒内;
#: 再久就当它转不出来,别把一次 HTTP 请求拖死。
DEFAULT_TIMEOUT_SECONDS = 120
#: "装了没有"这个结论缓存多久。这不是会在一分钟内变化的事,但运维真装上之后
#: 最多等这么久在线预览就该生效,不用重启服务。
PROBE_TTL_SECONDS = 300
#: 产物位置缓存:省掉每一次点开的 HEAD 请求。到点重新问后端,
#: 于是 sweep 删掉的产物不会在这一进程里被当成"还在"。
ARTIFACT_TTL_SECONDS = 600
#: 数页数用的两个粗匹配:面板上那句"共 N 页"是给人看的,不为此引一个 PDF 库
_PDF_PAGE = re.compile(rb"/Type\s*/Page[^s]")
#: 页面树根上的页数(`/Kids` 那一层的 `/Count`)。中间节点也可能有,取最大那一个
_PDF_COUNT = re.compile(rb"/Count\s+(\d+)")
#: 同时最多转几份。**每个进程各一把**:一趟 LibreOffice 峰值几百 MB,而 Pod 只给了 2Gi,
#: 四个人同时点开四份 PPT 就能把它撑爆。多 worker 部署时按 worker 数折算。
DEFAULT_CONCURRENCY = 2
_slot_size = 0
_slot_gate = threading.BoundedSemaphore(DEFAULT_CONCURRENCY)
def _slot() -> threading.BoundedSemaphore:
"""按当前配置拿转换槽位;界面上改了并发数,下一趟就换新的一把闸。"""
global _slot_size, _slot_gate
want = settings().concurrency
with _locks_guard:
if _slot_size != want:
_slot_gate = threading.BoundedSemaphore(max(1, want))
_slot_size = want
return _slot_gate
@dataclass(frozen=True)
class ConvertSettings:
"""这一层用到的运行配置(存库即生效,界面上改完不用重启)。"""
#: off = 只用结构化正文;auto = 机器上有 LibreOffice 就转 PDF;on = 强制转(转不了就报错)
mode: str = "auto"
#: 超过这个体积不做转换。转 PDF 比读正文重得多,单独给一道闸,别和解析上限共用一个数
max_mb: int = 100
#: soffice 可执行文件;留空 = 在 PATH 与常见安装位置里找
binary: str = ""
timeout_seconds: int = DEFAULT_TIMEOUT_SECONDS
#: 同一进程里最多同时转几份
concurrency: int = DEFAULT_CONCURRENCY
def settings() -> ConvertSettings:
"""当前生效的转换配置。取值分层与存储层一致:环境变量 > 库 > 配置文件 > 默认。"""
values = dbconfig.values()
mode = str(values.get("preview_convert") or "auto").strip().lower()
if mode not in {"off", "auto", "on"}:
mode = "auto"
return ConvertSettings(
mode=mode,
max_mb=_positive(values.get("preview_convert_max_mb"), 100),
binary=str(values.get("soffice_path") or "").strip(),
timeout_seconds=_positive(values.get("preview_convert_timeout_seconds"), DEFAULT_TIMEOUT_SECONDS),
concurrency=_positive(values.get("preview_convert_concurrency"), DEFAULT_CONCURRENCY),
)
def _positive(value: Any, fallback: int) -> int:
try:
number = int(value)
except (TypeError, ValueError):
return fallback
return number if number > 0 else fallback
def convertible(name: str) -> bool:
"""这一份值不值得交给 LibreOffice。只看扩展名,不碰字节。"""
return extension_of(clean_name(name)) in CONVERTIBLE
def wanted(name: str, size: int = 0) -> bool:
"""格式与配置这两头是否要求按原版式在线看(不看这台机器上装没装 LibreOffice)。"""
config = settings()
if config.mode == "off" or not convertible(name):
return False
if config.max_mb > 0 and int(size or 0) > config.max_mb * 1024 * 1024:
return False
return True
# ------------------------------------------------------------------ 可执行文件
_probe: tuple[str, float, str] = ("", 0.0, "")
_probe_lock = threading.Lock()
def _discover(configured: str) -> str:
"""找出能用的那个 soffice,回绝对路径;找不到回空串。
配置里点名了就用点名的那一个(哪怕它此刻不存在,也不再回头猜 PATH):运维显式填错
地址应当安静地退回正文预览,而不是悄悄拿系统里另一个版本去转——那转出来的版式
对不上他以为装着的那个。
"""
if configured:
candidate = Path(configured).expanduser()
return str(candidate) if candidate.is_file() and os.access(candidate, os.X_OK) else ""
for name in ("soffice", "libreoffice"):
where = shutil.which(name)
if where:
return where
# macOS 上装了 LibreOffice.app 但没链进 PATH 是很常见的情形
for app in (
"/Applications/LibreOffice.app/Contents/MacOS/soffice",
"/Applications/LibreOfficeDev.app/Contents/MacOS/soffice",
):
if Path(app).is_file():
return app
return ""
def _binary() -> str:
"""带缓存的探测。缓存键含配置里点名的路径,改了它当场重探。"""
global _probe
configured = settings().binary
now = time.time()
with _probe_lock:
seen_configured, seen_at, seen_found = _probe
if seen_configured == configured and now - seen_at < PROBE_TTL_SECONDS:
return seen_found
found = _discover(configured)
_probe = (configured, now, found)
return found
def reset_probe() -> None:
"""丢掉"有没有 LibreOffice"这个结论(刚装完软件、或改了配置之后用)。"""
global _probe
with _probe_lock:
_probe = ("", 0.0, "")
def available() -> bool:
"""这台机器上能不能转 PDF。"""
return bool(_binary())
# ------------------------------------------------------------------ 产物位置
_locks: dict[str, threading.Lock] = {}
_locks_guard = threading.Lock()
_artifacts: dict[str, tuple[str, int, float]] = {}
def _lock_for(key: str) -> threading.Lock:
with _locks_guard:
lock = _locks.get(key)
if lock is None:
if len(_locks) > 4096: # 别被一长串历史附件把内存吃干净
_locks.clear()
lock = threading.Lock()
_locks[key] = lock
return lock
def artifact_relative(uri: str, kind: str, size: int = 0) -> str:
"""产物在这个后端内的相对位置:``preview/<kind>/<源对象名>-<哈希>.pdf``。
哈希吃"源位置 + 字节数",所以位置唯一性不依赖目录结构:MinIO 改过上传路径前缀、
本地磁盘存过绝对路径,都不影响算出来的这一个位置。
文件名前缀取**源对象在存储里的名字**(``<uuid>.<ext>``),不取用户上传的显示名:
排障时是在桶里对着对象键找,中文名洗成 ``____`` 反而对不上;显示名在数据库那条记录里。
"""
text = str(uri or "")
digest = hashlib.sha1(f"{text}|{int(size or 0)}".encode("utf-8")).hexdigest()[:20]
stem = re.sub(r"[^0-9A-Za-z._-]", "_", text.rpartition("/")[2] or "file")[:64] or "file"
return f"{ARTIFACT_PREFIX}/{kind}/{stem}-{digest}.pdf"
def artifact_location(store: FileStore, uri: str, size: int = 0) -> str:
"""产物在这个后端上的完整位置串。
一律走 ``uri_for()``:MinIO 会补上配置的上传路径前缀,本地磁盘就是相对存储根。
于是产物永远跟"现在这套存储配置"待在一块儿,不会因为前缀改过而算出一个读不到的位置。
"""
return store.uri_for(artifact_relative(uri, store.kind, size))
def is_artifact_key(key: str, kind: str = "") -> bool:
"""后端列举出来的这个键是不是本层产出来的派生文件。"""
text = str(key or "").lstrip("/")
head = f"{ARTIFACT_PREFIX}/{kind}/" if kind else f"{ARTIFACT_PREFIX}/"
return text.startswith(head) or f"/{head}" in f"/{text}"
def _cache_key(store: FileStore, uri: str) -> str:
from .. import storageconfig
return f"{storageconfig.current().fingerprint()}|{store.kind}|{uri}"
def _remember(store: FileStore, uri: str, location: str, size: int) -> None:
_artifacts[_cache_key(store, uri)] = (location, size, time.time())
def _recall(store: FileStore, uri: str) -> tuple[str, int] | None:
hit = _artifacts.get(_cache_key(store, uri))
if hit and time.time() - hit[2] < ARTIFACT_TTL_SECONDS:
return hit[0], hit[1]
return None
def forget(uri: str) -> None:
"""源文件被删/被替换时丢掉它的产物缓存。字节的回收是 :func:`sweep` 的活。"""
text = str(uri or "")
for key in [key for key in _artifacts if key.endswith(f"|{text}")]:
_artifacts.pop(key, None)
# -------------------------------------------------------------------- 转换本身
def _run_soffice(binary: str, source: Path, outdir: Path, timeout: int) -> tuple[Path | None, int]:
"""真的调一次 LibreOffice,回 (产出的 PDF, 退出码)。
退出码要带回去:``--convert-to`` 碰上打不开的文件(截断的 docx、加了密的簿子)
会**非零退出且不产出**,而"这份文件坏了"和"服务器上的转换器缺组件"是两件事,
话说反了会让人白折腾半天。
"""
profile = Path(tempfile.mkdtemp(prefix="unisoa-soffice-"))
command = [
binary,
"--headless",
"--norestore",
"--nolockcheck",
"--nodefault",
f"-env:UserInstallation=file://{profile}",
"--convert-to",
"pdf",
"--outdir",
str(outdir),
str(source),
]
try:
result = subprocess.run(
command,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
timeout=timeout,
check=False,
)
except subprocess.TimeoutExpired as exc:
raise StorageError(f"这份文件转换超时({timeout} 秒),请改用正文预览或下载后查看") from exc
except OSError as exc:
raise StorageError(f"无法调用文档转换器({binary}):{exc}") from exc
finally:
shutil.rmtree(profile, ignore_errors=True)
produced = sorted(outdir.glob("*.pdf"), key=lambda item: item.stat().st_mtime, reverse=True)
if not produced:
tail = (result.stdout or b"").decode("utf-8", "replace").strip()[-200:]
logger.warning("soffice 没有产出 PDF(exit=%s):%s", result.returncode, tail)
return None, int(result.returncode or 0)
return produced[0], int(result.returncode or 0)
def _count_pages(path: Path, limit: int = 100_000) -> int:
"""这份 PDF 有几页。
先认页面树根上的 ``/Count``(那才是页数的正解),认不出来才退回数 ``/Type /Page``
对象。数对象这一手在页对象被塞进对象流(压缩 xref)的 PDF 上会少数,而 ``/Count``
不管哪种写法都在——LibreOffice 自己产的那两种都对,但转换目标不总是它产的,
宁可多写两行也别在面板上少报几页。
"""
try:
data = path.read_bytes()
except OSError:
return 0
counts = [int(value) for value in _PDF_COUNT.findall(data)]
if counts:
return min(max(counts), limit)
return min(len(_PDF_PAGE.findall(data)), limit)
def convert(store: FileStore, uri: str, name: str, size: int) -> tuple[str, int, int]:
"""转成 PDF 并落到源文件所属的那个后端。回 (产物位置, 产物字节数, 页数)。
已经转好就直接回——包括"后端上已经有、进程内还没记住"这一种,所以重启之后不会把
历史附件重转一遍。同一份产物同一把锁,两个人同时点开只转一次。
"""
hit = _recall(store, uri)
if hit:
return hit[0], hit[1], 0
config = settings()
binary = _binary()
if not binary and config.mode != "on":
raise StorageError("服务端未安装 LibreOffice(soffice),无法按原版式在线阅览")
target = artifact_location(store, uri, size)
relative = artifact_relative(uri, store.kind, size)
with _lock_for(target):
hit = _recall(store, uri)
if hit:
return hit[0], hit[1], 0
if store.exists(target):
try:
existing = store.size(target)
except StorageError:
existing = 0
if existing > 0:
_remember(store, uri, target, existing)
return target, existing, 0
with tempfile.TemporaryDirectory(prefix="unisoa-convert-") as work:
workdir = Path(work)
extension = extension_of(clean_name(name))
# 源文件一律改名成 source.<ext>:文件名里那些空格、引号、`--` 前缀
# 不该有机会变成命令行参数
source = workdir / f"source.{extension}" if extension else workdir / "source"
with store.open_stream(uri) as handle, source.open("wb") as target_handle:
shutil.copyfileobj(handle, target_handle, 1024 * 1024)
outdir = workdir / "out"
outdir.mkdir()
started = time.time()
executable = binary or "soffice"
# 排队等槽位:宁可让人多等两秒,也别让一屋子 soffice 把容器内存吃穿
with _slot():
produced, exit_code = _run_soffice(executable, source, outdir, config.timeout_seconds)
if produced is None:
# 转不出来分两种,说反了会白折腾半天:非零退出 = 转换器压根打不开这份
# 文件(十有八九是它坏了);退出 0 却没产出 = 转换器这边缺东西
if exit_code:
raise StorageUnreadableError(
"这份文档连转换器都打不开,多半已损坏、加了密或后缀与内容不符,"
"请下载后确认,或改用正文预览"
)
raise StorageError(
"文档转换器没能为这份文件转出版式(服务器上的 LibreOffice 可能缺组件或缺字体),"
"请改用正文预览,或联系管理员检查转换器"
)
payload = produced.read_bytes()
if not payload:
raise StorageUnreadableError("这份文件转出来是空的,请下载后查看")
pages = _count_pages(produced)
saved = store.save(
purpose=ARTIFACT_PREFIX,
name=Path(relative).name,
data=payload,
content_type="application/pdf",
key=relative,
)
_remember(store, uri, target, saved.size)
logger.info(
"在线阅览版式转换完成:%s(%.1fMB -> %.1fMB,%s 页,%.1f 秒)",
clean_name(name),
int(size or 0) / 1048576,
saved.size / 1048576,
pages or "?",
time.time() - started,
)
return target, saved.size, pages
def probe() -> dict[str, Any]:
"""给系统设置页看的体检结论:装没装、在哪、能转哪些格式。"""
config = settings()
found = _binary()
return {
"mode": config.mode,
"max_mb": config.max_mb,
"timeout_seconds": config.timeout_seconds,
"concurrency": config.concurrency,
"configured": config.binary,
"resolved": found,
"available": bool(found),
"extensions": sorted(CONVERTIBLE),
}
# ------------------------------------------------------------------ 产物回收
def sweep(store: FileStore, live: set[str], min_age_minutes: int = 60) -> dict[str, Any]:
"""删掉"源文件已经没人引用"的派生产物。
``live`` 是 :func:`app.service.storage_gc.artifact_locations` 算出来的那一份
"按现存业务记录该存在的产物位置"。只动 ``preview/`` 这一层,别的字节一个不碰——
业务字节的账在 :mod:`app.service.storage_gc`,产物不是业务数据,不该混进同一本账,
也不该进"待补删"那张表。
``min_age_minutes`` 防的是"正在转的那一趟":产物刚落盘、业务记录的引用却还没提交,
这时候删掉,下一次点开只会重转一次,但白扔一趟 LibreOffice 的时间。
"""
deadline = datetime.now() - timedelta(minutes=max(0, int(min_age_minutes)))
try:
listing = [item for item in store.iter_keys() if is_artifact_key(item.key, store.kind)]
except StorageError as exc:
return {"removed": 0, "freed": 0, "skipped": f"后端不支持列举({exc})"}
removed = 0
freed = 0
protected = 0
for item in listing:
location = _location_of_key(store, item.key)
if location in live:
continue
stamp = item.last_modified
if stamp and stamp > deadline:
protected += 1
continue
try:
store.delete(location)
removed += 1
freed += int(item.size or 0)
except StorageError as exc:
logger.warning("派生预览文件删除失败 %s:%s", item.key, exc)
_artifacts.clear()
return {"removed": removed, "freed": freed, "protected_by_age": protected, "listed": len(listing)}
def _location_of_key(store: FileStore, key: str) -> str:
"""把后端列举出来的键还原成能删的位置串。
照 :func:`app.service.storage_gc.location_of_key` 的口径:桶那边的键是完整对象键
(可能落在改过之前的上传路径前缀下面),再走一次 ``uri_for()`` 会把前缀拼两遍,
删到一个不存在的位置上。
"""
from .minio_store import MinioStore
if isinstance(store, MinioStore):
return store.uri(key)
return store.uri_for(key)
__all__ = [
"ARTIFACT_PREFIX",
"CONVERTIBLE",
"ConvertSettings",
"artifact_location",
"artifact_relative",
"available",
"convert",
"convertible",
"forget",
"is_artifact_key",
"probe",
"reset_probe",
"settings",
"sweep",
"wanted",
]