Skip to content

Commit

Permalink
fix(server): res.close event order
Browse files Browse the repository at this point in the history
  • Loading branch information
Peter Marton committed Jun 5, 2018
1 parent ca0a501 commit b6491ec
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 14 deletions.
20 changes: 13 additions & 7 deletions lib/server.js
Expand Up @@ -1143,20 +1143,26 @@ Server.prototype._setupRequest = function _setupRequest(req, res) {
// the connection (or we lose the connection).
// we consider a closed request as flushed from metrics point of view
function onClose() {
res._flushed = true;
req._timeFlushed = process.hrtime();

res.removeListener('finish', onFinish);
res.removeListener('error', onError);
req._connectionState = 'close';

if (res._flushed) {
return;
}

res._flushed = true;
req._timeFlushed = process.hrtime();

// Request was aborted or closed. Override the status code
res.statusCode = 444;

self._finishReqResCycle(req, res, new errors.RequestCloseError());
self._finishReqResCycle(
req,
res,
res.err || new errors.RequestCloseError()
);
}
req.once('close', function reqOnceClose() {
// TODO: Node v10 workaround
req.once('close', function onReqClose() {
setImmediate(onClose);
});

Expand Down
17 changes: 12 additions & 5 deletions test/plugins/audit.test.js
Expand Up @@ -676,16 +676,23 @@ describe('audit logger', function() {
assert.ok(data);
assert.ok(data.req_id);
assert.isNumber(data.latency);
assert.equal(444, data.res.statusCode);
assert.equal(data.res.statusCode, 444);
done();
});

SERVER.get('/audit', function(req, res, next) {
req.emit('close');
res.send();
next();
setTimeout(function() {
res.send();
next();
}, 100);
});

CLIENT.get('/audit', function(err, req, res) {});
CLIENT.get(
{
path: '/audit',
requestTimeout: 50
},
function(err, req, res) {}
);
});
});
8 changes: 6 additions & 2 deletions test/server.test.js
Expand Up @@ -1924,8 +1924,12 @@ test("should emit 'after' on successful request", function(t) {
});

SERVER.get('/foobar', function(req, res, next) {
res.send('hello world');
next();
setTimeout(function() {
res.send('hello world');
setTimeout(function() {
next();
}, 500);
}, 500);
});

CLIENT.get('/foobar', function(err, _, res) {
Expand Down

0 comments on commit b6491ec

Please sign in to comment.