fix(frontend): scale upload timeout with payload size
postUpload inherited the axios instance's 30s default, so any upload taking longer than 30s was aborted client-side no matter what MAX_FILE_SIZE_MB was set to. On a ~30 Mbps uplink that caps uploads at roughly 100MB even when the deployment is configured for 200MB — and every layer underneath (reverse proxy, frontend nginx, Go handler, docreader gRPC) had already accepted the configured limit. The server only saw the request after the browser had given up, and logged "failed to upload file to MinIO: context canceled" with a sub-second latency. Four of the five postUpload call sites worked around this by passing an explicit timeout; knowledge-base file upload and chat temporary attachments did not. Derive the default from the payload so correct behaviour no longer depends on each caller remembering to opt in — an explicit config.timeout still wins. The aborted request also surfaced as "network error, please check your connection": axios timeouts arrive without error.response, so they landed in the same branch as an unreachable server and sent people chasing a network problem that did not exist. Report the two separately.main
parent
92e7c0ab37
commit
a8aa19f721
|
|
@ -4501,6 +4501,7 @@ export default {
|
|||
},
|
||||
error: {
|
||||
networkError: 'Network error, please check your connection',
|
||||
requestTimeout: 'Request timed out. Large files or slow connections may need another try.',
|
||||
invalidCredentials: 'Invalid username or password',
|
||||
tokenRefreshFailed: 'Token refresh failed',
|
||||
pleaseRelogin: 'Please log in again',
|
||||
|
|
|
|||
|
|
@ -4501,6 +4501,7 @@ export default {
|
|||
},
|
||||
error: {
|
||||
networkError: 'ネットワークエラーです。接続を確認してください',
|
||||
requestTimeout: 'リクエストがタイムアウトしました。大きなファイルや低速な回線では再試行してください',
|
||||
invalidCredentials: 'ユーザ名またはパスワードが正しくありません',
|
||||
tokenRefreshFailed: 'トークンの更新に失敗しました',
|
||||
pleaseRelogin: '再度ログインしてください',
|
||||
|
|
|
|||
|
|
@ -2947,6 +2947,7 @@ export default {
|
|||
},
|
||||
error: {
|
||||
networkError: '네트워크 오류, 연결을 확인해 주세요',
|
||||
requestTimeout: '요청 시간이 초과되었습니다. 파일이 크거나 네트워크가 느린 경우 다시 시도해 주세요',
|
||||
invalidCredentials: '사용자 이름 또는 비밀번호가 올바르지 않습니다',
|
||||
tokenRefreshFailed: '토큰 갱신 실패',
|
||||
pleaseRelogin: '다시 로그인해 주세요',
|
||||
|
|
|
|||
|
|
@ -2947,6 +2947,7 @@ export default {
|
|||
},
|
||||
error: {
|
||||
networkError: 'Ошибка сети, проверьте подключение',
|
||||
requestTimeout: 'Время ожидания запроса истекло. Для больших файлов или медленного соединения повторите попытку',
|
||||
invalidCredentials: 'Неверное имя пользователя или пароль',
|
||||
tokenRefreshFailed: 'Не удалось обновить токен',
|
||||
pleaseRelogin: 'Пожалуйста, войдите снова',
|
||||
|
|
|
|||
|
|
@ -2949,6 +2949,7 @@ export default {
|
|||
},
|
||||
error: {
|
||||
networkError: '网络错误,请检查您的网络连接',
|
||||
requestTimeout: '请求超时,文件较大或网络较慢时请稍后重试',
|
||||
invalidCredentials: '用户名或密码错误',
|
||||
tokenRefreshFailed: 'Token刷新失败',
|
||||
pleaseRelogin: '请重新登录',
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import { generateRandomString, MAX_FILE_SIZE_MB, MAX_SKILL_BUNDLE_SIZE_MB } from
|
|||
import i18n from '@/i18n'
|
||||
import { getApiBaseUrl } from './api-base';
|
||||
import { isSkillBundleUploadUrl } from './uploadLimit';
|
||||
import { isTimeoutError, uploadTimeoutMs } from './requestTimeouts';
|
||||
import {
|
||||
forceReloginRedirect,
|
||||
isEmbedPage,
|
||||
|
|
@ -135,7 +136,12 @@ instance.interceptors.response.use(
|
|||
const originalRequest = error.config;
|
||||
|
||||
if (!error.response) {
|
||||
return Promise.reject({ message: t('error.networkError') });
|
||||
// A timeout and an unreachable server both arrive without a response, but
|
||||
// telling someone whose upload timed out to "check your connection" sends
|
||||
// them after the wrong problem.
|
||||
return Promise.reject({
|
||||
message: t(isTimeoutError(error) ? 'error.requestTimeout' : 'error.networkError'),
|
||||
});
|
||||
}
|
||||
|
||||
// 文件下载失败时服务端仍返回 JSON;先还原错误信息,避免被 Blob 隐藏。
|
||||
|
|
@ -242,6 +248,11 @@ export function postUpload(
|
|||
config: any = {},
|
||||
): Promise<WithStatus<any>> {
|
||||
return instance.post(url, data, {
|
||||
// Uploads are bounded by transfer time, not by the 30s default that suits
|
||||
// JSON calls. Derive the budget from the payload so a deployment raising
|
||||
// MAX_FILE_SIZE_MB doesn't silently abort its own uploads; an explicit
|
||||
// `config.timeout` still wins.
|
||||
timeout: uploadTimeoutMs(data),
|
||||
...config,
|
||||
headers: {
|
||||
"Content-Type": "multipart/form-data",
|
||||
|
|
|
|||
|
|
@ -0,0 +1,46 @@
|
|||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import {
|
||||
UPLOAD_TIMEOUT_FLOOR_MS,
|
||||
isTimeoutError,
|
||||
uploadPayloadBytes,
|
||||
uploadTimeoutMs,
|
||||
} from './requestTimeouts'
|
||||
|
||||
const formDataWith = (...sizes: number[]) => {
|
||||
const form = new FormData()
|
||||
form.append('name', 'not-a-blob')
|
||||
sizes.forEach((size, i) => form.append(`file${i}`, new Blob([new Uint8Array(size)])))
|
||||
return form
|
||||
}
|
||||
|
||||
test('payload size counts blobs and ignores plain fields', () => {
|
||||
assert.equal(uploadPayloadBytes(formDataWith()), 0)
|
||||
assert.equal(uploadPayloadBytes(formDataWith(1024)), 1024)
|
||||
assert.equal(uploadPayloadBytes(formDataWith(1024, 2048)), 3072)
|
||||
})
|
||||
|
||||
test('non-FormData payloads contribute no bytes', () => {
|
||||
assert.equal(uploadPayloadBytes({ file: 'x' }), 0)
|
||||
assert.equal(uploadPayloadBytes(undefined), 0)
|
||||
})
|
||||
|
||||
test('small uploads still get the floor', () => {
|
||||
assert.equal(uploadTimeoutMs(formDataWith(1024)), UPLOAD_TIMEOUT_FLOOR_MS)
|
||||
})
|
||||
|
||||
test('large uploads scale past the floor', () => {
|
||||
// 100MB at the budgeted 10MB/min is 10 minutes — comfortably past the 5min
|
||||
// floor, and far past the 30s default that silently aborted these uploads.
|
||||
const tenMinutes = 10 * 60 * 1000
|
||||
assert.equal(uploadTimeoutMs(formDataWith(100 * 1024 * 1024)), tenMinutes)
|
||||
assert.ok(uploadTimeoutMs(formDataWith(200 * 1024 * 1024)) > tenMinutes)
|
||||
})
|
||||
|
||||
test('timeouts are distinguished from unreachable-server failures', () => {
|
||||
assert.equal(isTimeoutError({ code: 'ECONNABORTED', message: 'timeout of 30000ms exceeded' }), true)
|
||||
assert.equal(isTimeoutError({ code: 'ETIMEDOUT' }), true)
|
||||
assert.equal(isTimeoutError({ message: 'timeout exceeded' }), true)
|
||||
assert.equal(isTimeoutError({ code: 'ERR_NETWORK', message: 'Network Error' }), false)
|
||||
assert.equal(isTimeoutError(null), false)
|
||||
})
|
||||
|
|
@ -0,0 +1,52 @@
|
|||
// Timeout budgets for HTTP requests whose duration is dominated by payload
|
||||
// transfer rather than server processing.
|
||||
//
|
||||
// The axios instance uses a 30s default, which is right for JSON calls but
|
||||
// unreachable for file uploads: MAX_FILE_SIZE_MB is deployment-configurable
|
||||
// (200MB is a realistic value) and no ordinary uplink pushes that in 30s.
|
||||
// Callers used to work around this by passing an explicit timeout, which only
|
||||
// some of them remembered to do.
|
||||
|
||||
/**
|
||||
* Lower bound for any upload, regardless of size. Matches the value the skill
|
||||
* and model upload call sites already pass explicitly.
|
||||
*/
|
||||
export const UPLOAD_TIMEOUT_FLOOR_MS = 5 * 60 * 1000
|
||||
|
||||
/**
|
||||
* Worst-case sustained uplink we budget for: 10MB per minute (~170KB/s).
|
||||
* Deliberately pessimistic — the timeout is a ceiling that only matters when a
|
||||
* transfer stalls, so an over-generous budget costs nothing on healthy links.
|
||||
*/
|
||||
const UPLOAD_BYTES_PER_MINUTE = 10 * 1024 * 1024
|
||||
|
||||
/** Total byte size of every Blob/File carried by a FormData payload. */
|
||||
export function uploadPayloadBytes(data: unknown): number {
|
||||
if (typeof FormData === 'undefined' || !(data instanceof FormData)) return 0
|
||||
let total = 0
|
||||
data.forEach((value) => {
|
||||
if (typeof Blob !== 'undefined' && value instanceof Blob) total += value.size
|
||||
})
|
||||
return total
|
||||
}
|
||||
|
||||
/**
|
||||
* Timeout budget for an upload payload: the floor for small payloads, scaling
|
||||
* linearly beyond it.
|
||||
*/
|
||||
export function uploadTimeoutMs(data: unknown): number {
|
||||
const scaled = Math.ceil((uploadPayloadBytes(data) / UPLOAD_BYTES_PER_MINUTE) * 60_000)
|
||||
return Math.max(UPLOAD_TIMEOUT_FLOOR_MS, scaled)
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a rejected request timed out, as opposed to failing to reach the
|
||||
* server at all. Both arrive without `error.response`, but reporting a timeout
|
||||
* as "check your network connection" sends people chasing the wrong problem.
|
||||
*/
|
||||
export function isTimeoutError(error: unknown): boolean {
|
||||
if (!error || typeof error !== 'object') return false
|
||||
const { code, message } = error as { code?: unknown; message?: unknown }
|
||||
if (code === 'ECONNABORTED' || code === 'ETIMEDOUT') return true
|
||||
return typeof message === 'string' && /timeout/i.test(message)
|
||||
}
|
||||
Loading…
Reference in New Issue