205 lines
6.6 KiB
Python
205 lines
6.6 KiB
Python
"""存储后端抽象层。
|
||
|
||
对外只有两种东西:
|
||
|
||
* ``FileStore`` -- 一个后端(本地磁盘 / MinIO),负责读写二进制;
|
||
* ``uri`` -- 写进数据库 ``storage`` 字段的位置串,例如
|
||
``minio://unisoa/unisoa/attachment/202609/3f1a.pdf``、
|
||
``local://202609/3f1a.pdf``。
|
||
|
||
没有前缀的绝对路径是老数据,按本地磁盘处理,升级后不用洗库。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import mimetypes
|
||
import os
|
||
from abc import ABC, abstractmethod
|
||
from dataclasses import dataclass
|
||
from datetime import datetime
|
||
from typing import BinaryIO, Iterator, NamedTuple
|
||
|
||
|
||
class StorageError(RuntimeError):
|
||
"""后端连不上、对象不存在、权限不足等存储层错误。"""
|
||
|
||
|
||
class UnsupportedOperation(StorageError):
|
||
"""当前后端不支持该操作。"""
|
||
|
||
|
||
class StorageValidationError(StorageError):
|
||
"""文件本身不合规则(超尺寸、扩展名不在白名单)。
|
||
|
||
单独一个类型是因为它该回 400:文件超限是调用方的问题,跟 MinIO 连不连得上
|
||
没关系。混在 502 里会把人引去看配置文件,而真正要改的是传上来的文件。
|
||
"""
|
||
|
||
|
||
class StorageUnreadableError(StorageError):
|
||
"""文件本身读不出正文:损坏、加了密、改了后缀、或者压根没有正文。
|
||
|
||
跟 ``StorageValidationError`` 一样该回 400——要改的是那个文件,不是 MinIO 的
|
||
配置。落到 502 会让人去翻服务端,而服务端其实好得很。
|
||
"""
|
||
|
||
|
||
class ListedObject(NamedTuple):
|
||
"""``iter_keys()`` 带回的一条对象:位置、体积、最后修改时间。
|
||
|
||
清点桶里的孤儿文件要拿"最后修改时间"挡一下正在上传的东西,所以时间戳得跟着
|
||
一起回来;本地磁盘用 mtime,MinIO 用 last_modified,两边共用这一个字段。
|
||
"""
|
||
|
||
key: str
|
||
size: int = 0
|
||
last_modified: datetime | None = None
|
||
|
||
|
||
@dataclass
|
||
class StoredObject:
|
||
uri: str
|
||
name: str
|
||
size: int
|
||
content_type: str = ""
|
||
etag: str = ""
|
||
#: 相对各自根目录的位置(local 相对 storage 根,minio 为对象键)
|
||
key: str = ""
|
||
|
||
|
||
def guess_type(name: str) -> str:
|
||
guessed, _ = mimetypes.guess_type(name)
|
||
return guessed or "application/octet-stream"
|
||
|
||
|
||
def normalize_relative(value: str) -> str:
|
||
"""Collapse a user supplied relative path, refusing anything that escapes.
|
||
|
||
``..`` and absolute paths must never reach the backend -- a single dot-dot is
|
||
enough to walk out of the storage root.
|
||
"""
|
||
text = (value or "").replace("\\", "/").strip().strip("/")
|
||
parts: list[str] = []
|
||
for piece in text.split("/"):
|
||
if piece in ("", "."):
|
||
continue
|
||
if piece == "..":
|
||
raise StorageError("路径不合法:不允许越出存储根目录")
|
||
parts.append(piece)
|
||
return "/".join(parts)
|
||
|
||
|
||
def clean_name(value: str, default: str = "file") -> str:
|
||
"""Keep the base name only, dropping any directories a client may smuggle in."""
|
||
name = os.path.basename((value or "").replace("\\", "/").strip())
|
||
return name or default
|
||
|
||
|
||
def extension_of(name: str) -> str:
|
||
return name.rsplit(".", 1)[-1].lower() if "." in name else ""
|
||
|
||
|
||
#: 批注/审批意见里按图片预览(贴出来能直接看缩略图)的扩展名
|
||
IMAGE_EXTENSIONS = {"png", "jpg", "jpeg", "gif", "webp", "bmp", "svg", "avif", "heic"}
|
||
|
||
|
||
def is_image_name(name: str) -> bool:
|
||
"""这条附件该不该当图片渲染。
|
||
|
||
只按扩展名判断,不看 ``guess_type``:截图、剪贴板贴图在浏览器里都带着 ``.png``
|
||
这样的文件名,而 ``mimetypes`` 在个别系统上连 ``.svg`` 都认不出来,两处口径不
|
||
一致会让"贴上去有缩略图、刷新一下就变成文件条"。
|
||
"""
|
||
return extension_of(name) in IMAGE_EXTENSIONS
|
||
|
||
|
||
def build_object_key(purpose: str, name: str, now: datetime | None = None) -> str:
|
||
"""``<purpose>/<YYYYMM>/<uuid>.<ext>`` -- shared by every backend."""
|
||
import uuid
|
||
|
||
stamp = (now or datetime.now()).strftime("%Y%m")
|
||
extension = extension_of(name)
|
||
token = uuid.uuid4().hex
|
||
return f"{purpose.strip('/')}/{stamp}/{token}.{extension}" if extension else f"{purpose.strip('/')}/{stamp}/{token}"
|
||
|
||
|
||
class FileStore(ABC):
|
||
"""Common surface for every backend."""
|
||
|
||
kind = "local"
|
||
writable = True
|
||
|
||
# ------------------------------------------------------------------ naming
|
||
def accepts(self, uri: str) -> bool:
|
||
return str(uri or "").startswith(f"{self.kind}://")
|
||
|
||
# ------------------------------------------------------------------- write
|
||
@abstractmethod
|
||
def save(
|
||
self,
|
||
*,
|
||
purpose: str,
|
||
name: str,
|
||
data: bytes | BinaryIO,
|
||
content_type: str = "",
|
||
key: str | None = None,
|
||
) -> StoredObject:
|
||
"""Persist a stream and return its uri plus the recorded metadata."""
|
||
|
||
@abstractmethod
|
||
def delete(self, uri: str) -> None:
|
||
"""Remove an object; missing is not an error."""
|
||
|
||
# -------------------------------------------------------------------- read
|
||
@abstractmethod
|
||
def open_stream(self, uri: str) -> BinaryIO:
|
||
"""Open an object for reading in binary mode."""
|
||
|
||
@abstractmethod
|
||
def exists(self, uri: str) -> bool:
|
||
...
|
||
|
||
@abstractmethod
|
||
def size(self, uri: str) -> int:
|
||
...
|
||
|
||
def read_bytes(self, uri: str) -> bytes:
|
||
with self.open_stream(uri) as handle:
|
||
return handle.read()
|
||
|
||
def uri_for(self, relative: str) -> str:
|
||
"""Location string for a path that is already relative to this store's root."""
|
||
raise UnsupportedOperation(f"{self.kind} 存储不支持按路径寻址")
|
||
|
||
# ------------------------------------------------------------------- audit
|
||
def iter_keys(self, prefix: str = "") -> Iterator[ListedObject]:
|
||
"""List what is actually sitting on this backend, for the orphan audit.
|
||
|
||
两个真后端各自实现;没实现的后端宁可当场说"不支持",也不能回一份空清单——
|
||
那等于告诉清点脚本"这儿一个孤儿文件都没有",是假清白。
|
||
"""
|
||
raise UnsupportedOperation(f"{self.kind} 存储不支持列举对象")
|
||
|
||
# ------------------------------------------------------------------ health
|
||
@abstractmethod
|
||
def test(self) -> dict:
|
||
"""Lightweight connectivity probe used by the settings page."""
|
||
|
||
def describe(self) -> dict:
|
||
return {"kind": self.kind}
|
||
|
||
|
||
__all__ = [
|
||
"FileStore",
|
||
"StoredObject",
|
||
"ListedObject",
|
||
"StorageError",
|
||
"StorageUnreadableError",
|
||
"UnsupportedOperation",
|
||
"build_object_key",
|
||
"clean_name",
|
||
"extension_of",
|
||
"guess_type",
|
||
"normalize_relative",
|
||
]
|