merge: 配置写入重试 NTFS 瞬时重命名错误并清理临时文件

This commit is contained in:
margrop
2026-12-04 04:19:02 +08:00
2 changed files with 76 additions and 6 deletions

View File

@@ -5,10 +5,11 @@
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import fs from 'fs';
import { MAX_CONFIG_RENAME_RETRIES } from '@/lib/config/store';
// Mock fs module
vi.mock('fs', () => {
const mocked = { readFileSync: vi.fn(), writeFileSync: vi.fn(), renameSync: vi.fn(), mkdirSync: vi.fn(), chmodSync: vi.fn() };
const mocked = { readFileSync: vi.fn(), writeFileSync: vi.fn(), renameSync: vi.fn(), mkdirSync: vi.fn(), chmodSync: vi.fn(), rmSync: vi.fn() };
return { default: mocked, ...mocked };
});
@@ -275,7 +276,7 @@ describe('config module', () => {
updateAppConfig({ aiProvider: 'openai' });
const tmp = vi.mocked(fs.writeFileSync).mock.calls[0][0] as string;
expect(tmp).toMatch(/app-config\.json\.\d+\.tmp$/);
expect(tmp).toMatch(/app-config\.json\.\d+\.[0-9a-f-]{36}\.tmp$/);
expect(fs.renameSync).toHaveBeenCalledWith(tmp, expect.stringMatching(/app-config\.json$/));
expect(fs.chmodSync).toHaveBeenCalledWith(tmp, 0o600);
expect(fs.chmodSync).toHaveBeenCalledWith(expect.stringMatching(/config$/), 0o700);
@@ -345,5 +346,38 @@ describe('config module', () => {
expect(result.allowRegistration).toBe(false);
});
it('改名遇 EPERM/EBUSY 瞬时错误时重试成功并清理临时文件', async () => {
mockNoConfigFile();
vi.mocked(fs.renameSync)
.mockImplementationOnce(() => {
throw Object.assign(new Error('EPERM: operation not permitted'), { code: 'EPERM' });
})
.mockImplementationOnce(() => {
throw Object.assign(new Error('EBUSY: resource busy'), { code: 'EBUSY' });
});
const { updateAppConfig } = await import('@/lib/config');
const result = updateAppConfig({ aiProvider: 'openai' });
expect(result.aiProvider).toBe('openai');
expect(fs.renameSync).toHaveBeenCalledTimes(3);
const tmp = vi.mocked(fs.writeFileSync).mock.calls[0][0] as string;
expect(fs.rmSync).toHaveBeenCalledWith(tmp, { force: true });
});
it('改名持续失败时按上限重试、抛出原错误并清理临时文件', async () => {
mockNoConfigFile();
vi.mocked(fs.renameSync).mockReset();
vi.mocked(fs.renameSync).mockImplementation(() => {
throw Object.assign(new Error('EPERM: operation not permitted'), { code: 'EPERM' });
});
const { updateAppConfig } = await import('@/lib/config');
expect(() => updateAppConfig({ aiProvider: 'openai' })).toThrow('EPERM');
expect(fs.renameSync).toHaveBeenCalledTimes(1 + MAX_CONFIG_RENAME_RETRIES);
const tmp = vi.mocked(fs.writeFileSync).mock.calls[0][0] as string;
expect(fs.rmSync).toHaveBeenCalledWith(tmp, { force: true });
});
});
});

View File

@@ -2,6 +2,7 @@ import "server-only";
import fs from 'fs';
import path from 'path';
import { randomUUID } from 'crypto';
import { createLogger } from '../logger';
import { DEFAULT_QUESTION_NUMBERING, isQuestionNumbering } from "../seq-no/seq-no-format";
import type { QuestionNumbering } from "../seq-no/seq-no-format";
@@ -36,16 +37,51 @@ function readConfigFile(): string | null {
}
}
/** Windows NTFS 上杀毒扫描或并发读取可能让 rename 短暂失败,按次数与间隔重试 */
export const MAX_CONFIG_RENAME_RETRIES = 5;
const RENAME_RETRY_DELAY_MS = 50;
const TRANSIENT_RENAME_CODES: Record<string, true> = { EPERM: true, EBUSY: true, EACCES: true };
/** 同步等待:配置写入在主线程,重试间隔必须短且不能引入异步时序 */
function sleepSync(ms: number): void {
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
}
function renameConfigFile(tmp: string, file: string): void {
let lastError: NodeJS.ErrnoException | undefined;
for (let attempt = 0; attempt <= MAX_CONFIG_RENAME_RETRIES; attempt += 1) {
try {
fs.renameSync(tmp, file);
return;
} catch (error) {
lastError = error as NodeJS.ErrnoException;
if (attempt === MAX_CONFIG_RENAME_RETRIES || !TRANSIENT_RENAME_CODES[lastError.code ?? '']) break;
sleepSync(RENAME_RETRY_DELAY_MS);
}
}
throw lastError ?? new Error('CONFIG_RENAME_FAILED');
}
/** 先写临时文件再改名替换,避免其他请求读到写了一半的配置 */
function writeConfigFile(config: unknown): void {
const file = configFilePath();
const directory = path.dirname(file);
const tmp = `${file}.${process.pid}.tmp`;
// 唯一后缀避免同进程并发写入互相覆盖
const tmp = `${file}.${process.pid}.${randomUUID()}.tmp`;
fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
fs.chmodSync(directory, 0o700);
fs.writeFileSync(tmp, JSON.stringify(config, null, 2), { mode: 0o600 });
fs.chmodSync(tmp, 0o600);
fs.renameSync(tmp, file);
try {
fs.writeFileSync(tmp, JSON.stringify(config, null, 2), { mode: 0o600 });
fs.chmodSync(tmp, 0o600);
renameConfigFile(tmp, file);
} finally {
// 写入或改名失败时清理临时文件,不污染 config 目录
try {
fs.rmSync(tmp, { force: true });
} catch {
// 清理失败不影响主流程,临时文件仍可被后续排查
}
}
}
export function getAppConfig(): AppConfig {