🔀 merge: 合并 WebDAV 偏移上传前端流程
This commit is contained in:
commit
da54bf40c9
10 files changed
+108
-12
No files matched your search
@@ -30,6 +30,7 @@ export function useSendFlow() {
|
||||
const showDrawer = ref(false)
|
||||
const selectedRecord = ref<SentFileRecord | null>(null)
|
||||
const isSubmitting = ref(false)
|
||||
const isFinalizing = ref(false)
|
||||
const fileHash = ref('')
|
||||
const sendRecords = computed(() => fileDataStore.shareData)
|
||||
const uploadDescription = computed(() =>
|
||||
@@ -63,6 +64,7 @@ export function useSendFlow() {
|
||||
onProgress: (progress) => {
|
||||
uploadProgress.value = progress
|
||||
},
|
||||
onFinalizing: () => { isFinalizing.value = true },
|
||||
onHashCalculated: (hash) => {
|
||||
fileHash.value = hash
|
||||
}
|
||||
@@ -284,6 +286,7 @@ export function useSendFlow() {
|
||||
} finally {
|
||||
uploadProgress.value = 0
|
||||
isSubmitting.value = false
|
||||
isFinalizing.value = false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -319,6 +322,7 @@ export function useSendFlow() {
|
||||
showDrawer,
|
||||
selectedRecord,
|
||||
isSubmitting,
|
||||
isFinalizing,
|
||||
sendRecords,
|
||||
uploadDescription,
|
||||
expirationOptions,
|
||||
|
||||
@@ -13,6 +13,7 @@ type UseSendSubmitOptions = {
|
||||
notify: (message: string, type: AlertType) => void
|
||||
translate: Translate
|
||||
onProgress: (progress: number) => void
|
||||
onFinalizing: () => void
|
||||
onHashCalculated: (hash: string) => void
|
||||
}
|
||||
|
||||
@@ -46,6 +47,7 @@ export function useSendSubmit(options: UseSendSubmitOptions) {
|
||||
expireValue,
|
||||
expireStyle,
|
||||
onHashCalculated: options.onHashCalculated,
|
||||
onFinalizing: options.onFinalizing,
|
||||
onProgress: (progress: UploadProgress) => {
|
||||
options.onProgress(progress.percentage)
|
||||
},
|
||||
|
||||
@@ -312,7 +312,7 @@ export default {
|
||||
status: {
|
||||
initializing: 'Preparing upload...',
|
||||
uploading: 'Uploading files...',
|
||||
confirming: 'Confirming upload...',
|
||||
confirming: 'Verifying file before creating a retrieval code…',
|
||||
success: 'Upload complete!'
|
||||
}
|
||||
},
|
||||
|
||||
@@ -312,7 +312,7 @@ export default {
|
||||
status: {
|
||||
initializing: '正在初始化上传...',
|
||||
uploading: '正在上传文件...',
|
||||
confirming: '正在确认上传...',
|
||||
confirming: '正在校验文件,完成后生成取件码…',
|
||||
success: '上传成功!'
|
||||
}
|
||||
},
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import type { ApiResponse } from '@/types'
|
||||
|
||||
export function isTransientCompletionError(error: unknown): boolean {
|
||||
const failure = error as { response?: { status?: number } }
|
||||
return !failure?.response || [408, 502, 503, 504].includes(failure.response.status || 0)
|
||||
}
|
||||
|
||||
export async function waitForUploadCompletion<T>(request: () => Promise<ApiResponse<T>>, onFinalizing?: () => void): Promise<ApiResponse<T>> {
|
||||
let announced = false, failures = 0
|
||||
while (true) {
|
||||
try {
|
||||
const response = await request()
|
||||
failures = 0
|
||||
if (response.code !== 202) return response
|
||||
if (!announced) { announced = true; onFinalizing?.() }
|
||||
} catch (error) {
|
||||
if (!isTransientCompletionError(error) || ++failures >= 4) throw error
|
||||
}
|
||||
await new Promise(resolve => setTimeout(resolve, Math.min(1000 * (failures || 1), 3000)))
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { FileService } from './file'
|
||||
import { waitForUploadCompletion, isTransientCompletionError } from './upload-completion'
|
||||
import type { ApiResponse, ChunkUploadInitResponse, FileUploadResponse, UploadProgress } from '@/types'
|
||||
import { calculateFileHash } from '@/utils/file-processing'
|
||||
|
||||
@@ -7,6 +8,7 @@ const CHUNK_SIZE = 5 * 1024 * 1024
|
||||
type ChunkedUploadOptions = {
|
||||
expireValue: number
|
||||
expireStyle: string
|
||||
onFinalizing?: () => void
|
||||
onHashCalculated?: (hash: string) => void
|
||||
onProgress?: (progress: UploadProgress) => void
|
||||
messages?: {
|
||||
@@ -18,6 +20,26 @@ type ChunkedUploadOptions = {
|
||||
|
||||
type ChunkedUploadResult = ChunkUploadInitResponse | FileUploadResponse
|
||||
|
||||
// Keep the completion session across a manual retry after a network failure.
|
||||
// The same File object is retained by the send form; no credentials are persisted.
|
||||
const pendingCompletion = new WeakMap<File, { uploadId: string; expireValue: number; expireStyle: string }>()
|
||||
|
||||
async function finishUpload(file: File, options: ChunkedUploadOptions): Promise<ApiResponse<ChunkedUploadResult>> {
|
||||
const session = pendingCompletion.get(file)!
|
||||
options.onFinalizing?.()
|
||||
try {
|
||||
const response = await waitForUploadCompletion(() => FileService.completeChunkUpload(session.uploadId, {
|
||||
expire_value: session.expireValue, expire_style: session.expireStyle
|
||||
}))
|
||||
if (response.code !== 200) throw new Error(options.messages?.completeFailed || 'Complete chunk upload failed')
|
||||
pendingCompletion.delete(file)
|
||||
return response
|
||||
} catch (error) {
|
||||
if (!isTransientCompletionError(error)) pendingCompletion.delete(file)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const calculateCompletedBytes = (uploadedChunks: Set<number>, chunkSize: number, fileSize: number) =>
|
||||
Array.from(uploadedChunks).reduce((total, index) => {
|
||||
const chunkStart = index * chunkSize
|
||||
@@ -29,6 +51,7 @@ export const uploadChunkedFile = async (
|
||||
file: File,
|
||||
options: ChunkedUploadOptions
|
||||
): Promise<ApiResponse<ChunkedUploadResult>> => {
|
||||
if (pendingCompletion.has(file)) return finishUpload(file, options)
|
||||
const fileHash = await calculateFileHash(file)
|
||||
options.onHashCalculated?.(fileHash)
|
||||
|
||||
@@ -84,14 +107,6 @@ export const uploadChunkedFile = async (
|
||||
uploadedChunks.add(index)
|
||||
}
|
||||
|
||||
const completeResponse = await FileService.completeChunkUpload(uploadId, {
|
||||
expire_value: options.expireValue,
|
||||
expire_style: options.expireStyle
|
||||
})
|
||||
|
||||
if (completeResponse.code !== 200) {
|
||||
throw new Error(options.messages?.completeFailed || 'Complete chunk upload failed')
|
||||
}
|
||||
|
||||
return completeResponse
|
||||
pendingCompletion.set(file, { uploadId, expireValue: options.expireValue, expireStyle: options.expireStyle })
|
||||
return finishUpload(file, options)
|
||||
}
|
||||
@@ -26,6 +26,8 @@
|
||||
:selected-file="selectedFile"
|
||||
:selected-files="selectedFiles"
|
||||
:progress="uploadProgress"
|
||||
:disabled="isSubmitting"
|
||||
:upload-status="isFinalizing ? 'confirming' : isSubmitting ? 'uploading' : 'idle'"
|
||||
:description="uploadDescription"
|
||||
@file-selected="handleFileSelected"
|
||||
@files-selected="handleFilesSelected"
|
||||
@@ -162,6 +164,7 @@ const {
|
||||
showDrawer,
|
||||
selectedRecord,
|
||||
isSubmitting,
|
||||
isFinalizing,
|
||||
sendRecords,
|
||||
uploadDescription,
|
||||
expirationOptions,
|
||||
|
||||
@@ -69,3 +69,9 @@ Playwright Page。Vite 固定运行于 `127.0.0.1:5180`;分别传入 `http`
|
||||
- `localShare.browser.mjs`:导出 `runLocalShareChecks(page, dark)`;Vite 运行于
|
||||
`127.0.0.1:5180`。管理 API 全部拦截为独立数据,覆盖目录/搜索/分页、生成失败重试、
|
||||
取件码/链接复制、空目录/加载错误和移动端溢出检查。
|
||||
|
||||
## WebDAV 后台完成上传
|
||||
|
||||
`uploadCompletion.test.mjs` 覆盖 202 轮询、临时网络错误重试及明确失败退出;
|
||||
`uploadStrategy.integration.test.mjs` 验证用户在丢失完成响应后手动重试时复用原上传 ID,
|
||||
不重新上传分片。发送页在此阶段显示文件校验提示,确认成功后才给出取件码。
|
||||
@@ -0,0 +1,21 @@
|
||||
import {test} from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import {waitForUploadCompletion} from '../src/services/upload-completion.ts'
|
||||
|
||||
test('pending verification is polled until a code is issued and finalizing is announced once',async()=>{
|
||||
const responses=[{code:202},{code:202},{code:200,detail:{code:'ABCD2345'}}];let checks=0,notices=0
|
||||
const result=await waitForUploadCompletion(async()=>responses[checks++],()=>notices++)
|
||||
assert.equal(result.detail.code,'ABCD2345');assert.equal(checks,3);assert.equal(notices,1)
|
||||
})
|
||||
test('legacy synchronous success and failure are returned without polling',async()=>{
|
||||
for(const code of [200,400]){let calls=0;const r=await waitForUploadCompletion(async()=>{calls++;return {code}});assert.equal(r.code,code);assert.equal(calls,1)}
|
||||
})
|
||||
test('non-retryable authentication failure stops polling',async()=>{
|
||||
let calls=0;await assert.rejects(waitForUploadCompletion(async()=>{calls++;throw Object.assign(new Error('unauthorized'),{response:{status:401}})}),/unauthorized/);assert.equal(calls,1)
|
||||
})
|
||||
|
||||
test('transient network failure during verification retries the same completion request',async()=>{
|
||||
let calls=0;const result=await waitForUploadCompletion(async()=>{
|
||||
calls++;if(calls===1)return {code:202};if(calls===2)throw new Error('offline');return {code:200,detail:{code:'SAMECODE'}}
|
||||
});assert.equal(calls,3);assert.equal(result.detail.code,'SAMECODE')
|
||||
})
|
||||
@@ -0,0 +1,24 @@
|
||||
import {test,before,after} from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import {createServer} from 'vite'
|
||||
let server,upload,service
|
||||
before(async()=>{
|
||||
server=await createServer({server:{middlewareMode:true,watch:null},appType:'custom'})
|
||||
service=(await server.ssrLoadModule('/src/services/file.ts')).FileService
|
||||
upload=(await server.ssrLoadModule('/src/services/upload-strategy.ts')).uploadChunkedFile
|
||||
})
|
||||
after(async()=>await server?.close())
|
||||
test('manual retry after lost completion response reuses upload id and never retransmits chunks',async()=>{
|
||||
const originals={init:service.initChunkUpload,chunk:service.uploadChunk,complete:service.completeChunkUpload}
|
||||
let inits=0,chunks=0,completions=0
|
||||
const previousWindow=globalThis.window;globalThis.window={isSecureContext:true}
|
||||
service.initChunkUpload=async()=>{inits++;return {code:200,detail:{upload_id:'original-session',uploaded_chunks:[]}}}
|
||||
service.uploadChunk=async()=>{chunks++;return {code:200}}
|
||||
service.completeChunkUpload=async(id)=>{assert.equal(id,'original-session');completions++;if(completions<=4)throw new Error('offline');return {code:200,detail:{code:'ORIGINAL'}}}
|
||||
const file=new File(['small payload'],'file.txt'),options={expireValue:1,expireStyle:'day'}
|
||||
try {
|
||||
await assert.rejects(upload(file,options),/offline/)
|
||||
const result=await upload(file,options)
|
||||
assert.equal(result.detail.code,'ORIGINAL');assert.equal(inits,1);assert.equal(chunks,1);assert.equal(completions,5)
|
||||
}finally{service.initChunkUpload=originals.init;service.uploadChunk=originals.chunk;service.completeChunkUpload=originals.complete;globalThis.window=previousWindow}
|
||||
})
|
||||
Reference in new issue
Block a user