mirror of
https://github.com/jxxghp/MoviePilot.git
synced 2026-12-02 00:46:27 +08:00
fix(storage): 核验 115 上传回调并隔离不确定结果 (#7434)
* fix(storage): verify 115 upload callbacks before retry Preserve uncertain completion results for manual review instead of replaying uploads. Refs #7433. * docs: sync architecture import count
This commit is contained in:
@@ -41,6 +41,7 @@ from app.domain.context import MediaInfo, MusicInfo
|
||||
from app.domain.media import is_music_media_source
|
||||
from app.domain.meta.metamusic import MetaMusic
|
||||
from app.runtime.log import logger
|
||||
from app.schemas.exception import StorageOperationUncertainError
|
||||
from app.schemas.transfer import TransferInfo
|
||||
from app.schemas.types import (
|
||||
MediaSource,
|
||||
@@ -147,12 +148,20 @@ class _DurableTransferStepRunner:
|
||||
) -> TransferStepResult:
|
||||
"""
|
||||
在事务外执行副作用,异常后先探测结果再决定重试或人工复核。
|
||||
|
||||
适配器已确认写入结果不确定时,保留其判断,避免目录延迟可见被误判为未执行。
|
||||
"""
|
||||
try:
|
||||
result = execute()
|
||||
except Exception as error:
|
||||
try:
|
||||
observation = observe()
|
||||
if isinstance(error, StorageOperationUncertainError):
|
||||
observation = TransferOperationObservation(
|
||||
state=TransferOperationObservationState.UNKNOWN,
|
||||
evidence=TransferStepResult(payload={"execute_error": str(error)}),
|
||||
)
|
||||
else:
|
||||
observation = observe()
|
||||
except Exception as observe_error:
|
||||
observation = TransferOperationObservation(
|
||||
state=TransferOperationObservationState.UNKNOWN,
|
||||
|
||||
@@ -20,7 +20,7 @@ from app.runtime.log import logger
|
||||
from app.runtime.rate import QpsRateLimiter, RateStats
|
||||
from app.runtime.settings import get_runtime_setting
|
||||
from app.runtime.stop import runtime_stop_state
|
||||
from app.schemas.exception import StorageQueryError
|
||||
from app.schemas.exception import StorageOperationUncertainError, StorageQueryError
|
||||
from app.schemas.file import FileItem as _SchemaFileItem
|
||||
from app.schemas.file import StorageUsage as _SchemaStorageUsage
|
||||
from app.schemas.types import StorageSchema
|
||||
@@ -693,11 +693,13 @@ class U115Pan(StorageBase, metaclass=WeakSingleton):
|
||||
普通上传会创建新的 OSS 分片任务,凭据过期时对当前分片或完成请求最多刷新重试 5 次。
|
||||
取消不主动中止远端分片任务;分片阶段的其他异常向上传播。
|
||||
成功后若索引尚不可见,按目标路径合成文件项,不保证此时已有远端文件标识。
|
||||
完成回调失败时先核验目标身份,无法确认则交由调用方人工复核,禁止自动重传。
|
||||
|
||||
:param target_dir: 带文件标识的目标目录
|
||||
:param local_path: 本地源文件,完成后保留
|
||||
:param new_name: 目标文件名;为空时沿用源文件名
|
||||
:return: 上传或已存在的目标项;初始化、完成回调失败或取消时返回 None
|
||||
:return: 上传或已存在的目标项;初始化、明确上传失败或取消时返回 None
|
||||
:raises StorageOperationUncertainError: 数据可能已上传,但无法确认 115 目标文件身份
|
||||
"""
|
||||
# oss2 连同阿里云 SDK 约 19MB,存储发现会导入全部存储实现,上传时才按需导入
|
||||
import oss2
|
||||
@@ -944,20 +946,15 @@ class U115Pan(StorageBase, metaclass=WeakSingleton):
|
||||
bucket = refresh_upload_bucket()
|
||||
continue
|
||||
raise
|
||||
if result.status != 200:
|
||||
if result.status not in (200, 203):
|
||||
logger.warn(f"【115】{target_name} 上传失败,错误码: {result.status}")
|
||||
return None
|
||||
try:
|
||||
callback_result = result.resp.response.json()
|
||||
except Exception as e:
|
||||
logger.error(f"【115】{target_name} 上传完成回调解析失败: {str(e)}")
|
||||
return None
|
||||
logger.debug(f"【115】上传 Step 6 回调结果:{callback_result}")
|
||||
if not callback_result or not callback_result.get("state"):
|
||||
logger.warn(f"【115】{target_name} 上传完成回调失败: {callback_result}")
|
||||
return None
|
||||
logger.info(f"【115】{target_name} 上传成功")
|
||||
return self.__resolve_upload_completion(
|
||||
result, target_path, local_path, file_size, file_sha1,
|
||||
)
|
||||
except oss2.exceptions.OssError as e:
|
||||
if e.status == 203 or e.code == "CallbackFailed":
|
||||
return self.__verify_completed_upload(target_path, file_size, file_sha1)
|
||||
if e.code == "FileAlreadyExists":
|
||||
logger.warn(f"【115】{target_name} 已存在")
|
||||
else:
|
||||
@@ -973,6 +970,86 @@ class U115Pan(StorageBase, metaclass=WeakSingleton):
|
||||
)
|
||||
return self.__build_uploaded_fileitem(target_path, local_path, file_size)
|
||||
|
||||
def __resolve_upload_completion(
|
||||
self, result: Any, target_path: Path, local_path: Path,
|
||||
file_size: int, file_sha1: str,
|
||||
) -> _SchemaFileItem:
|
||||
"""
|
||||
解析 OSS 完成回调,回调失败时仅凭远端身份核验确认成功。
|
||||
|
||||
HTTP 203 表示 OSS 已保存对象但回调失败;缺失或无效回调同样不能证明 115 已登记文件。
|
||||
只有明确成功的 HTTP 200 回调继续允许索引延迟时使用临时元数据。
|
||||
|
||||
:param result: OSS 完成请求返回的 200 或 203 响应
|
||||
:param target_path: 上传请求指定的完整目标路径
|
||||
:param local_path: 本地源文件,仅用于成功回执的兼容元数据
|
||||
:param file_size: 已上传文件的精确字节数
|
||||
:param file_sha1: 上传初始化使用的完整 SHA1
|
||||
:return: 已确认的远端文件或明确成功回调对应的临时文件项
|
||||
:raises StorageOperationUncertainError: 回调及远端查询无法确认目标身份
|
||||
"""
|
||||
try:
|
||||
callback_result = result.resp.response.json()
|
||||
except Exception:
|
||||
callback_result = None
|
||||
if (result.status == 203 or not isinstance(callback_result, dict)
|
||||
or not callback_result.get("state")):
|
||||
logger.warn(
|
||||
f"【115】{target_path.name} 上传完成回调未确认(HTTP {result.status}),正在核验远端文件"
|
||||
)
|
||||
callback_data = callback_result.get("data") if isinstance(callback_result, dict) else None
|
||||
file_id = callback_data.get("file_id") if isinstance(callback_data, dict) else None
|
||||
return self.__verify_completed_upload(target_path, file_size, file_sha1, file_id)
|
||||
logger.info(f"【115】{target_path.name} 上传成功")
|
||||
return self.get_item(target_path) or self.__build_uploaded_fileitem(
|
||||
target_path, local_path, file_size,
|
||||
)
|
||||
|
||||
def __verify_completed_upload(
|
||||
self, target_path: Path, file_size: int, file_sha1: str,
|
||||
file_id: Optional[Union[str, int]] = None,
|
||||
) -> _SchemaFileItem:
|
||||
"""
|
||||
按目标目录和名称核验回调异常后的文件,不触发初始化、补传或源文件删除。
|
||||
|
||||
必须取得文件标识、文件类型、原名和精确大小;回调提供标识或远端提供 SHA1 时一并核对。
|
||||
目录暂不可见、查询失败和身份不符均保留不确定性,不能当作上传未执行。
|
||||
|
||||
:param target_path: 上传指定的完整目标路径,路径查询同时限定目标目录
|
||||
:param file_size: 本地上传内容的精确字节数
|
||||
:param file_sha1: 上传初始化使用的完整 SHA1
|
||||
:param file_id: 回调可用时返回的远端文件标识;未提供时不核对该项
|
||||
:return: 身份核验通过的远端文件项
|
||||
:raises StorageOperationUncertainError: 目标不可见、查询失败或文件身份不一致
|
||||
"""
|
||||
try:
|
||||
resp = self._request_api(
|
||||
"POST", "/open/folder/get_info", data={"path": target_path.as_posix()},
|
||||
no_error_log=True, accepted_codes=U115_GET_INFO_ACCEPTED_CODES,
|
||||
)
|
||||
data = resp.get("data") if resp and resp.get("state") else None
|
||||
if not isinstance(data, dict) or not data.get("file_id"):
|
||||
raise ValueError("目标文件元数据尚不可见")
|
||||
if (str(data.get("file_category")) != "1"
|
||||
or data.get("file_name") != target_path.name
|
||||
or str(data.get("size_byte")) != str(file_size)):
|
||||
raise ValueError("目标文件类型、名称或精确大小不一致")
|
||||
if file_id is not None and str(data["file_id"]) != str(file_id):
|
||||
raise ValueError("目标文件标识与回调不一致")
|
||||
if data.get("sha1") and str(data["sha1"]).casefold() != file_sha1.casefold():
|
||||
raise ValueError("目标文件 SHA1 不一致")
|
||||
return _SchemaFileItem(
|
||||
storage=self.schema.value, fileid=str(data["file_id"]),
|
||||
path=target_path.as_posix(), type="file", name=target_path.name,
|
||||
basename=target_path.stem, extension=target_path.suffix[1:] or None,
|
||||
size=file_size, pickcode=data.get("pick_code"), modify_time=data.get("utime"),
|
||||
)
|
||||
except Exception as error:
|
||||
raise StorageOperationUncertainError(
|
||||
f"【115】{target_path} 上传可能已完成,但无法确认远端文件身份,"
|
||||
f"已保留源文件,禁止自动重传,请人工复核:{error}"
|
||||
) from error
|
||||
|
||||
def __build_uploaded_fileitem(
|
||||
self, target_path: Path, local_path: Path, file_size: int
|
||||
) -> _SchemaFileItem:
|
||||
|
||||
@@ -94,6 +94,14 @@ class StorageQueryError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class StorageOperationUncertainError(RuntimeError):
|
||||
"""
|
||||
存储写入可能已经生效,但适配器无法确认目标文件身份。
|
||||
|
||||
调用方必须保留源文件并转人工复核,不能仅凭目录暂不可见就自动重放写入。
|
||||
"""
|
||||
|
||||
|
||||
class PersistenceUnavailableError(RuntimeError):
|
||||
"""
|
||||
持久化执行能力暂时拒绝新操作,调用方可在稍后重试。
|
||||
|
||||
@@ -851,7 +851,7 @@ flowchart LR
|
||||
| 指标 | 当前值 |
|
||||
|---|---:|
|
||||
| Python 模块 | 1166 |
|
||||
| 内部导入边 | 10,184 |
|
||||
| 内部导入边 | 10,185 |
|
||||
| 非平凡 SCC | 1(29 个模块的 TMDB vendor 精确 containment) |
|
||||
| Application / Chain 具体 Adapter 直连 | 0 / 0 |
|
||||
| Direct egress | 51(精确 policy 准入,Application / Chain 均为 0) |
|
||||
|
||||
@@ -209,6 +209,13 @@ with patch.object(SomeModule, "fetch", new=AsyncMock(return_value=FAKE)):
|
||||
|
||||
### 存储严格查询回执回归
|
||||
|
||||
`tests/test_u115_storage.py` 在 OSS 和 115 API 边界模拟分片完成返回 203、HTTP 200 回调失败、
|
||||
目录暂不可见及身份冲突,核对目标目录/名称、文件标识、精确字节数和可用的 SHA1。
|
||||
身份未确认时保留源文件,不能合成成功元数据;跨存储移动只在核验成功后删除源文件。
|
||||
`tests/test_transfer_execution_runner.py` 使用独立数据库验证这种不确定结果持久进入人工复核,
|
||||
通用路径查询不能把它降级为可重试失败,旧 worker 也不能再次上传。这些离线用例不代表真实
|
||||
115 回调故障已复现或报告者 Docker 环境已验收。
|
||||
|
||||
`tests/test_storage_cleanup_receipts.py` 通过真实 StorageChain、模块调度器和 FileManager,
|
||||
验证未知存储、未初始化模块、缺失模块和适配器不可用均保留整理历史。自定义存储提供方
|
||||
放在插件优先路径或宿主前后顺序时,都须能传递明确的文件项/不存在回执;普通查询仍可返回空值。
|
||||
|
||||
@@ -87,7 +87,7 @@
|
||||
"app/modules/emby/emby.py:Emby.get_tv_episodes": 18,
|
||||
"app/modules/emby/emby.py:Emby.get_webhook_message": 18,
|
||||
"app/modules/filemanager/storages/alipan.py:AliPan.upload": 16,
|
||||
"app/modules/filemanager/storages/u115.py:U115Pan.upload": 33,
|
||||
"app/modules/filemanager/storages/u115.py:U115Pan.upload": 32,
|
||||
"app/modules/filemanager/transhandler.py:TransHandler.__transfer_command": 19,
|
||||
"app/modules/filemanager/transhandler.py:TransHandler.execute_transfer_plan": 19,
|
||||
"app/modules/filter/__init__.py:FilterModule.__match_rule": 24,
|
||||
|
||||
@@ -977,8 +977,8 @@
|
||||
"runtime_only": true
|
||||
}
|
||||
},
|
||||
"edge_count": 10184,
|
||||
"edge_sha256": "3eef6f4da0dc03f53a42dfaf719246d1d262a08b1dfa4afca94cdcb103160866",
|
||||
"edge_count": 10185,
|
||||
"edge_sha256": "7f38852ed55a0002549c7dbe94b8810841659290fce66ed8721376f3a518dc14",
|
||||
"edges": [
|
||||
"app -> app.foundation",
|
||||
"app -> app.foundation.environment",
|
||||
@@ -6076,6 +6076,7 @@
|
||||
"app.chain.transfer.execution -> app.runtime",
|
||||
"app.chain.transfer.execution -> app.runtime.log",
|
||||
"app.chain.transfer.execution -> app.schemas",
|
||||
"app.chain.transfer.execution -> app.schemas.exception",
|
||||
"app.chain.transfer.execution -> app.schemas.transfer",
|
||||
"app.chain.transfer.execution -> app.schemas.types",
|
||||
"app.chain.transfer.facade -> app.chain",
|
||||
|
||||
@@ -13,6 +13,7 @@ from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from app.application.transfer.execution import (
|
||||
TransferExecutionCommand,
|
||||
TransferExecutionLeaseLostError,
|
||||
TransferExecutionState,
|
||||
TransferManualReviewDecision,
|
||||
TransferOperationObservation,
|
||||
@@ -39,6 +40,7 @@ from app.domain.context import MediaInfo
|
||||
from app.domain.meta.metabase import MetaBase
|
||||
from app.modules.filemanager.storages.local import LocalStorage
|
||||
from app.modules.filemanager.transhandler import TransHandler
|
||||
from app.schemas.exception import StorageOperationUncertainError
|
||||
from app.schemas.types import MediaType
|
||||
from app.schemas.workflow import FileItem
|
||||
|
||||
@@ -297,6 +299,37 @@ def test_runner_defers_after_execute_error_observed_not_applied(
|
||||
assert snapshot.steps[0].state.value == "failed"
|
||||
|
||||
|
||||
def test_runner_preserves_storage_uncertainty_and_blocks_replay(execution_repository) -> None:
|
||||
"""
|
||||
存储已判定写入结果不确定时,即使通用目录探测会报不存在也必须持久隔离并阻止重放。
|
||||
"""
|
||||
execute = Mock(side_effect=StorageOperationUncertainError("OSS 203,远端文件身份待确认"))
|
||||
observe = Mock(return_value=TransferOperationObservation(
|
||||
state=TransferOperationObservationState.NOT_APPLIED,
|
||||
evidence=TransferStepResult(payload={"target_exists": False}),
|
||||
))
|
||||
|
||||
with pytest.raises(transfer_chain_module._TransferManualReviewRequired, match="OSS 203"):
|
||||
_runner(execution_repository).run(
|
||||
phase="transfer", kind="materialize_target", payload=_runner_step_payload(),
|
||||
execute=execute, observe=observe,
|
||||
)
|
||||
# 人工复核已释放任务租约;旧 worker 重入也不能再次执行上传。
|
||||
with pytest.raises(TransferExecutionLeaseLostError):
|
||||
_runner(execution_repository).run(
|
||||
phase="transfer", kind="materialize_target", payload=_runner_step_payload(),
|
||||
execute=execute, observe=observe,
|
||||
)
|
||||
|
||||
snapshot = execution_repository.get_snapshot(task_id="task-runner")
|
||||
assert snapshot.state is TransferExecutionState.MANUAL_REVIEW
|
||||
assert snapshot.steps[0].state.value == "manual_review"
|
||||
assert snapshot.retry_count == 0
|
||||
assert snapshot.steps[0].result.payload == {"execute_error": "OSS 203,远端文件身份待确认"}
|
||||
execute.assert_called_once()
|
||||
observe.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"observation_state",
|
||||
[
|
||||
|
||||
@@ -16,6 +16,7 @@ from app.modules.filemanager.storages.u115 import U115Pan
|
||||
from app.modules.filemanager.transhandler import TransHandler
|
||||
from app.monitor.poller import RemotePoller
|
||||
from app.monitor.snapshot import SnapshotStore
|
||||
from app.schemas.exception import StorageOperationUncertainError
|
||||
from app.schemas.file import FileItem
|
||||
|
||||
|
||||
@@ -72,6 +73,7 @@ class _FakeBucket:
|
||||
"""
|
||||
|
||||
complete_payload = {"state": True}
|
||||
complete_status = 200
|
||||
|
||||
def __init__(self, *_args, **_kwargs):
|
||||
"""
|
||||
@@ -96,7 +98,7 @@ class _FakeBucket:
|
||||
返回可配置的 115 回调结果。
|
||||
"""
|
||||
response = SimpleNamespace(json=lambda: self.complete_payload)
|
||||
return SimpleNamespace(status=200, resp=SimpleNamespace(response=response))
|
||||
return SimpleNamespace(status=self.complete_status, resp=SimpleNamespace(response=response))
|
||||
|
||||
|
||||
def _build_storage() -> U115Pan:
|
||||
@@ -211,9 +213,9 @@ def test_instant_upload_move_uses_exact_bytes_before_deleting_source(
|
||||
assert not local_file.exists()
|
||||
|
||||
|
||||
def test_upload_returns_none_when_complete_callback_reports_failure(tmp_path):
|
||||
def test_upload_requires_review_when_complete_callback_reports_failure(tmp_path):
|
||||
"""
|
||||
115 完成回调失败时,不应把文件视为上传成功。
|
||||
115 完成回调失败且目标未确认时,应保留源文件并禁止自动重传。
|
||||
"""
|
||||
local_file = tmp_path / "Test.Show.S01E02.mkv"
|
||||
local_file.write_bytes(b"movie")
|
||||
@@ -224,9 +226,216 @@ def test_upload_returns_none_when_complete_callback_reports_failure(tmp_path):
|
||||
"complete_payload",
|
||||
{"state": False, "message": "callback failed"},
|
||||
):
|
||||
uploaded_item = _upload_with_fakes(storage, _target_dir(), local_file)
|
||||
with pytest.raises(StorageOperationUncertainError, match="禁止自动重传"):
|
||||
_upload_with_fakes(storage, _target_dir(), local_file)
|
||||
assert local_file.read_bytes() == b"movie"
|
||||
|
||||
assert uploaded_item is None
|
||||
|
||||
@pytest.mark.parametrize("callback_payload", [
|
||||
{"state": False}, {"state": True, "data": {"file_id": "200"}}, None, [],
|
||||
])
|
||||
@pytest.mark.parametrize("remote_hash", [None, "SHA1"])
|
||||
def test_callback_203_requires_matching_remote_identity(
|
||||
tmp_path, monkeypatch, callback_payload, remote_hash,
|
||||
):
|
||||
"""
|
||||
203 只能在目标路径、名称、类型、精确字节数及可用的标识和哈希一致时成功。
|
||||
"""
|
||||
local_file = tmp_path / "episode.mkv"
|
||||
local_file.write_bytes(b"movie")
|
||||
target_dir = _target_dir()
|
||||
target_path = Path(target_dir.path) / local_file.name
|
||||
info = {
|
||||
"file_id": "200", "file_category": "1", "file_name": local_file.name,
|
||||
"size_byte": "5", "size": "0.00 KB", "sha1": remote_hash,
|
||||
}
|
||||
calls = []
|
||||
|
||||
def request_api(method, endpoint, *args, **kwargs):
|
||||
"""
|
||||
在开放接口边界返回可核验的目标,保留真实上传及元数据解析。
|
||||
"""
|
||||
calls.append(endpoint)
|
||||
if endpoint == "/open/folder/get_info":
|
||||
assert method == "POST" and kwargs["data"] == {"path": target_path.as_posix()}
|
||||
return {"state": True, "data": info}
|
||||
return _fake_request_api(method, endpoint, *args, **kwargs)
|
||||
|
||||
storage = _build_storage()
|
||||
storage._request_api = request_api
|
||||
monkeypatch.setattr(_FakeBucket, "complete_status", 203)
|
||||
monkeypatch.setattr(_FakeBucket, "complete_payload", callback_payload)
|
||||
item = _upload_with_fakes(storage, target_dir, local_file)
|
||||
|
||||
assert item.fileid == "200" and item.path == target_path.as_posix()
|
||||
assert item.size == 5 and local_file.read_bytes() == b"movie"
|
||||
assert calls.count("/open/upload/init") == 1
|
||||
assert calls.count("/open/folder/get_info") == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize("remote_data", [
|
||||
None, {}, {"file_id": None}, {"file_id": "201"}, {"file_category": "0"},
|
||||
{"file_name": "other.mkv"}, {"size_byte": 6}, {"size_byte": None},
|
||||
{"size_byte": 5.9}, {"sha1": "different"},
|
||||
])
|
||||
def test_callback_203_rejects_incomplete_or_conflicting_metadata(tmp_path, monkeypatch, remote_data):
|
||||
"""
|
||||
203 后目标暂不可见、身份缺失或冲突时不得伪造成功回执,也不能删除本地源。
|
||||
"""
|
||||
local_file = tmp_path / "episode.mkv"
|
||||
local_file.write_bytes(b"movie")
|
||||
info = {
|
||||
"file_id": "200", "file_category": "1", "file_name": local_file.name,
|
||||
"size_byte": 5, "sha1": "sha1",
|
||||
}
|
||||
|
||||
def request_api(method, endpoint, *args, **kwargs):
|
||||
"""
|
||||
模拟 203 后目标元数据仍不可用或已与上传身份冲突。
|
||||
"""
|
||||
if endpoint == "/open/folder/get_info":
|
||||
data = {**info, **remote_data} if remote_data else remote_data
|
||||
return {"state": True, "data": data}
|
||||
return _fake_request_api(method, endpoint, *args, **kwargs)
|
||||
|
||||
storage = _build_storage()
|
||||
storage._request_api = request_api
|
||||
monkeypatch.setattr(_FakeBucket, "complete_status", 203)
|
||||
monkeypatch.setattr(_FakeBucket, "complete_payload", {"state": False, "data": {"file_id": "200"}})
|
||||
with pytest.raises(StorageOperationUncertainError, match="禁止自动重传"):
|
||||
_upload_with_fakes(storage, _target_dir(), local_file)
|
||||
assert local_file.read_bytes() == b"movie"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("callback_payload", [{"state": False}, None])
|
||||
def test_callback_200_failure_also_verifies_remote_file(tmp_path, monkeypatch, callback_payload):
|
||||
"""
|
||||
HTTP 200 的业务失败或缺失回调也先核验远端,避免误触发第二次上传。
|
||||
"""
|
||||
local_file = tmp_path / "episode.mkv"
|
||||
local_file.write_bytes(b"movie")
|
||||
|
||||
def request_api(method, endpoint, *args, **kwargs):
|
||||
"""
|
||||
回调未确认时提供完整的目标身份。
|
||||
"""
|
||||
if endpoint == "/open/folder/get_info":
|
||||
return {"state": True, "data": {
|
||||
"file_id": "200", "file_category": "1", "file_name": local_file.name,
|
||||
"size_byte": 5, "sha1": "sha1",
|
||||
}}
|
||||
return _fake_request_api(method, endpoint, *args, **kwargs)
|
||||
|
||||
storage = _build_storage()
|
||||
storage._request_api = request_api
|
||||
monkeypatch.setattr(_FakeBucket, "complete_payload", callback_payload)
|
||||
assert _upload_with_fakes(storage, _target_dir(), local_file).fileid == "200"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("response_kind", ["xml", "exception", "query_error"])
|
||||
def test_callback_203_handles_xml_sdk_errors_and_failed_verification(tmp_path, monkeypatch, response_kind):
|
||||
"""
|
||||
兼容 OSS 的 XML 错误体和异常形式;核验接口失败时仍保留不确定性。
|
||||
"""
|
||||
from oss2.exceptions import ServerError
|
||||
|
||||
local_file = tmp_path / "episode.mkv"
|
||||
local_file.write_bytes(b"movie")
|
||||
|
||||
def request_api(method, endpoint, *args, **kwargs):
|
||||
"""
|
||||
仅在目标详情接口模拟不可用,其余请求复用正常上传响应。
|
||||
"""
|
||||
if endpoint == "/open/folder/get_info":
|
||||
if response_kind == "query_error":
|
||||
raise ConnectionError("verification unavailable")
|
||||
return {"state": True, "data": {
|
||||
"file_id": "200", "file_category": "1", "file_name": local_file.name,
|
||||
"size_byte": 5, "sha1": "sha1",
|
||||
}}
|
||||
return _fake_request_api(method, endpoint, *args, **kwargs)
|
||||
|
||||
storage = _build_storage()
|
||||
storage._request_api = request_api
|
||||
complete = Mock()
|
||||
if response_kind == "exception":
|
||||
complete.side_effect = ServerError(203, {}, b"", details={"Code": "CallbackFailed"})
|
||||
else:
|
||||
response = SimpleNamespace(json=Mock(side_effect=ValueError("XML CallbackFailed")))
|
||||
complete.return_value = SimpleNamespace(status=203, resp=SimpleNamespace(response=response))
|
||||
monkeypatch.setattr(_FakeBucket, "complete_multipart_upload", complete)
|
||||
|
||||
if response_kind == "query_error":
|
||||
with pytest.raises(StorageOperationUncertainError, match="verification unavailable"):
|
||||
_upload_with_fakes(storage, _target_dir(), local_file)
|
||||
else:
|
||||
assert _upload_with_fakes(storage, _target_dir(), local_file).fileid == "200"
|
||||
complete.assert_called_once()
|
||||
assert local_file.read_bytes() == b"movie"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("complete_status", [201, 202, 204, 500])
|
||||
def test_upload_does_not_accept_arbitrary_completion_status(tmp_path, monkeypatch, complete_status):
|
||||
"""
|
||||
未约定的 OSS 完成状态不能按通用 2xx 规则视为上传成功。
|
||||
"""
|
||||
local_file = tmp_path / "episode.mkv"
|
||||
local_file.write_bytes(b"movie")
|
||||
monkeypatch.setattr(_FakeBucket, "complete_status", complete_status)
|
||||
assert _upload_with_fakes(_build_storage(), _target_dir(), local_file) is None
|
||||
assert local_file.exists()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("confirmed", [False, True])
|
||||
def test_callback_203_move_deletes_source_only_after_identity_verification(tmp_path, monkeypatch, confirmed):
|
||||
"""
|
||||
真实跨存储移动编排必须等 203 的远端身份核验成功后才删除源文件。
|
||||
"""
|
||||
local_file = tmp_path / "episode.mkv"
|
||||
local_file.write_bytes(b"movie")
|
||||
target_dir = _target_dir()
|
||||
target_path = Path(target_dir.path) / local_file.name
|
||||
info = {
|
||||
"file_id": "200", "file_category": "1", "file_name": local_file.name,
|
||||
"size_byte": 5, "sha1": "sha1", "pick_code": "pickcode", "utime": 1,
|
||||
}
|
||||
calls = []
|
||||
|
||||
def request_api(method, endpoint, *args, **kwargs):
|
||||
"""
|
||||
在真实 115 API 边界分别模拟目标可核验与仍不可见。
|
||||
"""
|
||||
calls.append(endpoint)
|
||||
if endpoint == "/open/folder/get_info":
|
||||
return {"state": True, "data": info if confirmed else None}
|
||||
return _fake_request_api(method, endpoint, *args, **kwargs)
|
||||
|
||||
storage = _build_storage()
|
||||
storage._request_api = request_api
|
||||
storage.get_folder = lambda _path: target_dir
|
||||
local = object.__new__(LocalStorage)
|
||||
source = local.get_item_strict(local_file)
|
||||
monkeypatch.setattr(_FakeBucket, "complete_status", 203)
|
||||
with patch("oss2.StsAuth", return_value=object()), patch("oss2.Bucket", _FakeBucket), patch(
|
||||
"app.modules.filemanager.storages.u115.transfer_process", return_value=lambda _progress: None,
|
||||
):
|
||||
if not confirmed:
|
||||
with pytest.raises(StorageOperationUncertainError, match="禁止自动重传"):
|
||||
TransHandler._TransHandler__execute_transfer_with_steps(
|
||||
step_runner=None, source_fileitem=source.model_dump(mode="json"),
|
||||
target_storage="u115", source_oper=local, target_oper=storage,
|
||||
target_file=target_path, transfer_type="move",
|
||||
)
|
||||
assert local_file.read_bytes() == b"movie"
|
||||
else:
|
||||
item, error = TransHandler._TransHandler__execute_transfer_with_steps(
|
||||
step_runner=None, source_fileitem=source.model_dump(mode="json"),
|
||||
target_storage="u115", source_oper=local, target_oper=storage,
|
||||
target_file=target_path, transfer_type="move",
|
||||
)
|
||||
assert error == "" and item.fileid == "200"
|
||||
assert not local_file.exists()
|
||||
assert calls.count("/open/upload/init") == 1
|
||||
|
||||
|
||||
def test_upload_uses_dynamic_part_size(tmp_path):
|
||||
|
||||
Reference in New Issue
Block a user