| 'use strict';
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| 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';
|
| }
|
| }
|
|
|
|
|
| function sleepSync(ms) {
|
| Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
| }
|
|
|
| |
| |
| |
| |
| |
| |
| |
|
|
| 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;
|
| } 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);
|
| if (opts.onStaleClear) opts.onStaleClear(age);
|
| continue;
|
| }
|
| } catch (e2) {
|
|
|
| }
|
| 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) {
|
|
|
| }
|
| }
|
|
|
|
|
| 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,
|
| };
|
|
|