Skip to content

Commit

Permalink
Retry on EPERM when locking and reading
Browse files Browse the repository at this point in the history
See: #116
Signed-off-by: Juan Cruz Viotti <jv@jviotti.com>
  • Loading branch information
jviotti committed Dec 2, 2018
1 parent 6e18b27 commit 3756fae
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 17 deletions.
17 changes: 14 additions & 3 deletions lib/lock.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ const lockFile = require('lockfile');
*/
const lockOptions = {
stale: 10000,
retries: Infinity,
retries: 100,
retryWait: 50
};

Expand All @@ -52,8 +52,19 @@ const lockOptions = {
* }
* })
*/
exports.lock = function(file, callback) {
lockFile.lock(file, lockOptions, callback);
exports.lock = function(file, callback, times) {
times = times || 0;

lockFile.lock(file, lockOptions, function(error) {
if (error && error.code === 'EPERM' && times < 10) {
setTimeout(function() {
exports.unlock(file, callback, times + 1);
}, 1000);
return;
}

return callback(error);
});
};

/**
Expand Down
43 changes: 29 additions & 14 deletions lib/storage.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,31 @@ const path = require('path');
const utils = require('./utils');
const lock = require('./lock');

const readFile = function(fileName, callback, times) {
times = times || 0;

fs.readFile(fileName, {
encoding: 'utf8'
}, function(error, object) {
if (!error) {
return callback(null, object);
}

if (error.code === 'ENOENT') {
return callback(null, JSON.stringify({}));
}

if (error.code === 'EPERM' && times < 10) {
setTimeout(function() {
readFile(fileName, callback, times + 1);
}, 1000);
return;
}

return callback(error);
});
};

/**
* @summary Get the default data path
* @function
Expand Down Expand Up @@ -134,26 +159,16 @@ exports.get = function(key, options, callback) {
function(made, next) {
lock.lock(utils.getLockFileName(fileName), function(error) {
if (error && error.code === 'EEXIST') {
return exports.get(key, options, callback);
setTimeout(function() {
return exports.get(key, options, callback);
}, 500);
}

return next(error);
});
},
function(callback) {
fs.readFile(fileName, {
encoding: 'utf8'
}, function(error, object) {
if (!error) {
return callback(null, object);
}

if (error.code === 'ENOENT') {
return callback(null, JSON.stringify({}));
}

return callback(error);
});
readFile(fileName, callback);
},
function(object, callback) {
var objectJSON = {};
Expand Down

0 comments on commit 3756fae

Please sign in to comment.