Skip to content

Commit

Permalink
fix(HttpClient): semaphore emitResult
Browse files Browse the repository at this point in the history
  • Loading branch information
Peter Marton committed Nov 27, 2019
1 parent edde83b commit f570972
Showing 1 changed file with 12 additions and 2 deletions.
14 changes: 12 additions & 2 deletions lib/HttpClient.js
Expand Up @@ -289,6 +289,10 @@ function rawRequest(opts, cb) {
// the inflight request counter only ever decrements once for a given
// request.
var hasDecrementedInflightCounter = false;
// We emit result when response is ended or request has an error. Race
// condition can happen between the two, so we use a semaphore to ensure
// it is only emitted once.
var hasResultEmitted = false;
req = proto.request(opts, function onResponse(res) {
var latency = Date.now() - requestTime;
res.headers['x-request-received'] = requestTime;
Expand Down Expand Up @@ -343,7 +347,10 @@ function rawRequest(opts, cb) {
emitAfter(req, res, err);
});

emitResult((err || null), req, res);
if (!hasResultEmitted) {
hasResultEmitted = true;
emitResult((err || null), req, res);
}

// The 'readable' event listener has to be added after we emit the
// 'result' event to keep the response stream readable in flowing mode.
Expand Down Expand Up @@ -423,7 +430,10 @@ function rawRequest(opts, cb) {
cb(realErr, req);

process.nextTick(function () {
emitResult(realErr, req, null);
if (!hasResultEmitted) {
hasResultEmitted = true;
emitResult(realErr, req, null);
}
emitAfter(req, null, realErr);
});
});
Expand Down

0 comments on commit f570972

Please sign in to comment.