147 lines
5.3 KiB
Python
147 lines
5.3 KiB
Python
"""本地磁盘后端:默认实现,也是其它后端故障时的兜底。"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import os
|
|
import shutil
|
|
from pathlib import Path
|
|
from datetime import datetime
|
|
from typing import BinaryIO
|
|
|
|
from .base import (
|
|
FileStore,
|
|
StoredObject,
|
|
ListedObject,
|
|
StorageError,
|
|
build_object_key,
|
|
clean_name,
|
|
guess_type,
|
|
normalize_relative,
|
|
)
|
|
from ..storageconfig import LocalConfig
|
|
|
|
SCHEME = "local://"
|
|
|
|
|
|
class LocalStore(FileStore):
|
|
kind = "local"
|
|
|
|
def __init__(self, config: LocalConfig | None = None, root: Path | None = None) -> None:
|
|
self.config = config or LocalConfig()
|
|
# ``resolve()`` matters on macOS where /tmp is a symlink -- without it a
|
|
# relative_to() round trip fails and uris would come back absolute.
|
|
self.root = Path(root).resolve() if root else self.config.path.resolve()
|
|
self.root.mkdir(parents=True, exist_ok=True)
|
|
|
|
# ------------------------------------------------------------------- paths
|
|
def key(self, uri: str) -> str:
|
|
text = str(uri or "")
|
|
if text.startswith(SCHEME):
|
|
return normalize_relative(text[len(SCHEME) :])
|
|
return text
|
|
|
|
def resolve(self, uri: str) -> Path:
|
|
key = self.key(uri)
|
|
if not key:
|
|
raise StorageError("存储路径为空")
|
|
candidate = Path(key)
|
|
if candidate.is_absolute():
|
|
# 老数据存的是绝对路径,直接沿用;新写入一律是相对 uri。
|
|
return candidate
|
|
base = self.root
|
|
target = (base / key).resolve()
|
|
if base not in target.parents and target != base:
|
|
raise StorageError("存储路径越界")
|
|
return target
|
|
|
|
def uri(self, path: Path) -> str:
|
|
try:
|
|
return SCHEME + os.path.relpath(path.resolve(), self.root).replace(os.sep, "/")
|
|
except ValueError:
|
|
return str(path)
|
|
|
|
def uri_for(self, relative: str) -> str:
|
|
clean = normalize_relative(relative)
|
|
return SCHEME + clean if clean else SCHEME
|
|
|
|
# ------------------------------------------------------------------- write
|
|
def save(self, *, purpose: str, name: str, data, content_type: str = "", key: str | None = None) -> StoredObject:
|
|
clean = clean_name(name)
|
|
relative = normalize_relative(key) if key else build_object_key(purpose, clean)
|
|
target = self.resolve(SCHEME + relative)
|
|
target.parent.mkdir(parents=True, exist_ok=True)
|
|
if isinstance(data, (bytes, bytearray)):
|
|
target.write_bytes(bytes(data))
|
|
else:
|
|
with target.open("wb") as handle:
|
|
shutil.copyfileobj(data, handle)
|
|
size = target.stat().st_size
|
|
return StoredObject(
|
|
uri=self.uri(target),
|
|
key=normalize_relative(self.key(self.uri(target))),
|
|
name=clean,
|
|
size=size,
|
|
content_type=content_type or guess_type(clean),
|
|
etag=f"{int(target.stat().st_mtime)}-{size}",
|
|
)
|
|
|
|
def delete(self, uri: str) -> None:
|
|
path = self.resolve(uri)
|
|
if path.is_dir():
|
|
shutil.rmtree(path, ignore_errors=True)
|
|
elif path.exists():
|
|
path.unlink(missing_ok=True)
|
|
|
|
# -------------------------------------------------------------------- read
|
|
def open_stream(self, uri: str) -> BinaryIO:
|
|
path = self.resolve(uri)
|
|
if not path.is_file():
|
|
raise StorageError("文件不存在或已被删除")
|
|
return path.open("rb")
|
|
|
|
def exists(self, uri: str) -> bool:
|
|
try:
|
|
return self.resolve(uri).exists()
|
|
except StorageError:
|
|
return False
|
|
|
|
def size(self, uri: str) -> int:
|
|
path = self.resolve(uri)
|
|
return path.stat().st_size if path.is_file() else 0
|
|
|
|
# ------------------------------------------------------------------- audit
|
|
def iter_keys(self, prefix: str = ""):
|
|
"""Walk the storage root and yield every file under it, as relative keys."""
|
|
root = self.root
|
|
wanted = normalize_relative(prefix) if prefix else ""
|
|
for base, _dirs, files in os.walk(root):
|
|
for name in files:
|
|
path = Path(base) / name
|
|
try:
|
|
relative = path.resolve().relative_to(root).as_posix()
|
|
stat = path.stat()
|
|
except (OSError, ValueError):
|
|
continue
|
|
if wanted and not relative.startswith(wanted):
|
|
continue
|
|
yield ListedObject(
|
|
key=relative, size=stat.st_size, last_modified=datetime.fromtimestamp(stat.st_mtime)
|
|
)
|
|
|
|
# ------------------------------------------------------------------ health
|
|
def test(self) -> dict:
|
|
probe = self.root / ".unisoa-probe"
|
|
try:
|
|
probe.write_bytes(b"ok")
|
|
readable = probe.read_text() == "ok"
|
|
probe.unlink(missing_ok=True)
|
|
return {"ok": readable, "message": f"本地目录可读写: {self.root}", "detail": str(self.root)}
|
|
except OSError as exc:
|
|
return {"ok": False, "message": f"本地目录不可写: {self.root}", "detail": str(exc)}
|
|
|
|
def describe(self) -> dict:
|
|
return {"kind": self.kind, "root": str(self.root)}
|
|
|
|
|
|
__all__ = ["LocalStore", "SCHEME"]
|