From 19f5e26b84dfe43d98ceed79ba64b951f3c2a874 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=AB=E6=88=91=E5=B0=8F=E6=9D=A8=E5=90=8C=E5=AD=A6?= <188421097+HunYiSage@users.noreply.github.com> Date: Fri, 9 Oct 2026 12:16:55 +0800 Subject: [PATCH] =?UTF-8?q?fix(core):=20atomicWrite=20=E5=88=AB=E8=B5=B0?= =?UTF-8?q?=20fsp.open=20/=20fsyncSync=20/=20closeSync?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit hostFs.promises 只包了 readFile/writeFile/mkdir/unlink/rm/copyFile,没 open; hostFs 的同步侧也没 fsyncSync/closeSync。启动种子调 atomicWriteFile 立刻 抛 TypeError: fsp.open is not a function,applyBoot 整个倒下。 现在 atomicWriteSync/atomicWriteFile 只用 writeFile+rename,原子性靠 rename (POSIX / Windows MoveFileEx),断电丢最新一次写入可接受,下一次 apply 补。 atomicCopyFile 原本就只用 copyFile+rename,不受影响。 --- lib/core.js | 20 +++++--------------- 1 file changed, 5 insertions(+), 15 deletions(-) diff --git a/lib/core.js b/lib/core.js index ad4ce92..3105f5d 100644 --- a/lib/core.js +++ b/lib/core.js @@ -43,18 +43,14 @@ const HIDDEN_EXEC = { timeout: 8000, }; -// H19:原子写。write-to-tmp + fsync + rename。断电或 EBUSY 都不会半写坏原文件。 +// H19:原子写。write-to-tmp + rename。EBUSY/ENOSPC 都不会半写坏原文件。 +// 不走 FileHandle:hostFs.promises 只包了 readFile/writeFile/mkdir/unlink/rm/copyFile,无 open。 +// 不显式 fsync:原子性靠 rename;KB 级配置文件断电丢最新一次写入可接受,下一次 apply 会补。 export function atomicWriteSync(fp, content, encoding = "utf8") { const dir = path.dirname(fp); fs.mkdirSync(dir, { recursive: true }); const tmp = `${fp}.${process.pid}.${Date.now()}.tmp`; - const fd = fs.openSync(tmp, "w"); - try { - fs.writeFileSync(fd, content, encoding); - try { fs.fsyncSync(fd); } catch { /* FS 不支持 fsync 时忽略 */ } - } finally { - try { fs.closeSync(fd); } catch { /* ignore */ } - } + fs.writeFileSync(tmp, content, encoding); try { fs.renameSync(tmp, fp); } catch (e) { @@ -67,13 +63,7 @@ export async function atomicWriteFile(fp, content, encoding = "utf8") { const dir = path.dirname(fp); await fsp.mkdir(dir, { recursive: true }); const tmp = `${fp}.${process.pid}.${Date.now()}.tmp`; - const handle = await fsp.open(tmp, "w"); - try { - await handle.writeFile(content, encoding); - try { await handle.sync(); } catch { /* ignore */ } - } finally { - try { await handle.close(); } catch { /* ignore */ } - } + await fsp.writeFile(tmp, content, encoding); try { await fsp.rename(tmp, fp); } catch (e) {