diff --git a/UPGRADE.md b/UPGRADE.md index 45f4bbe..aa5b1c1 100644 --- a/UPGRADE.md +++ b/UPGRADE.md @@ -309,3 +309,40 @@ WebDAV 保持 legacy 路径。新模式仍支持重试、续传、取消、配 `/root/backups/filecodebox-test-upload-20261006-020407`。 - 正式前端合并提交 `b67d36d8a0d1f337983b5fba2eb45bde7ab7200a`; 后端合入 master 并推送后独立构建正式镜像,不复用测试镜像标签。 + +## CloudDrive 原生分片写入(2026-10-06) + +- 配置 `FCB_CLOUDDRIVE_ADDRESS`、`FCB_CLOUDDRIVE_TOKEN` 和 `FCB_CLOUDDRIVE_ROOT` + 后,新 WebDAV 分片会话使用 `clouddrive-native`。三项必须齐全;不把令牌放入 + 公共配置或前端。令牌根目录必须与 WebDAV 用户根目录相同。 +- 浏览器仍按 chunkSizeMB(默认 90 MiB)上传;后端拆为 1 MiB gRPC WriteToFile, + 写入同一个打开的 upload.bin,所有分片完成后才 CloseFile。CD 单消息限制 + 4 MiB,包含 protobuf 字段,不能把整个 90 MiB 分片作为一个 RPC。 +- 文件句柄和关闭状态保存在现有 KeyValue 中,支持 FileCodeBox 重启及丢失创建、 + 写入、关闭响应后的恢复;按原偏移重试不会追加重复数据。CD 重启导致句柄失效时 + 明确拒绝继续写入,要求取消后重新上传,不能重建文件后假装已接收分片仍存在。 +- 完成仍逐分片核对 SHA-256、完整长度和完整 SHA-256,再 MOVE 发布, + 不读取所有独立分片并 PUT 整文件。取消、过期及重复完成统一关闭句柄、 + 清理临时对象和状态;远端写入完成前取消清理会等待,保护已发布文件。 +- 老的 stream/offset/legacy 会话继续原流程。不配置原生上传时新会话仍用 stream; + 活动原生会话存在时不能删除原生配置或回滚到不识别该协议的镜像。 +- 使用 `core/clouddrive.proto` 的官方 1.1.1 兼容子集和生成客户端; + 生成命令为 `python -m grpc_tools.protoc -I . --python_out=. --grpc_python_out=. core/clouddrive.proto`, + 运行依赖固定 grpcio 1.80.0 和 protobuf 6.33.6。 +- 真实 CD 1.1.1 专用令牌及文件句柄验证通过;测试、生产令牌分别限定 + `/123云盘/WebDAV/filecodebox-test` 和 `/123云盘/WebDAV/filecodebox`,只给上传、 + 读取及运行信息权限,不给令牌管理权限;配置保存在服务器 `.clouddrive.env`。 +- Python 3.12 部署镜像内 195 项单元/集成及 24 个子场景通过,总覆盖率 63%, + 原生上传模块 94%。包含真实 gRPC/HTTP DAV、90 MiB 拆分、响应丢失、句柄失效、 + 取消写入竞争、过期清理、旧会话兼容及完整内容校验。服务器配置、令牌不入库。 + 本机 Python 3.9 无法安装当前 aiohttp 固定版本,验证使用与生产一致的容器环境。 +- 测试分支 a887a8a 先推送,再构建部署;前端保持 main b67d36d(本轮未改前端)。 + 镜像构建及本地前端 79 项和覆盖率检查通过;Node 原生覆盖率不包含 Vite SSR 动态模块。 +- 测试站真实首片写入后重启 FileCodeBox,再续传、重传首片、完成、下载校验及清理通过; + 另一个半成品取消清理通过。已发布文件及旧协议兼容由集成测试覆盖。 +- 浏览器真实上传 BNApp64.apk(327728669 字节)使用四个 HTTP 分片:90/90/90/42.55 MiB, + 总耗时 213.998 秒,完成阶段 9.408 秒。本轮公网传输约 204 秒,不以 SSH 测速替代。 + 取件码成功展示;数据库和完整下载 SHA-256 均与本地一致,验收副本彻底清理。 +- 测试部署备份 `/root/backups/filecodebox-test-upload-20261006-141857`; + 原生凭据仅位于服务器 `.clouddrive.env`,Compose 通过 env_file 引用,升级备份包含该文件。 +- 后端合入 master 并推送后从正式提交重新构建生产镜像;前端无需再次合并无变更代码。 diff --git a/apps/base/views.py b/apps/base/views.py index 72b6db8..43364fa 100644 --- a/apps/base/views.py +++ b/apps/base/views.py @@ -576,7 +576,7 @@ async def upload_chunk( existing_chunk = await UploadChunk.filter( upload_id=upload_id, chunk_index=chunk_index, completed=True ).first() - if existing_chunk and chunk_info.storage_mode not in {"webdav-offset", "webdav-stream"}: + if existing_chunk and chunk_info.storage_mode not in {"webdav-offset", "webdav-stream", "clouddrive-native"}: return APIResponse( detail={"chunk_hash": existing_chunk.chunk_hash, "skipped": True} ) @@ -610,7 +610,7 @@ async def upload_chunk( expected_size = min(chunk_info.chunk_size, chunk_info.file_size-chunk_index*chunk_info.chunk_size) if chunk_size != expected_size: raise HTTPException(400, "分片大小与声明值不一致") - if chunk_info.storage_mode in {"webdav-offset", "webdav-stream"}: + if chunk_info.storage_mode in {"webdav-offset", "webdav-stream", "clouddrive-native"}: if existing_chunk: if existing_chunk.chunk_hash != chunk_hash: raise HTTPException(409, "重传分片内容不一致") @@ -709,7 +709,7 @@ async def _cancel_upload(upload_id): try: await storage.clean_chunks(upload_id, save_path) except Exception as e: - if chunk_info.storage_mode in {"webdav-offset", "webdav-stream"}: + if chunk_info.storage_mode in {"webdav-offset", "webdav-stream", "clouddrive-native"}: raise pass @@ -762,7 +762,7 @@ async def complete_upload( info = await UploadChunk.filter(upload_id=upload_id, chunk_index=-1).first() if is_cancelling(upload_id): raise HTTPException(409, "上传正在取消") - if info is None or info.storage_mode not in {"webdav-offset", "webdav-stream"}: + if info is None or info.storage_mode not in {"webdav-offset", "webdav-stream", "clouddrive-native"}: return await _complete_upload(upload_id, data, ip) task = completion_task(upload_id) if task is None: @@ -808,7 +808,7 @@ async def _complete_upload(upload_id, data, ip): try: await storage.clean_chunks(upload_id, save_path) except Exception: - if chunk_info.storage_mode in {"webdav-offset", "webdav-stream"}: + if chunk_info.storage_mode in {"webdav-offset", "webdav-stream", "clouddrive-native"}: raise pass await UploadChunk.filter(upload_id=upload_id).delete() @@ -857,7 +857,7 @@ async def _complete_upload(upload_id, data, ip): except HTTPException: raise except Exception as e: - if chunk_info.storage_mode in {"webdav-offset", "webdav-stream"}: + if chunk_info.storage_mode in {"webdav-offset", "webdav-stream", "clouddrive-native"}: raise HTTPException(500, "上传完成状态保存失败,请重试完成上传") from e # 合并失败时清理临时文件 try: diff --git a/core/clouddrive.proto b/core/clouddrive.proto new file mode 100644 index 0000000..2c4b99d --- /dev/null +++ b/core/clouddrive.proto @@ -0,0 +1,21 @@ +// Wire-compatible subset of CloudDrive 1.1.1's public API. +// Source: https://www.clouddrive2.com/api/clouddrive.proto +syntax = "proto3"; +package clouddrive; +service CloudDriveFileSrv { + rpc GetOpenFileTable(GetOpenFileTableRequest) returns (OpenFileTable) {} + rpc CreateFile(CreateFileRequest) returns (CreateFileResult) {} + rpc WriteToFile(WriteFileRequest) returns (WriteFileResult) {} + rpc CloseFile(CloseFileRequest) returns (FileOperationResult) {} +} +message GetOpenFileTableRequest { bool includeDir = 1; } +message OpenFileTable { map openFileTable = 1; uint64 localOpenFileCount = 2; } +message CreateFileRequest { string parentPath = 1; string fileName = 2; } +message CreateFileResult { uint64 fileHandle = 1; } +message WriteFileRequest { + uint64 fileHandle = 1; uint64 startPos = 2; uint64 length = 3; + bytes buffer = 4; bool closeFile = 5; +} +message WriteFileResult { uint64 bytesWritten = 1; } +message CloseFileRequest { uint64 fileHandle = 1; } +message FileOperationResult { bool success = 1; string errorMessage = 2; repeated string resultFilePaths = 3; } diff --git a/core/clouddrive_pb2.py b/core/clouddrive_pb2.py new file mode 100644 index 0000000..c6c4eec --- /dev/null +++ b/core/clouddrive_pb2.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# NO CHECKED-IN PROTOBUF GENCODE +# source: core/clouddrive.proto +# Protobuf Python Version: 6.31.1 +"""Generated protocol buffer code.""" +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import runtime_version as _runtime_version +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder +_runtime_version.ValidateProtobufRuntimeVersion( + _runtime_version.Domain.PUBLIC, + 6, + 31, + 1, + '', + 'core/clouddrive.proto' +) +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x15\x63ore/clouddrive.proto\x12\nclouddrive\"-\n\x17GetOpenFileTableRequest\x12\x12\n\nincludeDir\x18\x01 \x01(\x08\"\xa6\x01\n\rOpenFileTable\x12\x43\n\ropenFileTable\x18\x01 \x03(\x0b\x32,.clouddrive.OpenFileTable.OpenFileTableEntry\x12\x1a\n\x12localOpenFileCount\x18\x02 \x01(\x04\x1a\x34\n\x12OpenFileTableEntry\x12\x0b\n\x03key\x18\x01 \x01(\x04\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"9\n\x11\x43reateFileRequest\x12\x12\n\nparentPath\x18\x01 \x01(\t\x12\x10\n\x08\x66ileName\x18\x02 \x01(\t\"&\n\x10\x43reateFileResult\x12\x12\n\nfileHandle\x18\x01 \x01(\x04\"k\n\x10WriteFileRequest\x12\x12\n\nfileHandle\x18\x01 \x01(\x04\x12\x10\n\x08startPos\x18\x02 \x01(\x04\x12\x0e\n\x06length\x18\x03 \x01(\x04\x12\x0e\n\x06\x62uffer\x18\x04 \x01(\x0c\x12\x11\n\tcloseFile\x18\x05 \x01(\x08\"\'\n\x0fWriteFileResult\x12\x14\n\x0c\x62ytesWritten\x18\x01 \x01(\x04\"&\n\x10\x43loseFileRequest\x12\x12\n\nfileHandle\x18\x01 \x01(\x04\"U\n\x13\x46ileOperationResult\x12\x0f\n\x07success\x18\x01 \x01(\x08\x12\x14\n\x0c\x65rrorMessage\x18\x02 \x01(\t\x12\x17\n\x0fresultFilePaths\x18\x03 \x03(\t2\xd0\x02\n\x11\x43loudDriveFileSrv\x12T\n\x10GetOpenFileTable\x12#.clouddrive.GetOpenFileTableRequest\x1a\x19.clouddrive.OpenFileTable\"\x00\x12K\n\nCreateFile\x12\x1d.clouddrive.CreateFileRequest\x1a\x1c.clouddrive.CreateFileResult\"\x00\x12J\n\x0bWriteToFile\x12\x1c.clouddrive.WriteFileRequest\x1a\x1b.clouddrive.WriteFileResult\"\x00\x12L\n\tCloseFile\x12\x1c.clouddrive.CloseFileRequest\x1a\x1f.clouddrive.FileOperationResult\"\x00\x62\x06proto3') + +_globals = globals() +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'core.clouddrive_pb2', _globals) +if not _descriptor._USE_C_DESCRIPTORS: + DESCRIPTOR._loaded_options = None + _globals['_OPENFILETABLE_OPENFILETABLEENTRY']._loaded_options = None + _globals['_OPENFILETABLE_OPENFILETABLEENTRY']._serialized_options = b'8\001' + _globals['_GETOPENFILETABLEREQUEST']._serialized_start=37 + _globals['_GETOPENFILETABLEREQUEST']._serialized_end=82 + _globals['_OPENFILETABLE']._serialized_start=85 + _globals['_OPENFILETABLE']._serialized_end=251 + _globals['_OPENFILETABLE_OPENFILETABLEENTRY']._serialized_start=199 + _globals['_OPENFILETABLE_OPENFILETABLEENTRY']._serialized_end=251 + _globals['_CREATEFILEREQUEST']._serialized_start=253 + _globals['_CREATEFILEREQUEST']._serialized_end=310 + _globals['_CREATEFILERESULT']._serialized_start=312 + _globals['_CREATEFILERESULT']._serialized_end=350 + _globals['_WRITEFILEREQUEST']._serialized_start=352 + _globals['_WRITEFILEREQUEST']._serialized_end=459 + _globals['_WRITEFILERESULT']._serialized_start=461 + _globals['_WRITEFILERESULT']._serialized_end=500 + _globals['_CLOSEFILEREQUEST']._serialized_start=502 + _globals['_CLOSEFILEREQUEST']._serialized_end=540 + _globals['_FILEOPERATIONRESULT']._serialized_start=542 + _globals['_FILEOPERATIONRESULT']._serialized_end=627 + _globals['_CLOUDDRIVEFILESRV']._serialized_start=630 + _globals['_CLOUDDRIVEFILESRV']._serialized_end=966 +# @@protoc_insertion_point(module_scope) diff --git a/core/clouddrive_pb2_grpc.py b/core/clouddrive_pb2_grpc.py new file mode 100644 index 0000000..b9bbf1b --- /dev/null +++ b/core/clouddrive_pb2_grpc.py @@ -0,0 +1,226 @@ +# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! +"""Client and server classes corresponding to protobuf-defined services.""" +import grpc +import warnings + +from core import clouddrive_pb2 as core_dot_clouddrive__pb2 + +GRPC_GENERATED_VERSION = '1.80.0' +GRPC_VERSION = grpc.__version__ +_version_not_supported = False + +try: + from grpc._utilities import first_version_is_lower + _version_not_supported = first_version_is_lower(GRPC_VERSION, GRPC_GENERATED_VERSION) +except ImportError: + _version_not_supported = True + +if _version_not_supported: + raise RuntimeError( + f'The grpc package installed is at version {GRPC_VERSION},' + + ' but the generated code in core/clouddrive_pb2_grpc.py depends on' + + f' grpcio>={GRPC_GENERATED_VERSION}.' + + f' Please upgrade your grpc module to grpcio>={GRPC_GENERATED_VERSION}' + + f' or downgrade your generated code using grpcio-tools<={GRPC_VERSION}.' + ) + + +class CloudDriveFileSrvStub(object): + """Missing associated documentation comment in .proto file.""" + + def __init__(self, channel): + """Constructor. + + Args: + channel: A grpc.Channel. + """ + self.GetOpenFileTable = channel.unary_unary( + '/clouddrive.CloudDriveFileSrv/GetOpenFileTable', + request_serializer=core_dot_clouddrive__pb2.GetOpenFileTableRequest.SerializeToString, + response_deserializer=core_dot_clouddrive__pb2.OpenFileTable.FromString, + _registered_method=True) + self.CreateFile = channel.unary_unary( + '/clouddrive.CloudDriveFileSrv/CreateFile', + request_serializer=core_dot_clouddrive__pb2.CreateFileRequest.SerializeToString, + response_deserializer=core_dot_clouddrive__pb2.CreateFileResult.FromString, + _registered_method=True) + self.WriteToFile = channel.unary_unary( + '/clouddrive.CloudDriveFileSrv/WriteToFile', + request_serializer=core_dot_clouddrive__pb2.WriteFileRequest.SerializeToString, + response_deserializer=core_dot_clouddrive__pb2.WriteFileResult.FromString, + _registered_method=True) + self.CloseFile = channel.unary_unary( + '/clouddrive.CloudDriveFileSrv/CloseFile', + request_serializer=core_dot_clouddrive__pb2.CloseFileRequest.SerializeToString, + response_deserializer=core_dot_clouddrive__pb2.FileOperationResult.FromString, + _registered_method=True) + + +class CloudDriveFileSrvServicer(object): + """Missing associated documentation comment in .proto file.""" + + def GetOpenFileTable(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def CreateFile(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def WriteToFile(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def CloseFile(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + +def add_CloudDriveFileSrvServicer_to_server(servicer, server): + rpc_method_handlers = { + 'GetOpenFileTable': grpc.unary_unary_rpc_method_handler( + servicer.GetOpenFileTable, + request_deserializer=core_dot_clouddrive__pb2.GetOpenFileTableRequest.FromString, + response_serializer=core_dot_clouddrive__pb2.OpenFileTable.SerializeToString, + ), + 'CreateFile': grpc.unary_unary_rpc_method_handler( + servicer.CreateFile, + request_deserializer=core_dot_clouddrive__pb2.CreateFileRequest.FromString, + response_serializer=core_dot_clouddrive__pb2.CreateFileResult.SerializeToString, + ), + 'WriteToFile': grpc.unary_unary_rpc_method_handler( + servicer.WriteToFile, + request_deserializer=core_dot_clouddrive__pb2.WriteFileRequest.FromString, + response_serializer=core_dot_clouddrive__pb2.WriteFileResult.SerializeToString, + ), + 'CloseFile': grpc.unary_unary_rpc_method_handler( + servicer.CloseFile, + request_deserializer=core_dot_clouddrive__pb2.CloseFileRequest.FromString, + response_serializer=core_dot_clouddrive__pb2.FileOperationResult.SerializeToString, + ), + } + generic_handler = grpc.method_handlers_generic_handler( + 'clouddrive.CloudDriveFileSrv', rpc_method_handlers) + server.add_generic_rpc_handlers((generic_handler,)) + server.add_registered_method_handlers('clouddrive.CloudDriveFileSrv', rpc_method_handlers) + + + # This class is part of an EXPERIMENTAL API. +class CloudDriveFileSrv(object): + """Missing associated documentation comment in .proto file.""" + + @staticmethod + def GetOpenFileTable(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary( + request, + target, + '/clouddrive.CloudDriveFileSrv/GetOpenFileTable', + core_dot_clouddrive__pb2.GetOpenFileTableRequest.SerializeToString, + core_dot_clouddrive__pb2.OpenFileTable.FromString, + options, + channel_credentials, + insecure, + call_credentials, + compression, + wait_for_ready, + timeout, + metadata, + _registered_method=True) + + @staticmethod + def CreateFile(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary( + request, + target, + '/clouddrive.CloudDriveFileSrv/CreateFile', + core_dot_clouddrive__pb2.CreateFileRequest.SerializeToString, + core_dot_clouddrive__pb2.CreateFileResult.FromString, + options, + channel_credentials, + insecure, + call_credentials, + compression, + wait_for_ready, + timeout, + metadata, + _registered_method=True) + + @staticmethod + def WriteToFile(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary( + request, + target, + '/clouddrive.CloudDriveFileSrv/WriteToFile', + core_dot_clouddrive__pb2.WriteFileRequest.SerializeToString, + core_dot_clouddrive__pb2.WriteFileResult.FromString, + options, + channel_credentials, + insecure, + call_credentials, + compression, + wait_for_ready, + timeout, + metadata, + _registered_method=True) + + @staticmethod + def CloseFile(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary( + request, + target, + '/clouddrive.CloudDriveFileSrv/CloseFile', + core_dot_clouddrive__pb2.CloseFileRequest.SerializeToString, + core_dot_clouddrive__pb2.FileOperationResult.FromString, + options, + channel_credentials, + insecure, + call_credentials, + compression, + wait_for_ready, + timeout, + metadata, + _registered_method=True) diff --git a/core/clouddrive_upload.py b/core/clouddrive_upload.py new file mode 100644 index 0000000..3010550 --- /dev/null +++ b/core/clouddrive_upload.py @@ -0,0 +1,174 @@ +"""Write HTTP chunks into one open CloudDrive file, closing only at completion.""" +import asyncio +import os +import json +import re +from contextlib import asynccontextmanager +from pathlib import PurePosixPath + +import aiohttp +import grpc +from fastapi import HTTPException + +from apps.base.models import KeyValue, UploadChunk +from core import clouddrive_pb2 as pb +from core.clouddrive_pb2_grpc import CloudDriveFileSrvStub +from core.webdav_chunks import OFFSET_TIMEOUT + +NATIVE_MODE = 'clouddrive-native' +RPC_BLOCK_SIZE = 1024 * 1024 # CD limits decoded messages to 4 MiB, including protobuf. + + +def native_configured(): + address = os.environ.get('FCB_CLOUDDRIVE_ADDRESS', '') + token = os.environ.get('FCB_CLOUDDRIVE_TOKEN', '') + root = os.environ.get('FCB_CLOUDDRIVE_ROOT', '') + if any((address, token, root)) and not all((address, token, root)): + raise HTTPException(503, 'CloudDrive 原生上传配置不完整') + return bool(address and token and root) + + +async def settle(coroutine): + """Let an in-flight remote mutation settle before cancellation can clean it.""" + task = asyncio.create_task(coroutine) + try: + return await asyncio.shield(task) + except asyncio.CancelledError: + await task + raise + + +class NativeClient: + def __init__(self, stub, token): + self.stub = stub + self.metadata = [('authorization', 'Bearer ' + token)] + + async def call(self, method, request): + try: + return await getattr(self.stub, method)(request, metadata=self.metadata, timeout=30) + except grpc.RpcError as exc: + # Never expose token or remote diagnostic details in public errors. + raise HTTPException(503, 'CloudDrive 原生上传连接失败,请重试') from exc + + +class CloudDriveUploadMixin: + @asynccontextmanager + async def _native_client(self): + if not native_configured(): + raise HTTPException(503, 'CloudDrive 原生上传配置不可用,请恢复配置后重试') + channel = grpc.aio.insecure_channel(os.environ['FCB_CLOUDDRIVE_ADDRESS']) + try: + yield NativeClient(CloudDriveFileSrvStub(channel), os.environ['FCB_CLOUDDRIVE_TOKEN']) + finally: + await channel.close() + + async def _native_session(self, upload_id): + return await UploadChunk.filter(upload_id=upload_id, chunk_index=-1, storage_mode=NATIVE_MODE).first() + + def _native_state_key(self, upload_id): + return 'clouddrive-upload:' + upload_id + + async def _native_handles(self, client, path): + # Tokens must be scoped to the same root as this adapter's WebDAV user. + target = str(PurePosixPath(os.environ['FCB_CLOUDDRIVE_ROOT']) / path.lstrip('/')) + table = await client.call('GetOpenFileTable', pb.GetOpenFileTableRequest()) + handles = set() + for handle, description in table.openFileTable.items(): + # CD 1.1.1 returns Rust debug text, not only the file path. + match = re.search(r'\bpath:("(?:[^"\\]|\\.)*")$', description) + file_path = json.loads(match.group(1)) if match else description + if str(PurePosixPath(file_path)) == target: + handles.add(handle) + return handles + + async def save_native_chunk(self, info, index, data): + expected = min(info.chunk_size, info.file_size - index * info.chunk_size) + if len(data) != expected: + raise HTTPException(400, '分片大小与声明值不一致') + if await UploadChunk.filter(upload_id=info.upload_id, completed=True, chunk_index__lt=index).count() != index: + raise HTTPException(409, '请先上传前面的分片,再重试当前分片') + path = self._offset_path(info.upload_id, info.save_path) + async with self._native_client() as client: + state = await KeyValue.filter(key=self._native_state_key(info.upload_id)).first() + handles = await self._native_handles(client, path) + if state: + if state.value['closed']: + raise HTTPException(409, '文件已进入校验阶段,请重试完成上传') + handle = int(state.value['handle']) + if handle not in handles: + raise HTTPException(409, 'CloudDrive 文件句柄已失效,请取消后重新上传') + else: + if not handles and await UploadChunk.filter(upload_id=info.upload_id, completed=True).exists(): + raise HTTPException(409, 'CloudDrive 上传状态已失效,请取消后重新上传') + if len(handles) > 1: + raise HTTPException(503, 'CloudDrive 上传句柄异常,请重试') + # Recover a CreateFile reply/DB acknowledgement lost in transit. + async def create(): + if handles: + handle = next(iter(handles)) + else: + await self._mkdir_p(str(PurePosixPath(path).parent)) + result = await client.call('CreateFile', pb.CreateFileRequest( + parentPath='/' + str(PurePosixPath(path).parent), fileName=PurePosixPath(path).name)) + handle = result.fileHandle + if not handle: + raise HTTPException(503, 'CloudDrive 创建上传文件失败,请重试') + await KeyValue.update_or_create(key=self._native_state_key(info.upload_id), + defaults={'value': {'handle': str(handle), 'closed': False}}) + return handle + handle = await settle(create()) + + async def write(): + start = index * info.chunk_size + for offset in range(0, len(data), RPC_BLOCK_SIZE): + block = data[offset:offset + RPC_BLOCK_SIZE] + result = await client.call('WriteToFile', pb.WriteFileRequest( + fileHandle=handle, startPos=start + offset, length=len(block), buffer=block, closeFile=False)) + if result.bytesWritten != len(block): + raise HTTPException(503, 'CloudDrive 分片写入不完整,请重试') + await settle(write()) + + async def _close_native(self, client, upload_id, path): + state = await KeyValue.filter(key=self._native_state_key(upload_id)).first() + handles = await self._native_handles(client, path) + if state and state.value['closed']: + return + if state: + expected = int(state.value['handle']) + handles = handles & {expected} + # A missing handle can mean CloseFile succeeded but its reply was lost, + # or CD restarted. Full verification below must still prove every byte. + async def close(): + for handle in handles: + result = await client.call('CloseFile', pb.CloseFileRequest(fileHandle=handle)) + if not result.success: + raise HTTPException(503, 'CloudDrive 关闭上传文件失败,请重试') + if state: + state.value = {**state.value, 'closed': True} + await state.save(update_fields=['value']) + await settle(close()) + + async def finish_native_upload(self, info, save_path): + records = await UploadChunk.filter(upload_id=info.upload_id, completed=True).order_by('chunk_index') + if [r.chunk_index for r in records] != list(range(info.total_chunks)): + raise ValueError('分片不完整') + staging = self._offset_path(info.upload_id, save_path) + async with self._native_client() as native: + await self._close_native(native, info.upload_id, staging) + async with aiohttp.ClientSession(auth=self.auth, timeout=OFFSET_TIMEOUT) as client: + # Verify the published file first to recover a lost MOVE reply. + digest = await self._verify_stream_file(client, save_path, info, records) + if digest is not None: + return save_path, digest + digest = await self._verify_stream_file(client, staging, info, records) + if digest is None: + raise ValueError('CloudDrive 上传文件不存在,请取消后重新上传') + await settle(self._publish_offset(client, staging, save_path)) + return save_path, digest + + async def clean_native_upload(self, upload_id, save_path): + staging = self._offset_path(upload_id, save_path) + async with self._native_client() as client: + await self._close_native(client, upload_id, staging) + await self.clean_offset_upload(upload_id, save_path) + await KeyValue.filter(key=self._native_state_key(upload_id)).delete() diff --git a/core/storage.py b/core/storage.py index 257e236..8717fbf 100644 --- a/core/storage.py +++ b/core/storage.py @@ -20,6 +20,7 @@ import re import aioboto3 from botocore.config import Config from fastapi import HTTPException, Response, UploadFile +from core.clouddrive_upload import CloudDriveUploadMixin from core.response import APIResponse from core.settings import data_root, settings from apps.base.models import FileCodes, UploadChunk @@ -1064,7 +1065,7 @@ from core.webdav_chunks import WebDAVOffsetMixin from core.webdav_stream import WebDAVStreamMixin -class WebDAVFileStorage(WebDAVStreamMixin, WebDAVOffsetMixin, FileStorageInterface): +class WebDAVFileStorage(CloudDriveUploadMixin, WebDAVStreamMixin, WebDAVOffsetMixin, FileStorageInterface): _instance: Optional["WebDAVFileStorage"] = None def __init__(self): @@ -1248,6 +1249,9 @@ class WebDAVFileStorage(WebDAVStreamMixin, WebDAVOffsetMixin, FileStorageInterfa async def save_chunk(self, upload_id: str, chunk_index: int, chunk_data: bytes, chunk_hash: str, save_path: str): """保存分片到 WebDAV""" + native = await self._native_session(upload_id) + if native is not None: + return await self.save_native_chunk(native, chunk_index, chunk_data) stream = await self._stream_session(upload_id) if stream is not None: return await self.save_stream_chunk(stream, chunk_index, chunk_data, chunk_hash) @@ -1275,6 +1279,8 @@ class WebDAVFileStorage(WebDAVStreamMixin, WebDAVOffsetMixin, FileStorageInterfa 合并 WebDAV 上的分片文件 使用临时文件避免内存问题 """ + if chunk_info.storage_mode == "clouddrive-native": + return await self.finish_native_upload(chunk_info, save_path) if chunk_info.storage_mode == "webdav-stream": return await self.finish_stream_upload(chunk_info, save_path) if chunk_info.storage_mode == "webdav-offset": @@ -1350,6 +1356,8 @@ class WebDAVFileStorage(WebDAVStreamMixin, WebDAVOffsetMixin, FileStorageInterfa :param upload_id: 上传会话ID :param save_path: 文件保存路径 """ + if await self._native_session(upload_id) is not None: + return await self.clean_native_upload(upload_id, save_path) if await self._stream_session(upload_id) is not None: return await self.clean_stream_upload(upload_id, save_path) if await self._offset_session(upload_id) is not None: diff --git a/core/webdav_chunks.py b/core/webdav_chunks.py index 9e44781..4f581d6 100644 --- a/core/webdav_chunks.py +++ b/core/webdav_chunks.py @@ -18,7 +18,8 @@ class WebDAVOffsetMixin: return str(PurePosixPath(save_path).parent / 'chunks' / upload_id / 'upload.bin') async def chunk_upload_mode(self): - return "webdav-stream" + from core.clouddrive_upload import native_configured, NATIVE_MODE + return NATIVE_MODE if native_configured() else "webdav-stream" async def offset_upload_mode(self): async with aiohttp.ClientSession(auth=self.auth, timeout=OFFSET_TIMEOUT) as client: diff --git a/requirements.txt b/requirements.txt index 1e572e6..651039e 100644 --- a/requirements.txt +++ b/requirements.txt @@ -7,3 +7,5 @@ pydantic==2.12.5 uvicorn==0.51.0 tortoise-orm==0.25.3 python-multipart==0.0.32 +grpcio==1.80.0 +protobuf==6.33.6 diff --git a/tests/test_clouddrive_native_upload.py b/tests/test_clouddrive_native_upload.py new file mode 100644 index 0000000..9b8a0a2 --- /dev/null +++ b/tests/test_clouddrive_native_upload.py @@ -0,0 +1,251 @@ +"""FastAPI/SQLite + real gRPC and HTTP DAV tests for native upload recovery.""" +import asyncio +import hashlib +import json +import os +from unittest.mock import patch + +import grpc +from fastapi import HTTPException + +from apps.base.models import FileCodes, KeyValue, UploadChunk +from core import clouddrive_pb2 as pb +from core import clouddrive_pb2_grpc as rpc +from core.settings import settings +from tests.test_webdav_offset_upload import WebDAVFixture + + +class NativeService(rpc.CloudDriveFileSrvServicer): + def __init__(self, fixture): + self.fixture = fixture + self.handles = {} + self.serial = 0 + self.writes = [] + self.creates = 0 + self.fail_write = self.fail_create = self.fail_close = self.short_write = False + self.block_write = None + self.write_started = asyncio.Event() + + async def GetOpenFileTable(self, request, context): + if dict(context.invocation_metadata()).get('authorization') != 'Bearer test-native-token': + await context.abort(grpc.StatusCode.UNAUTHENTICATED, 'secret diagnostics') + return pb.OpenFileTable(openFileTable={handle: 'process: GRPC Client path:'+json.dumps(path) for handle,path in self.handles.items()}) + + async def CreateFile(self, request, context): + self.serial += 1; self.creates += 1 + path = '/dav' + request.parentPath + '/' + request.fileName + self.handles[self.serial] = path + self.fixture.files[path] = b'' + if self.fail_create: + self.fail_create = False + await context.abort(grpc.StatusCode.UNAVAILABLE, 'reply lost') + return pb.CreateFileResult(fileHandle=self.serial) + + async def WriteToFile(self, request, context): + self.write_started.set() + if self.block_write: await self.block_write.wait() + path = self.handles.get(request.fileHandle) + if path is None: await context.abort(grpc.StatusCode.NOT_FOUND, 'invalid handle') + self.writes.append((request.startPos, request.length, request.closeFile)) + data = bytearray(self.fixture.files[path]); end = request.startPos + request.length + data.extend(b'\0' * max(0, end - len(data))) + data[request.startPos:end] = request.buffer + self.fixture.files[path] = bytes(data) + if self.fail_write: + self.fail_write = False + await context.abort(grpc.StatusCode.UNAVAILABLE, 'reply lost') + if self.short_write: + self.short_write = False + return pb.WriteFileResult(bytesWritten=request.length - 1) + return pb.WriteFileResult(bytesWritten=request.length) + + async def CloseFile(self, request, context): + self.handles.pop(request.fileHandle, None) + if self.fail_close: + self.fail_close = False + await context.abort(grpc.StatusCode.UNAVAILABLE, 'reply lost') + return pb.FileOperationResult(success=True) + + +class NativeUploadTests(WebDAVFixture): + async def asyncSetUp(self): + await super().asyncSetUp() + self.grpc = grpc.aio.server() + self.native = NativeService(self) + rpc.add_CloudDriveFileSrvServicer_to_server(self.native, self.grpc) + port = self.grpc.add_insecure_port('127.0.0.1:0') + await self.grpc.start() + self.env = patch.dict(os.environ, {'FCB_CLOUDDRIVE_ADDRESS':f'127.0.0.1:{port}', + 'FCB_CLOUDDRIVE_TOKEN':'test-native-token', 'FCB_CLOUDDRIVE_ROOT':'/dav'}) + self.env.start() + + async def asyncTearDown(self): + await super().asyncTearDown() + self.env.stop() + await self.grpc.stop(0) + + async def test_roundtrip_uses_one_open_file_and_no_full_put(self): + uid = await self.upload_all() + info = await UploadChunk.get(upload_id=uid, chunk_index=-1) + self.assertEqual(info.storage_mode, 'clouddrive-native') + self.assertEqual(len(self.native.handles), 1) + done = await self.complete(uid) + self.assertEqual(done.status_code, 200, done.text) + self.assertEqual(list(self.files.values()), [self.payload]) + self.assertFalse(self.native.handles) + self.assertFalse(any(c[0] in ('PUT', 'PATCH') for c in self.calls)) + self.assertEqual(self.native.creates, 1) + record = await FileCodes.get(upload_id=uid) + self.assertEqual(record.file_hash, hashlib.sha256(self.payload).hexdigest()) + self.assertFalse(await KeyValue.filter(key='clouddrive-upload:'+uid).exists()) + self.assertTrue(all(not close for _, _, close in self.native.writes)) + + async def test_lost_create_reply_recovers_open_handle(self): + uid = await self.init(); self.native.fail_create = True + self.assertEqual((await self.chunk(uid,0)).status_code,503) + self.assertEqual((await self.chunk(uid,0)).status_code,200) + self.assertEqual(self.native.creates,1) + self.assertEqual(len(self.native.handles),1) + + async def test_lost_write_reply_rewrites_same_offset_without_duplication(self): + uid = await self.init(); self.native.fail_write = True + self.assertEqual((await self.chunk(uid,0)).status_code,503) + self.assertFalse(await UploadChunk.filter(upload_id=uid,completed=True).exists()) + self.assertEqual((await self.chunk(uid,0)).status_code,200) + for index in (1,2):self.assertEqual((await self.chunk(uid,index)).status_code,200) + done = await self.complete(uid);self.assertEqual(done.status_code,200,done.text) + self.assertEqual(list(self.files.values()),[self.payload]) + self.assertEqual(self.native.creates,1) + self.assertEqual(self.native.writes[0][:2],self.native.writes[1][:2]) + + async def test_short_write_is_not_marked_complete(self): + uid = await self.init();self.native.short_write=True + self.assertEqual((await self.chunk(uid,0)).status_code,503) + self.assertFalse(await UploadChunk.filter(upload_id=uid,completed=True).exists()) + self.assertEqual((await self.chunk(uid,0)).status_code,200) + + async def test_durable_handle_resumes_after_adapter_recreation(self): + uid = await self.init();self.assertEqual((await self.chunk(uid,0)).status_code,200) + # New channels/adapter calls recover state from SQLite, not Python memory. + state = await KeyValue.get(key='clouddrive-upload:'+uid) + self.assertEqual(int(state.value['handle']),next(iter(self.native.handles))) + for index in (1,2):self.assertEqual((await self.chunk(uid,index)).status_code,200) + done=await self.complete(uid);self.assertEqual(done.status_code,200,done.text) + self.assertEqual(self.native.creates,1) + + async def test_changed_retry_and_out_of_order_chunk_are_rejected(self): + uid=await self.init() + self.assertEqual((await self.chunk(uid,1)).status_code,409) + self.assertFalse(self.native.handles) + self.assertEqual((await self.chunk(uid,0)).status_code,200) + self.assertEqual((await self.chunk(uid,0,b'XXXXXXXX')).status_code,409) + self.assertEqual((await self.chunk(uid,0)).status_code,200) + self.assertEqual(len(self.native.writes),1) + + async def test_lost_close_and_move_replies_recover_without_new_upload(self): + uid=await self.upload_all();self.native.fail_close=True + self.assertEqual((await self.complete(uid)).status_code,503) + self.fail_move_reply=True + self.assertEqual((await self.complete(uid)).status_code,503) + done=await self.complete(uid);self.assertEqual(done.status_code,200,done.text) + self.assertEqual(list(self.files.values()),[self.payload]) + self.assertEqual(self.native.creates,1) + + async def test_corrupt_remote_file_is_not_published(self): + uid=await self.upload_all();path=next(iter(self.files));self.files[path]=b'X'*len(self.payload) + done=await self.complete(uid);self.assertEqual(done.status_code,400,done.text) + self.assertFalse(await FileCodes.all().exists()) + self.assertTrue(await KeyValue.filter(key='clouddrive-upload:'+uid).exists()) + cancel=await self.client.delete('/chunk/upload/'+uid);self.assertEqual(cancel.status_code,200) + self.assertFalse(self.files) + + async def test_cd_restart_does_not_silently_truncate_accepted_chunks(self): + uid=await self.init();await self.chunk(uid,0);self.native.handles.clear() + response=await self.chunk(uid,1);self.assertEqual(response.status_code,409) + self.assertEqual(self.native.creates,1) + self.assertEqual(list(self.files.values()),[self.payload[:8]]) + cancel=await self.client.delete('/chunk/upload/'+uid);self.assertEqual(cancel.status_code,200) + self.assertFalse(self.files) + + async def test_cancellation_closes_handle_and_preserves_published_file(self): + uid=await self.init();await self.chunk(uid,0) + cancel=await self.client.delete('/chunk/upload/'+uid);self.assertEqual(cancel.status_code,200) + self.assertFalse(self.native.handles);self.assertFalse(self.files) + self.assertFalse(await KeyValue.all().exists()) + uid=await self.upload_all();done=await self.complete(uid);self.assertEqual(done.status_code,200) + cancel=await self.client.delete('/chunk/upload/'+uid);self.assertEqual(cancel.status_code,200) + self.assertEqual(list(self.files.values()),[self.payload]) + + async def test_native_upload_does_not_change_old_stream_session(self): + uid=await self.init() + await UploadChunk.filter(upload_id=uid,chunk_index=-1).update(storage_mode='webdav-stream') + for index in range(3):self.assertEqual((await self.chunk(uid,index)).status_code,200) + done=await self.complete(uid);self.assertEqual(done.status_code,200,done.text) + self.assertEqual(self.native.creates,0) + self.assertTrue(any(c[0]=='PUT' for c in self.calls)) + + async def test_90mib_http_chunk_is_split_below_rpc_limit(self): + self.payload=b'a'*(90*1024*1024)+b'end' + settings.uploadSize=settings.storageLimit=len(self.payload)+1 + result=await self.client.post('/chunk/upload/init/',json={'file_name':'large.bin','file_size':len(self.payload), + 'chunk_size':90*1024*1024,'file_hash':hashlib.sha256(self.payload).hexdigest()}) + self.assertEqual(result.status_code,200,result.text);uid=result.json()['detail']['upload_id'] + for index in (0,1): + start=index*90*1024*1024 + result=await self.client.post(f'/chunk/upload/raw/{uid}/{index}',content=self.payload[start:start+90*1024*1024]) + self.assertEqual(result.status_code,200,result.text) + self.assertEqual(len(self.native.writes),91) + self.assertLessEqual(max(length for _,length,_ in self.native.writes),1024*1024) + self.assertEqual(list(self.files.values()),[self.payload]) + + async def test_cancellation_waits_for_inflight_write_before_cleanup(self): + uid=await self.init();self.native.block_write=asyncio.Event() + task=asyncio.create_task(self.chunk(uid,0));await self.native.write_started.wait() + task.cancel();await asyncio.sleep(0) + cancel=asyncio.create_task(self.client.delete('/chunk/upload/'+uid)) + await asyncio.sleep(.02);self.assertFalse(cancel.done()) + self.native.block_write.set() + await asyncio.gather(task,return_exceptions=True) + self.assertEqual((await cancel).status_code,200) + self.assertFalse(self.files);self.assertFalse(self.native.handles) + + async def test_transport_errors_are_sanitized(self): + os.environ['FCB_CLOUDDRIVE_TOKEN']='wrong-secret' + uid=await self.init();response=await self.chunk(uid,0) + self.assertEqual(response.status_code,503) + self.assertNotIn('wrong-secret',response.text) + self.assertNotIn('secret diagnostics',response.text) + + async def test_partial_configuration_does_not_silently_fallback(self): + from core.clouddrive_upload import native_configured + os.environ['FCB_CLOUDDRIVE_TOKEN']='' + with self.assertRaises(HTTPException):native_configured() + + async def test_missing_durable_state_never_recreates_over_accepted_chunks(self): + uid=await self.init();await self.chunk(uid,0) + await KeyValue.filter(key='clouddrive-upload:'+uid).delete();self.native.handles.clear() + response=await self.chunk(uid,1);self.assertEqual(response.status_code,409) + self.assertEqual(self.native.creates,1) + self.assertEqual(list(self.files.values()),[self.payload[:8]]) + + async def test_cleanup_failure_preserves_state_and_session_until_retry(self): + uid=await self.init();await self.chunk(uid,0);self.fail_delete=True + result=await self.client.delete('/chunk/upload/'+uid);self.assertEqual(result.status_code,503) + self.assertTrue(await KeyValue.filter(key='clouddrive-upload:'+uid).exists()) + self.assertTrue(await UploadChunk.filter(upload_id=uid).exists()) + self.fail_delete=False + result=await self.client.delete('/chunk/upload/'+uid);self.assertEqual(result.status_code,200) + self.assertFalse(await KeyValue.filter(key='clouddrive-upload:'+uid).exists()) + self.assertFalse(self.files) + + async def test_expiration_closes_handle_and_releases_quota(self): + import datetime + from core.tasks import clean_expired_chunk_session + from core.utils import get_now + from apps.base.models import StorageReservation + uid=await self.init();await self.chunk(uid,0) + now=await get_now();await UploadChunk.filter(upload_id=uid).update(created_at=now-datetime.timedelta(days=2)) + await clean_expired_chunk_session(uid,now-datetime.timedelta(days=1)) + self.assertFalse(self.native.handles);self.assertFalse(self.files) + self.assertFalse(await KeyValue.filter(key='clouddrive-upload:'+uid).exists()) + self.assertFalse(await StorageReservation.filter(token='chunk:'+uid).exists())