fix: ускорить и стабилизировать tus-загрузку (Firefox HTTP/2 + resume)

Симптом: в Firefox загрузка ползла (~32МБ за минуты), в Chrome быстро.
Причина — nginx proxy_request_buffering off + HTTP/2: nginx лениво слал
WINDOW_UPDATE, Firefox застревал. Фикс nginx (на сервере): убрать
proxy_request_buffering off — при chunked-загрузке куски маленькие,
буферизация per-chunk дешёвая.

Фронт (этот коммит):
- chunkSize 32→8 МБ: плавный прогресс, быстрее восстановление после сбоя.
- защита от двойного клика (uploadingActive + блокировка кнопок на время).
- самолечение застрявшего resume: на 404/409 — чистая загрузка заново.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
anor
2026-06-02 16:11:25 +10:00
co-authored by Claude Opus 4.8
parent 522b157acc
commit b5e824487b
+49 -30
View File
@@ -369,11 +369,11 @@ function jwtExpSoon() {
// Resumable upload of one file via the tus protocol. Survives network drops and
// page reloads (tus-js-client stores the upload URL and resumes from the offset
// the server already has). Resolves {name, ok, status}.
function uploadOne(file, onPct) {
function uploadOne(file, onPct, fresh) {
return new Promise((resolve) => {
const upload = new tus.Upload(file, {
endpoint: API + '/api/tus',
chunkSize: 32 * 1024 * 1024,
chunkSize: 8 * 1024 * 1024,
retryDelays: [0, 3000, 5000, 10000, 20000],
removeFingerprintOnSuccess: true,
metadata: { filename: file.name, tab_id: tabId },
@@ -391,43 +391,62 @@ function uploadOne(file, onPct) {
onSuccess() { resolve({ name: file.name, ok: true }); },
onError(error) {
const s = error.originalResponse ? error.originalResponse.getStatus() : 0;
if (s === 401) logout();
if (s === 401) { logout(); resolve({ name: file.name, ok: false, status: s }); return; }
// A stale resumed upload can wedge on 404/409 — abandon it and retry once cleanly.
if (!fresh && (s === 404 || s === 409)) { resolve(uploadOne(file, onPct, true)); return; }
resolve({ name: file.name, ok: false, status: s });
},
});
upload.findPreviousUploads().then((prev) => {
if (prev.length) upload.resumeFromPreviousUpload(prev[0]);
upload.start();
});
if (fresh) {
upload.start(); // clean upload, skip resuming any stored partial
} else {
upload.findPreviousUploads().then((prev) => {
if (prev.length) upload.resumeFromPreviousUpload(prev[0]);
upload.start();
});
}
});
}
let uploadingActive = false;
async function uploadFiles() {
if (typeof tus === 'undefined') return uploadFilesLegacy(); // CDN blocked → degrade
const files = pendingFiles.slice();
const prog = files.map(f => ({ name: f.name, pct: 0 }));
const fl = document.getElementById('file-list');
const render = () => {
fl.innerHTML = '';
prog.forEach(p => {
const b = document.createElement('span');
b.className = 'file-badge';
b.textContent = `${p.name} — ${p.pct}%`;
fl.appendChild(b);
});
};
render();
const results = [];
for (let i = 0; i < files.length; i++) {
results.push(await uploadOne(files[i], (pct) => { prog[i].pct = pct; render(); }));
if (uploadingActive) return []; // ignore re-entry (double-click)
uploadingActive = true;
const fileBtn = document.getElementById('file-btn');
const sendBtn = document.getElementById('send-btn');
if (fileBtn) fileBtn.disabled = true;
if (sendBtn) sendBtn.disabled = true;
try {
const files = pendingFiles.slice();
const prog = files.map(f => ({ name: f.name, pct: 0 }));
const fl = document.getElementById('file-list');
const render = () => {
fl.innerHTML = '';
prog.forEach(p => {
const b = document.createElement('span');
b.className = 'file-badge';
b.textContent = `${p.name} — ${p.pct}%`;
fl.appendChild(b);
});
};
render();
const results = [];
for (let i = 0; i < files.length; i++) {
results.push(await uploadOne(files[i], (pct) => { prog[i].pct = pct; render(); }));
}
pendingFiles = [];
renderFileList();
const failed = results.filter(r => !r.ok);
if (failed.length && !failed.some(r => r.status === 401)) {
addMsg('error', 'Не загружены: ' + failed.map(r => r.name).join(', '));
}
return results.filter(r => r.ok).map(r => r.name);
} finally {
uploadingActive = false;
if (fileBtn) fileBtn.disabled = false;
if (sendBtn) sendBtn.disabled = false;
}
pendingFiles = [];
renderFileList();
const failed = results.filter(r => !r.ok);
if (failed.length && !failed.some(r => r.status === 401)) {
addMsg('error', 'Не загружены: ' + failed.map(r => r.name).join(', '));
}
return results.filter(r => r.ok).map(r => r.name);
}
// Fallback for when the tus client isn't available (e.g. CDN unreachable).