Skip to content

Commit 034a24b

Browse files
committed
http: add drop request event for http server
1 parent b3f2af9 commit 034a24b

File tree

3 files changed

+49
-1
lines changed

3 files changed

+49
-1
lines changed

doc/api/http.md

+14
Original file line numberDiff line numberDiff line change
@@ -1445,6 +1445,20 @@ This event is guaranteed to be passed an instance of the {net.Socket} class,
14451445
a subclass of {stream.Duplex}, unless the user specifies a socket
14461446
type other than {net.Socket}.
14471447

1448+
### Event: `'dropRequest'`
1449+
1450+
<!-- YAML
1451+
added: REPLACEME
1452+
-->
1453+
1454+
* `request` {http.IncomingMessage} Arguments for the HTTP request, as it is in
1455+
the [`'request'`][] event
1456+
* `socket` {stream.Duplex} Network socket between the server and client
1457+
1458+
When the number of requests on a socket reaches the threshold of
1459+
`server.maxRequestsPerSocket`, the server will drop new requests
1460+
and emit `'dropRequest'` event instead.
1461+
14481462
### `server.close([callback])`
14491463

14501464
<!-- YAML

lib/_http_server.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -985,7 +985,7 @@ function parserOnIncoming(server, socket, state, req, keepAlive) {
985985
if (isRequestsLimitSet &&
986986
(server.maxRequestsPerSocket < state.requestsCount)) {
987987
handled = true;
988-
988+
server.emit('dropRequest', req, socket);
989989
res.writeHead(503);
990990
res.end();
991991
} else if (req.headers.expect !== undefined) {
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
'use strict';
2+
3+
const common = require('../common');
4+
const http = require('http');
5+
const net = require('net');
6+
const assert = require('assert');
7+
8+
function request(socket) {
9+
socket.write('GET / HTTP/1.1\r\n');
10+
socket.write('Connection: keep-alive\r\n');
11+
socket.write('\r\n\r\n');
12+
}
13+
14+
const server = http.createServer(common.mustCall((req, res) => {
15+
res.end('ok');
16+
}));
17+
18+
server.on('dropRequest', common.mustCall((request, socket) => {
19+
assert.strictEqual(request instanceof http.IncomingMessage, true);
20+
assert.strictEqual(socket instanceof net.Socket, true);
21+
server.close();
22+
}));
23+
24+
server.listen(0, common.mustCall(() => {
25+
const socket = net.connect(server.address().port);
26+
socket.on('connect', common.mustCall(() => {
27+
request(socket);
28+
request(socket);
29+
}));
30+
socket.on('data', common.mustCallAtLeast());
31+
socket.on('close', common.mustCall());
32+
}));
33+
34+
server.maxRequestsPerSocket = 1;

0 commit comments

Comments
 (0)