Created
February 15, 2010 18:04
-
-
Save blaine/304844 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
var sys = require('sys'), | |
http = require('http'), | |
url = require('url'); | |
var subscriptions = {} | |
function getSubscribers (did) { | |
if (subscriptions[did]) { | |
// log open already. | |
return subscriptions[did]; | |
} else if (subscriptions[did] == false) { | |
// log is closed. | |
return false; | |
} else { | |
// create a new log. | |
subscriptions[did] = []; | |
return subscriptions[did]; | |
} | |
} | |
var logs = {}; | |
http.createServer(function (req, res) { | |
var requrl = url.parse(req, true); | |
if (requrl.pathname == '/newlogmessage') { | |
// We have an incoming message from the runner. | |
var subscribers = getSubscribers(requrl.query.deployid); | |
if (subscribers === false) { | |
// this shouldn't happen. we're getting a new message for a closed log. | |
res.sendHeader(400, {'Content-Type': 'text/plain'}); | |
res.sendBody('wtf dude, you closed the log, now new messages? screw off.'); | |
res.finish(); | |
} | |
var subl = subscribers.length; | |
var message = ''; | |
req.addListener('body', function(chunk) { | |
if (!logs[requrl.query.deployid) { | |
logs[requrl.query.deployid] = ''; | |
} | |
logs[requrl.query.deployid] += chunk; | |
for (var i = 0; i < subl; i++) { | |
subscribers[i].sendBody(chunk); | |
} | |
}); | |
} else if (requrl.pathname == '/endlog') { | |
// Close off the log. | |
var subscribers = getSubscribers(requrl.query.deployid); | |
// finish all the subscription requests. | |
for (var i = 0, l = subscribers.length; i < l; i++) { | |
subscribers[i].finish(); | |
} | |
subscriptions[requrl.query.deployid] = false; | |
} else if (requrl.pathname == '/listen') { | |
// There's a user connecting to listen to the stream. | |
var subscribers = getSubscribers(requrl.query.deployid); | |
if (subscribers === false) { | |
if (logs[requrl.query.deployid]) { | |
res.sendHeader(200, {'Content-Type': 'text/plain'}); | |
res.sendBody(logs[requrl.query.deployid]); | |
res.finish(); | |
} else { | |
res.sendHeader(404, {'Content-Type': 'text/plaine'}); | |
res.sendBody('no record of that deploy'); | |
res.finish(); | |
} else { | |
// There's an open log with that id. Start streaming. | |
res.sendHeader(200, {'Content-Type': 'text/plain'}); | |
// Send any existing log. | |
if (logs[requrl.query.deployid]) { | |
res.sendBody(logs[requrl.query.deployid]); | |
} | |
// Add this client to the list of clients that should receive updates. | |
subscribers.push(res); | |
} | |
} | |
}).listen(8000); | |
sys.puts('Server running at http://127.0.0.1:8000/'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment