Skip to content

Commit

Permalink
lib: add flag to drop connection when running in cluster mode
Browse files Browse the repository at this point in the history
  • Loading branch information
theanarkh committed Sep 13, 2024
1 parent ce531af commit 59f2e8d
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 3 deletions.
19 changes: 17 additions & 2 deletions doc/api/net.md
Original file line number Diff line number Diff line change
Expand Up @@ -599,12 +599,27 @@ changes:

* {integer}

Set this property to reject connections when the server's connection count gets
high.
When the number of connections reaches the threshold of `server.maxConnections`.

1. Node.js will close the connection if the process is not running in cluster mode.
2. Node.js will send the connection to other worker process by default if the process
is running in cluster mode, you can set `server.dropMaxConnection` to `true` to
close the connection.

It is not recommended to use this option once a socket has been sent to a child
with [`child_process.fork()`][].

### `server.dropMaxConnection`

<!-- YAML
added: REPLACEME
-->

* {boolean}

Set this property to `true` to close the connection when the number of connections
reaches the threshold of `server.maxConnections`. It only works in cluster mode.

### `server.ref()`

<!-- YAML
Expand Down
4 changes: 3 additions & 1 deletion lib/internal/cluster/child.js
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,9 @@ function onconnection(message, handle) {

if (accepted && server[owner_symbol]) {
const self = server[owner_symbol];
if (self.maxConnections != null && self._connections >= self.maxConnections) {
if (self.maxConnections != null &&
self._connections >= self.maxConnections &&
!self.dropMaxConnection) {
accepted = false;
}
}
Expand Down
21 changes: 21 additions & 0 deletions test/parallel/test-net-server-drop-connections-in-cluster.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
'use strict';
const common = require('../common');
const cluster = require('cluster');
const http = require('http');

if (cluster.isPrimary) {
cluster.fork();
} else {
const server = http.createServer();
server.maxConnections = 0;
server.dropMaxConnection = true;
// When dropMaxConnection is false, the main process will continue to
// distribute the request to the child process, if true, the child will
// close the connection directly and emit drop event.
server.on('drop', common.mustCall((a) => {
process.exit();
}));
server.listen(common.mustCall(() => {
http.get(`http://localhost:${server.address().port}`).on('error', console.error);
}));
}

0 comments on commit 59f2e8d

Please sign in to comment.