← Files Flows by plugin.spaceARCHIVED FILE

lib/local-state.mjs

1.65 KB · Nov 30, 2026 · 00:17 UTC

↓ Download file

import { mkdir, open, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
import { randomUUID } from 'node:crypto';

// Library membership and account receipts share one inter-process lock. In
// particular, two viewer/CLI processes cannot both claim the last free slot.
export async function withLibraryLock(root, action) {
  await mkdir(root, { recursive: true, mode: 0o700 });
  const path = join(root, 'library.lock');
  let lock;
  for (let attempt = 0; attempt < 150; attempt++) {
    try { lock = await open(path, 'wx', 0o600); await lock.writeFile(String(process.pid)); break; }
    catch (error) {
      if (error.code !== 'EEXIST') throw error;
      try {
        const before = await stat(path), pid = Number(await readFile(path, 'utf8'));
        let abandoned = !Number.isInteger(pid) || pid <= 0;
        if (!abandoned) { try { process.kill(pid, 0); } catch (failure) { abandoned = failure.code === 'ESRCH'; } }
        if (abandoned && Date.now() - before.mtimeMs > 1000 && (await stat(path)).ino === before.ino) await rm(path, { force: true });
      } catch { /* Another writer released the lock. */ }
      await new Promise(resolve => setTimeout(resolve, 20));
    }
  }
  if (!lock) throw Object.assign(new Error('Library is busy. Try again.'), { status: 409 });
  try { return await action(); }
  finally { await lock.close(); await rm(path, { force: true }); }
}

export async function writeState(path, value) {
  const temp = `${path}.${randomUUID()}.tmp`;
  try { await writeFile(temp, JSON.stringify(value), { mode: 0o600, flag: 'wx' }); await rename(temp, path); }
  finally { await rm(temp, { force: true }); }
}

SHA-256: 8ccc07075d45f594cbc4e24bc2b59fdb48e144d80ab2df87ee785f5cac97b177