nodedb-json
Version:
A lightweight JSON-based database for Node.js with TypeScript support, indexing, and complex query capabilities
122 lines • 3.67 kB
JavaScript
import * as fs from 'fs';
import * as path from 'path';
import { FileLockError } from '../errors/file-lock-error.js';
import { ensureParentDirectory } from './atomic-writer.js';
const activeLocks = new Map();
let exitHookInstalled = false;
export class FileLock {
constructor(options) {
this.acquired = false;
this.lockPath = options.lockPath;
this.enabled = options.enabled;
this.staleLockMs = options.staleLockMs;
this.lockId = `${process.pid}:${Date.now()}:${Math.random().toString(16).slice(2)}`;
}
acquire() {
if (!this.enabled || this.acquired) {
return;
}
ensureParentDirectory(this.lockPath);
this.removeStaleLock();
try {
fs.writeFileSync(this.lockPath, this.createLockPayload(), {
encoding: 'utf-8',
flag: 'wx'
});
this.acquired = true;
activeLocks.set(this.lockPath, this.lockId);
installExitHook();
}
catch (error) {
if ((error === null || error === void 0 ? void 0 : error.code) === 'EEXIST') {
throw new FileLockError(this.lockPath);
}
throw error;
}
}
release() {
if (!this.enabled || !this.acquired) {
return;
}
this.acquired = false;
activeLocks.delete(this.lockPath);
unlinkLockFile(this.lockPath, this.lockId);
}
get path() {
return this.lockPath;
}
removeStaleLock() {
if (!this.staleLockMs || this.staleLockMs <= 0 || !fs.existsSync(this.lockPath)) {
return;
}
const stat = fs.statSync(this.lockPath);
if (Date.now() - stat.mtimeMs < this.staleLockMs) {
return;
}
const lockOwnerPid = readLockOwnerPid(this.lockPath);
if (lockOwnerPid === undefined || !isProcessAlive(lockOwnerPid)) {
fs.unlinkSync(this.lockPath);
}
}
createLockPayload() {
return `${JSON.stringify({
pid: process.pid,
id: this.lockId,
cwd: process.cwd(),
file: path.resolve(this.lockPath),
createdAt: new Date().toISOString()
}, null, 2)}\n`;
}
}
function readLockOwnerPid(lockPath) {
try {
const content = fs.readFileSync(lockPath, 'utf-8');
const parsed = JSON.parse(content);
return Number.isInteger(parsed.pid) && parsed.pid > 0 ? parsed.pid : undefined;
}
catch (_a) {
return undefined;
}
}
function isProcessAlive(pid) {
try {
process.kill(pid, 0);
return true;
}
catch (error) {
return (error === null || error === void 0 ? void 0 : error.code) === 'EPERM';
}
}
function installExitHook() {
if (exitHookInstalled) {
return;
}
exitHookInstalled = true;
process.once('exit', () => {
for (const [lockPath, lockId] of activeLocks) {
try {
unlinkLockFile(lockPath, lockId);
}
catch (_a) {
// Process exit cleanup is best-effort.
}
}
activeLocks.clear();
});
}
function unlinkLockFile(lockPath, expectedId) {
try {
const content = fs.readFileSync(lockPath, 'utf-8');
const parsed = JSON.parse(content);
if (parsed.id !== expectedId) {
return;
}
fs.unlinkSync(lockPath);
}
catch (error) {
if ((error === null || error === void 0 ? void 0 : error.code) !== 'ENOENT') {
throw error;
}
}
}
//# sourceMappingURL=file-lock.js.map