fix: config.json 원자적 쓰기 + 동시 저장 직렬화

updateConfig()는 fire-and-forget이고 호출 지점이 41곳(대부분 HTTP 라우트)인데
saveConfig()가 평범한 writeFile을 써서, 두 저장이 겹치면 파일이 깨졌다.
writeFile은 truncate 후 청크 단위로 쓰기 때문에 짧은 쪽이 온전히 기록된 뒤
긴 쪽의 남은 청크가 자기 fd 오프셋에 덧붙어, 유효한 JSON 뒤에 "}}" 조각이
붙은 형태가 된다. 재현 시 200회 중 196회 손상, 실제 손상 파일과 꼬리 패턴 일치.
2026-08-08 밤부터 08-09 새벽까지 세 번 발생했다.

- temp 파일에 쓰고 fsync 후 rename (같은 파일시스템 내 원자적 교체)
- writeQueue 프라미스 체인으로 동시 저장 직렬화
- 파싱 실패 시 config.json.corrupt-<timestamp>로 백업.
  DEFAULT_CONFIG 폴백 상태에서 updateConfig가 한 번만 돌아도 기본값이
  파일을 덮어써 29개 섹션(NVR/collabora/email/telegram 등)이 영구 소실된다.

검증: 재현 테스트 196/200 → 0/200, 임시 파일 누수 없음.
라이브 API 동시 저장 6건에도 config 정상.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
kimandClaude Opus 5 committed 2026-08-09 01:03:59 +09:00
1 parent 1071f7205d
commit de738c3abd
1 file changed
+42 -1
+42 -1
View File
@@ -399,6 +399,14 @@ function migrateSecretsToVault(config: any, configDir: string): any {
export class ConfigManager {
private config: SmallClawConfig;
/**
* Serializes saveConfig() calls. updateConfig() is fire-and-forget and is
* reachable from ~40 call sites (mostly HTTP routes), so two saves can
* otherwise overlap: a plain writeFile truncates and then writes in chunks,
* letting the shorter write land complete while the longer one appends its
* tail past the end — producing valid JSON followed by a stray "}}" fragment.
*/
private writeQueue: Promise<void> = Promise.resolve();
constructor() {
this.config = this.loadConfig();
@@ -462,6 +470,18 @@ export class ConfigManager {
}
} catch (error) {
console.warn('Failed to load config, using defaults:', error);
// The in-memory config is now DEFAULT_CONFIG, and the next updateConfig()
// would write those defaults straight over the unreadable file — losing
// every section it still contains. Keep a copy so it stays recoverable.
try {
if (fs.existsSync(CONFIG_FILE)) {
const backup = `${CONFIG_FILE}.corrupt-${new Date().toISOString().replace(/[:.]/g, '-')}`;
fs.copyFileSync(CONFIG_FILE, backup);
console.warn(`[Config] Saved unreadable config to ${backup} before falling back to defaults`);
}
} catch (backupErr: any) {
console.error('[Config] Could not back up unreadable config:', String(backupErr?.message || backupErr));
}
}
return DEFAULT_CONFIG;
}
@@ -476,6 +496,14 @@ export class ConfigManager {
}
public async saveConfig(): Promise<void> {
// Chain onto any in-flight save so writes never interleave.
const run = this.writeQueue.then(() => this.writeConfigAtomic());
// Keep the queue alive even if this save rejects.
this.writeQueue = run.catch(() => {});
return run;
}
private async writeConfigAtomic(): Promise<void> {
try {
if (!fs.existsSync(CONFIG_DIR)) {
fs.mkdirSync(CONFIG_DIR, { recursive: true });
@@ -483,7 +511,20 @@ export class ConfigManager {
// Before writing, migrate any plaintext secrets to the vault
// so they are never stored in config.json going forward.
const sanitized = migrateSecretsToVault(this.config, CONFIG_DIR);
await fs.promises.writeFile(CONFIG_FILE, JSON.stringify(sanitized, null, 2));
const payload = JSON.stringify(sanitized, null, 2);
// Write to a temp file in the same directory, then rename. rename(2) is
// atomic within a filesystem, so readers see either the old or the new
// file — never a half-written one.
const tmp = `${CONFIG_FILE}.tmp-${process.pid}-${Date.now()}`;
const handle = await fs.promises.open(tmp, 'w');
try {
await handle.writeFile(payload, 'utf-8');
await handle.sync();
} finally {
await handle.close();
}
await fs.promises.rename(tmp, CONFIG_FILE);
} catch (error) {
console.error('Failed to save config:', error);
throw error;