fix(phase-5.2): 消项 CR 第二轮 P1/P2/P3(通道/证据链/交付时序/后管证据页)
This commit is contained in:
@@ -31,6 +31,14 @@ export const CHUNK_UPLOAD_THRESHOLD = UPLOAD_PART_SIZE
|
||||
/** 每片重试次数(不含首次)。 */
|
||||
const PART_RETRY_LIMIT = 2
|
||||
|
||||
/**
|
||||
* 单次直传的超时预算(P3-5:这条尺子在本仓只有一个出口):30s 保底 + 每 MB 15s,
|
||||
* 慢公网传 100MB 视频不再被固定 120s 掐死。桌面桥的浏览器降级直传也走这里。
|
||||
*/
|
||||
export function uploadTimeoutForBytes(bytes: number): number {
|
||||
return 30_000 + Math.ceil(bytes / (1024 * 1024)) * 15_000
|
||||
}
|
||||
|
||||
function uploadPartUrl(uploadId: string, index: number): string {
|
||||
return `${JAVA_API_PREFIX}/files/chunk/${encodeURIComponent(uploadId)}/part/${index}`
|
||||
}
|
||||
@@ -98,6 +106,61 @@ function clearStoredSession(key: string): void {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 服务端对「这个会话还在不在」的三种答复:还在(顺带已到片号)/确实没了/问不出来。
|
||||
* 第三态是 P1-11 的关键——过去它和前两态被揉进一个 catch,断网=整包作废。
|
||||
*/
|
||||
type ProbeOutcome
|
||||
= { state: 'ok'; parts: number[] }
|
||||
| { state: 'gone' }
|
||||
| { state: 'transient' }
|
||||
|
||||
/** 后端回收会话的原文案(ChunkedUploadService.readMeta);BusinessException 不带 code ⇒ HTTP 200 出。 */
|
||||
function messageSaysSessionGone(text: unknown): boolean {
|
||||
const message = typeof text === 'string' ? text : ''
|
||||
return ['不存在', '过期'].some((marker) => message.includes(marker))
|
||||
}
|
||||
|
||||
/**
|
||||
* 判据顺序=可信度顺序:404 与后端点名句才清状态;5xx/429/别的业务失败一律瞬态。
|
||||
* 拿"问不到"当"没了",就是用一次网关抖动换整包重传。
|
||||
*/
|
||||
function classifyProbe(response: unknown): ProbeOutcome {
|
||||
const status = (response as { status?: unknown } | null | undefined)?.status
|
||||
const numeric = typeof status === 'number' ? status : -1
|
||||
if (numeric === 404) return { state: 'gone' }
|
||||
if (numeric >= 500 || numeric === 408 || numeric === 429) return { state: 'transient' }
|
||||
const body = bodyOf<{ uploaded_parts?: unknown }>(response)
|
||||
if (body && typeof body === 'object' && body.success === false) {
|
||||
return messageSaysSessionGone(body.message) ? { state: 'gone' } : { state: 'transient' }
|
||||
}
|
||||
if (numeric !== -1 && (numeric < 200 || numeric > 299)) return { state: 'transient' }
|
||||
const arrived = body?.data?.uploaded_parts
|
||||
return { state: 'ok', parts: Array.isArray(arrived) ? arrived.map((index) => Number(index)) : [] }
|
||||
}
|
||||
|
||||
/**
|
||||
* 探测已达片号(P1-11)。
|
||||
* validateStatus 恒真:本仓响应拦截器会把失败折叠成 `new Error(中文文案)`,状态码到不了这里,
|
||||
* 404/5xx 全靠这一步自己按码分因;能走到 catch 的就只剩网络层失败与超时=铁定瞬态。
|
||||
*/
|
||||
async function probeUploadedParts(uploadId: string): Promise<ProbeOutcome> {
|
||||
try {
|
||||
const response = await http.get<JavaApiResponse<{ uploaded_parts?: unknown[] }>>(
|
||||
`${JAVA_API_PREFIX}/files/chunk/${encodeURIComponent(uploadId)}`,
|
||||
{ validateStatus: () => true },
|
||||
)
|
||||
return classifyProbe(response)
|
||||
} catch (error) {
|
||||
const status = (error as { response?: { status?: unknown } } | null | undefined)?.response?.status
|
||||
if (status === 404) return { state: 'gone' }
|
||||
if (messageSaysSessionGone((error as { message?: unknown } | null | undefined)?.message)) {
|
||||
return { state: 'gone' }
|
||||
}
|
||||
return { state: 'transient' }
|
||||
}
|
||||
}
|
||||
|
||||
/** 单次 multipart 上传(小文件短链路)。超时按体积给,不再固定 120s。 */
|
||||
async function singleUpload(
|
||||
file: File,
|
||||
@@ -122,8 +185,8 @@ async function singleUpload(
|
||||
headers: {
|
||||
'Content-Type': 'multipart/form-data',
|
||||
},
|
||||
// 30s 保底 + 每 MB 15s:慢公网传 100MB 视频不再被固定 120s 掐死(S1-F3)
|
||||
timeout: 30_000 + Math.ceil(file.size / (1024 * 1024)) * 15_000,
|
||||
// 超时按体积给(见 uploadTimeoutForBytes),不再固定 120s
|
||||
timeout: uploadTimeoutForBytes(file.size),
|
||||
onUploadProgress: (event) => {
|
||||
if (!onProgress) return
|
||||
const total = event.total || file.size
|
||||
@@ -148,17 +211,16 @@ async function chunkedUpload(
|
||||
let uploadId = readStoredSession(sessionKey, file)
|
||||
let done = new Set<number>()
|
||||
if (uploadId) {
|
||||
try {
|
||||
const status = ensureOk(bodyOf<{ uploaded_parts?: unknown[] }>(await http.get(
|
||||
`${JAVA_API_PREFIX}/files/chunk/${encodeURIComponent(uploadId)}`,
|
||||
)))
|
||||
const arrived = status.data?.uploaded_parts
|
||||
done = new Set<number>(Array.isArray(arrived) ? arrived.map((index) => Number(index)) : [])
|
||||
} catch {
|
||||
// 会话已被服务端回收/过期:只能清掉重开,否则这个件每次都在同一个死会话上失败。
|
||||
const probed = await probeUploadedParts(uploadId)
|
||||
if (probed.state === 'gone') {
|
||||
// 服务端确实说会话没了(404/「不存在或已过期」):只能清掉重开,否则这个件每次都在同一个死会话上失败。
|
||||
clearStoredSession(sessionKey)
|
||||
uploadId = ''
|
||||
} else if (probed.state === 'ok') {
|
||||
done = new Set<number>(probed.parts)
|
||||
}
|
||||
// transient(断网/超时/5xx/别的业务失败):会话还在服务端,片号未知也要接着往里写——
|
||||
// 同一片重复上传按覆盖处理(后端 savePart 幂等),重开 init 等于把已传上去的整包作废。
|
||||
}
|
||||
if (!uploadId) {
|
||||
const init = ensureOk(bodyOf<{ upload_id?: string }>(await http.post(
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
|
||||
import type { DesktopConfig, DesktopConfigUpdate, PywebviewApi } from './pywebview'
|
||||
import { extractErrorMessage, http } from '@/shared/api/http'
|
||||
import { uploadTimeoutForBytes } from '@/shared/api/upload.ts'
|
||||
|
||||
/**
|
||||
* 虚拟路径 → 浏览器 File 对象(虚拟路径仅存活于当前页面会话,刷新即失效)
|
||||
@@ -240,7 +241,10 @@ export const webFallbackApi: PywebviewApi = {
|
||||
}
|
||||
try {
|
||||
// http 实例对 /newApi 前缀自动附带 Bearer;FormData 的 Content-Type 交由浏览器自动生成(含 boundary)
|
||||
const response = await http.post('/newApi/api/files/upload', form, { timeout: 120000 })
|
||||
// 超时按体积给(P3-5:与 upload.ts 同一把尺),几 MB 的 xlsx/zip 不再被固定 120s 掐死
|
||||
const response = await http.post('/newApi/api/files/upload', form, {
|
||||
timeout: uploadTimeoutForBytes(file.size),
|
||||
})
|
||||
// 消费完即释放:文件已落到服务端,页面后续只用返回的 fileKey/url,不再需要这份本地 File。
|
||||
// 失败分支保留条目,让用户能在不重新选文件的情况下重试(超量时由 rememberWebFile 的 FIFO 淘汰兜底)。
|
||||
if (response.data?.success) {
|
||||
|
||||
@@ -54,4 +54,40 @@ describe('AC-11 用户端大档上传', () => {
|
||||
`AC-11:9MB 视频仍走单次上传,实际出口:${urls.join(', ')}`,
|
||||
).toBe(true)
|
||||
})
|
||||
|
||||
// P2-9:上面那格的桩直接把包体当返回值,bodyOf 的真实 axios 分支(包体在 .data)零行为覆盖。
|
||||
// 形状误判的代价是静默的——upload_id 取不到就报"后端未返回分片会话",已达片号取不到就整包从 0 重传,
|
||||
// 而桩版本照样绿。这一格按真机形状(AxiosResponse{status, data})对撞,缺牙就判红。
|
||||
it('真实 axios 响应形状必须被认下来(P2-9 反桩形假绿)', async () => {
|
||||
const uploadId = 'b'.repeat(32)
|
||||
const envelope = (body: unknown) => ({
|
||||
status: 200,
|
||||
statusText: 'OK',
|
||||
headers: {},
|
||||
config: {},
|
||||
data: { success: true, message: '', data: body },
|
||||
})
|
||||
mocks.post.mockImplementation((url: string) => Promise.resolve(
|
||||
String(url).includes('/complete')
|
||||
? envelope({
|
||||
fileKey: 'tmp/big.mp4', originalFilename: 'big.mp4', localPath: '/tmp/big.mp4', size: 9437184,
|
||||
url: 'https://oss.example/big.mp4', objectKey: 'image-video/big.mp4', mediaType: 'video',
|
||||
})
|
||||
: envelope({ upload_id: uploadId, total_parts: 2, received_parts: 1 }),
|
||||
))
|
||||
mocks.get.mockResolvedValue(envelope({ upload_id: uploadId, uploaded_parts: [] }))
|
||||
|
||||
const file = new File([new Uint8Array(9 * 1024 * 1024)], 'big.mp4', { type: 'video/mp4' })
|
||||
const uploaded = await uploadImageVideoMedia(file)
|
||||
|
||||
expect(uploaded.objectKey, '包体在 .data 时仍要取到 complete 的结果').toBe('image-video/big.mp4')
|
||||
const partUrls = mocks.post.mock.calls
|
||||
.map(([url]) => String(url))
|
||||
.filter((url) => /\/part\/\d+$/.test(url))
|
||||
expect(partUrls.length, '9MB=2 片,一片都不能少').toBe(2)
|
||||
expect(
|
||||
partUrls.every((url) => url.includes(uploadId)),
|
||||
`bodyOf 没按 axios 形状取 upload_id,实际出口:${partUrls.join(', ')}`,
|
||||
).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
// P1-11(AC-9/铁律 18「瞬态失败不得把会话打掉」的用户端那一半)。
|
||||
//
|
||||
// 评审实录:GET 已达片号那一步用无差别 catch ⇒ 断网/超时/5xx 一律 clearStoredSession + 重开
|
||||
// upload_id,一次抖动就把 90MB 打回从 0。本文件按两个方向钉死:
|
||||
// ① 服务端确实说会话没了(HTTP 404/现网形状 HTTP 200+success:false+「不存在或已过期」)⇒ 重开;
|
||||
// ② 网络层失败/5xx/非会话类业务失败 ⇒ 保留 upload_id,绝不再发 init。
|
||||
// 另附 P2-9:桩必须能吃真实 axios 形状(包体在 .data),否则 bodyOf 的 axios 分支零行为覆盖,
|
||||
// 形状误判会让 done 成空集=静默从 0 而不判红。
|
||||
//
|
||||
// 跑法:npm run test:mount(tests/mount/** 走 vitest+happy-dom,localStorage 可用,不出网)。
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
post: vi.fn(),
|
||||
get: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/shared/api/http.ts', () => ({
|
||||
http: { post: mocks.post, get: mocks.get },
|
||||
post: mocks.post,
|
||||
get: mocks.get,
|
||||
unwrapJavaResponse: (value: unknown) => value,
|
||||
}))
|
||||
|
||||
import { UPLOAD_PART_SIZE, uploadTempFileToJava } from '@/shared/api/upload.ts'
|
||||
|
||||
const SESSION_ID = 's'.repeat(32)
|
||||
const FRESH_ID = 'f'.repeat(32)
|
||||
const TWO_PARTS = UPLOAD_PART_SIZE * 2
|
||||
|
||||
function sessionKeyOf(file: File): string {
|
||||
return `shufu:chunk:${file.name}:${file.size}:${file.lastModified}:`
|
||||
}
|
||||
|
||||
function seedSession(file: File, uploadId: string): void {
|
||||
localStorage.setItem(sessionKeyOf(file), JSON.stringify({
|
||||
uploadId,
|
||||
size: file.size,
|
||||
lastModified: file.lastModified,
|
||||
}))
|
||||
}
|
||||
|
||||
function storedUploadId(file: File): string {
|
||||
const raw = localStorage.getItem(sessionKeyOf(file))
|
||||
if (!raw) return ''
|
||||
return String((JSON.parse(raw) as { uploadId?: unknown }).uploadId ?? '')
|
||||
}
|
||||
|
||||
function makeBigFile(name = 'resume.mp4'): File {
|
||||
return new File([new Uint8Array(TWO_PARTS)], name, { type: 'video/mp4' })
|
||||
}
|
||||
|
||||
/** 真实 axios 出口形状:状态码与包体分家(测试桩过去直接把 body 当返回值,见 P2-9)。 */
|
||||
function axiosResponse(status: number, body: unknown) {
|
||||
return { status, data: body }
|
||||
}
|
||||
|
||||
function javaOk(body: unknown) {
|
||||
return axiosResponse(200, { success: true, message: '', data: body })
|
||||
}
|
||||
|
||||
function javaGone() {
|
||||
// 现网实读:ChunkedUploadService 抛 BusinessException 不带 code ⇒ GlobalExceptionHandler
|
||||
// 按 HTTP 200 + success:false 出,只有文案可依据。
|
||||
return axiosResponse(200, { success: false, message: '分片会话不存在或已过期', data: null })
|
||||
}
|
||||
|
||||
/** 按 URL 分派的 POST 桩:init 发新会话号,片与 complete 一律成功。 */
|
||||
function routePosts(initUploadId: string) {
|
||||
mocks.post.mockImplementation((url: string) => {
|
||||
const text = String(url)
|
||||
if (text.includes('/files/chunk/init')) {
|
||||
return Promise.resolve(javaOk({ upload_id: initUploadId, total_parts: 2 }))
|
||||
}
|
||||
if (text.includes('/complete')) {
|
||||
return Promise.resolve(javaOk({
|
||||
fileKey: 'tmp/resume.mp4', originalFilename: 'resume.mp4', localPath: '/tmp/resume.mp4',
|
||||
size: TWO_PARTS, url: 'https://oss.example/resume.mp4', objectKey: 'image-video/resume.mp4',
|
||||
}))
|
||||
}
|
||||
return Promise.resolve(javaOk({ received_parts: 1 }))
|
||||
})
|
||||
}
|
||||
|
||||
function postedUrls(): string[] {
|
||||
return mocks.post.mock.calls.map(([url]) => String(url))
|
||||
}
|
||||
|
||||
function initedCount(): number {
|
||||
return postedUrls().filter((url) => url.includes('/files/chunk/init')).length
|
||||
}
|
||||
|
||||
function partUrls(): string[] {
|
||||
return postedUrls().filter((url) => /\/part\/\d+$/.test(url))
|
||||
}
|
||||
|
||||
describe('P1-11 分片会话探测失败必须分因', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
localStorage.clear()
|
||||
routePosts(FRESH_ID)
|
||||
})
|
||||
|
||||
it('HTTP 404:服务端说会话没了 ⇒ 清状态并重新 init', async () => {
|
||||
const file = makeBigFile()
|
||||
seedSession(file, SESSION_ID)
|
||||
mocks.get.mockResolvedValue(axiosResponse(404, { success: false, message: 'Not Found', data: null }))
|
||||
|
||||
await uploadTempFileToJava(file, { uploadToOss: true, moduleType: 'IMAGE_VIDEO' })
|
||||
|
||||
expect(initedCount(), '404 之后必须重新开会话').toBe(1)
|
||||
expect(partUrls().every((url) => url.includes(FRESH_ID)), '新片必须挂在新的会话号上').toBe(true)
|
||||
expect(partUrls().some((url) => url.includes(SESSION_ID)), '旧会话号已判死,不得再往它写片').toBe(false)
|
||||
})
|
||||
|
||||
it('HTTP 200+success:false+「不存在或已过期」(现网形状)⇒ 同样重开', async () => {
|
||||
const file = makeBigFile()
|
||||
seedSession(file, SESSION_ID)
|
||||
mocks.get.mockResolvedValue(javaGone())
|
||||
|
||||
await uploadTempFileToJava(file, { uploadToOss: true, moduleType: 'IMAGE_VIDEO' })
|
||||
|
||||
expect(initedCount(), '会话确实回收后不重建就永远卡死').toBe(1)
|
||||
expect(partUrls().every((url) => url.includes(FRESH_ID))).toBe(true)
|
||||
})
|
||||
|
||||
it('HTTP 503:瞬态 ⇒ 保留 upload_id,一条 init 都不许发', async () => {
|
||||
const file = makeBigFile()
|
||||
seedSession(file, SESSION_ID)
|
||||
mocks.get.mockResolvedValue(axiosResponse(503, '<html>Bad Gateway</html>'))
|
||||
|
||||
await uploadTempFileToJava(file, { uploadToOss: true, moduleType: 'IMAGE_VIDEO' })
|
||||
|
||||
expect(initedCount(), '一次网关抖动就把整包打回从 0,正是本迭代要消灭的行为').toBe(0)
|
||||
expect(partUrls().every((url) => url.includes(SESSION_ID)), '片仍要写进原来那个会话').toBe(true)
|
||||
})
|
||||
|
||||
it('探测超时(网络层错误):瞬态 ⇒ 保留 upload_id 并续传', async () => {
|
||||
const file = makeBigFile()
|
||||
seedSession(file, SESSION_ID)
|
||||
mocks.get.mockRejectedValue(new Error('timeout of 30000ms exceeded'))
|
||||
|
||||
await uploadTempFileToJava(file, { uploadToOss: true, moduleType: 'IMAGE_VIDEO' })
|
||||
|
||||
expect(initedCount()).toBe(0)
|
||||
expect(partUrls().every((url) => url.includes(SESSION_ID))).toBe(true)
|
||||
})
|
||||
|
||||
it('非会话类业务失败(如权限):不许顺手清掉会话', async () => {
|
||||
const file = makeBigFile()
|
||||
seedSession(file, SESSION_ID)
|
||||
mocks.get.mockResolvedValue(axiosResponse(200, { success: false, message: '无权访问该分片会话', data: null }))
|
||||
|
||||
await uploadTempFileToJava(file, { uploadToOss: true, moduleType: 'IMAGE_VIDEO' })
|
||||
|
||||
expect(initedCount()).toBe(0)
|
||||
expect(partUrls().every((url) => url.includes(SESSION_ID))).toBe(true)
|
||||
})
|
||||
|
||||
it('真实 axios 形状:已到片号必须被跳过(P2-9 形状误判即静默从 0)', async () => {
|
||||
const file = makeBigFile()
|
||||
seedSession(file, SESSION_ID)
|
||||
mocks.get.mockResolvedValue(javaOk({ upload_id: SESSION_ID, uploaded_parts: [0] }))
|
||||
|
||||
await uploadTempFileToJava(file, { uploadToOss: true, moduleType: 'IMAGE_VIDEO' })
|
||||
|
||||
expect(partUrls(), '第 0 片服务端已有,不得重传').toEqual([
|
||||
`/newApi/api/files/chunk/${SESSION_ID}/part/1`,
|
||||
])
|
||||
expect(mocks.get.mock.calls.length, '探测要带 upload_id 问服务端').toBe(1)
|
||||
})
|
||||
|
||||
it('探测失败+分片也失败 ⇒ 会话留在 localStorage,且不 DELETE', async () => {
|
||||
const file = makeBigFile()
|
||||
seedSession(file, SESSION_ID)
|
||||
mocks.get.mockRejectedValue(new Error('Network Error'))
|
||||
mocks.post.mockRejectedValue(new Error('Network Error'))
|
||||
|
||||
await expect(uploadTempFileToJava(file, { uploadToOss: true, moduleType: 'IMAGE_VIDEO' }))
|
||||
.rejects.toThrow(/Network Error/)
|
||||
|
||||
expect(storedUploadId(file), '瞬态失败后会话必须还在,下次刷新才能从断点续传').toBe(SESSION_ID)
|
||||
expect(initedCount()).toBe(0)
|
||||
})
|
||||
})
|
||||
@@ -42,3 +42,23 @@ test('图片视频大档上传必须接分片通道', () => {
|
||||
'AC-11:uploadImageVideoMedia 仍是一次 multipart+固定 120s(大档一断就从 0 重传)',
|
||||
)
|
||||
})
|
||||
|
||||
// P3-5:8MB 阈值原先三处各写一遍(客户端 main.py:1479、本仓 upload.ts、后管 chunk-upload.ts),
|
||||
// 改一处就分叉——本仓这一侧收成一个具名常量,别的文件只许引用、不许再写数。
|
||||
test('分片阈值在本仓只能有一个出口', () => {
|
||||
const pattern = /8\s*\*\s*1024\s*\*\s*1024|8388608/
|
||||
const sites = srcFiles
|
||||
.map(rel)
|
||||
.filter((file) => pattern.test(readFileSync(resolve(root, file), 'utf-8')))
|
||||
assert.deepEqual(
|
||||
sites,
|
||||
['src/shared/api/upload.ts'],
|
||||
`8MB 阈值散写到了多处:${sites.join(', ')}(阈值只有一个出口=upload.ts::UPLOAD_PART_SIZE)`,
|
||||
)
|
||||
const source = readFileSync(resolve(root, 'src/shared/api/upload.ts'), 'utf-8')
|
||||
assert.match(
|
||||
source,
|
||||
/export const UPLOAD_PART_SIZE\s*=\s*8\s*\*\s*1024\s*\*\s*1024[\s\S]{0,120}export const CHUNK_UPLOAD_THRESHOLD\s*=\s*UPLOAD_PART_SIZE/,
|
||||
'AC-11:阈值必须由片大小单点派生,不得各写一份 8MB',
|
||||
)
|
||||
})
|
||||
|
||||
@@ -66,6 +66,13 @@ test('pending_ac17_上传必须分片且不再单次 120s', () => {
|
||||
assert.doesNotMatch(source, /timeout:\s*120000/,
|
||||
'S1-F3:单次 120s 超时的整包 multipart 必须被分片通道取代')
|
||||
assert.match(source, /onProgress|progress/, '进度必须可见')
|
||||
|
||||
// P3-5:桌面桥的浏览器降级直传也是大档出口,固定 120s 会在同一把尺子上漏半条链。
|
||||
const bridge = read('src/shared/bridges/web-fallback.ts')
|
||||
assert.doesNotMatch(bridge, /timeout:\s*120_?000/,
|
||||
'P3-5:web-fallback 的大档上传仍写死 120s,慢链路传 Excel/zip 会被自己掐死')
|
||||
assert.match(bridge, /uploadTimeoutForBytes/,
|
||||
'P3-5:超时预算只有一个出口(upload.ts::uploadTimeoutForBytes),桥侧必须复用它')
|
||||
})
|
||||
|
||||
test('pending_ac18_表格必须窗口化渲染或走服务端分页', () => {
|
||||
|
||||
Reference in New Issue
Block a user