// One process per data folder (lab 12). // // The per-session queue (lab 08) keeps turns in order inside ONE process. Two processes on the // same data folder would each have their own queue and could interleave writes to the same // session log. So the process that serves Steward takes a lock file, /steward.pid, // created with the "wx" flag (fails if it exists). A lock left by a crashed process is detected // (its pid is gone) and taken over. import { mkdir, readFile, unlink, writeFile } from 'node:fs/promises'; import path from 'node:path'; export class LockError extends Error {} function alive(pid: number): boolean { try { process.kill(pid, 0); return true; } catch (err) { return (err as NodeJS.ErrnoException).code === 'EPERM'; } } export class ProcessLock { readonly file: string; private held = false; constructor(dataDir: string) { this.file = path.join(dataDir, 'steward.pid'); } async acquire(): Promise { await mkdir(path.dirname(this.file), { recursive: true }); for (let attempt = 0; attempt < 2; attempt++) { try { await writeFile(this.file, `${process.pid}\n`, { flag: 'wx' }); this.held = true; return; } catch (err) { if ((err as NodeJS.ErrnoException).code !== 'EEXIST') throw err; const pid = Number((await readFile(this.file, 'utf8').catch(() => '')).trim()); if (pid && pid !== process.pid && alive(pid)) { throw new LockError( `another Steward process (pid ${pid}) is using ${path.dirname(this.file)}. ` + 'Stop it first, or use a different STEWARD_DATA_DIR.', ); } await unlink(this.file).catch(() => undefined); // stale lock from a crashed process } } throw new LockError(`could not take the lock ${this.file}`); } async release(): Promise { if (!this.held) return; this.held = false; const pid = Number((await readFile(this.file, 'utf8').catch(() => '')).trim()); if (pid === process.pid) await unlink(this.file).catch(() => undefined); } }