Skip to content

Commit

Permalink
lib: fix hashing
Browse files Browse the repository at this point in the history
  • Loading branch information
indutny committed Feb 18, 2012
1 parent 5f7c4ef commit 963c619
Showing 1 changed file with 21 additions and 11 deletions.
32 changes: 21 additions & 11 deletions lib/sticky-session.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,25 @@
var net = require('net'),
cluster = require('cluster');

function hash(ip, seed) {
var hash = ip.reduce(function(r, num) {
r += parseInt(num, 10);
r %= 2147483648;
r += (r << 10)
r %= 2147483648;
r ^= r >> 6;
return r;
}, seed);

hash += hash << 3;
hash %= 2147483648;
hash ^= hash >> 11;
hash += hash << 15;
hash %= 2147483648;

return hash >>> 0;
}

module.exports = function sticky(num, callback) {
var server;

Expand Down Expand Up @@ -28,22 +47,13 @@ module.exports = function sticky(num, callback) {
server = net.createServer(function(c) {
// Get int31 hash of ip
var worker,
hash = c.remoteAddress.split(/\./g).reduce(function(r, num) {
r += num;
r += (r << 10) & 2147483647;
r ^= r >> 6;
return r & 2147483647;
}, seed);

hash += hash << 3;
hash ^= hash >> 11;
hash += (hash << 15) & 2147483647;
ipHash = hash((c.remoteAddress || '').split(/\./g), seed);

// Pause socket (so we won't loose any data)
c.pause();

// Pass connection to worker
worker = workers[hash % workers.length];
worker = workers[ipHash % workers.length];
worker.send('sticky-session:connection', c._handle);

// And detach socket from master process
Expand Down

0 comments on commit 963c619

Please sign in to comment.