nomad / scripts /lib /file-lock.js
LucioLiu's picture
Initial release - mirrors github.com/LucioLiu/nomad
0110783 verified
Raw
History Blame Contribute Delete
3.66 kB
'use strict';
/**
* file-lock.js — concurrency-safe file locking primitive (Nomad scripts/ port).
*
* Ported from a production concurrency module, deployed at `91-team-tools/concurrency/lib/file-lock.js`,
* desensitized: no hardcoded paths, no reference to any specific deployment's
* history. Same algorithm, same defaults — atomic lock-file creation to queue
* concurrent writers, stale-lock self-healing, atomic replace-via-rename.
*
* Used by append-log.js (safe team-log append) and available to any script in
* this package that needs "many writers, one file, no corruption" guarantees.
*/
const fs = require('fs');
const crypto = require('crypto');
class LockError extends Error {
constructor(message, code) {
super(message);
this.name = 'LockError';
this.code = code || 'LOCK_ERROR';
}
}
/** Synchronous sleep without busy-waiting (Atomics.wait blocks the current thread cheaply). */
function sleepSync(ms) {
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
}
/**
* Atomically create a lock file to queue writers. If a lock already exists,
* check its mtime — older than staleMs is treated as a crashed holder's
* leftover and force-cleared (self-healing, no permanent deadlock).
* @param {string} lockPath usually `<targetFile>.lock`
* @param {{staleMs?:number, retryMax?:number, retryIntervalMs?:number, onWait?:Function, onStaleClear?:Function}} [opts]
* @throws {LockError} if the lock cannot be acquired within retryMax attempts
*/
function acquireLockSync(lockPath, opts) {
opts = opts || {};
const staleMs = opts.staleMs != null ? opts.staleMs : 30 * 1000;
const retryMax = opts.retryMax != null ? opts.retryMax : 30;
const retryIntervalMs = opts.retryIntervalMs != null ? opts.retryIntervalMs : 1000;
for (let i = 0; i < retryMax; i++) {
try {
fs.writeFileSync(lockPath, process.pid + ' ' + new Date().toISOString(), { flag: 'wx' });
return; // lock acquired
} catch (e) {
if (e.code !== 'EEXIST') throw new LockError('Failed to create lock file: ' + e.message, 'LOCK_CREATE_FAIL');
try {
const age = Date.now() - fs.statSync(lockPath).mtimeMs;
if (age > staleMs) {
fs.unlinkSync(lockPath); // stale leftover — clear and retry next loop
if (opts.onStaleClear) opts.onStaleClear(age);
continue;
}
} catch (e2) {
/* lock was just released by the holder — next loop will grab it */
}
if (i === 0 && opts.onWait) opts.onWait();
sleepSync(retryIntervalMs);
}
}
throw new LockError(
'Still could not acquire the lock after ' + retryMax + 's. If you are sure no one else is writing, ' +
'manually delete ' + lockPath + ' and retry.',
'LOCK_TIMEOUT'
);
}
function releaseLock(lockPath) {
try {
fs.unlinkSync(lockPath);
} catch (e) {
/* already cleared or never existed */
}
}
/** Temp file + rename atomic replace (Node's rename on Windows overwrites an existing target). UTF-8, no BOM. */
function atomicWriteSync(targetPath, content) {
const tmp = targetPath + '.tmp_' + process.pid + '_' + Date.now();
fs.writeFileSync(tmp, content, 'utf8');
fs.renameSync(tmp, targetPath);
}
function sha256Hex(content) {
return crypto.createHash('sha256').update(content, 'utf8').digest('hex');
}
function fileSha256Hex(filePath) {
return sha256Hex(fs.readFileSync(filePath, 'utf8'));
}
module.exports = {
LockError,
sleepSync,
acquireLockSync,
releaseLock,
atomicWriteSync,
sha256Hex,
fileSha256Hex,
};