⚡️ perf: 使用 CloudDrive 原生分片写入避免整文件重传
* 保留 90MiB 浏览器分片并按 1MiB 原生请求写入同一文件 * 持久化文件句柄并恢复响应丢失、重复分片和完成状态 * 完整校验后发布,取消和过期清理等待远端写入结束 * 保持旧会话兼容并验证真实 gRPC 和 WebDAV 上传生命周期
This commit is contained in:
1 parent
2ba7bace02
commit
a887a8acd5
10 files changed
+774
-8
No files matched your search
@@ -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<uint64,string> 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; }
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
@@ -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()
|
||||
+9
-1
@@ -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:
|
||||
|
||||
@@ -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:
|
||||
|
||||
Reference in new issue
Block a user