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

268 lines
9.7 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.

"""存储层入口:文件该落哪儿,由数据库里的 ``config:storage`` 决定。
路由规则只有一张表(``storageconfig.PURPOSE_BACKEND``),用途本身不给配:
=============== =============================
``attachment`` 表单/流程「上传附件」 MinIO
``portal`` 首页「信息资讯」封面与正文附件 MinIO
``drive`` 「网盘」文件 本地磁盘(暂不参与配置)
=============== =============================
MinIO 连不上时按 ``fallback_to_local`` 退回本地磁盘或直接报错。
``resolve_uri()`` 反过来按 uri 前缀找后端,所以历史上落在别处的文件依然能下载。
**改配置不用重启**:Store 实例与探活结果都按"落盘参数指纹"缓存,界面上改了
MinIO 地址 / 密钥 / 桶 / 上传路径 / 本地目录之后,指纹一变就自动重建客户端,
下一次上传走的就是新后端。
"""
from __future__ import annotations
import logging
import time
from .. import storageconfig
from ..storageconfig import LOCAL, MINIO, MinioConfig
from .base import (
FileStore,
StorageUnreadableError,
StoredObject,
StorageError,
StorageValidationError,
UnsupportedOperation,
clean_name,
extension_of,
guess_type,
is_image_name,
normalize_relative,
)
from .local import LocalStore
from .minio_store import MinioStore
from .preview import PreviewInfo
from .preview import classify as classify_preview
from .preview import describe as describe_preview
logger = logging.getLogger("unisoa.storage")
_HEALTH_TTL_SECONDS = 60
_stores: dict[str, FileStore] = {}
_health: dict[str, tuple[float, bool, str]] = {}
def fingerprint() -> str:
"""当前落盘参数的指纹。界面上改了 MinIO 或本地目录,这个值就会变。"""
return storageconfig.current().fingerprint()
def local_store() -> LocalStore:
key = f"local:{fingerprint()}"
store = _stores.get(key)
if not isinstance(store, LocalStore):
_stores.clear() # 配置一改就丢掉旧实例,别让一柜子用过的客户端占着内存
store = LocalStore(storageconfig.current().local)
_stores[key] = store
return store
def minio_store() -> MinioStore:
key = f"minio:{fingerprint()}"
store = _stores.get(key)
if not isinstance(store, MinioStore):
_stores.clear()
store = MinioStore(storageconfig.current().minio)
_stores[key] = store
return store
def build(kind: str) -> FileStore:
if kind == MINIO:
return minio_store()
return local_store()
def configured(kind: str) -> bool:
"""配置文件里是否把这个后端描述完整了。"""
if kind == MINIO:
return storageconfig.current().minio.configured
return True
def reachable(kind: str) -> tuple[bool, str]:
"""Cached connectivity probe so a dead MinIO does not stall every upload.
缓存键带落盘参数指纹:改了 MinIO 配置之后不会继续吃六十秒前的探活结果。
"""
now = time.time()
key = f"{kind}:{fingerprint()}"
hit = _health.get(key)
if hit and now - hit[0] < _HEALTH_TTL_SECONDS:
return hit[1], hit[2]
if not configured(kind):
result = (False, f"{kind} 后端还没配置完整(endpoint / access_key / bucket)")
else:
try:
report = build(kind).test()
result = (bool(report.get("ok")), str(report.get("message", "")))
except StorageError as exc:
result = (False, str(exc))
except Exception as exc: # pragma: no cover - 兜住 SDK 抛出的意外异常
result = (False, f"{kind} 后端不可用:{exc}")
_health[key] = (now, result[0], result[1])
return result
def store_for(purpose: str) -> FileStore:
"""按用途取后端;目标后端不可用时按 ``fallback_to_local`` 决定退退还是报错。"""
kind = storageconfig.current().backend_for(purpose)
if kind == LOCAL:
return local_store()
if configured(kind):
if reachable(kind)[0]:
return build(kind)
if not storageconfig.current().fallback_to_local:
raise StorageError(_health.get(kind, (0, False, "后端不可用"))[2])
logger.warning("%s 后端不可用,本次落盘改用本地磁盘:%s", purpose, _health.get(kind, (0, False, ""))[2])
return local_store()
if not storageconfig.current().fallback_to_local:
raise StorageError(f"{purpose} 要放 {kind},但配置文件中该后端未配置完整")
logger.warning("%s 要放 %s 但未配置完整,落盘改用本地磁盘", purpose, kind)
return local_store()
def resolve_uri(uri: str) -> FileStore:
"""Pick the store that owns a stored ``storage`` value."""
text = str(uri or "")
if text.startswith("minio://"):
return minio_store()
if text.startswith("local://"):
return local_store()
# 老数据:磁盘绝对路径,或者空值。
return local_store()
def check_upload(name: str, size: int) -> str:
"""Validate size / extension limits; returns the cleaned file name."""
clean = clean_name(name)
limit = storageconfig.current().max_upload_mb
if limit and size > limit * 1024 * 1024:
raise StorageValidationError(f"文件超过上限 {limit}MB")
allowed = storageconfig.current().allowed_extensions
if allowed:
extension = extension_of(clean)
if extension not in allowed:
raise StorageValidationError(f"不支持的文件类型 .{extension or '未知'},允许:{'/'.join(allowed)}")
return clean
def status_report() -> dict:
"""Per-backend configuration + live health, for the settings page."""
from ..storageconfig import public_view
purposes = {
"attachment": storageconfig.current().attachment_backend,
"portal": storageconfig.current().portal_backend,
"drive": storageconfig.current().drive_backend,
}
active: dict[str, dict] = {}
for purpose, kind in purposes.items():
try:
store = store_for(purpose)
active[purpose] = {"configured": kind, "active": store.kind, **store.describe()}
except StorageError as exc:
active[purpose] = {"configured": kind, "active": "unavailable", "error": str(exc)}
# 并行探活:串行探下去,一个连不上的 MinIO 就能把设置页卡住十几秒
from concurrent.futures import ThreadPoolExecutor
kinds = (MINIO, LOCAL)
with ThreadPoolExecutor(max_workers=len(kinds)) as pool:
probes = dict(zip(kinds, pool.map(reachable, kinds)))
health = {kind: {"ok": flags, "message": message} for kind, (flags, message) in probes.items()}
return {"config": public_view(), "purposes": active, "health": health}
def test_backend(kind: str, overrides: MinioConfig | None = None) -> dict:
"""探活。``overrides`` 让状态页能拿一组还没写进配置文件的 MinIO 参数先试一次。"""
if kind == MINIO and overrides is not None:
store: FileStore = MinioStore(overrides)
else:
store = build(kind if kind in (LOCAL, MINIO) else LOCAL)
try:
return {"kind": store.kind, **store.test()}
except StorageError as exc:
return {"kind": store.kind, "ok": False, "message": str(exc)}
def reset_cache() -> None:
"""Forget cached stores/health after a config change(配置变更后由 dbconfig 调用)。"""
_stores.clear()
_health.clear()
def minio_config_from(payload: dict) -> MinioConfig:
"""把状态页表单拼成一个 MinioConfig,用于「拿还没写进配置文件的参数试一次」。
规则要说清楚,否则「留空」到底是清空还是沿用会两头不讨好:
* 字段没出现在 payload 里 -> 沿用当前配置(部分覆盖);
* 字段出现了但值是空串 -> 按空值算;
* ``secret_key`` 是唯一的例外:接口从来不回显密钥,留空表示沿用配置里的值。
"""
current = storageconfig.current().minio
if not payload:
return current
def text(key: str, fallback: str) -> str:
return str(payload[key]).strip() if key in payload else fallback
def number(key: str, fallback: int) -> int:
value = payload.get(key)
return int(value) if value not in (None, "") else fallback
secret = str(payload.get("secret_key") or "")
return MinioConfig(
endpoint=text("endpoint", current.endpoint),
access_key=text("access_key", current.access_key),
secret_key=secret or current.secret_key,
bucket=text("bucket", current.bucket),
secure=bool(payload["secure"]) if payload.get("secure") is not None else current.secure,
prefix=normalize_relative(str(payload["upload_path"])) if "upload_path" in payload else current.prefix,
region=text("region", current.region),
presigned_ttl_seconds=number("presigned_ttl_seconds", current.presigned_ttl_seconds),
public_base_url=text("public_base_url", current.public_base_url),
connect_timeout_seconds=number("connect_timeout_seconds", current.connect_timeout_seconds),
read_timeout_seconds=number("read_timeout_seconds", current.read_timeout_seconds),
)
__all__ = [
"FileStore",
"LocalStore",
"MinioStore",
"StorageError",
"StorageUnreadableError",
"StorageValidationError",
"StoredObject",
"UnsupportedOperation",
"build",
"check_upload",
"clean_name",
"configured",
"extension_of",
"guess_type",
"local_store",
"is_image_name",
"minio_store",
"normalize_relative",
"reachable",
"reset_cache",
"resolve_uri",
"minio_config_from",
"status_report",
"store_for",
"test_backend",
"PreviewInfo",
"classify_preview",
"describe_preview",
]