Skip to content

Commit

Permalink
UUID for lock ownership check
Browse files Browse the repository at this point in the history
  • Loading branch information
TheDeveloper committed Aug 29, 2014
1 parent 6a09d89 commit f1e048c
Showing 1 changed file with 11 additions and 12 deletions.
23 changes: 11 additions & 12 deletions lib/warlock.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
var crypto = require('crypto');
var Scripty = require('node-redis-scripty');
var UUID = require('uuid');

var scripty;

Expand All @@ -9,7 +10,7 @@ module.exports = function(redis){
scripty = new Scripty(redis);

warlock.makeKey = function(key) {
return 'lock:' + crypto.createHash('md5').update(key).digest('hex').substr(0, 10);
return key + ':lock';
};

/**
Expand All @@ -23,33 +24,31 @@ module.exports = function(redis){

if (typeof key !== 'string') return cb(new Error('lock key must be string'));

scripty.loadScriptFile('lock', __dirname + '/lua/lock.lua', function(err, lock){
var id;
UUID.v1(null, (id = new Buffer(16)));
id = id.toString('base64');
redis.set(warlock.makeKey(key), id, 'PX', ttl, 'NX', function(err, lockSet) {
if (err) return cb(err);

var timestamp = Date.now();
lock.run(3, warlock.makeKey(key), ttl, timestamp, function(err, lockSet) {
if (err) return cb(err);

var unlock = warlock.unlock.bind(warlock, key, timestamp);
var unlock = warlock.unlock.bind(warlock, key, id);

if (!lockSet) unlock = false;
if (!lockSet) unlock = false;

return cb(err, unlock);
});
return cb(err, unlock);
});

return key;
};

warlock.unlock = function(key, timestamp, cb) {
warlock.unlock = function(key, id, cb) {
cb = cb || function(){};

if (typeof key !== 'string') return cb(new Error('lock key must be string'));

scripty.loadScriptFile('parityDel', __dirname + '/lua/parityDel.lua', function(err, parityDel){
if (err) return cb(err);

return parityDel.run(2, warlock.makeKey(key), timestamp, cb);
return parityDel.run(2, warlock.makeKey(key), id, cb);
});
};

Expand Down

0 comments on commit f1e048c

Please sign in to comment.