feat(phase-4): AC-16/17/18 前端登录态与分片上传、后管包体与竞态门

AC-16(S1-F1/S1-F2)
- frontend-vue ensureAuth:清态前先判 isAuthError——弱网/超时/5xx 不再把人踢回登录页;
  http.ts 的 onResponseRejected 给错误打鉴权标记(HTTP 401 与业务 401/4011 都算),
  纯网络错误保留底层文案供调用方区分"断网"与"掉登录";clearLocalSession 导出复用。
- admin 全局错误兜底:main.ts 装 app.config.errorHandler(首屏就崩也接得住),
  window error / unhandledrejection 由 App.vue setup 调 useGlobalErrorReporting() 接线,
  卸载出口在 onBeforeUnmount 摘监听与提示定时器(后管的 timer-cleanup-pairing 尺子要求
  "注册点所在文件找得回反注册 + 卸载钩子",故接线必须在组件作用域,不在 main.ts)。
  上报体只带 kind/message/stack/route/ts 并过脱敏(Bearer、JWT 三段式、query 里疑似
  token/key/secret 的取值一律打码),凭据零容忍;服务端新增
  /api/admin/client-errors(requireAdmin,字段截断 2000 后 WARN 落日志,不落库)。

AC-17(S1-F3)
- 后端新增分片通道 ChunkedUploadService(init/part/status/complete/abort):8MB/片、
  同片重复上传幂等覆盖、流式拼装复算 sha256、超限与缺片直接拒绝、24h 过期回收;
  FileUploadController 暴露 /api/files/chunk/**,LocalFileStorageService 加
  saveTempFileFromFile(同一套扩展名黑名单与 fileKey 索引);三键显式写进 application.yml
  (不进"只在代码默认值里"的名单)。
- 工作台安装包 93MB:WorkbenchClientPackageService 走同一分片通道转存 client 桶
  (objectKey 写进会话 purpose,拼装时逐字匹配,防借分片接口覆盖已发布包),
  confirm 失败带 cleanupUnconfirmedObject 补偿清理未登记对象;后管 ≤64MB 仍直传预签名 PUT。
- 用户端 upload.ts:大文件分片 + 逐片重试 + 进度回调,超时按体积给(不再固定 120s);
  断点探测失败不再静默按"全缺"重传(catch-silence 棘轮因此一格没涨,blocks 300→301 已记名)。

AC-18(P1-F1/P1-F2/P1-F4/S1-F4)
- 后管 manualChunks 摘掉 element-plus(按需引入已在 src/plugins/element.ts 生效):
  实测构建产物已无 element-plus 独立 chunk,index.html 只 modulepreload vue 块。
- UsersPage/DeviceLogsPage 接 createLatestRequestGate,旧响应不再覆盖新页;
  用户端新增 useServerTablePaging(只驻留当前页 + 自带竞态门 + 失败给原因),
  挂载用例 3 例钉住"翻页重取/旧响应作废/失败可见"。
- DeliveryVideoWorkspace 两处轮询接 document.visibilityState,隐藏标签页暂停。

激活 Phase 0 预置契约 7 例(用户端 5 + 后管 5,共 12 例;其中 AC-16 后管两支按"接线在组件作用域"
的口径改写并把判据加强到反注册配对 + 根组件接线,见蓝图 §5)。
门禁读数:后端 mvn -o test-compile rc=0,CatchSilenceRatchetTest 9 例绿(total 1034→1045、
notRethrow 585→591、logOnly 182→188 逐处记名,EMPTY 未涨)、ChunkedUploadServiceTest 8 例、
WorkbenchClientPackageServiceTest 21 例、ClientErrorReportControllerTest 4 例;后管 1848 例 +
mount 33 例 + vue-tsc + build 全绿;用户端 955 例 + mount 30 例 + vue-tsc + build 全绿。
真机:OssWorkbenchClientLiveVerificationTest 以线上 MinIO 实测 PUT→stat→sha256→presign→删除
全链 1 例绿(凭据只走环境变量,不落任何文件)。

⚠ 按 pathspec 只圈本轮文件:application.yml 用索引手术只提交分片三键那一格,他人
「PENDING 不再按 2 小时判死」的 StaleTaskRepairService/ClientTaskPullSpi/application.yml
注释件与 useLiveTaskBoard/BrandAppearancePatentTab/task-delete-target 四件在飞改动
原样留在工作树未提交。
This commit is contained in:
2026-10-29 13:47:21 +08:00
parent 62a1b50067
commit 0586df2df0
31 changed files with 1798 additions and 64 deletions
+114 -8
View File
@@ -24,14 +24,23 @@ export interface UploadTempFileOptions {
moduleType?: string;
}
export async function uploadTempFileToJava(
/** 分片阈值与片大小(S1-F3/AC-17):≤8MB 单次 multipart 足够;再大必须分片,
* 否则视频/大包一断就从 0 重传,且 120s 固定超时对慢链路根本不够用。 */
export const UPLOAD_PART_SIZE = 8 * 1024 * 1024
export const CHUNK_UPLOAD_THRESHOLD = UPLOAD_PART_SIZE
/** 每片重试次数(不含首次)。 */
const PART_RETRY_LIMIT = 2
function uploadPartUrl(uploadId: string, index: number): string {
return `${JAVA_API_PREFIX}/files/chunk/${encodeURIComponent(uploadId)}/part/${index}`
}
/** 单次 multipart 上传(小文件短链路)。超时按体积给,不再固定 120s。 */
async function singleUpload(
file: File,
relativePathOrOptions?: string | UploadTempFileOptions,
) {
const options =
typeof relativePathOrOptions === 'string'
? { relativePath: relativePathOrOptions }
: relativePathOrOptions || {}
options: UploadTempFileOptions,
onProgress?: (percent: number) => void,
): Promise<JavaApiResponse<UploadFileVo>> {
const formData = new FormData()
formData.append('file', file)
if (options.relativePath) {
@@ -50,8 +59,105 @@ export async function uploadTempFileToJava(
headers: {
'Content-Type': 'multipart/form-data',
},
timeout: 120000,
// 30s 保底 + 每 MB 15s:慢公网传 100MB 视频不再被固定 120s 掐死(S1-F3)
timeout: 30_000 + Math.ceil(file.size / (1024 * 1024)) * 15_000,
onUploadProgress: (event) => {
if (!onProgress) return
const total = event.total || file.size
onProgress(total > 0 ? Math.min(Math.round((event.loaded / total) * 100), 100) : 0)
},
},
)
return response.data
}
/**
* 分片上传(AC-17):init → 逐片 POST(每片独立重试)→ complete 服务端拼装。
* 开传前查询已到片号:上一次断掉的会话可跳过已传片(后端保留 24h)。
*/
async function chunkedUpload(
file: File,
options: UploadTempFileOptions,
onProgress?: (percent: number) => void,
): Promise<JavaApiResponse<UploadFileVo>> {
const totalParts = Math.max(1, Math.ceil(file.size / UPLOAD_PART_SIZE))
const init = await http.post<JavaApiResponse<{ upload_id?: string }>>(
`${JAVA_API_PREFIX}/files/chunk/init`,
null,
{ params: { fileName: file.name, totalParts, totalBytes: file.size } },
)
const uploadId = String(init.data?.data?.upload_id ?? '')
if (!uploadId) {
throw new Error('后端未返回分片会话,请重试')
}
// 开传前先问到已达片号:上一次断掉的会话可以跳过已传片(后端保留 24h)。
// 这一问失败不再静默按"全缺"重传:断网/5xx 当场说清楚,别闷头把整包从 0 再传一遍。
const status = await http.get<JavaApiResponse<{ uploaded_parts?: unknown[] }>>(
`${JAVA_API_PREFIX}/files/chunk/${encodeURIComponent(uploadId)}`,
)
const arrived = status.data?.data?.uploaded_parts
const done = new Set<number>(Array.isArray(arrived) ? arrived.map((index) => Number(index)) : [])
const report = (partialBytes: number) => {
if (!onProgress) return
const loaded = done.size * UPLOAD_PART_SIZE + partialBytes
onProgress(Math.min(Math.round((loaded / file.size) * 100), 99))
}
for (let index = 0; index < totalParts; index += 1) {
if (done.has(index)) {
report(0)
continue
}
const blob = file.slice(index * UPLOAD_PART_SIZE, Math.min(file.size, (index + 1) * UPLOAD_PART_SIZE))
let lastError: unknown = null
for (let attempt = 0; attempt <= PART_RETRY_LIMIT; attempt += 1) {
const form = new FormData()
form.append('file', blob, `part-${index}`)
try {
await http.post(uploadPartUrl(uploadId, index), form, {
headers: { 'Content-Type': 'multipart/form-data' },
timeout: 300_000,
onUploadProgress: (event) => report(Math.min(event.loaded || 0, blob.size)),
})
done.add(index)
lastError = null
break
} catch (error) {
lastError = error
}
}
if (lastError) {
await http.delete(`${JAVA_API_PREFIX}/files/chunk/${encodeURIComponent(uploadId)}`).catch(() => undefined)
throw lastError instanceof Error ? lastError : new Error('分片上传失败')
}
}
const params: Record<string, string | boolean> = {}
if (options.relativePath) params.relativePath = options.relativePath
if (options.uploadToOss) params.uploadToOss = true
if (options.moduleType) params.moduleType = options.moduleType
const response = await http.post<JavaApiResponse<UploadFileVo>>(
`${JAVA_API_PREFIX}/files/chunk/${encodeURIComponent(uploadId)}/complete`,
null,
{ params, timeout: 600_000 },
)
if (onProgress) onProgress(100)
return response.data
}
export async function uploadTempFileToJava(
file: File,
relativePathOrOptions?: string | UploadTempFileOptions,
onProgress?: (percent: number) => void,
): Promise<JavaApiResponse<UploadFileVo>> {
const options =
typeof relativePathOrOptions === 'string'
? { relativePath: relativePathOrOptions }
: relativePathOrOptions || {}
if (file.size > CHUNK_UPLOAD_THRESHOLD) {
return chunkedUpload(file, options, onProgress)
}
return singleUpload(file, options, onProgress)
}