Skip to content

Commit

Permalink
Merge pull request hapijs#267 from kanongil/use-abort
Browse files Browse the repository at this point in the history
Refactor early abort detection to use the 'abort' event
  • Loading branch information
hueniverse authored Jan 4, 2020
2 parents f4dc437 + 6175453 commit 3fe90e3
Showing 1 changed file with 13 additions and 21 deletions.
34 changes: 13 additions & 21 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,17 @@ internals.Client = class {
return finishOnce(Boom.badGateway('Client request error', err));
};

const onAbort = () => {

if (!req.socket) {
// Fake an ECONNRESET error on early abort

const error = new Error('socket hang up');
error.code = 'ECONNRESET';
finishOnce(error);
}
};

req.once('error', onError);

const onResponse = (res) => {
Expand Down Expand Up @@ -250,9 +261,9 @@ internals.Client = class {
req.abort();
}

req.abort = _abort; // Restore original function to release memory
req.removeListener('response', onResponse);
req.removeListener('error', onError);
req.removeListener('abort', onAbort);
req.on('error', Hoek.ignore);

clearTimeout(timeoutId);
Expand All @@ -271,26 +282,7 @@ internals.Client = class {
delete options.timeout;
}

// Custom abort method to detect early aborts

const _abort = req.abort;
let aborted = false;
req.abort = () => {

if (!aborted && !req.res && !req.socket) {
process.nextTick(() => {

// Fake an ECONNRESET error

const error = new Error('socket hang up');
error.code = 'ECONNRESET';
finishOnce(error);
});
}

aborted = true;
return _abort.call(req);
};
req.on('abort', onAbort);

// Write payload

Expand Down

0 comments on commit 3fe90e3

Please sign in to comment.