Skip to content

Commit 0423cf7

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 b5a66a4 commit 0423cf7

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\CancellablePromiseInterface;
1314
use React\Promise\PromiseInterface;
@@ -87,6 +88,8 @@ final class StreamingServer extends EventEmitter
8788

8889
/** @var Clock */
8990
private $clock;
91+
private $loop;
92+
private $idleConnectionTimeout;
9093

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

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

141168
/** @internal */
@@ -353,7 +380,7 @@ public function handleResponse(ConnectionInterface $connection, ServerRequestInt
353380

354381
// either wait for next request over persistent connection or end connection
355382
if ($persist) {
356-
$this->parser->handle($connection);
383+
$this->handle($connection);
357384
} else {
358385
$connection->end();
359386
}
@@ -374,10 +401,10 @@ public function handleResponse(ConnectionInterface $connection, ServerRequestInt
374401
// write streaming body and then wait for next request over persistent connection
375402
if ($persist) {
376403
$body->pipe($connection, array('end' => false));
377-
$parser = $this->parser;
378-
$body->on('end', function () use ($connection, $parser, $body) {
404+
$that = $this;
405+
$body->on('end', function () use ($connection, $that, $body) {
379406
$connection->removeListener('close', array($body, 'close'));
380-
$parser->handle($connection);
407+
$that->handle($connection);
381408
});
382409
} else {
383410
$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)