* 保留 90MiB 浏览器分片并按 1MiB 原生请求写入同一文件 * 持久化文件句柄并恢复响应丢失、重复分片和完成状态 * 完整校验后发布,取消和过期清理等待远端写入结束 * 保持旧会话兼容并验证真实 gRPC 和 WebDAV 上传生命周期
175 lines
8.6 KiB
Python
175 lines
8.6 KiB
Python
"""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()
|