Skip to content

Commit e76a58b

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

File tree

6 files changed

+146
-12
lines changed

6 files changed

+146
-12
lines changed

README.md

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,7 @@ multiple concurrent HTTP requests without blocking.
7878
* [ServerRequest](#serverrequest)
7979
* [ResponseException](#responseexception)
8080
* [React\Http\Middleware](#reacthttpmiddleware)
81+
* [InactiveConnectionTimeoutMiddleware](#inactiveconnectiontimeoutmiddleware)
8182
* [StreamingRequestMiddleware](#streamingrequestmiddleware)
8283
* [LimitConcurrentRequestsMiddleware](#limitconcurrentrequestsmiddleware)
8384
* [RequestBodyBufferMiddleware](#requestbodybuffermiddleware)
@@ -2630,6 +2631,22 @@ access its underlying response object.
26302631

26312632
### React\Http\Middleware
26322633

2634+
#### InactiveConnectionTimeoutMiddleware
2635+
2636+
The `React\Http\Middleware\InactiveConnectionTimeoutMiddleware` is purely a configuration middleware to configure the
2637+
`HttpServer` to close any inactive connections between requests to close the connection and not leave them needlessly open.
2638+
2639+
The following example configures the `HttpServer` to close any inactive connections after one and a half second:
2640+
2641+
```php
2642+
$http = new React\Http\HttpServer(
2643+
new React\Http\Middleware\InactiveConnectionTimeoutMiddleware(1.5),
2644+
$handler
2645+
);
2646+
```
2647+
> Internally, this class is used as a "value object" to override the default timeout of one minute.
2648+
As such it doesn't have any behavior internally, that is all in the internal "StreamingServer".
2649+
26332650
#### StreamingRequestMiddleware
26342651

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

src/HttpServer.php

Lines changed: 7 additions & 3 deletions
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+
$idleConnectTimeout = 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+
$idleConnectTimeout = $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), $idleConnectTimeout);
259263

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

src/Io/StreamingServer.php

Lines changed: 33 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
use React\EventLoop\LoopInterface;
99
use React\Http\Message\Response;
1010
use React\Http\Message\ServerRequest;
11+
use React\Http\Middleware\InactiveConnectionTimeoutMiddleware;
1112
use React\Promise;
1213
use React\Promise\PromiseInterface;
1314
use React\Socket\ConnectionInterface;
@@ -86,6 +87,8 @@ final class StreamingServer extends EventEmitter
8687

8788
/** @var Clock */
8889
private $clock;
90+
private $loop;
91+
private $idleConnectionTimeout;
8992

9093
/**
9194
* Creates an HTTP server that invokes the given callback for each incoming HTTP request
@@ -97,14 +100,18 @@ final class StreamingServer extends EventEmitter
97100
*
98101
* @param LoopInterface $loop
99102
* @param callable $requestHandler
103+
* @param float $idleConnectTimeout
100104
* @see self::listen()
101105
*/
102-
public function __construct(LoopInterface $loop, $requestHandler)
106+
public function __construct(LoopInterface $loop, $requestHandler, $idleConnectTimeout = InactiveConnectionTimeoutMiddleware::DEFAULT_TIMEOUT)
103107
{
104108
if (!\is_callable($requestHandler)) {
105109
throw new \InvalidArgumentException('Invalid request handler given');
106110
}
107111

112+
$this->loop = $loop;
113+
$this->idleConnectionTimeout = $idleConnectTimeout;
114+
108115
$this->callback = $requestHandler;
109116
$this->clock = new Clock($loop);
110117
$this->parser = new RequestHeaderParser($this->clock);
@@ -134,7 +141,27 @@ public function __construct(LoopInterface $loop, $requestHandler)
134141
*/
135142
public function listen(ServerInterface $socket)
136143
{
137-
$socket->on('connection', array($this->parser, 'handle'));
144+
$socket->on('connection', array($this, 'handle'));
145+
}
146+
147+
/** @internal */
148+
public function handle(ConnectionInterface $conn)
149+
{
150+
$timer = $this->loop->addTimer($this->idleConnectionTimeout, function () use ($conn) {
151+
$conn->close();
152+
});
153+
$loop = $this->loop;
154+
$conn->once('data', function () use ($loop, $timer) {
155+
$loop->cancelTimer($timer);
156+
});
157+
$conn->on('end', function () use ($loop, $timer) {
158+
$loop->cancelTimer($timer);
159+
});
160+
$conn->on('close', function () use ($loop, $timer) {
161+
$loop->cancelTimer($timer);
162+
});
163+
164+
$this->parser->handle($conn);
138165
}
139166

140167
/** @internal */
@@ -352,7 +379,7 @@ public function handleResponse(ConnectionInterface $connection, ServerRequestInt
352379

353380
// either wait for next request over persistent connection or end connection
354381
if ($persist) {
355-
$this->parser->handle($connection);
382+
$this->handle($connection);
356383
} else {
357384
$connection->end();
358385
}
@@ -373,10 +400,10 @@ public function handleResponse(ConnectionInterface $connection, ServerRequestInt
373400
// write streaming body and then wait for next request over persistent connection
374401
if ($persist) {
375402
$body->pipe($connection, array('end' => false));
376-
$parser = $this->parser;
377-
$body->on('end', function () use ($connection, $parser, $body) {
403+
$that = $this;
404+
$body->on('end', function () use ($connection, $that, $body) {
378405
$connection->removeListener('close', array($body, 'close'));
379-
$parser->handle($connection);
406+
$that->handle($connection);
380407
});
381408
} else {
382409
$body->pipe($connection);
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
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+
const DEFAULT_TIMEOUT = 60;
32+
33+
/**
34+
* @var float
35+
*/
36+
private $timeout;
37+
38+
/**
39+
* @param float $timeout
40+
*/
41+
public function __construct($timeout = self::DEFAULT_TIMEOUT)
42+
{
43+
$this->timeout = $timeout;
44+
}
45+
46+
public function __invoke(ServerRequestInterface $request, $next)
47+
{
48+
return $next($request);
49+
}
50+
51+
/**
52+
* @return float
53+
*/
54+
public function getTimeout()
55+
{
56+
return $this->timeout;
57+
}
58+
}

tests/HttpServerTest.php

Lines changed: 16 additions & 1 deletion
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;
@@ -257,6 +259,19 @@ function (ServerRequestInterface $request) use (&$streaming) {
257259
$this->assertEquals(true, $streaming);
258260
}
259261

262+
public function testIdleConnectionWillBeClosedAfterConfiguredTimeout()
263+
{
264+
$this->connection->expects($this->once())->method('close');
265+
266+
$loop = Factory::create();
267+
$http = new HttpServer($loop, new InactiveConnectionTimeoutMiddleware(0.1), $this->expectCallableNever());
268+
269+
$http->listen($this->socket);
270+
$this->socket->emit('connection', array($this->connection));
271+
272+
$loop->run();
273+
}
274+
260275
public function testForwardErrors()
261276
{
262277
$exception = new \Exception();
@@ -439,7 +454,7 @@ public function testConstructServerWithMemoryLimitDoesLimitConcurrency()
439454

440455
public function testConstructFiltersOutConfigurationMiddlewareBefore()
441456
{
442-
$http = new HttpServer(new StreamingRequestMiddleware(), function () { });
457+
$http = new HttpServer(new InactiveConnectionTimeoutMiddleware(0), new StreamingRequestMiddleware(), function () { });
443458

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

tests/Io/StreamingServerTest.php

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,19 @@ public function testRequestEventWillNotBeEmittedForIncompleteHeaders()
6161
$this->connection->emit('data', array($data));
6262
}
6363

64+
public function testIdleConnectionWillBeClosedAfterConfiguredTimeout()
65+
{
66+
$this->connection->expects($this->once())->method('close');
67+
68+
$loop = Factory::create();
69+
$server = new StreamingServer($loop, $this->expectCallableNever(), 0.1);
70+
71+
$server->listen($this->socket);
72+
$this->socket->emit('connection', array($this->connection));
73+
74+
$loop->run();
75+
}
76+
6477
public function testRequestEventIsEmitted()
6578
{
6679
$server = new StreamingServer(Loop::get(), $this->expectCallableOnce());
@@ -3240,9 +3253,9 @@ public function testNewConnectionWillInvokeParserTwiceAfterInvokingRequestHandle
32403253
// pretend parser just finished parsing
32413254
$server->handleRequest($this->connection, $request);
32423255

3243-
$this->assertCount(2, $this->connection->listeners('close'));
3256+
$this->assertCount(3, $this->connection->listeners('close'));
32443257
$body->end();
3245-
$this->assertCount(1, $this->connection->listeners('close'));
3258+
$this->assertCount(3, $this->connection->listeners('close'));
32463259
}
32473260

32483261
private function createGetRequest()

0 commit comments

Comments
 (0)