lib: add flag to drop connection when running in cluster mode

PR-URL: https://github.com/nodejs/node/pull/54927
Refs: https://github.com/nodejs/node/issues/54882
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
This commit is contained in:
theanarkh 2024-10-17 23:11:41 +08:00 committed by GitHub
parent ddfef05f11
commit cf7406927f
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 39 additions and 3 deletions

View File

@ -603,12 +603,25 @@ changes:
* {integer}
Set this property to reject connections when the server's connection count gets
high.
When the number of connections reaches the `server.maxConnections` threshold:
1. If the process is not running in cluster mode, Node.js will close the connection.
2. If the process is running in cluster mode, Node.js will, by default, route the connection to another worker process. To close the connection instead, set \[`server.dropMaxConnection`]\[] to `true`.
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 begin closing connections once the number of connections reaches the \[`server.maxConnections`]\[] threshold. This setting is only effective in cluster mode.
### `server.ref()`
<!-- YAML

View File

@ -231,7 +231,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;
}
}

View File

@ -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);
}));
}