From 9ea64d7dbbfeec8520541817016b142a2ceb0136 Mon Sep 17 00:00:00 2001 From: Fedor Indutny Date: Fri, 12 May 2017 16:53:15 -0400 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. --- doc/api/http.md | 36 ++++++++++ lib/_http_agent.js | 22 ++++-- test/parallel/test-http-keepalive-override.js | 67 +++++++++++++++++++ 3 files changed, 120 insertions(+), 5 deletions(-) create mode 100644 test/parallel/test-http-keepalive-override.js diff --git a/doc/api/http.md b/doc/api/http.md index 2ceeaf6dac04ea..493222d409d808 100644 --- a/doc/api/http.md +++ b/doc/api/http.md @@ -157,6 +157,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()