Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Re-add support for clientError listeners #1897

Merged
merged 2 commits into from Mar 24, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
29 changes: 29 additions & 0 deletions lib/server.js
Expand Up @@ -205,6 +205,8 @@ function Server(options) {
});

// Now the things we can't blindly proxy
proxyEventWhenListenerAdded('clientError', this, this.server);

this.server.on('checkContinue', function onCheckContinue(req, res) {
if (self.listeners('checkContinue').length > 0) {
self.emit('checkContinue', req, res);
Expand Down Expand Up @@ -274,6 +276,33 @@ util.inherits(Server, EventEmitter);

module.exports = Server;

/**
* Only add a listener on the wrappedEmitter when a listener for the event is
* added to the wrapperEmitter. This is useful when just adding a listener to
* the wrappedEmittter overrides/disables a default behavior.
*
* @param {string} eventName - The name of the event to proxy
* @param {EventEmitter} wrapperEmitter - The emitter that proxies events from the wrappedEmitter
* @param {EventEmitter} wrappedEmitter - The proxied emitter
* @returns {undefined} NA
*/
function proxyEventWhenListenerAdded(
eventName,
wrapperEmitter,
wrappedEmitter
) {
var isEventProxied = false;
wrapperEmitter.on('newListener', function onNewListener(handledEventName) {
if (handledEventName === eventName && !isEventProxied) {
isEventProxied = true;
wrappedEmitter.on(
eventName,
wrapperEmitter.emit.bind(wrapperEmitter, eventName)
);
}
});
}

///--- Server lifecycle methods

// eslint-disable-next-line jsdoc/check-param-names
Expand Down
132 changes: 132 additions & 0 deletions test/server.test.js
Expand Up @@ -33,6 +33,8 @@ var CLIENT;
var FAST_CLIENT;
var SERVER;

var NODE_MAJOR_VERSION = process.versions.node.split('.')[0];

if (SKIP_IP_V6) {
console.warn('IPv6 tests are skipped: No IPv6 network is available');
}
Expand Down Expand Up @@ -2820,3 +2822,133 @@ test('async handler should discard value', function(t) {
t.end();
});
});

test('Server returns 400 on invalid method', function(t) {
SERVER.get('/snickers/bar', function echoId(req, res, next) {
res.send();
next();
});

var opts = {
hostname: '127.0.0.1',
port: PORT,
path: '/snickers/bar',
method: 'CANDYBARS',
agent: false
};
http.request(opts, function(res) {
t.equal(res.statusCode, 400);
t.equal(res.statusMessage, 'Bad Request');
res.on('data', function() {
t.fail('Data was sent on 400 error');
});
res.on('end', function() {
t.end();
});
}).end();
});

test('Server returns 4xx when header size is too large', function(t) {
SERVER.get('/jellybeans', function echoId(req, res, next) {
res.send();
next();
});

var opts = {
hostname: '127.0.0.1',
port: PORT,
path: '/jellybeans',
method: 'GET',
agent: false,
headers: {
'jellybean-colors': 'purple,green,red,black,pink,'.repeat(1000)
}
};
http.request(opts, function(res) {
if (NODE_MAJOR_VERSION > '10') {
t.equal(res.statusCode, 431);
t.equal(res.statusMessage, 'Request Header Fields Too Large');
} else {
t.equal(res.statusCode, 400);
t.equal(res.statusMessage, 'Bad Request');
}
res.on('data', function() {
t.fail('Data was sent on 431 error');
});
res.on('end', function() {
t.end();
});
}).end();
});

test('Server supports adding custom clientError listener', function(t) {
SERVER.get('/popcorn', function echoId(req, res, next) {
res.send();
next();
});

SERVER.on('clientError', function(err, socket) {
if (err.code !== 'HPE_HEADER_OVERFLOW') {
t.fail('Expected HPE_HEADER_OVERFLOW but err.code was ' + err.code);
}
socket.write("HTTP/1.1 418 I'm a teapot\r\nConnection: close\r\n\r\n");
socket.destroy(err);
});

var opts = {
hostname: '127.0.0.1',
port: PORT,
path: '/popcorn',
method: 'GET',
agent: false,
headers: {
'jellybean-colors': 'purple,green,red,black,pink,'.repeat(1000)
}
};
http.request(opts, function(res) {
t.equal(res.statusCode, 418);
t.equal(res.statusMessage, "I'm a teapot");
res.on('data', function() {});
res.on('end', function() {
t.end();
});
}).end();
});

test('Server correctly handles multiple clientError listeners', function(t) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure about this. So it is an event emitter, so obviously two handlers is technically valid, but the use case here is almost certainly to be sending a response in some cases, which shifts the burden onto each handler to make sure it properly checks before sending the response and closing the socket. If a user does this in multiple handlers they could get some pretty unexpected error results if they are not careful.

Could a better user experience from restify be to error or warn when they try to add a second handler?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@wesleytodd, I agree generally. This is more of a contrived test rather than a valid usage example. I added this test to make sure that the proxying is done correctly / doesn't emit the proxied event multiple times if multiple listeners are added.

My goal with this change was to restore the ability to add a clientError listener after #1895 removed it, so am matching the original behavior here. I don't think folks would do this very often if at all. One actual use case might be to do the response in one handler and log in another. I'm not opposed to adding a warning but feels beyond the scope of this change.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cool, yeah makes sense. I just wanted to bring up this as I have thought before that sometimes these kind of api's from node core have foot guns, and I think frameworks are generally good places to shore up those gaps. I for sure don't think this one is a common issue worth spending much time on. So 👍 to the change!

SERVER.get('/popcorn', function echoId(req, res, next) {
res.send();
next();
});

let numListenerCalls = 0;
SERVER.on('clientError', function(err, socket) {
socket.write("HTTP/1.1 418 I'm a teapot\r\nConnection: close\r\n\r\n");
numListenerCalls += 1;
});
SERVER.on('clientError', function(err, socket) {
if (numListenerCalls !== 1) {
t.fail('listener was called ' + numListenerCalls + ' times');
}
socket.destroy(err);
});

var opts = {
hostname: '127.0.0.1',
port: PORT,
path: '/popcorn',
method: 'GET',
agent: false,
headers: {
'jellybean-colors': 'purple,green,red,black,pink,'.repeat(1000)
}
};
http.request(opts, function(res) {
t.equal(res.statusCode, 418);
t.equal(res.statusMessage, "I'm a teapot");
res.on('data', function() {});
res.on('end', function() {
t.end();
});
}).end();
});