Recover interrupted update downloads with bounded verified retries
CI / verify (push) Canceled after 0s
CI / verify (push) Canceled after 0s
This commit is contained in:
1 parent
2b1e01a0e8
commit
e9287545ee
5 files changed
+81
-128
No files matched your search
+78
-61
@@ -1,6 +1,7 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const crypto = require('crypto');
|
||||
const { setTimeout: delay } = require('node:timers/promises');
|
||||
const { app } = require('electron');
|
||||
|
||||
const UPDATE_REPO = 'Administrator/Multi-Hoster-Upload';
|
||||
@@ -239,8 +240,9 @@ function verifyExeHeader(buf) {
|
||||
|
||||
async function prepareUpdate(onProgress, options = {}) {
|
||||
if (activeAbort) activeAbort.abort();
|
||||
activeAbort = new AbortController();
|
||||
const signal = activeAbort.signal;
|
||||
const controller = new AbortController();
|
||||
activeAbort = controller;
|
||||
const signal = controller.signal;
|
||||
const fetchImpl = options.fetchImpl || fetch;
|
||||
const now = typeof options.now === 'function' ? options.now : Date.now;
|
||||
let stagedInstallerPath = '';
|
||||
@@ -273,68 +275,83 @@ async function prepareUpdate(onProgress, options = {}) {
|
||||
const tmpDir = options.tempDir || app.getPath('temp');
|
||||
const installerPath = path.join(tmpDir, check.assetName);
|
||||
|
||||
const res = await fetchImpl(check.assetUrl, {
|
||||
method: 'GET',
|
||||
signal,
|
||||
redirect: 'follow'
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error(`Download fehlgeschlagen: HTTP ${res.status}`);
|
||||
}
|
||||
|
||||
const totalBytes = manifest.size;
|
||||
let downloadedBytes = 0;
|
||||
let lastReportedPercent = -1;
|
||||
const downloadStartedAt = now();
|
||||
const chunks = [];
|
||||
|
||||
const DOWNLOAD_STALL_MS = 45000;
|
||||
let stallTimer = null;
|
||||
const reader = res.body.getReader();
|
||||
while (true) {
|
||||
if (signal.aborted) throw new Error('Abgebrochen');
|
||||
let chunk;
|
||||
let fileBuffer;
|
||||
for (let attempt = 1; attempt <= 3; attempt++) {
|
||||
signal.throwIfAborted();
|
||||
const downloadController = new AbortController();
|
||||
const onAbort = () => downloadController.abort();
|
||||
signal.addEventListener('abort', onAbort, { once: true });
|
||||
let reader;
|
||||
let stallTimer;
|
||||
let timedOut = false;
|
||||
const resetDeadline = () => {
|
||||
clearTimeout(stallTimer);
|
||||
stallTimer = setTimeout(() => {
|
||||
timedOut = true;
|
||||
downloadController.abort();
|
||||
}, options.downloadStallMs ?? 45000);
|
||||
};
|
||||
let retry = false;
|
||||
try {
|
||||
chunk = await Promise.race([
|
||||
reader.read(),
|
||||
new Promise((_, reject) => { stallTimer = setTimeout(() => reject(new Error('__STALL__')), DOWNLOAD_STALL_MS); })
|
||||
]);
|
||||
} catch (e) {
|
||||
if (e && e.message === '__STALL__') {
|
||||
try { activeAbort.abort(); } catch {}
|
||||
throw new Error('Download hängt — seit 45 s keine Daten (Netzwerk/Server überlastet). Bitte laufende Uploads stoppen und erneut versuchen.');
|
||||
}
|
||||
throw e;
|
||||
} finally {
|
||||
if (stallTimer) { clearTimeout(stallTimer); stallTimer = null; }
|
||||
}
|
||||
const { done, value } = chunk;
|
||||
if (done) break;
|
||||
chunks.push(value);
|
||||
downloadedBytes += value.length;
|
||||
const percent = Math.max(0, Math.min(100, Math.floor((downloadedBytes / totalBytes) * 100)));
|
||||
if (onProgress && percent !== lastReportedPercent) {
|
||||
const elapsedMs = Math.max(1, now() - downloadStartedAt);
|
||||
const bytesPerSecond = Math.round((downloadedBytes * 1000) / elapsedMs);
|
||||
const etaSeconds = bytesPerSecond > 0 ? Math.ceil(Math.max(0, totalBytes - downloadedBytes) / bytesPerSecond) : null;
|
||||
lastReportedPercent = percent;
|
||||
onProgress({
|
||||
stage: 'downloading',
|
||||
percent,
|
||||
bytesDownloaded: downloadedBytes,
|
||||
bytesTotal: totalBytes,
|
||||
bytesPerSecond,
|
||||
etaSeconds
|
||||
resetDeadline();
|
||||
const res = await fetchImpl(check.assetUrl, {
|
||||
method: 'GET', signal: downloadController.signal, redirect: 'follow',
|
||||
cache: 'no-store', headers: { 'Cache-Control': 'no-cache', 'Accept-Encoding': 'identity' }
|
||||
});
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
if (!res.ok) {
|
||||
const error = new Error(`Download fehlgeschlagen: HTTP ${res.status}`);
|
||||
error.retryable = [408, 429, 500, 502, 503, 504].includes(res.status);
|
||||
throw error;
|
||||
}
|
||||
reader = res.body.getReader();
|
||||
let downloadedBytes = 0;
|
||||
let lastReportedPercent = -1;
|
||||
const downloadStartedAt = now();
|
||||
const chunks = [];
|
||||
if (attempt > 1 && onProgress) onProgress({ stage: 'downloading', percent: 0, bytesDownloaded: 0, bytesTotal: manifest.size, bytesPerSecond: 0, etaSeconds: null, attempt });
|
||||
while (true) {
|
||||
signal.throwIfAborted();
|
||||
resetDeadline();
|
||||
const { done, value } = await reader.read();
|
||||
clearTimeout(stallTimer);
|
||||
if (done) break;
|
||||
downloadedBytes += value.length;
|
||||
if (downloadedBytes > manifest.size) throw new Error('Heruntergeladene Datei hat eine abweichende Größe');
|
||||
chunks.push(value);
|
||||
const percent = Math.floor((downloadedBytes / manifest.size) * 100);
|
||||
if (onProgress && percent !== lastReportedPercent) {
|
||||
const elapsedMs = Math.max(1, now() - downloadStartedAt);
|
||||
const bytesPerSecond = Math.round((downloadedBytes * 1000) / elapsedMs);
|
||||
const etaSeconds = bytesPerSecond > 0 ? Math.ceil(Math.max(0, manifest.size - downloadedBytes) / bytesPerSecond) : null;
|
||||
lastReportedPercent = percent;
|
||||
onProgress({ stage: 'downloading', percent, bytesDownloaded: downloadedBytes, bytesTotal: manifest.size, bytesPerSecond, etaSeconds, attempt });
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
}
|
||||
}
|
||||
signal.throwIfAborted();
|
||||
if (downloadedBytes !== manifest.size) {
|
||||
const error = new Error('Heruntergeladene Datei ist unvollständig');
|
||||
error.retryable = true;
|
||||
throw error;
|
||||
}
|
||||
fileBuffer = Buffer.concat(chunks);
|
||||
} catch (error) {
|
||||
signal.throwIfAborted();
|
||||
retry = timedOut || error.retryable === true || ['UND_ERR_SOCKET', 'ECONNRESET', 'ETIMEDOUT', 'EPIPE', 'UND_ERR_CONNECT_TIMEOUT', 'UND_ERR_BODY_TIMEOUT'].includes(error.cause?.code || error.code) || /^(terminated|fetch failed)$/i.test(error.message);
|
||||
if (!retry) throw error;
|
||||
if (attempt === 3) throw new Error('Update-Download nach 3 Versuchen unterbrochen. Bitte Verbindung prüfen oder den Installer manuell herunterladen.', { cause: error });
|
||||
} finally {
|
||||
clearTimeout(stallTimer);
|
||||
signal.removeEventListener('abort', onAbort);
|
||||
downloadController.abort();
|
||||
if (reader) {
|
||||
try { reader.releaseLock?.(); } catch {}
|
||||
}
|
||||
}
|
||||
if (!retry) break;
|
||||
await delay(options.retryDelayMs ?? attempt * 1000, undefined, { signal });
|
||||
}
|
||||
|
||||
const fileBuffer = Buffer.concat(chunks);
|
||||
if (fileBuffer.length !== manifest.size) {
|
||||
throw new Error('Heruntergeladene Datei hat eine abweichende Größe');
|
||||
}
|
||||
signal.throwIfAborted();
|
||||
|
||||
// Stage: verifying
|
||||
if (onProgress) onProgress({ stage: 'verifying', percent: 0 });
|
||||
@@ -372,7 +389,7 @@ async function prepareUpdate(onProgress, options = {}) {
|
||||
if (onProgress) onProgress({ stage: signal.aborted ? 'aborted' : 'error', error: failure.message });
|
||||
throw failure;
|
||||
} finally {
|
||||
activeAbort = null;
|
||||
if (activeAbort === controller) activeAbort = null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user