feat(saves): localize battle and preset names, merge overview form and guard cache writes

This commit is contained in:
N0VAN0M4LY committed 2026-11-30 19:26:13 +08:00
1 parent e6e75d92c6
commit 7cb1011f0d
11 files changed
+276 -59

No files matched your search

+26 -3
View File
@@ -2,12 +2,17 @@
* Write a file so that a crash leaves either the old or the new content, never a mix:
* write a temporary file next to it, flush it to disk, then rename it over the target.
*/
import { closeSync, fsyncSync, mkdirSync, openSync, renameSync, writeSync } from 'node:fs';
import { randomBytes } from 'node:crypto';
import { closeSync, fsyncSync, mkdirSync, openSync, renameSync, rmSync, writeSync } from 'node:fs';
import { dirname } from 'node:path';
const TRANSIENT_RENAME_ERRORS = new Set(['EPERM', 'EBUSY', 'EACCES']);
const MAX_RENAME_ATTEMPTS = 6;
const WAIT_BUFFER = new Int32Array(new SharedArrayBuffer(4));
export function writeFileAtomic(path: string, content: Uint8Array | string): void {
mkdirSync(dirname(path), { recursive: true });
const temporary = `${path}.${process.pid}.tmp`;
const temporary = `${path}.${process.pid}.${randomBytes(6).toString('hex')}.tmp`;
const fd = openSync(temporary, 'w');
try {
writeSync(fd, typeof content === 'string' ? Buffer.from(content, 'utf8') : content);
@@ -15,5 +20,23 @@ export function writeFileAtomic(path: string, content: Uint8Array | string): voi
} finally {
closeSync(fd);
}
renameSync(temporary, path);
try {
renameWithRetry(temporary, path);
} catch (error) {
try { rmSync(temporary, { force: true }); } catch { /* ignore cleanup errors */ }
throw error;
}
}
function renameWithRetry(source: string, target: string): void {
for (let attempt = 1; ; attempt += 1) {
try {
renameSync(source, target);
return;
} catch (error) {
const code = (error as NodeJS.ErrnoException).code;
if (attempt >= MAX_RENAME_ATTEMPTS || !code || !TRANSIENT_RENAME_ERRORS.has(code)) throw error;
Atomics.wait(WAIT_BUFFER, 0, 0, attempt * 25);
}
}
}