fix(settings): clean up orphaned temp files and harden atomic writes

This commit is contained in:
Bohdan Triapitsyn
2026-08-22 11:55:38 +03:00
parent 735a9463ca
commit fcbe2c0414
8 changed files with 142 additions and 25 deletions
+8 -3
View File
@@ -77,10 +77,15 @@ const writeJsonRoot = async (settingsFilePath, root) => {
await fsp.mkdir(path.dirname(settingsFilePath), { recursive: true });
// Atomic write: concurrent readers (main.mjs, web server) would otherwise
// see partial JSON and readJsonRoot()'s catch would silently coerce to {},
// causing the next read-modify-write to wipe the entire settings file.
// causing the next read-modify-write wipe the entire settings file.
const tmp = `${settingsFilePath}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
await fsp.writeFile(tmp, JSON.stringify(root, null, 2));
await fsp.rename(tmp, settingsFilePath);
try {
await fsp.writeFile(tmp, JSON.stringify(root, null, 2));
await fsp.rename(tmp, settingsFilePath);
} catch (error) {
await fsp.rm(tmp, { force: true }).catch(() => {});
throw error;
}
};
const defaultTrue = () => true;