bitcore-wallet-service/lib/locallock.js

57 lines
1.1 KiB
JavaScript
Raw Normal View History

2015-04-07 13:02:08 -07:00
var _ = require('lodash');
var $ = require('preconditions').singleton();
var locks = {};
2015-04-08 06:21:01 -07:00
function Lock() {
2015-04-07 13:02:08 -07:00
};
2015-04-08 06:21:01 -07:00
Lock.prototype._runOne = function(token) {
var self = this;
2015-04-08 07:39:15 -07:00
var item = _.first(locks[token]);
if (!item || item.started) return;
item.started = true;
if (item.maxRunningTime > 0) {
setTimeout(function() {
var it = _.first(locks[token]);
if (it != item) return;
locks[token].shift();
self._runOne(token);
}, item.maxRunningTime);
}
2015-04-08 06:21:01 -07:00
2015-04-08 07:39:15 -07:00
item.fn(null, function() {
2015-04-08 06:21:01 -07:00
locks[token].shift();
self._runOne(token);
});
2015-04-07 13:02:08 -07:00
};
2015-04-08 06:21:01 -07:00
Lock.prototype.locked = function(token, wait, max, task) {
2015-04-08 07:39:15 -07:00
var self = this;
2015-04-08 06:21:01 -07:00
if (_.isUndefined(locks[token])) {
locks[token] = [];
2015-04-07 13:02:08 -07:00
}
2015-04-08 07:39:15 -07:00
var item = {
maxRunningTime: max,
started: false,
fn: task,
};
locks[token].push(item);
if (wait > 0) {
setTimeout(function() {
var it = _.find(locks[token], item);
if (!it || it.started) return;
locks[token] = _.without(locks[token], it);
it.fn(new Error('Could not acquire lock ' + token));
}, wait);
2015-04-07 13:02:08 -07:00
}
2015-04-08 07:39:15 -07:00
self._runOne(token);
2015-04-07 13:02:08 -07:00
};
module.exports = Lock;