Last active
December 13, 2015 18:38
-
-
Save thehydroimpulse/4956319 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function History(options) { | |
this.timestamp = options.timestamp || new Date(); | |
this.time = options.time || new Date().getTime(); | |
} | |
function Server(options) { | |
this.port = options.port || null; | |
this.alias = options.alias || null; | |
this.queue = []; | |
this.history = options.history || []; | |
this.numOpenRequests = 0; | |
this.lastTime = null; | |
} | |
Server.prototype.addHistory = function(history) { | |
this.history.push(history); | |
}; | |
function Cluster() { | |
this.previous = null; | |
this.servers = []; | |
} | |
Cluster.prototype.addServer = function(options) { | |
this.servers.push(new Server(options)); | |
}; | |
// Algorithm: | |
Cluster.prototype.next = function() { | |
// Find any server that doesn't have any open connections or any queues: | |
var points = {}; | |
var last_time = {index: null, time: 0}; | |
var self = this; | |
var processedFirst = false; | |
this.servers.forEach(function(s, index) { | |
if (!points[index]) points[index] = 0; | |
// Add 50 points for this process: | |
if (s.queue.length === 0 && s.numOpenRequests === 0) { | |
points[index] += 50; | |
} else { | |
points[index] -= 30; | |
} | |
// Now process the completion time from the last request: | |
if (last_time.index === null) { | |
last_time.index = index; | |
last_time.time = self.servers[index].lastTime; | |
} | |
if (last_time.time < self.servers[index].lastTime) { | |
// Increase points by 18 | |
points[index] += 18; | |
// Decrease the last index by 18: | |
points[index-1] -= 18; | |
} | |
}); | |
var bigger = 0; | |
var index = 0; | |
for (var i = 0; i< Object.keys(points).length; i++) { | |
var p = points[i]; | |
if (p > bigger) { | |
bigger = p; | |
index = i; | |
} else if (p === bigger) { | |
var random = Math.floor(Math.random() * (i - 0 + 1)) + 0; | |
bigger = points[random]; | |
index = random; | |
} | |
} | |
return this.servers[index]; | |
}; | |
// Testing: | |
var cluster = new Cluster(); | |
cluster.addServer({ | |
port: 9999, | |
alias: 'server#113' | |
}); | |
cluster.addServer({ | |
port: 1111, | |
alias: 'server#11' | |
}); | |
//console.log(cluster); | |
function HTTPServer() { | |
} | |
HTTPServer.prototype.request = function(req, res) { | |
console.log("Accepting a request"); | |
// Find the next server responsible for this request: | |
var next = cluster.next(); | |
console.log("Responsible Server: ", next, " with a port of: #" + next.port); | |
}; | |
window.http = new HTTPServer(); | |
cluster.next(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment