forked from errorception/redis-lock
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
82 lines (66 loc) · 2.06 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
"use strict";
function acquireLock(client, lockName, timeout, retryDelay, onLockAquired) {
function retry() {
setTimeout(function() {
acquireLock(client, lockName, timeout, retryDelay, onLockAquired);
}, retryDelay);
}
var lockTimeoutValue = (Date.now() + timeout + 1);
client.setnx(lockName, lockTimeoutValue, function(err, result) {
if(err) return retry();
if(result === 0) {
// Lock couldn't be aquired. Check if the existing lock has timed out.
client.get(lockName, function(err, existingLockTimestamp) {
if(err) return retry();
if(!existingLockTimestamp) {
// Wait, the lock doesn't exist!
// Someone must have called .del after we called .setnx but before .get.
// https://github.com/errorception/redis-lock/pull/4
return retry();
}
existingLockTimestamp = parseFloat(existingLockTimestamp);
if(existingLockTimestamp > Date.now()) {
// Lock looks valid so far. Wait some more time.
return retry();
}
lockTimeoutValue = (Date.now() + timeout + 1)
client.getset(lockName, lockTimeoutValue, function(err, result) {
if(err) return retry();
if(result == existingLockTimestamp) {
onLockAquired(lockTimeoutValue);
} else {
retry();
}
});
});
} else {
onLockAquired(lockTimeoutValue);
}
});
}
module.exports = function(client, retryDelay) {
if(!(client && client.setnx)) {
throw new Error("You must specify a client instance of http://github.com/mranney/node_redis");
}
retryDelay = retryDelay || 50;
return function(lockName, timeout, taskToPerform) {
if(!lockName) {
throw new Error("You must specify a lock string. It is on the basis on this the lock is acquired.");
}
if(!taskToPerform) {
taskToPerform = timeout;
timeout = 5000;
}
lockName = "lock." + lockName;
acquireLock(client, lockName, timeout, retryDelay, function(lockTimeoutValue) {
taskToPerform(function(done) {
done = done || function() {};
if(lockTimeoutValue > Date.now()) {
client.del(lockName, done);
} else {
done();
}
});
});
}
};