src/runtime/atomic.ts
2 KB - Voir le fichier brut
// Small helpers for files that several tasks in one process update: the session index, the
// job list, and the policy overrides (labs 02, 05, 09).
//
// Two things go wrong without them, even with one process:
// 1. Two writers use the same temp file name: one renames it away and the other fails.
// 2. Two read-modify-write updates interleave: both read the old file and the last write wins,
// so one change is lost.
// `writeFileAtomic` uses a unique temp name per write; `Mutex` runs updates one at a time.
// Separate processes are kept apart by the process lock (lab 12).
import { randomBytes } from 'node:crypto';
import { mkdir, rename, rm, writeFile } from 'node:fs/promises';
import path from 'node:path';
/** Write to a unique temp file, then rename: readers see the old file or the new one. */
export async function writeFileAtomic(file: string, content: string): Promise<void> {
await mkdir(path.dirname(file), { recursive: true });
const temp = `${file}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
try {
await writeFile(temp, content, 'utf8');
await rename(temp, file);
} catch (err) {
await rm(temp, { force: true });
throw err;
}
}
/** Runs async functions one at a time, in call order. A failure does not block the next one. */
export class Mutex {
private tail: Promise<unknown> = Promise.resolve();
run<T>(work: () => Promise<T>): Promise<T> {
const result = this.tail.then(work, work);
this.tail = result.catch(() => undefined);
return result;
}
}