feat(storage): 本地存储增加引用链接(reflink)整理方式 (#7077)

This commit is contained in:
秋澪Akimio
2026-10-19 16:48:41 +08:00
committed by GitHub
parent 379c26a300
commit 114c2cebe5
14 changed files with 1249 additions and 75 deletions

View File

@@ -3,6 +3,7 @@
"""
import asyncio
import ctypes
import datetime
import hashlib
import os
@@ -542,6 +543,67 @@ class SystemUtils:
except Exception as err:
return -1, str(err)
@staticmethod
def reflink(src: Path, dest: Path) -> Tuple[int, str]:
"""
创建引用链接(写时复制 / Cow / Reflink)
采用原子暂存模式将源文件克隆到临时路径,成功后移动至目标路径。
:param src: 源文件路径
:param dest: 目标文件路径
:return: (状态码, 错误信息),0 表示成功
"""
tmp_path = dest.with_suffix(dest.suffix + ".mp")
try:
# 检查临时目标路径是否已存在,如果存在则先清理
if tmp_path.exists():
tmp_path.unlink()
# 调用私有辅助方法执行底层克隆
code, msg = SystemUtils._reflink_copy(src, tmp_path)
if code != 0:
if tmp_path.exists():
tmp_path.unlink()
return code, msg
# 克隆成功,原子移动替换到目标路径
shutil.move(tmp_path, dest)
return 0, ""
except Exception as err:
if tmp_path.exists():
try:
tmp_path.unlink()
except Exception:
pass
return -1, str(err)
@staticmethod
def _reflink_copy(src: Path, dest: Path) -> Tuple[int, str]:
"""
调用底层操作系统能力执行文件引用链接(写时复制克隆)
:param src: 源文件路径
:param dest: 目标文件路径
:return: (状态码, 错误信息),0 表示成功
"""
if sys.platform == "darwin":
libc = ctypes.CDLL(None, use_errno=True)
ret = libc.clonefile(os.fsencode(str(src)), os.fsencode(str(dest)), ctypes.c_uint32(0))
if ret != 0:
err = ctypes.get_errno()
return -1, f"clonefile 失败: {os.strerror(err)}"
return 0, ""
if sys.platform.startswith("linux"):
if fcntl is None:
return -1, "fcntl 不可用"
try:
with open(src, "rb") as s, open(dest, "wb") as d:
fcntl.ioctl(d.fileno(), 0x40049409, s.fileno())
shutil.copystat(src, dest)
return 0, ""
except OSError as err:
return -1, f"Linux ioctl(FICLONE) 失败: {err}"
return -1, f"当前操作系统 ({sys.platform}) 不支持引用链接 (reflink)"
@staticmethod
def list_files(directory: Path, extensions: list = None,
min_filesize: int = 0, recursive: bool = True) -> List[Path]:

View File

@@ -495,7 +495,7 @@ FIELD_DESCRIPTIONS = {
"total_episode": "订阅预期总集数。",
"total_tracks": "音乐项目预期或已记录的曲目数。",
"transfer_task_id": "历史记录关联的稳定持久化整理任务标识。",
"transfer_type": "手动整理方式,例如 move、copy、link、softlink。",
"transfer_type": "手动整理方式,例如 move、copy、link、softlink、reflink。",
"trigger_type": "工作流触发方式筛选:timer、event、manual 或 all。",
"type": "所选操作要求的媒体或存储项目类型。",
"type_name": "仅凭来源标识无法区分时使用的显式媒体类型名。",

View File

@@ -150,11 +150,12 @@ class FileManagerModule(_ModuleBase):
return False, f"{d.name} 的媒体库目录未设置"
if d.library_storage == "local" and not Path(library_path).exists():
return False, f"{d.name} 的媒体库目录 {library_path} 不存在"
if d.transfer_type == "link" \
if d.transfer_type in ("link", "reflink") \
and d.storage == "local" \
and d.library_storage == "local" \
and not SystemUtils.is_same_disk(Path(download_path), Path(library_path)):
return False, f"{d.name} 的下载目录 {download_path} 与媒体库目录 {library_path} 不在同一磁盘,无法硬链接"
action_name = "引用链接" if d.transfer_type == "reflink" else "硬链接"
return False, f"{d.name} 的下载目录 {download_path} 与媒体库目录 {library_path} 不在同一磁盘,无法{action_name}"
storage_oper = self.__get_storage_oper(d.storage)
if storage_oper:
if not storage_oper.check():

View File

@@ -389,6 +389,16 @@ class StorageBase(metaclass=ABCMeta):
"""
pass
def reflink(self, fileitem: _SchemaFileItem, target_file: Path) -> bool:
"""
在支持引用链接的存储中创建目标文件。
:param fileitem: 源文件项
:param target_file: 完整目标文件路径
:return: 引用链接创建成功标记;不支持的实现返回 False
"""
return False
@abstractmethod
def usage(self) -> Optional[_SchemaStorageUsage]:
"""

View File

@@ -33,7 +33,8 @@ class LocalStorage(StorageBase):
"copy": "复制",
"move": "移动",
"link": "硬链接",
"softlink": "软链接"
"softlink": "软链接",
"reflink": "引用链接",
}
# 文件复制块大小,默认 10 MiB
@@ -535,6 +536,23 @@ class LocalStorage(StorageBase):
return False
return True
def reflink(self, fileitem: _SchemaFileItem, target_file: Path) -> bool:
"""
创建本地引用链接。
:param fileitem: 源文件项
:param target_file: 完整目标链接路径
:return: 系统操作返回成功时为 True,否则为 False
"""
if not fileitem.path:
return False
file_path = Path(fileitem.path)
code, message = SystemUtils.reflink(file_path, target_file)
if code != 0:
logger.error(f"【本地】引用链接文件失败:{message}")
return False
return True
def usage(self) -> Optional[_SchemaStorageUsage]:
"""
汇总已配置下载目录和媒体库目录所在文件系统的容量。

View File

@@ -961,7 +961,7 @@ class TransHandler:
:param source_oper: 源严格查询适配器
:param target_oper: 目标严格查询适配器
:param target_file: 已冻结目标文件路径
:param transfer_type: move、copy、link 或 softlink
:param transfer_type: move、copy、link、softlink 或 reflink
:return: 完成状态及文件证据;无法证明内容或查询失败时返回未知状态
"""
try:
@@ -1016,6 +1016,14 @@ class TransHandler:
applied = source_path.is_file() and target_file.samefile(source_path)
elif transfer_type == "softlink":
applied = target_file.is_symlink() and target_file.resolve() == source_path.resolve()
elif transfer_type == "reflink":
applied = (
source_path.is_file()
and target_file.is_file()
and not target_file.is_symlink()
and not target_file.samefile(source_path)
and filecmp.cmp(source_path, target_file, shallow=False)
)
else:
return TransferOperationObservation(
state=TransferOperationObservationState.UNKNOWN,
@@ -2032,6 +2040,91 @@ class TransHandler:
return False, f"{fileitem.path} 源文件删除失败"
return True, ""
@staticmethod
def __transfer_local_to_local(
source_oper: StorageBase,
fileitem: FileItem,
target_file: Path,
transfer_type: str,
) -> Tuple[bool, str]:
"""
执行本地存储之间的单文件传输操作。
:param source_oper: 本地存储适配器
:param fileitem: 源文件项
:param target_file: 目标文件完整路径
:param transfer_type: 整理方式
:return: 操作成功标记及错误说明
"""
if not target_file.parent.exists():
target_file.parent.mkdir(parents=True, exist_ok=True)
if transfer_type == "copy":
state = source_oper.copy(fileitem, target_file.parent, target_file.name)
elif transfer_type == "move":
state = source_oper.move(fileitem, target_file.parent, target_file.name)
elif transfer_type in ("link", "softlink", "reflink"):
action = getattr(source_oper, transfer_type, None)
state = bool(callable(action) and action(fileitem, target_file))
else:
return False, f"不支持的整理方式:{transfer_type}"
if state:
return True, ""
return False, f"{fileitem.path} {transfer_type} 失败"
@staticmethod
def __transfer_same_remote_storage(
fileitem: FileItem,
target_storage: str,
source_oper: StorageBase,
target_oper: StorageBase,
target_file: Path,
transfer_type: str,
get_remote_targetitem: Callable[[FileItem, Path], FileItem],
) -> Tuple[Optional[FileItem], str]:
"""
在相同的非本地远端存储间执行文件复制、移动或链接操作。
:param fileitem: 源文件项
:param target_storage: 目标存储标识
:param source_oper: 源存储适配器
:param target_oper: 目标存储适配器
:param target_file: 目标文件完整路径
:param transfer_type: 整理方式
:param get_remote_targetitem: 获取远端目标项回调
:return: 目标文件项及错误说明
"""
if not source_oper.is_support_transtype(transfer_type):
return None, f"存储 {fileitem.storage} 不支持 {transfer_type} 整理方式"
if transfer_type in ("copy", "move"):
target_fileitem = target_oper.get_folder(target_file.parent)
if not target_fileitem:
return None, f"【{target_storage}】{target_file.parent} 目录获取失败"
action_name = "copy_item" if transfer_type == "copy" else "move_item"
custom_item_action = getattr(source_oper, action_name, None)
if callable(custom_item_action):
new_item = custom_item_action(
fileitem, Path(target_fileitem.path), target_file.name
)
if new_item:
return new_item, ""
fallback_action = getattr(source_oper, transfer_type, None)
if callable(fallback_action) and fallback_action(
fileitem, Path(target_fileitem.path), target_file.name
):
return get_remote_targetitem(fileitem, target_file), ""
action_desc = "复制" if transfer_type == "copy" else "移动"
return None, f"【{target_storage}】{fileitem.path} {action_desc}文件失败"
if transfer_type in ("link", "reflink"):
action = getattr(source_oper, transfer_type, None)
if callable(action) and action(fileitem, target_file):
return get_remote_targetitem(fileitem, target_file), ""
action_desc = "引用链接" if transfer_type == "reflink" else "硬链接"
return None, f"【{target_storage}】{fileitem.path} 创建{action_desc}失败"
return None, f"不支持的整理方式:{transfer_type}"
@staticmethod
def __transfer_command(
fileitem: FileItem,
@@ -2052,7 +2145,7 @@ class TransHandler:
:param source_oper: 源存储适配器
:param target_oper: 目标存储适配器
:param target_file: 最终文件路径,必要时创建父目录
:param transfer_type: copy、move、link 或 softlink,支持范围取决于存储组合
:param transfer_type: copy、move、link、softlink 或 reflink,支持范围取决于存储组合
:return: 目标文件项及错误文本;失败时文件项为 None
"""
@@ -2118,22 +2211,15 @@ class TransHandler:
return None, f"不支持 {fileitem.storage} 到 {target_storage} 的文件整理"
if fileitem.storage == "local" and target_storage == "local":
if not target_file.parent.exists():
target_file.parent.mkdir(parents=True, exist_ok=True)
if transfer_type == "copy":
state = source_oper.copy(fileitem, target_file.parent, target_file.name)
elif transfer_type == "move":
state = source_oper.move(fileitem, target_file.parent, target_file.name)
elif transfer_type == "link":
state = source_oper.link(fileitem, target_file)
elif transfer_type == "softlink":
state = source_oper.softlink(fileitem, target_file)
else:
return None, f"不支持的整理方式:{transfer_type}"
state, error = TransHandler.__transfer_local_to_local(
source_oper=source_oper,
fileitem=fileitem,
target_file=target_file,
transfer_type=transfer_type,
)
if state:
return __get_targetitem(target_file), ""
else:
return None, f"{fileitem.path} {transfer_type} 失败"
return None, error
elif fileitem.storage == "local" and target_storage != "local":
filepath = Path(fileitem.path)
if not filepath.exists():
@@ -2178,56 +2264,15 @@ class TransHandler:
)
return (__get_targetitem(target_file), "") if state else (None, error)
elif fileitem.storage == target_storage:
if not source_oper.is_support_transtype(transfer_type):
return None, f"存储 {fileitem.storage} 不支持 {transfer_type} 整理方式"
if transfer_type == "copy":
target_fileitem = target_oper.get_folder(target_file.parent)
if target_fileitem:
copy_item = getattr(source_oper, "copy_item", None)
if callable(copy_item):
new_item = copy_item(
fileitem, Path(target_fileitem.path), target_file.name
)
if new_item:
return new_item, ""
elif source_oper.copy(
fileitem, Path(target_fileitem.path), target_file.name
):
return __get_remote_targetitem(fileitem, target_file), ""
return None, f"【{target_storage}】{fileitem.path} 复制文件失败"
else:
return (
None,
f"【{target_storage}】{target_file.parent} 目录获取失败",
)
elif transfer_type == "move":
target_fileitem = target_oper.get_folder(target_file.parent)
if target_fileitem:
move_item = getattr(source_oper, "move_item", None)
if callable(move_item):
new_item = move_item(
fileitem, Path(target_fileitem.path), target_file.name
)
if new_item:
return new_item, ""
elif source_oper.move(
fileitem, Path(target_fileitem.path), target_file.name
):
return __get_remote_targetitem(fileitem, target_file), ""
return None, f"【{target_storage}】{fileitem.path} 移动文件失败"
else:
return (
None,
f"【{target_storage}】{target_file.parent} 目录获取失败",
)
elif transfer_type == "link":
if source_oper.link(fileitem, target_file):
return __get_remote_targetitem(fileitem, target_file), ""
else:
return None, f"【{target_storage}】{fileitem.path} 创建硬链接失败"
else:
return None, f"不支持的整理方式:{transfer_type}"
return TransHandler.__transfer_same_remote_storage(
fileitem=fileitem,
target_storage=target_storage,
source_oper=source_oper,
target_oper=target_oper,
target_file=target_file,
transfer_type=transfer_type,
get_remote_targetitem=__get_remote_targetitem,
)
return None, "未知错误"

View File

@@ -809,7 +809,7 @@ class TransferInterceptEventData(ChainEventData):
mediainfo: Any = Field(..., description="媒体信息")
target_storage: str = Field(..., description="目标存储")
target_path: Path = Field(..., description="目标路径")
transfer_type: str = Field(..., description="整理方式(copy、move、link、softlink等)")
transfer_type: str = Field(..., description="整理方式(copy、move、link、softlink、reflink等)")
options: Optional[dict] = Field(default=None, description="其他参数")
# 输出参数
@@ -833,7 +833,7 @@ class TransferOverwriteCheckEventData(ChainEventData):
target_storage: str = Field(..., description="目标存储")
target_path: Path = Field(..., description="目标文件路径")
overwrite_mode: str = Field(..., description="覆盖模式(always、size、never、latest)")
transfer_type: str = Field(..., description="整理方式")
transfer_type: str = Field(..., description="整理方式(copy、move、link、softlink、reflink等)")
options: Optional[dict] = Field(default=None, description="其他参数")
# 输出参数

View File

@@ -446,7 +446,7 @@ class TransferDirectoryConf(BaseModel):
download_category_folder: Optional[bool] = Field(default=False, description="下载类别子目录")
monitor_type: Optional[str] = Field(default=None, description="监控方式 downloader/monitor,None为不监控")
monitor_mode: Optional[str] = Field(default="fast", description="监控模式 fast / compatibility")
transfer_type: Optional[str] = Field(default=None, description="整理方式 move/copy/link/softlink")
transfer_type: Optional[str] = Field(default=None, description="整理方式 move/copy/link/softlink/reflink")
overwrite_mode: Optional[str] = Field(default=None, description="文件覆盖模式 always/size/never/latest")
library_path: Optional[str] = Field(default=None, description="整理到媒体库目录")
library_storage: Optional[str] = Field(default=None, description="媒体库目录存储")

View File

@@ -2073,6 +2073,7 @@ def _collect_directory_config() -> dict[str, Any]:
"softlink": "软链接",
"copy": "复制",
"move": "移动",
"reflink": "引用链接",
},
default="link",
)

View File

@@ -92,7 +92,7 @@
"app/modules/filemanager/storages/alipan.py:AliPan.upload": 16,
"app/modules/filemanager/storages/u115.py:U115Pan.upload": 33,
"app/modules/filemanager/transhandler.py:TransHandler.__resolve_overwrite": 16,
"app/modules/filemanager/transhandler.py:TransHandler.__transfer_command": 37,
"app/modules/filemanager/transhandler.py:TransHandler.__transfer_command": 19,
"app/modules/filemanager/transhandler.py:TransHandler.execute_transfer_plan": 20,
"app/modules/filter/__init__.py:FilterModule.__match_rule": 24,
"app/modules/imdb/__init__.py:ImdbModule._to_media_info": 17,

View File

@@ -674,7 +674,7 @@
"union-attr": 32
},
"app/modules/filemanager/transhandler.py": {
"arg-type": 17,
"arg-type": 15,
"assignment": 1,
"no-redef": 1,
"no-untyped-def": 2,

View File

@@ -0,0 +1,254 @@
"""
引用链接(reflink)存储能力、支持校验与目录配置同盘检查的单元测试。
"""
from pathlib import Path
from types import SimpleNamespace
from typing import Optional, Tuple
import pytest
from app.adapters.system.host import SystemUtils
from app.modules.filemanager.module import FileManagerModule
from app.modules.filemanager.storages import StorageBase
from app.modules.filemanager.storages.local import LocalStorage
from app.modules.filemanager.storages.rclone import Rclone
from app.modules.filemanager.storages.smb import SMB as SmbStorage
from app.schemas.file import FileItem
def _make_local_storage() -> LocalStorage:
"""
构造绕过配置持久化初始化的本地存储实例。
:return: 本地存储实例
"""
return object.__new__(LocalStorage)
def test_local_storage_transtype_contains_reflink() -> None:
"""
测试 LocalStorage.transtype 声明包含引用链接整理方式。
"""
assert "reflink" in LocalStorage.transtype
assert LocalStorage.transtype["reflink"] == "引用链接"
def test_local_storage_is_support_transtype_reflink() -> None:
"""
测试 LocalStorage.is_support_transtype("reflink") 返回 True。
"""
storage = _make_local_storage()
assert storage.is_support_transtype("reflink") is True
def test_remote_storages_do_not_support_reflink() -> None:
"""
测试非本地存储(如 SmbStorage 和 Rclone)的 is_support_transtype("reflink") 返回 False。
"""
smb_storage = object.__new__(SmbStorage)
assert smb_storage.is_support_transtype("reflink") is False
rclone_storage = object.__new__(Rclone)
assert rclone_storage.is_support_transtype("reflink") is False
def test_storage_base_reflink_defaults_to_false(tmp_path: Path) -> None:
"""
测试 StorageBase 基类的 reflink 方法默认返回 False。
"""
class _DummyStorage(StorageBase):
"""
测试用的抽象基类存根实现。
"""
def init_storage(self) -> None:
pass
def check(self) -> bool:
return True
def list(self, fileitem: FileItem) -> list[FileItem]:
return []
def create_folder(self, fileitem: FileItem, name: str) -> Optional[FileItem]:
return None
def get_folder(self, path: Path) -> Optional[FileItem]:
return None
def get_item(self, path: Path) -> Optional[FileItem]:
return None
def delete(self, fileitem: FileItem) -> bool:
return False
def rename(self, fileitem: FileItem, name: str) -> bool:
return False
def download(self, fileitem: FileItem, path: Optional[Path] = None) -> Optional[Path]:
return None
def upload(self, fileitem: FileItem, path: Path, new_name: Optional[str] = None) -> Optional[FileItem]:
return None
def detail(self, fileitem: FileItem) -> Optional[FileItem]:
return None
def copy(self, fileitem: FileItem, path: Path, new_name: str) -> bool:
return False
def move(self, fileitem: FileItem, path: Path, new_name: str) -> bool:
return False
def link(self, fileitem: FileItem, target_file: Path) -> bool:
return False
def softlink(self, fileitem: FileItem, target_file: Path) -> bool:
return False
def usage(self) -> None:
return None
storage = object.__new__(_DummyStorage)
fileitem = FileItem(path=str(tmp_path / "src.mkv"), name="src.mkv")
target_path = tmp_path / "dst.mkv"
result = storage.reflink(fileitem, target_path)
assert result is False
def test_local_storage_reflink_success(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
"""
测试 LocalStorage.reflink 成功时调用 SystemUtils.reflink 返回 True。
"""
storage = _make_local_storage()
source_file = tmp_path / "source.mkv"
target_file = tmp_path / "target.mkv"
fileitem = FileItem(path=str(source_file), name="source.mkv")
called_args: dict[str, Path] = {}
def fake_reflink(src: Path, dest: Path) -> Tuple[int, str]:
called_args["src"] = src
called_args["dest"] = dest
return 0, ""
monkeypatch.setattr(SystemUtils, "reflink", fake_reflink, raising=False)
result = storage.reflink(fileitem, target_file)
assert result is True
assert called_args["src"] == source_file
assert called_args["dest"] == target_file
def test_local_storage_reflink_failure(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
"""
测试 LocalStorage.reflink 失败时记录错误日志并返回 False。
"""
storage = _make_local_storage()
source_file = tmp_path / "source.mkv"
target_file = tmp_path / "target.mkv"
fileitem = FileItem(path=str(source_file), name="source.mkv")
def fake_reflink_fail(src: Path, dest: Path) -> Tuple[int, str]:
return -1, "Operation not supported on transport endpoint"
monkeypatch.setattr(SystemUtils, "reflink", fake_reflink_fail, raising=False)
logged_errors: list[str] = []
monkeypatch.setattr(
"app.modules.filemanager.storages.local.logger.error",
lambda msg: logged_errors.append(msg),
)
result = storage.reflink(fileitem, target_file)
assert result is False
assert any("【本地】引用链接文件失败:Operation not supported on transport endpoint" in err for err in logged_errors)
def test_filemanager_check_reflink_same_disk(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
"""
测试目录整理方式为 reflink 且同盘时校验通过。
"""
module = FileManagerModule()
download_dir = tmp_path / "downloads"
library_dir = tmp_path / "library"
download_dir.mkdir()
library_dir.mkdir()
dir_conf = SimpleNamespace(
name="测试本地目录",
download_path=str(download_dir),
library_path=str(library_dir),
storage="local",
library_storage="local",
transfer_type="reflink",
)
monkeypatch.setattr(module.directoryhelper, "get_dirs", lambda: [dir_conf])
monkeypatch.setattr(SystemUtils, "is_same_disk", lambda p1, p2: True)
storage_oper = _make_local_storage()
monkeypatch.setattr(module, "_FileManagerModule__get_storage_oper", lambda storage: storage_oper)
success, message = module.test()
assert success is True
assert message == ""
def test_filemanager_check_reflink_different_disk(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
"""
测试目录整理方式为 reflink 但非同盘时校验失败并提示无法引用链接。
"""
module = FileManagerModule()
download_dir = tmp_path / "downloads"
library_dir = tmp_path / "library"
download_dir.mkdir()
library_dir.mkdir()
dir_conf = SimpleNamespace(
name="测试本地目录",
download_path=str(download_dir),
library_path=str(library_dir),
storage="local",
library_storage="local",
transfer_type="reflink",
)
monkeypatch.setattr(module.directoryhelper, "get_dirs", lambda: [dir_conf])
monkeypatch.setattr(SystemUtils, "is_same_disk", lambda p1, p2: False)
storage_oper = _make_local_storage()
monkeypatch.setattr(module, "_FileManagerModule__get_storage_oper", lambda storage: storage_oper)
success, message = module.test()
assert success is False
assert "不在同一磁盘,无法引用链接" in message
def test_filemanager_check_reflink_unsupported_storage(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
"""
测试非本地存储不支持 reflink 整理方式时校验失败。
"""
module = FileManagerModule()
download_dir = tmp_path / "downloads"
library_dir = tmp_path / "library"
download_dir.mkdir()
library_dir.mkdir()
dir_conf = SimpleNamespace(
name="测试远端目录",
download_path=str(download_dir),
library_path=str(library_dir),
storage="smb",
library_storage="smb",
transfer_type="reflink",
)
monkeypatch.setattr(module.directoryhelper, "get_dirs", lambda: [dir_conf])
smb_storage = object.__new__(SmbStorage)
monkeypatch.setattr(smb_storage, "check", lambda: True)
monkeypatch.setattr(module, "_FileManagerModule__get_storage_oper", lambda storage: smb_storage)
success, message = module.test()
assert success is False
assert "测试远端目录 的存储不支持 reflink 整理方式" in message

View File

@@ -0,0 +1,332 @@
"""
测试系统引用链接(reflink / 写时复制)功能的跨平台实现与异常处理。
"""
import errno
import os
import shutil
import sys
import warnings
from pathlib import Path
from unittest.mock import MagicMock
import psutil
import pytest
from app.adapters.system.host import SystemUtils
def _get_filesystem_type(path: Path) -> str:
"""
获取指定路径所在挂载点文件系统的格式类型。
:param path: 目标路径
:return: 小写文件系统名称(例如 apfs, btrfs, xfs, ext4)
"""
resolved = path.resolve()
best_mount = ""
best_fstype = ""
try:
for part in psutil.disk_partitions(all=True):
try:
mount = Path(part.mountpoint).resolve()
if resolved == mount or mount in resolved.parents:
if len(str(mount)) > len(best_mount):
best_mount = str(mount)
best_fstype = (part.fstype or "").lower()
except Exception:
continue
except Exception:
pass
if best_fstype:
return best_fstype
if sys.platform.startswith("linux"):
try:
with open("/proc/mounts", "r", encoding="utf-8") as stream:
for line in stream:
parts = line.split()
if len(parts) >= 3:
mount = Path(parts[1]).resolve()
if resolved == mount or mount in resolved.parents:
if len(str(mount)) > len(best_mount):
best_mount = str(mount)
best_fstype = parts[2].lower()
except Exception:
pass
if best_fstype:
return best_fstype
if sys.platform == "darwin":
return "apfs"
return "unknown"
def _probe_reflink_support(path: Path) -> bool:
"""
真实探测文件系统是否支持写时复制。
:param path: 探测临时目录
:return: 支持写时复制时为 True
"""
src = path / ".probe_reflink_src"
dest = path / ".probe_reflink_dest"
try:
src.write_bytes(b"probe")
code, _ = SystemUtils.reflink(src, dest)
return code == 0
except Exception:
return False
finally:
src.unlink(missing_ok=True)
dest.unlink(missing_ok=True)
def _require_reflink_filesystem(tmp_path: Path) -> str:
"""
检查测试目录文件系统格式,非写时复制格式发出警告并跳过测试。
:param tmp_path: pytest 临时测试目录
:return: 当前被确认支持写时复制的文件系统格式
"""
fstype = _get_filesystem_type(tmp_path)
supported_types = {"apfs", "btrfs", "xfs", "zfs"}
if fstype not in supported_types or not _probe_reflink_support(tmp_path):
warning_message = (
f"当前测试目录所在文件系统格式为 [{fstype}],"
f"非写时复制格式(需为 {supported_types} 且启用 CoW),已跳过对应引用链接测试"
)
warnings.warn(warning_message, UserWarning, stacklevel=2)
pytest.skip(warning_message)
return fstype
def test_reflink_success_on_current_platform(tmp_path: Path):
"""
测试在当前支持引用链接的系统(如 macOS APFS)上成功创建 reflink,
验证内容一致、不同 Inode、写时复制独立修改以及文件大小一致。
"""
_require_reflink_filesystem(tmp_path)
src = tmp_path / "source.bin"
dest = tmp_path / "cloned.bin"
test_content = b"MoviePilot reflink test data: " + b"X" * 1024
src.write_bytes(test_content)
code, msg = SystemUtils.reflink(src, dest)
assert code == 0
assert msg == ""
# 1. 验证目标文件存在且内容与源文件一致
assert dest.exists()
assert dest.read_bytes() == test_content
# 2. 验证目标文件与源文件大小一致
assert dest.stat().st_size == src.stat().st_size
# 3. 验证不是同一个 Inode(不同于硬链接)
assert not os.path.samefile(src, dest)
# 4. 验证写时复制(CoW)特性:修改目标文件后源文件保持不变
dest.write_bytes(b"Modified cloned content")
assert src.read_bytes() == test_content
assert dest.read_bytes() == b"Modified cloned content"
def test_reflink_cleans_preexisting_temp_file(tmp_path: Path):
"""
测试当目标临时 .mp 文件预先存在时,reflink 能先清理临时文件并成功完成克隆。
"""
_require_reflink_filesystem(tmp_path)
src = tmp_path / "source.txt"
dest = tmp_path / "target.txt"
temp_file = dest.with_suffix(dest.suffix + ".mp")
src.write_text("source content", encoding="utf-8")
temp_file.write_text("old stale temp content", encoding="utf-8")
code, msg = SystemUtils.reflink(src, dest)
assert code == 0
assert msg == ""
assert dest.read_text(encoding="utf-8") == "source content"
assert not temp_file.exists()
def test_reflink_copy_failure_cleans_temp_file(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
"""
测试当底层 _reflink_copy 失败时,返回错误信息并清理残留的临时 .mp 文件。
"""
src = tmp_path / "source.txt"
dest = tmp_path / "target.txt"
temp_file = dest.with_suffix(dest.suffix + ".mp")
src.write_text("source data", encoding="utf-8")
def _mock_reflink_copy(_src: Path, _dest: Path):
# 模拟底层复制过程中生成了临时文件但最终报告失败
_dest.write_text("partial data", encoding="utf-8")
return -1, "底层克隆失败模拟错误"
monkeypatch.setattr(SystemUtils, "_reflink_copy", _mock_reflink_copy)
code, msg = SystemUtils.reflink(src, dest)
assert code == -1
assert "底层克隆失败模拟错误" in msg
# 验证临时文件已被清理且目标未生成
assert not temp_file.exists()
assert not dest.exists()
def test_reflink_source_file_not_found(tmp_path: Path):
"""
测试当源文件不存在时调用 reflink,返回失败状态码且不遗留临时或目标文件。
"""
src = tmp_path / "nonexistent_source.txt"
dest = tmp_path / "target.txt"
temp_file = dest.with_suffix(dest.suffix + ".mp")
code, msg = SystemUtils.reflink(src, dest)
assert code != 0
assert msg != ""
assert not temp_file.exists()
assert not dest.exists()
def test_reflink_unexpected_exception_handling(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
"""
测试当执行过程中发生未捕获异常(如 shutil.move 失败)时,妥善清理临时文件并返回错误。
"""
src = tmp_path / "source.txt"
dest = tmp_path / "target.txt"
temp_file = dest.with_suffix(dest.suffix + ".mp")
src.write_text("source data", encoding="utf-8")
def _mock_reflink_copy(_src: Path, _dest: Path):
_dest.write_text("cloned data", encoding="utf-8")
return 0, ""
def _mock_move(_src, _dest):
raise RuntimeError("模拟 shutil.move 移动文件异常")
monkeypatch.setattr(SystemUtils, "_reflink_copy", _mock_reflink_copy)
monkeypatch.setattr(shutil, "move", _mock_move)
code, msg = SystemUtils.reflink(src, dest)
assert code == -1
assert "模拟 shutil.move 移动文件异常" in msg
assert not temp_file.exists()
assert not dest.exists()
def test_reflink_copy_macos_clonefile_error(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
"""
测试 macOS 环境下 libc.clonefile 返回错误时的处理逻辑。
"""
monkeypatch.setattr(sys, "platform", "darwin")
src = tmp_path / "src.txt"
dest = tmp_path / "dest.txt"
src.write_text("data", encoding="utf-8")
mock_libc = MagicMock()
mock_libc.clonefile.return_value = -1
import app.adapters.system.host as host_module
monkeypatch.setattr(host_module.ctypes, "CDLL", lambda *args, **kwargs: mock_libc)
monkeypatch.setattr(host_module.ctypes, "get_errno", lambda: errno.EEXIST)
code, msg = SystemUtils._reflink_copy(src, dest)
assert code == -1
assert "clonefile 失败" in msg
assert os.strerror(errno.EEXIST) in msg
def test_reflink_copy_linux_success(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
"""
测试 Linux 环境下使用 ioctl(FICLONE) 成功克隆文件,并验证同步了元数据。
"""
monkeypatch.setattr(sys, "platform", "linux")
src = tmp_path / "src.txt"
dest = tmp_path / "dest.txt"
src_content = b"linux reflink content"
src.write_bytes(src_content)
import app.adapters.system.host as host_module
mock_fcntl = MagicMock()
monkeypatch.setattr(host_module, "fcntl", mock_fcntl)
copystat_called = []
def _mock_copystat(s, d):
copystat_called.append((s, d))
monkeypatch.setattr(shutil, "copystat", _mock_copystat)
code, msg = SystemUtils._reflink_copy(src, dest)
assert code == 0
assert msg == ""
# 验证调用了 ioctl(..., 0x40049409, ...)
mock_fcntl.ioctl.assert_called_once()
assert mock_fcntl.ioctl.call_args[0][1] == 0x40049409
# 验证调用了 copystat 同步元数据
assert len(copystat_called) == 1
assert copystat_called[0] == (src, dest)
def test_reflink_copy_linux_fcntl_none(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
"""
测试 Linux 环境下当 fcntl 模块不可用时的错误处理。
"""
monkeypatch.setattr(sys, "platform", "linux")
src = tmp_path / "src.txt"
dest = tmp_path / "dest.txt"
src.write_text("data", encoding="utf-8")
import app.adapters.system.host as host_module
monkeypatch.setattr(host_module, "fcntl", None)
code, msg = SystemUtils._reflink_copy(src, dest)
assert code == -1
assert msg == "fcntl 不可用"
def test_reflink_copy_linux_ioctl_oserror(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
"""
测试 Linux 环境下 ioctl(FICLONE) 抛出 OSError 时的错误处理。
"""
monkeypatch.setattr(sys, "platform", "linux")
src = tmp_path / "src.txt"
dest = tmp_path / "dest.txt"
src.write_text("data", encoding="utf-8")
import app.adapters.system.host as host_module
mock_fcntl = MagicMock()
mock_fcntl.ioctl.side_effect = OSError("Invalid cross-device link")
monkeypatch.setattr(host_module, "fcntl", mock_fcntl)
code, msg = SystemUtils._reflink_copy(src, dest)
assert code == -1
assert "Linux ioctl(FICLONE) 失败: Invalid cross-device link" in msg
def test_reflink_copy_unsupported_platform(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
"""
测试在不支持引用链接的操作系统(如 Windows)上的错误处理。
"""
monkeypatch.setattr(sys, "platform", "win32")
src = tmp_path / "src.txt"
dest = tmp_path / "dest.txt"
src.write_text("data", encoding="utf-8")
code, msg = SystemUtils._reflink_copy(src, dest)
assert code == -1
assert "当前操作系统 (win32) 不支持引用链接 (reflink)" in msg

View File

@@ -0,0 +1,451 @@
"""
引用链接(reflink)传输管道规划、执行整理与步骤观察集成测试。
"""
import filecmp
import os
import sys
import warnings
from pathlib import Path
from unittest.mock import MagicMock
import psutil
import pytest
from app.adapters.system.host import SystemUtils
from app.application.transfer.execution import TransferOperationObservationState
from app.application.transfer.workflow import (
TransferPlanCheckpoint,
TransferPlanningInput,
)
from app.domain.context import MediaInfo
from app.domain.meta.metabase import MetaBase
from app.modules.filemanager.storages import StorageBase
from app.modules.filemanager.storages.local import LocalStorage
from app.modules.filemanager.transhandler import TransHandler
from app.schemas.file import FileItem
from app.schemas.types import MediaType
def _make_local_storage() -> LocalStorage:
"""
构造绕过配置持久化初始化的本地存储适配器实例。
:return: LocalStorage 实例
"""
return object.__new__(LocalStorage)
def _get_filesystem_type(path: Path) -> str:
"""
获取指定路径所在挂载点文件系统的格式类型。
:param path: 目标路径
:return: 小写文件系统名称(例如 apfs, btrfs, xfs, ext4)
"""
resolved = path.resolve()
best_mount = ""
best_fstype = ""
try:
for part in psutil.disk_partitions(all=True):
try:
mount = Path(part.mountpoint).resolve()
if resolved == mount or mount in resolved.parents:
if len(str(mount)) > len(best_mount):
best_mount = str(mount)
best_fstype = (part.fstype or "").lower()
except Exception:
continue
except Exception:
pass
if best_fstype:
return best_fstype
if sys.platform.startswith("linux"):
try:
with open("/proc/mounts", "r", encoding="utf-8") as stream:
for line in stream:
parts = line.split()
if len(parts) >= 3:
mount = Path(parts[1]).resolve()
if resolved == mount or mount in resolved.parents:
if len(str(mount)) > len(best_mount):
best_mount = str(mount)
best_fstype = parts[2].lower()
except Exception:
pass
if best_fstype:
return best_fstype
if sys.platform == "darwin":
return "apfs"
return "unknown"
def _probe_reflink_support(path: Path) -> bool:
"""
真实探测文件系统是否支持写时复制。
:param path: 探测临时目录
:return: 支持写时复制时为 True
"""
src = path / ".probe_reflink_src"
dest = path / ".probe_reflink_dest"
try:
src.write_bytes(b"probe")
code, _ = SystemUtils.reflink(src, dest)
return code == 0
except Exception:
return False
finally:
src.unlink(missing_ok=True)
dest.unlink(missing_ok=True)
def _require_reflink_filesystem(tmp_path: Path) -> str:
"""
检查测试目录文件系统格式,非写时复制格式发出警告并跳过测试。
:param tmp_path: pytest 临时测试目录
:return: 当前被确认支持写时复制的文件系统格式
"""
fstype = _get_filesystem_type(tmp_path)
supported_types = {"apfs", "btrfs", "xfs", "zfs"}
if fstype not in supported_types or not _probe_reflink_support(tmp_path):
warning_message = (
f"当前测试目录所在文件系统格式为 [{fstype}],"
f"非写时复制格式(需为 {supported_types} 且启用 CoW),已跳过对应引用链接测试"
)
warnings.warn(warning_message, UserWarning, stacklevel=2)
pytest.skip(warning_message)
return fstype
def test_transhandler_plan_and_execute_reflink(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""
测试 TransHandler 使用 transfer_type="reflink" 规划并执行本地文件整理。
验证整理执行成功,目标文件被创建,源文件与目标文件内容完全一致,
且属于不同 Inode(非硬链接),也不是符号链接。
:param tmp_path: pytest 临时测试目录
:param monkeypatch: pytest 猴子补丁夹具
"""
_require_reflink_filesystem(tmp_path)
download_dir = tmp_path / "downloads"
library_dir = tmp_path / "library"
download_dir.mkdir(parents=True, exist_ok=True)
library_dir.mkdir(parents=True, exist_ok=True)
source_file = download_dir / "Test.Movie.2026.mkv"
source_content = b"MoviePilot reflink test content - " + b"M" * 2048
source_file.write_bytes(source_content)
storage = _make_local_storage()
source_item = storage.get_item_strict(source_file)
assert source_item is not None
planning_input = TransferPlanningInput(
source_fileitem=source_item.model_dump(mode="json"),
)
handler = TransHandler()
monkeypatch.setattr(handler, "_TransHandler__intercept_transfer", lambda **_kwargs: (True, ""))
monkeypatch.setattr(LocalStorage, "_LocalStorage__should_show_progress", lambda *_args: False)
meta = MetaBase("Test.Movie.2026.mkv")
mediainfo = MediaInfo(type=MediaType.MOVIE, title="Test Movie", year="2026")
# 规划引用链接整理
checkpoint = handler.plan_transfer(
planning_input,
meta=meta,
mediainfo=mediainfo,
source_oper=storage,
target_storage="local",
target_path=library_dir,
transfer_type="reflink",
need_scrape=False,
need_rename=False,
need_notify=False,
overwrite_mode=None,
episodes_info=None,
preview=False,
)
assert isinstance(checkpoint, TransferPlanCheckpoint)
assert checkpoint.resolved_transfer_type == "reflink"
assert checkpoint.skip_reason is None
# 执行整理计划
transfer_info = handler.execute_transfer_plan(
checkpoint,
meta=meta,
mediainfo=mediainfo,
source_oper=storage,
target_oper=storage,
)
assert transfer_info.success is True
target_file = Path(checkpoint.final_target_path)
# 验证目标文件已创建且为常规文件
assert target_file.exists()
assert target_file.is_file()
# 验证不是软链接
assert not target_file.is_symlink()
# 验证源文件和目标文件不同 Inode(独立引用)
assert not target_file.samefile(source_file)
# 验证内容完全一致
assert target_file.read_bytes() == source_content
assert filecmp.cmp(source_file, target_file, shallow=False)
def test_transhandler_reflink_overwrite_always(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""
测试在覆盖模式为 always 时,reflink 也能安全覆盖已存在的目标文件。
:param tmp_path: pytest 临时测试目录
:param monkeypatch: pytest 猴子补丁夹具
"""
_require_reflink_filesystem(tmp_path)
download_dir = tmp_path / "downloads"
library_dir = tmp_path / "library"
download_dir.mkdir(parents=True, exist_ok=True)
library_dir.mkdir(parents=True, exist_ok=True)
source_file = download_dir / "Test.Movie.2026.mkv"
new_content = b"New movie version bytes for reflink overwrite"
source_file.write_bytes(new_content)
target_file = library_dir / "Test.Movie.2026.mkv"
old_content = b"Old movie version bytes that will be replaced"
target_file.write_bytes(old_content)
storage = _make_local_storage()
source_item = storage.get_item_strict(source_file)
assert source_item is not None
planning_input = TransferPlanningInput(
source_fileitem=source_item.model_dump(mode="json"),
)
handler = TransHandler()
monkeypatch.setattr(handler, "_TransHandler__intercept_transfer", lambda **_kwargs: (True, ""))
monkeypatch.setattr(LocalStorage, "_LocalStorage__should_show_progress", lambda *_args: False)
meta = MetaBase("Test.Movie.2026.mkv")
mediainfo = MediaInfo(type=MediaType.MOVIE, title="Test Movie", year="2026")
# 规划强制覆盖的引用链接整理
checkpoint = handler.plan_transfer(
planning_input,
meta=meta,
mediainfo=mediainfo,
source_oper=storage,
target_storage="local",
target_path=library_dir,
transfer_type="reflink",
need_scrape=False,
need_rename=False,
need_notify=False,
overwrite_mode="always",
episodes_info=None,
preview=False,
)
assert isinstance(checkpoint, TransferPlanCheckpoint)
assert checkpoint.resolved_transfer_type == "reflink"
# 执行覆盖整理
transfer_info = handler.execute_transfer_plan(
checkpoint,
meta=meta,
mediainfo=mediainfo,
source_oper=storage,
target_oper=storage,
)
assert transfer_info.success is True
# 验证旧目标已被新版本的 reflink 内容原子替换
assert target_file.exists()
assert target_file.is_file()
assert not target_file.is_symlink()
assert not target_file.samefile(source_file)
assert target_file.read_bytes() == new_content
assert filecmp.cmp(source_file, target_file, shallow=False)
def test_transhandler_observe_reflink_operation_states(
tmp_path: Path,
) -> None:
"""
测试步骤观察器 __observe_transfer_operation 对 reflink 整理方式的状态判定。
验证:
1. 目标正常独立且内容一致时返回 APPLIED。
2. 目标文件缺失时返回 NOT_APPLIED。
3. 目标文件内容不一致时返回 CONFLICT。
4. 目标文件为同一 Inode(硬链接)时返回 CONFLICT。
5. 目标文件为符号链接(软链接)时返回 CONFLICT。
:param tmp_path: pytest 临时测试目录
"""
_require_reflink_filesystem(tmp_path)
source_dir = tmp_path / "src"
target_dir = tmp_path / "dst"
source_dir.mkdir(parents=True, exist_ok=True)
target_dir.mkdir(parents=True, exist_ok=True)
source_file = source_dir / "sample.mkv"
source_content = b"reflink observation test data"
source_file.write_bytes(source_content)
storage = _make_local_storage()
source_item = storage.get_item_strict(source_file)
assert source_item is not None
# 1. 成功创建的真实 reflink 文件 -> APPLIED
reflink_target = target_dir / "sample_reflink.mkv"
code, msg = SystemUtils.reflink(source_file, reflink_target)
assert code == 0, f"创建 reflink 失败: {msg}"
obs_applied = TransHandler._TransHandler__observe_transfer_operation(
fileitem=source_item,
target_storage="local",
source_oper=storage,
target_oper=storage,
target_file=reflink_target,
transfer_type="reflink",
)
assert obs_applied.state == TransferOperationObservationState.APPLIED
# 2. 目标文件不存在 -> NOT_APPLIED
missing_target = target_dir / "non_existent.mkv"
obs_missing = TransHandler._TransHandler__observe_transfer_operation(
fileitem=source_item,
target_storage="local",
source_oper=storage,
target_oper=storage,
target_file=missing_target,
transfer_type="reflink",
)
assert obs_missing.state == TransferOperationObservationState.NOT_APPLIED
# 3. 目标文件内容与源文件不一致 -> CONFLICT
diff_target = target_dir / "diff.mkv"
diff_target.write_bytes(b"different content")
obs_diff = TransHandler._TransHandler__observe_transfer_operation(
fileitem=source_item,
target_storage="local",
source_oper=storage,
target_oper=storage,
target_file=diff_target,
transfer_type="reflink",
)
assert obs_diff.state == TransferOperationObservationState.CONFLICT
# 4. 目标文件为硬链接(同一 Inode) -> CONFLICT
hardlink_target = target_dir / "hardlink.mkv"
os.link(source_file, hardlink_target)
obs_hardlink = TransHandler._TransHandler__observe_transfer_operation(
fileitem=source_item,
target_storage="local",
source_oper=storage,
target_oper=storage,
target_file=hardlink_target,
transfer_type="reflink",
)
assert obs_hardlink.state == TransferOperationObservationState.CONFLICT
# 5. 目标文件为符号链接 -> CONFLICT
symlink_target = target_dir / "symlink.mkv"
symlink_target.symlink_to(source_file)
obs_symlink = TransHandler._TransHandler__observe_transfer_operation(
fileitem=source_item,
target_storage="local",
source_oper=storage,
target_oper=storage,
target_file=symlink_target,
transfer_type="reflink",
)
assert obs_symlink.state == TransferOperationObservationState.CONFLICT
def test_transhandler_same_storage_reflink_dispatch(
tmp_path: Path,
) -> None:
"""
测试同远端/自定义存储分支中 transfer_type="reflink" 的分发逻辑。
验证:
1. 当存储实现 reflink 并成功时,返回新目标项。
2. 当存储实现 reflink 但返回失败时,返回错误信息。
3. 当存储未声明支持 reflink 整理方式时,返回不支持提示。
:param tmp_path: pytest 临时测试目录
"""
file_path = "/remote/path/source.mkv"
target_path = Path("/remote/path/target.mkv")
fileitem = FileItem(storage="custom", path=file_path, name="source.mkv")
# 创建模拟存储适配器
mock_oper = MagicMock(spec=StorageBase)
mock_oper.is_support_transtype.return_value = True
# 1. reflink 成功
mock_oper.reflink.return_value = True
mock_oper.get_item.return_value = FileItem(
storage="custom",
path=target_path.as_posix(),
name=target_path.name,
type="file",
)
new_item, err = TransHandler._TransHandler__transfer_command(
fileitem=fileitem,
target_storage="custom",
source_oper=mock_oper,
target_oper=mock_oper,
target_file=target_path,
transfer_type="reflink",
)
assert err == ""
assert new_item is not None
assert new_item.path == target_path.as_posix()
mock_oper.reflink.assert_called_once_with(fileitem, target_path)
# 2. reflink 失败
mock_oper.reflink.reset_mock()
mock_oper.reflink.return_value = False
fail_item, fail_err = TransHandler._TransHandler__transfer_command(
fileitem=fileitem,
target_storage="custom",
source_oper=mock_oper,
target_oper=mock_oper,
target_file=target_path,
transfer_type="reflink",
)
assert fail_item is None
assert "创建引用链接失败" in fail_err
mock_oper.reflink.assert_called_once_with(fileitem, target_path)
# 3. 存储未声明支持 reflink 整理方式
unsupported_oper = MagicMock(spec=StorageBase)
unsupported_oper.is_support_transtype.return_value = False
unsup_item, unsup_err = TransHandler._TransHandler__transfer_command(
fileitem=fileitem,
target_storage="custom",
source_oper=unsupported_oper,
target_oper=unsupported_oper,
target_file=target_path,
transfer_type="reflink",
)
assert unsup_item is None
assert "不支持 reflink 整理方式" in unsup_err