Skip to content

Commit cca3125

Browse files
committed
Close inactive connections and requests
This new middleware introduces a timeout of closing inactive connections between requests after a configured amount of seconds. This builds on top of #405 and partially on #422
1 parent 05e170d commit cca3125

6 files changed

+364
-128
lines changed

README.md

+17
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,7 @@ multiple concurrent HTTP requests without blocking.
8181
* [ServerRequest](#serverrequest)
8282
* [ResponseException](#responseexception)
8383
* [React\Http\Middleware](#reacthttpmiddleware)
84+
* [InactiveConnectionTimeoutMiddleware](#inactiveconnectiontimeoutmiddleware)
8485
* [StreamingRequestMiddleware](#streamingrequestmiddleware)
8586
* [LimitConcurrentRequestsMiddleware](#limitconcurrentrequestsmiddleware)
8687
* [RequestBodyBufferMiddleware](#requestbodybuffermiddleware)
@@ -2679,6 +2680,22 @@ access its underlying response object.
26792680

26802681
### React\Http\Middleware
26812682

2683+
#### InactiveConnectionTimeoutMiddleware
2684+
2685+
The `React\Http\Middleware\InactiveConnectionTimeoutMiddleware` is purely a configuration middleware to configure the
2686+
`HttpServer` to close any inactive connections between requests to close the connection and not leave them needlessly open.
2687+
2688+
The following example configures the `HttpServer` to close any inactive connections after one and a half second:
2689+
2690+
```php
2691+
$http = new React\Http\HttpServer(
2692+
new React\Http\Middleware\InactiveConnectionTimeoutMiddleware(1.5),
2693+
$handler
2694+
);
2695+
```
2696+
> Internally, this class is used as a "value object" to override the default timeout of one minute.
2697+
As such it doesn't have any behavior internally, that is all in the internal "StreamingServer".
2698+
26822699
#### StreamingRequestMiddleware
26832700

26842701
The `React\Http\Middleware\StreamingRequestMiddleware` can be used to

src/HttpServer.php

+7-3
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
use React\Http\Io\IniUtil;
99
use React\Http\Io\MiddlewareRunner;
1010
use React\Http\Io\StreamingServer;
11+
use React\Http\Middleware\InactiveConnectionTimeoutMiddleware;
1112
use React\Http\Middleware\LimitConcurrentRequestsMiddleware;
1213
use React\Http\Middleware\StreamingRequestMiddleware;
1314
use React\Http\Middleware\RequestBodyBufferMiddleware;
@@ -219,10 +220,13 @@ public function __construct($requestHandlerOrLoop)
219220
}
220221

221222
$streaming = false;
223+
$idleConnectionTimeout = InactiveConnectionTimeoutMiddleware::DEFAULT_TIMEOUT;
222224
foreach ((array) $requestHandlers as $handler) {
223225
if ($handler instanceof StreamingRequestMiddleware) {
224226
$streaming = true;
225-
break;
227+
}
228+
if ($handler instanceof InactiveConnectionTimeoutMiddleware) {
229+
$idleConnectionTimeout = $handler->getTimeout();
226230
}
227231
}
228232

@@ -252,10 +256,10 @@ public function __construct($requestHandlerOrLoop)
252256
* doing anything with the request.
253257
*/
254258
$middleware = \array_filter($middleware, function ($handler) {
255-
return !($handler instanceof StreamingRequestMiddleware);
259+
return !($handler instanceof StreamingRequestMiddleware) && !($handler instanceof InactiveConnectionTimeoutMiddleware);
256260
});
257261

258-
$this->streamingServer = new StreamingServer($loop, new MiddlewareRunner($middleware));
262+
$this->streamingServer = new StreamingServer($loop, new MiddlewareRunner($middleware), $idleConnectionTimeout);
259263

260264
$that = $this;
261265
$this->streamingServer->on('error', function ($error) use ($that) {

src/Io/StreamingServer.php

+47-7
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,12 @@ final class StreamingServer extends EventEmitter
8787
/** @var Clock */
8888
private $clock;
8989

90+
/** @var LoopInterface */
91+
private $loop;
92+
93+
/** @var int */
94+
private $idleConnectionTimeout;
95+
9096
/**
9197
* Creates an HTTP server that invokes the given callback for each incoming HTTP request
9298
*
@@ -95,19 +101,21 @@ final class StreamingServer extends EventEmitter
95101
* connections in order to then parse incoming data as HTTP.
96102
* See also [listen()](#listen) for more details.
97103
*
98-
* @param LoopInterface $loop
99104
* @param callable $requestHandler
105+
* @param int $idleConnectionTimeout
100106
* @see self::listen()
101107
*/
102-
public function __construct(LoopInterface $loop, $requestHandler)
108+
public function __construct(LoopInterface $loop, $requestHandler, $idleConnectionTimeout)
103109
{
104110
if (!\is_callable($requestHandler)) {
105111
throw new \InvalidArgumentException('Invalid request handler given');
106112
}
107113

114+
$this->loop = $loop;
108115
$this->callback = $requestHandler;
109116
$this->clock = new Clock($loop);
110117
$this->parser = new RequestHeaderParser($this->clock);
118+
$this->idleConnectionTimeout = $idleConnectionTimeout;
111119

112120
$that = $this;
113121
$this->parser->on('headers', function (ServerRequestInterface $request, ConnectionInterface $conn) use ($that) {
@@ -134,7 +142,7 @@ public function __construct(LoopInterface $loop, $requestHandler)
134142
*/
135143
public function listen(ServerInterface $socket)
136144
{
137-
$socket->on('connection', array($this->parser, 'handle'));
145+
$socket->on('connection', array($this, 'parseRequest'));
138146
}
139147

140148
/** @internal */
@@ -359,7 +367,7 @@ public function handleResponse(ConnectionInterface $connection, ServerRequestInt
359367

360368
// either wait for next request over persistent connection or end connection
361369
if ($persist) {
362-
$this->parser->handle($connection);
370+
$this->parseRequest($connection);
363371
} else {
364372
$connection->end();
365373
}
@@ -380,13 +388,45 @@ public function handleResponse(ConnectionInterface $connection, ServerRequestInt
380388
// write streaming body and then wait for next request over persistent connection
381389
if ($persist) {
382390
$body->pipe($connection, array('end' => false));
383-
$parser = $this->parser;
384-
$body->on('end', function () use ($connection, $parser, $body) {
391+
$that = $this;
392+
$body->on('end', function () use ($connection, $body, &$that) {
385393
$connection->removeListener('close', array($body, 'close'));
386-
$parser->handle($connection);
394+
$that->parseRequest($connection);
387395
});
388396
} else {
389397
$body->pipe($connection);
390398
}
391399
}
400+
401+
/**
402+
* @internal
403+
*/
404+
public function parseRequest(ConnectionInterface $connection)
405+
{
406+
$idleConnectionTimeout = $this->idleConnectionTimeout;
407+
$loop = $this->loop;
408+
$parser = $this->parser;
409+
$idleConnectionTimeoutHandler = function () use ($connection) {
410+
$connection->close();
411+
};
412+
$timer = $this->loop->addTimer($idleConnectionTimeout, $idleConnectionTimeoutHandler);
413+
$closeTimerCanceler = function () use ($loop, &$timer) {
414+
$loop->cancelTimer($timer);
415+
};
416+
$dataTimerCanceler = function () use ($loop, &$timer) {
417+
$loop->cancelTimer($timer);
418+
};
419+
$connection->once('close', $closeTimerCanceler);
420+
$connection->once('data', $dataTimerCanceler);
421+
$removeTimerHandler = function () use ($parser, $connection, $closeTimerCanceler, $dataTimerCanceler, &$removeTimerHandler) {
422+
$connection->removeListener('close', $closeTimerCanceler);
423+
$connection->removeListener('data', $dataTimerCanceler);
424+
$parser->removeListener('headers', $removeTimerHandler);
425+
$parser->removeListener('error', $removeTimerHandler);
426+
};
427+
$this->parser->on('headers', $removeTimerHandler);
428+
$this->parser->on('error', $removeTimerHandler);
429+
430+
$this->parser->handle($connection);
431+
}
392432
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
<?php
2+
3+
namespace React\Http\Middleware;
4+
5+
use Psr\Http\Message\ResponseInterface;
6+
use Psr\Http\Message\ServerRequestInterface;
7+
use React\Http\Io\HttpBodyStream;
8+
use React\Http\Io\PauseBufferStream;
9+
use React\Promise;
10+
use React\Promise\PromiseInterface;
11+
use React\Promise\Deferred;
12+
use React\Stream\ReadableStreamInterface;
13+
14+
/**
15+
* Closes any inactive connection after the specified amount of seconds since last activity.
16+
*
17+
* This allows you to set an alternative timeout to the default one minute (60 seconds). For example
18+
* thirteen and a half seconds:
19+
*
20+
* ```php
21+
* $http = new React\Http\HttpServer(
22+
* new React\Http\Middleware\InactiveConnectionTimeoutMiddleware(13.5),
23+
* $handler
24+
* );
25+
*
26+
* > Internally, this class is used as a "value object" to override the default timeout of one minute.
27+
* As such it doesn't have any behavior internally, that is all in the internal "StreamingServer".
28+
*/
29+
final class InactiveConnectionTimeoutMiddleware
30+
{
31+
/**
32+
* @internal
33+
*/
34+
const DEFAULT_TIMEOUT = 60;
35+
36+
/**
37+
* @var float
38+
*/
39+
private $timeout;
40+
41+
/**
42+
* @param float $timeout
43+
*/
44+
public function __construct($timeout = self::DEFAULT_TIMEOUT)
45+
{
46+
$this->timeout = $timeout;
47+
}
48+
49+
public function __invoke(ServerRequestInterface $request, $next)
50+
{
51+
return $next($request);
52+
}
53+
54+
/**
55+
* @return float
56+
* @internal
57+
*/
58+
public function getTimeout()
59+
{
60+
return $this->timeout;
61+
}
62+
}

tests/HttpServerTest.php

+19-1
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66
use React\EventLoop\Loop;
77
use React\Http\HttpServer;
88
use React\Http\Io\IniUtil;
9+
use React\Http\Io\StreamingServer;
10+
use React\Http\Middleware\InactiveConnectionTimeoutMiddleware;
911
use React\Http\Middleware\StreamingRequestMiddleware;
1012
use React\Promise;
1113
use React\Promise\Deferred;
@@ -60,6 +62,10 @@ public function testConstructWithoutLoopAssignsLoopAutomatically()
6062
$ref->setAccessible(true);
6163
$clock = $ref->getValue($streamingServer);
6264

65+
$ref = new \ReflectionProperty($streamingServer, 'parser');
66+
$ref->setAccessible(true);
67+
$parser = $ref->getValue($streamingServer);
68+
6369
$ref = new \ReflectionProperty($clock, 'loop');
6470
$ref->setAccessible(true);
6571
$loop = $ref->getValue($clock);
@@ -257,6 +263,18 @@ function (ServerRequestInterface $request) use (&$streaming) {
257263
$this->assertEquals(true, $streaming);
258264
}
259265

266+
public function testIdleConnectionWillBeClosedAfterConfiguredTimeout()
267+
{
268+
$this->connection->expects($this->once())->method('close');
269+
270+
$http = new HttpServer(Loop::get(), new InactiveConnectionTimeoutMiddleware(0.1), $this->expectCallableNever());
271+
272+
$http->listen($this->socket);
273+
$this->socket->emit('connection', array($this->connection));
274+
275+
Loop::run();
276+
}
277+
260278
public function testForwardErrors()
261279
{
262280
$exception = new \Exception();
@@ -439,7 +457,7 @@ public function testConstructServerWithMemoryLimitDoesLimitConcurrency()
439457

440458
public function testConstructFiltersOutConfigurationMiddlewareBefore()
441459
{
442-
$http = new HttpServer(new StreamingRequestMiddleware(), function () { });
460+
$http = new HttpServer(new InactiveConnectionTimeoutMiddleware(0), new StreamingRequestMiddleware(), function () { });
443461

444462
$ref = new \ReflectionProperty($http, 'streamingServer');
445463
$ref->setAccessible(true);

0 commit comments

Comments
 (0)