Commit 66afb2a2 authored by indexzero's avatar indexzero

[api] Revert to old 0.1.x codebase for bug testing and performance comparison

parent 69c162dc
node-http-proxy node-http-proxy
Copyright (c) 2010 Charlie Robbins, Mikeal Rogers, & Marak Squires Copyright (c) 2010 Charlie Robbins & Marak Squires http://github.com/nodejitsu/node-http-proxy
Permission is hereby granted, free of charge, to any person obtaining Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the a copy of this software and associated documentation files (the
......
# node-http-proxy - v0.2.0 # node-http-proxy - v0.1.5
<img src = "http://i.imgur.com/dSSUX.png"/> <img src = "http://i.imgur.com/dSSUX.png"/>
...@@ -52,9 +52,9 @@ see the [demo](http://github.com/nodejitsu/node-http-proxy/blob/master/demo.js) ...@@ -52,9 +52,9 @@ see the [demo](http://github.com/nodejitsu/node-http-proxy/blob/master/demo.js)
httpProxy = require('http-proxy'); httpProxy = require('http-proxy');
// create a proxy server with custom application logic // create a proxy server with custom application logic
httpProxy.createServer(function (req, res, proxyRequest) { httpProxy.createServer(function (req, res, proxy) {
// Put your custom server logic here // Put your custom server logic here
proxyRequest(9000, 'localhost'); proxy.proxyRequest(9000, 'localhost', req, res);
}).listen(8000); }).listen(8000);
http.createServer(function (req, res){ http.createServer(function (req, res){
...@@ -65,28 +65,37 @@ see the [demo](http://github.com/nodejitsu/node-http-proxy/blob/master/demo.js) ...@@ -65,28 +65,37 @@ see the [demo](http://github.com/nodejitsu/node-http-proxy/blob/master/demo.js)
</pre> </pre>
### How to proxy requests with latent operations (IO, etc.) ### How to proxy requests with a regular http server
<pre>
var http = require('http'),
httpProxy = require('http-proxy');
node-http-proxy supports event buffering, that means if an event (like 'data', or 'end') is raised by the incoming request before you have a chance to perform your custom server logic, those events will be captured and re-raised when you later proxy the request. Here's a simple example: // create a regular http server and proxy its handler
http.createServer(function (req, res){
var proxy = new httpProxy.HttpProxy;
proxy.watch(req, res);
// Put your custom server logic here
proxy.proxyRequest(9000, 'localhost', req, res);
}).listen(8001);
http.createServer(function (req, res){
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('request successfully proxied: ' + req.url +'\n' + JSON.stringify(req.headers, true, 2));
res.end();
}).listen(9000);
<pre>
httpProxy.createServer(function (req, res, proxyRequest) {
setTimeout(function () {
proxyRequest(port, server);
}, latency);
}).listen(8081);
</pre> </pre>
### Why doesn't node-http-proxy have more advanced features like x, y, or z? ### Why doesn't node-http-proxy have more advanced features like x, y, or z?
If you have a suggestion for a feature currently not supported, feel free to open a [support issue](http://github.com/nodejitsu/node-http-proxy/issues). node-http-proxy is designed to just proxy http requests from one server to another, but we will be soon releasing many other complimentary projects that can be used in conjunction with node-http-proxy. If you have a suggestion for a feature currently not supported, feel free to open a [support issue](http://github.com/nodejitsu/node-http-proxy/issues). node-http-proxy is designed to just proxy http requests from one server to another, but we will be soon releasing many other complimentary projects that can be used in conjunction with node-http-proxy.
<br/> <br/><hr/>
### License ### License
(The MIT License) (The MIT License)
Copyright (c) 2010 Charlie Robbins, Mikeal Rogers & Marak Squires Copyright (c) 2010 Charlie Robbins & Marak Squires http://github.com/nodejitsu/
Permission is hereby granted, free of charge, to any person obtaining Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the a copy of this software and associated documentation files (the
......
...@@ -45,17 +45,28 @@ httpProxy.createServer(9000, 'localhost').listen(8000); ...@@ -45,17 +45,28 @@ httpProxy.createServer(9000, 'localhost').listen(8000);
sys.puts('http proxy server'.blue + ' started '.green.bold + 'on port '.blue + '8000'.yellow); sys.puts('http proxy server'.blue + ' started '.green.bold + 'on port '.blue + '8000'.yellow);
/****** http proxy server with latency******/ /****** http proxy server with latency******/
httpProxy.createServer(function (req, res, proxyRequest){ httpProxy.createServer(function (req, res, proxy){
setTimeout(function(){ setTimeout(function(){
proxyRequest(9000, 'localhost', req, res); proxy.proxyRequest(9000, 'localhost', req, res);
}, 2000) }, 200)
}).listen(8001); }).listen(8001);
sys.puts('http proxy server '.blue + 'started '.green.bold + 'on port '.blue + '8001 '.yellow + 'with latency'.magenta.underline ); sys.puts('http proxy server '.blue + 'started '.green.bold + 'on port '.blue + '8001 '.yellow + 'with latency'.magenta.underline );
/****** regular http server ******/ /****** http server with proxyRequest handler and latency******/
http.createServer(function (req, res){ http.createServer(function (req, res){
var proxy = new httpProxy.HttpProxy;
proxy.watch(req, res);
setTimeout(function(){
proxy.proxyRequest(9000, 'localhost', req, res);
}, 200);
}).listen(8002);
sys.puts('http server '.blue + 'started '.green.bold + 'on port '.blue + '8002 '.yellow + 'with proxyRequest handler'.cyan.underline + ' and latency'.magenta);
/****** regular http server ******/
/*http.createServer(function (req, res){
res.writeHead(200, {'Content-Type': 'text/plain'}); res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('request successfully proxied to: ' + req.url + '\n' + JSON.stringify(req.headers, true, 2)); res.write('request successfully proxied to: ' + req.url + '\n' + JSON.stringify(req.headers, true, 2));
res.end(); res.end();
}).listen(9000); }).listen(9000);
sys.puts('http server '.blue + 'started '.green.bold + 'on port '.blue + '9000 '.yellow); sys.puts('http server '.blue + 'started '.green.bold + 'on port '.blue + '9000 '.yellow);*/
/* /*
node-http-proxy.js: http proxy for node.js with pooling and event buffering node-http-proxy.js: http proxy for node.js
Copyright (c) 2010 Mikeal Rogers, Charlie Robbins Copyright (c) 2010 Charlie Robbins & Marak Squires http://github.com/nodejitsu/node-http-proxy
Permission is hereby granted, free of charge, to any person obtaining Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the a copy of this software and associated documentation files (the
...@@ -26,9 +26,9 @@ ...@@ -26,9 +26,9 @@
var sys = require('sys'), var sys = require('sys'),
http = require('http'), http = require('http'),
pool = require('pool'), eyes = require('eyes'),
url = require('url'),
events = require('events'), events = require('events'),
pool = require('pool'),
min = 0, min = 0,
max = 100; max = 100;
...@@ -38,25 +38,9 @@ manager.setMinClients(min); ...@@ -38,25 +38,9 @@ manager.setMinClients(min);
manager.setMaxClients(max); manager.setMaxClients(max);
exports.createServer = function () { exports.createServer = function () {
var args, action, port, host; // Initialize the nodeProxy to start proxying requests
args = Array.prototype.slice.call(arguments); var proxy = new (exports.HttpProxy);
action = typeof args[args.length - 1] === 'function' && args.pop(); return proxy.createServer.apply(proxy, arguments);
if (args[0]) port = args[0];
if (args[1]) host = args[1];
var proxy = createProxy();
proxy.on('route', function (req, res, callback) {
var uri = url.parse(req.url);
if (action) {
action(req, res, callback);
}
else {
port = port ? port : uri.port ? uri.port : 80;
host = host ? host : uri.hostname;
callback(port, host);
}
});
return proxy;
}; };
exports.setMin = function (value) { exports.setMin = function (value) {
...@@ -67,49 +51,131 @@ exports.setMin = function (value) { ...@@ -67,49 +51,131 @@ exports.setMin = function (value) {
exports.setMax = function (value) { exports.setMax = function (value) {
max = value; max = value;
manager.setMaxClients(max); manager.setMaxClients(max);
} };
var createProxy = function () {
var server = http.createServer(function (req, res) {
var buffers = [],
b = function (chunk) { buffers.push(chunk) },
e = function () { e = false };
req.on('data', b); exports.HttpProxy = function () {
req.on('end', e); this.emitter = new(events.EventEmitter);
this.events = {};
this.listeners = {};
this.collisions = {};
};
server.emit('route', req, res, function (port, hostname) { exports.HttpProxy.prototype = {
var p = manager.getPool(port, hostname); toArray: function (obj){
var len = obj.length,
arr = new Array(len);
for (var i = 0; i < len; ++i) {
arr[i] = obj[i];
}
return arr;
},
p.request(req.method, req.url, req.headers, function (reverse_proxy) { createServer: function () {
var data = ''; var self = this,
reverse_proxy.on('error', function (err) { server,
res.writeHead(500, {'Content-Type': 'text/plain'}); port,
callback;
if(req.method !== 'HEAD') { if (typeof(arguments[0]) === "function") {
res.write('An error has occurred: ' + sys.puts(JSON.stringify(err))); callback = arguments[0];
}
else {
port = arguments[0];
server = arguments[1];
} }
res.end(); var proxyServer = http.createServer(function (req, res){
}); self.watch(req, res);
buffers.forEach(function (c) { // If we were passed a callback to process the request
data += c; // or response in some way, then call it.
reverse_proxy.write(c); if(callback) {
callback(req, res, self);
}
else {
self.proxyRequest(port, server, req, res);
}
}); });
buffers = null; return proxyServer;
req.removeListener('data', b); },
sys.pump(req, reverse_proxy);
if (e) { watch: function (req, res) {
req.removeListener('end', e); var self = this;
req.addListener('end', function () { reverse_proxy.end() });
// Create a unique id for this request so
// we can reference it later.
var id = new Date().getTime().toString();
// If we get a request in the same tick, we need to
// append to the id so it stays unique.
if(typeof this.collisions[id] === 'undefined') {
this.collisions[id] = 0;
} }
else { else {
reverse_proxy.end(); this.collisions[id]++;
id += this.collisions[id];
}
req.id = id;
this.events[req.id] = [];
this.listeners[req.id] = {
onData: function () {
self.events[req.id].push(['data'].concat(self.toArray(arguments)));
},
onEnd: function () {
self.events[req.id].push(['end'].concat(self.toArray(arguments)));
}
};
req.addListener('data', this.listeners[req.id].onData);
req.addListener('end', this.listeners[req.id].onEnd);
},
unwatch: function (req, res) {
req.removeListener('data', this.listeners[req.id].onData);
req.removeListener('end', this.listeners[req.id].onEnd);
// Rebroadcast any events that have been buffered
while(this.events[req.id].length > 0) {
var args = this.events[req.id].shift();
req.emit.apply(req, args);
} }
// Remove the data from the event and listeners hashes
delete this.listeners[req.id];
delete this.events[req.id];
// If this request id is a base time, delete it
if (typeof this.collisions[req.id] !== 'undefined') {
delete this.collisions[req.id];
}
},
proxyRequest: function (port, server, req, res) {
// Remark: nodeProxy.body exists solely for testability
this.body = '';
var self = this;
// Open new HTTP request to internal resource with will act as a reverse proxy pass
var p = manager.getPool(port, server);
eyes.inspect(req.headers);
// Make request to internal server, passing along the method and headers
p.request(req.method, req.url, req.headers, function (reverse_proxy) {
// Add a listener for the connection timeout event
reverse_proxy.connection.addListener('error', function (err) {
res.writeHead(200, {'Content-Type': 'text/plain'});
if(req.method !== 'HEAD') {
res.write('An error has occurred: ' + sys.puts(JSON.stringify(err)));
}
res.end();
});
// Add a listener for the reverse_proxy response event // Add a listener for the reverse_proxy response event
reverse_proxy.addListener('response', function (response) { reverse_proxy.addListener('response', function (response) {
if (response.headers.connection) { if (response.headers.connection) {
...@@ -117,23 +183,37 @@ var createProxy = function () { ...@@ -117,23 +183,37 @@ var createProxy = function () {
else response.headers.connection = 'close'; else response.headers.connection = 'close';
} }
// These two listeners are for testability and observation // Set the response headers of the client response
// of what's passed back from the target server res.writeHead(response.statusCode, response.headers);
// Add event handler for the proxied response in chunks
response.addListener('data', function (chunk) { response.addListener('data', function (chunk) {
data += chunk; if(req.method !== 'HEAD') {
res.write(chunk, 'binary');
self.body += chunk;
}
}); });
response.addListener('end', function() { // Add event listener for end of proxied response
server.emit('proxy', null, data); response.addListener('end', function () {
// Remark: Emit the end event for testability
self.emitter.emit('end', null, self.body);
res.end();
});
}); });
// Set the response headers of the client response // Chunk the client request body as chunks from the proxied request come in
res.writeHead(response.statusCode, response.headers); req.addListener('data', function (chunk) {
reverse_proxy.write(chunk, 'binary');
})
sys.pump(response, res); // At the end of the client request, we are going to stop the proxied request
}); req.addListener('end', function () {
reverse_proxy.end();
}); });
self.unwatch(req, res);
}); });
}) }
return server;
}; };
{ {
"name": "http-proxy", "name": "http-proxy",
"description": "A full-featured http reverse proxy for node.js", "description": "A full-featured http reverse proxy for node.js",
"version": "0.2.0", "version": "0.1.6",
"author": "Charlie Robbins <charlie.robbins@gmail.com>", "author": "Charlie Robbins <charlie.robbins@gmail.com>",
"contributors": [ "contributors": [
{ "name": "Mikeal Rogers", "email": "mikeal.rogers@gmail.com" }, { "name": "Marak Squires", "email": "marak.squires@gmail.com" }
{ "name": "Marak Squires", "email": "marak.squires@gmail.com" },
], ],
"repository": { "repository": {
"type": "git", "type": "git",
...@@ -13,10 +12,9 @@ ...@@ -13,10 +12,9 @@
}, },
"keywords": ["reverse", "proxy", "http"], "keywords": ["reverse", "proxy", "http"],
"dependencies": { "dependencies": {
"colors": ">= 0.3.0", "colors": ">= 0.3.0"
"pool": ">= 0.4.1"
}, },
"main": "./lib/node-http-proxy", "main": "./lib/node-http-proxy",
"scripts": { "test": "vows" }, "scripts": { "test": "vows" },
"engines": { "node": ">= 0.2.0" } "engines": { "node": ">= 0.1.98" }
} }
\ No newline at end of file
...@@ -29,14 +29,14 @@ var vows = require('vows'), ...@@ -29,14 +29,14 @@ var vows = require('vows'),
assert = require('assert'), assert = require('assert'),
http = require('http'); http = require('http');
var httpProxy = require('./../lib/node-http-proxy'); var httpProxy = require('http-proxy');
var testServers = {}; var testServers = {};
// //
// Creates the reverse proxy server // Creates the reverse proxy server
// //
var startProxyServer = function (port, server) { var startProxyServer = function (port, server, proxy) {
var proxyServer = httpProxy.createServer(port, server); var proxyServer = proxy.createServer(port, server);
proxyServer.listen(8080); proxyServer.listen(8080);
return proxyServer; return proxyServer;
}; };
...@@ -44,11 +44,11 @@ var startProxyServer = function (port, server) { ...@@ -44,11 +44,11 @@ var startProxyServer = function (port, server) {
// //
// Creates the reverse proxy server with a specified latency // Creates the reverse proxy server with a specified latency
// //
var startLatentProxyServer = function (port, server, latency) { var startLatentProxyServer = function (port, server, proxy, latency) {
// Initialize the nodeProxy and start proxying the request // Initialize the nodeProxy and start proxying the request
var proxyServer = httpProxy.createServer(function (req, res, proxy) { var proxyServer = proxy.createServer(function (req, res, proxy) {
setTimeout(function () { setTimeout(function () {
proxy(port, server); proxy.proxyRequest(port, server, req, res);
}, latency); }, latency);
}); });
...@@ -73,72 +73,57 @@ var startTargetServer = function (port) { ...@@ -73,72 +73,57 @@ var startTargetServer = function (port) {
// //
// The default test bootstrapper with no latency // The default test bootstrapper with no latency
// //
var startTest = function (port) { var startTest = function (proxy, port) {
var proxyServer = startProxyServer(port, 'localhost'),
targetServer = startTargetServer(port);
testServers.noLatency = []; testServers.noLatency = [];
testServers.noLatency.push(proxyServer); testServers.noLatency.push(startProxyServer(port, 'localhost', proxy));
testServers.noLatency.push(targetServer); testServers.noLatency.push(startTargetServer(port));
return proxyServer;
}; };
// //
// The test bootstrapper with some latency // The test bootstrapper with some latency
// //
var startTestWithLatency = function (port) { var startTestWithLatency = function (proxy, port) {
var proxyServer = startLatentProxyServer(port, 'localhost', 2000),
targetServer = startTargetServer(port);
testServers.latency = []; testServers.latency = [];
testServers.latency.push(proxyServer); testServers.latency.push(startLatentProxyServer(port, 'localhost', proxy, 2000));
testServers.latency.push(targetServer); testServers.latency.push(startTargetServer(port));
return proxyServer;
}; };
//var proxy = startTest(8082);
//var latent = startTestWithLatency(8083);
vows.describe('node-http-proxy').addBatch({ vows.describe('node-http-proxy').addBatch({
"A node-http-proxy": { "A node-http-proxy": {
"when instantiated directly": { "when instantiated directly": {
"and an incoming request is proxied to the helloNode server" : { "and an incoming request is proxied to the helloNode server" : {
"with no latency" : { "with no latency" : {
topic: function () { topic: function () {
var proxyServer = startTest(8082); var proxy = new (httpProxy.HttpProxy);
proxyServer.on('proxy', this.callback); startTest(proxy, 8082);
proxy.emitter.addListener('end', this.callback);
var client = http.createClient(8080, 'localhost'); var client = http.createClient(8080, 'localhost');
var request = client.request('GET', '/'); var request = client.request('GET', '/');
request.end(); request.end();
},
teardown: function () {
}, },
"it should received 'hello world'": function (err, body) { "it should received 'hello world'": function (err, body) {
assert.equal(body, 'hello world'); assert.equal(body, 'hello world');
testServers.noLatency.forEach(function (server) { testServers.noLatency.forEach(function (server) {
server.close(); server.close();
}); })
} }
}, },
"with latency": { "with latency": {
topic: function () { topic: function () {
var proxyServer = startTestWithLatency(8083); var proxy = new (httpProxy.HttpProxy);
proxyServer.on('proxy', this.callback); startTestWithLatency(proxy, 8083);
proxy.emitter.addListener('end', this.callback);
var client = http.createClient(8081, 'localhost'); var client = http.createClient(8081, 'localhost');
var request = client.request('GET', '/'); var request = client.request('GET', '/');
request.end(); request.end();
},
teardown: function () {
}, },
"it should receive 'hello world'": function (err, body) { "it should receive 'hello world'": function (err, body) {
assert.equal(body, 'hello world'); assert.equal(body, 'hello world');
testServers.latency.forEach(function (server) { testServers.latency.forEach(function (server) {
server.close(); server.close();
}); })
} }
} }
} }
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment