From 1390c280bca19658bb074672c42693ad13e19c59 Mon Sep 17 00:00:00 2001 From: Fedor Indutny Date: Mon, 15 Jan 2018 23:44:53 +0000 Subject: [PATCH] http: overridable keep-alive behavior of `Agent` Introduce two overridable `Agent` methods: * `keepSocketAlive(socket)` * `reuseSocket(socket, req)` These methods can be overridden by particular `Agent` class child to make keep-alive behavior customizable. Motivation: destroy persisted sockets after some configurable timeout. It is very non-trivial to do it with available primitives. Such program will most likely need to poke with undocumented events and methods of `Agent`. With introduced API such behavior is easy to implement. Backport-PR-URL: https://github.com/nodejs/node/pull/18168 PR-URL: https://github.com/nodejs/node/pull/13005 Reviewed-By: Matteo Collina Reviewed-By: Refael Ackermann Reviewed-By: Colin Ihrig Reviewed-By: Brian White Reviewed-By: Michael Dawson --- doc/api/http.md | 36 ++++++++++ lib/_http_agent.js | 24 +++++-- test/parallel/test-http-keepalive-override.js | 67 +++++++++++++++++++ 3 files changed, 121 insertions(+), 6 deletions(-) create mode 100644 test/parallel/test-http-keepalive-override.js diff --git a/doc/api/http.md b/doc/api/http.md index fac7798071eee1..d956c9e23d4be9 100644 --- a/doc/api/http.md +++ b/doc/api/http.md @@ -159,6 +159,42 @@ socket/stream from this function, or by passing the socket/stream to `callback`. `callback` has a signature of `(err, stream)`. +### agent.keepSocketAlive(socket) + + +* `socket` {net.Socket} + +Called when `socket` is detached from a request and could be persisted by the +Agent. Default behavior is to: + +```js +socket.unref(); +socket.setKeepAlive(agent.keepAliveMsecs); +``` + +This method can be overridden by a particular `Agent` subclass. If this +method returns a falsy value, the socket will be destroyed instead of persisting +it for use with the next request. + +### agent.reuseSocket(socket, request) + + +* `socket` {net.Socket} +* `request` {http.ClientRequest} + +Called when `socket` is attached to `request` after being persisted because of +the keep-alive options. Default behavior is to: + +```js +socket.ref(); +``` + +This method can be overridden by a particular `Agent` subclass. + ### agent.destroy()