fix(restore): guarantee cleanup of uploaded backup archive
Wrap temp-dir removal in removeTempDir() so a failed rmSync cannot hang the async restore handler and leave the archive on disk, close the peek stream descriptor, and clean wido-up-*/wido-rst-* on response finish and the missing-file path.
This commit is contained in:
@@ -81,6 +81,12 @@ function tarEntryFilter(root) {
|
||||
};
|
||||
}
|
||||
|
||||
function removeTempDir(dir) {
|
||||
try {
|
||||
if (dir) fs.rmSync(dir, { recursive: true, force: true });
|
||||
} catch {}
|
||||
}
|
||||
|
||||
function sweepRestoreTempDirs() {
|
||||
let names = [];
|
||||
try {
|
||||
@@ -111,5 +117,6 @@ module.exports = {
|
||||
isDiskFullError,
|
||||
isEntryInside,
|
||||
tarEntryFilter,
|
||||
removeTempDir,
|
||||
sweepRestoreTempDirs,
|
||||
};
|
||||
|
||||
@@ -41,6 +41,7 @@ const {
|
||||
backupRequestTimeoutMs,
|
||||
isDiskFullError,
|
||||
parseBackupLimitMb,
|
||||
removeTempDir,
|
||||
tarEntryFilter,
|
||||
sweepRestoreTempDirs,
|
||||
} = require('./lib/restore');
|
||||
@@ -6078,7 +6079,7 @@ async function buildBackupArchive() {
|
||||
const { size } = fs.statSync(outPath);
|
||||
return { file: outPath, name: `whatido-backup-${stamp}.tar.gz`, size, counts: payload.counts };
|
||||
} finally {
|
||||
fs.rmSync(staging, { recursive: true, force: true });
|
||||
removeTempDir(staging);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6155,14 +6156,12 @@ sweepBackupStorage();
|
||||
setInterval(() => { pruneBackupTickets(); sweepBackupStorage(); }, 60 * 1000).unref();
|
||||
|
||||
function cleanupUpload(req) {
|
||||
try {
|
||||
const dir = req?.file?.destination || req?._uploadDir;
|
||||
if (dir) fs.rmSync(dir, { recursive: true, force: true });
|
||||
} catch {}
|
||||
removeTempDir(req?.file?.destination || req?._uploadDir);
|
||||
}
|
||||
|
||||
function peekGunzip(filePath, n) {
|
||||
return new Promise((resolve) => {
|
||||
const src = fs.createReadStream(filePath);
|
||||
const gunz = zlib.createGunzip();
|
||||
const bufs = [];
|
||||
let total = 0;
|
||||
@@ -6174,22 +6173,35 @@ function peekGunzip(filePath, n) {
|
||||
total += Math.min(c.length, need);
|
||||
if (total >= n) {
|
||||
done = true;
|
||||
src.destroy();
|
||||
gunz.destroy();
|
||||
}
|
||||
});
|
||||
gunz.on('error', () => resolve(null));
|
||||
gunz.on('error', () => resolve(done ? Buffer.concat(bufs) : null));
|
||||
gunz.on('close', () => resolve(Buffer.concat(bufs)));
|
||||
fs.createReadStream(filePath).pipe(gunz);
|
||||
src.on('error', () => {
|
||||
gunz.destroy();
|
||||
resolve(null);
|
||||
});
|
||||
src.pipe(gunz);
|
||||
});
|
||||
}
|
||||
|
||||
app.post('/api/restore', requireAdmin, backupUploadGuard, uploadBackup.single('backup'), async (req, res) => {
|
||||
if (!req.file) return res.status(400).json({ error: 'backup file required' });
|
||||
if (!req.file) {
|
||||
cleanupUpload(req);
|
||||
return res.status(400).json({ error: 'backup file required' });
|
||||
}
|
||||
res.on('finish', () => {
|
||||
cleanupUpload(req);
|
||||
removeTempDir(req._restoreStaging);
|
||||
});
|
||||
let data;
|
||||
let legacyPhotos = [];
|
||||
let staging;
|
||||
try {
|
||||
staging = fs.mkdtempSync(path.join(os.tmpdir(), 'wido-rst-'));
|
||||
req._restoreStaging = staging;
|
||||
const head = await peekGunzip(req.file.path, 8);
|
||||
if (head && head[0] === 0x7b) {
|
||||
const buf = await fs.promises.readFile(req.file.path);
|
||||
@@ -6200,19 +6212,19 @@ app.post('/api/restore', requireAdmin, backupUploadGuard, uploadBackup.single('b
|
||||
assertRestoreSpace(staging, req.file.size);
|
||||
await tar.x({ file: req.file.path, cwd: staging, filter: tarEntryFilter(staging) });
|
||||
if (!fs.existsSync(path.join(staging, 'data.json')) && fs.existsSync(path.join(staging, 'db.sql.gz'))) {
|
||||
fs.rmSync(staging, { recursive: true, force: true });
|
||||
removeTempDir(staging);
|
||||
cleanupUpload(req);
|
||||
return res.status(400).json({ error: 'Это архив скрипта scripts/backup.sh (db.sql.gz + _uploads) — восстанавливайте его через scripts/restore.sh. Для веб-восстановления скачайте архив в Настройках админки.' });
|
||||
}
|
||||
if (!fs.existsSync(path.join(staging, 'data.json'))) {
|
||||
fs.rmSync(staging, { recursive: true, force: true });
|
||||
removeTempDir(staging);
|
||||
cleanupUpload(req);
|
||||
return res.status(400).json({ error: 'В архиве нет data.json — это не архив веб-бэкапа из админки.' });
|
||||
}
|
||||
data = JSON.parse(fs.readFileSync(path.join(staging, 'data.json'), 'utf8'));
|
||||
}
|
||||
} catch (e) {
|
||||
if (staging) fs.rmSync(staging, { recursive: true, force: true });
|
||||
if (staging) removeTempDir(staging);
|
||||
cleanupUpload(req);
|
||||
console.error('Restore unpack failed:', e);
|
||||
if (e && e.code === 'RESTORE_NO_SPACE') {
|
||||
@@ -6225,7 +6237,7 @@ app.post('/api/restore', requireAdmin, backupUploadGuard, uploadBackup.single('b
|
||||
}
|
||||
const formatVersion = Number(data && data.version);
|
||||
if (!isSupportedBackupVersion(data)) {
|
||||
fs.rmSync(staging, { recursive: true, force: true });
|
||||
removeTempDir(staging);
|
||||
cleanupUpload(req);
|
||||
return res.status(400).json({ error: 'Неверный формат бэкапа' });
|
||||
}
|
||||
@@ -6233,7 +6245,7 @@ app.post('/api/restore', requireAdmin, backupUploadGuard, uploadBackup.single('b
|
||||
try {
|
||||
ndata = normalizeRestoreData(data);
|
||||
} catch (e) {
|
||||
fs.rmSync(staging, { recursive: true, force: true });
|
||||
removeTempDir(staging);
|
||||
cleanupUpload(req);
|
||||
return res.status(400).json({ error: 'Неверный формат бэкапа: ' + e.message });
|
||||
}
|
||||
@@ -6241,7 +6253,7 @@ app.post('/api/restore', requireAdmin, backupUploadGuard, uploadBackup.single('b
|
||||
try {
|
||||
client = await pool.connect();
|
||||
} catch (e) {
|
||||
fs.rmSync(staging, { recursive: true, force: true });
|
||||
removeTempDir(staging);
|
||||
cleanupUpload(req);
|
||||
console.error('Restore connect failed:', e);
|
||||
return res.status(503).json({ error: 'Не удалось подключиться к базе данных: ' + e.message });
|
||||
@@ -6531,7 +6543,7 @@ app.post('/api/restore', requireAdmin, backupUploadGuard, uploadBackup.single('b
|
||||
await client.query('COMMIT');
|
||||
} catch (e) {
|
||||
await client.query('ROLLBACK').catch(() => {});
|
||||
fs.rmSync(staging, { recursive: true, force: true });
|
||||
removeTempDir(staging);
|
||||
cleanupUpload(req);
|
||||
console.error('Restore failed:', e);
|
||||
if (isDiskFullError(e)) {
|
||||
@@ -6552,7 +6564,7 @@ app.post('/api/restore', requireAdmin, backupUploadGuard, uploadBackup.single('b
|
||||
await storage.uploadTree(path.join(staging, 'uploads'));
|
||||
}
|
||||
} catch (e) {
|
||||
fs.rmSync(staging, { recursive: true, force: true });
|
||||
removeTempDir(staging);
|
||||
cleanupUpload(req);
|
||||
console.error('Restore files failed:', e);
|
||||
const reason = isDiskFullError(e)
|
||||
@@ -6563,7 +6575,7 @@ app.post('/api/restore', requireAdmin, backupUploadGuard, uploadBackup.single('b
|
||||
data_restored: true,
|
||||
});
|
||||
}
|
||||
fs.rmSync(staging, { recursive: true, force: true });
|
||||
removeTempDir(staging);
|
||||
cleanupUpload(req);
|
||||
try {
|
||||
await sweepOrphanedUploads().catch(err => console.error('Upload sweep:', err));
|
||||
|
||||
Reference in New Issue
Block a user