Skip to content

Commit 98e2b63

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 c313d4c commit 98e2b63

File tree

6 files changed

+143
-12
lines changed

6 files changed

+143
-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)
@@ -2618,6 +2619,22 @@ access its underlying response object.
26182619

26192620
### React\Http\Middleware
26202621

2622+
#### InactiveConnectionTimeoutMiddleware
2623+
2624+
The `React\Http\Middleware\InactiveConnectionTimeoutMiddleware` is purely a configuration middleware to configure the
2625+
`HttpServer` to close any inactive connections between requests to close the connection and not leave them needlessly open.
2626+
2627+
The following example configures the `HttpServer` to close any inactive connections after one and a half second:
2628+
2629+
```php
2630+
$http = new React\Http\HttpServer(
2631+
new React\Http\Middleware\InactiveConnectionTimeoutMiddleware(1.5),
2632+
$handler
2633+
);
2634+
```
2635+
> Internally, this class is used as a "value object" to override the default timeout of one minute.
2636+
As such it doesn't have any behavior internally, that is all in the internal "StreamingServer".
2637+
26212638
#### StreamingRequestMiddleware
26222639

26232640
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: 30 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;
@@ -85,6 +86,7 @@ final class StreamingServer extends EventEmitter
8586
private $callback;
8687
private $parser;
8788
private $loop;
89+
private $idleConnectionTimeout;
8890

8991
/**
9092
* Creates an HTTP server that invokes the given callback for each incoming HTTP request
@@ -96,15 +98,17 @@ final class StreamingServer extends EventEmitter
9698
*
9799
* @param LoopInterface $loop
98100
* @param callable $requestHandler
101+
* @param float $idleConnectTimeout
99102
* @see self::listen()
100103
*/
101-
public function __construct(LoopInterface $loop, $requestHandler)
104+
public function __construct(LoopInterface $loop, $requestHandler, $idleConnectTimeout = InactiveConnectionTimeoutMiddleware::DEFAULT_TIMEOUT)
102105
{
103106
if (!\is_callable($requestHandler)) {
104107
throw new \InvalidArgumentException('Invalid request handler given');
105108
}
106109

107110
$this->loop = $loop;
111+
$this->idleConnectionTimeout = $idleConnectTimeout;
108112

109113
$this->callback = $requestHandler;
110114
$this->parser = new RequestHeaderParser();
@@ -134,7 +138,27 @@ public function __construct(LoopInterface $loop, $requestHandler)
134138
*/
135139
public function listen(ServerInterface $socket)
136140
{
137-
$socket->on('connection', array($this->parser, 'handle'));
141+
$socket->on('connection', array($this, 'handle'));
142+
}
143+
144+
/** @internal */
145+
public function handle(ConnectionInterface $conn)
146+
{
147+
$timer = $this->loop->addTimer($this->idleConnectionTimeout, function () use ($conn) {
148+
$conn->close();
149+
});
150+
$loop = $this->loop;
151+
$conn->once('data', function () use ($loop, $timer) {
152+
$loop->cancelTimer($timer);
153+
});
154+
$conn->on('end', function () use ($loop, $timer) {
155+
$loop->cancelTimer($timer);
156+
});
157+
$conn->on('close', function () use ($loop, $timer) {
158+
$loop->cancelTimer($timer);
159+
});
160+
161+
$this->parser->handle($conn);
138162
}
139163

140164
/** @internal */
@@ -352,7 +376,7 @@ public function handleResponse(ConnectionInterface $connection, ServerRequestInt
352376

353377
// either wait for next request over persistent connection or end connection
354378
if ($persist) {
355-
$this->parser->handle($connection);
379+
$this->handle($connection);
356380
} else {
357381
$connection->end();
358382
}
@@ -373,10 +397,10 @@ public function handleResponse(ConnectionInterface $connection, ServerRequestInt
373397
// write streaming body and then wait for next request over persistent connection
374398
if ($persist) {
375399
$body->pipe($connection, array('end' => false));
376-
$parser = $this->parser;
377-
$body->on('end', function () use ($connection, $parser, $body) {
400+
$that = $this;
401+
$body->on('end', function () use ($connection, $that, $body) {
378402
$connection->removeListener('close', array($body, 'close'));
379-
$parser->handle($connection);
403+
$that->handle($connection);
380404
});
381405
} else {
382406
$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
@@ -7,6 +7,8 @@
77
use React\EventLoop\Loop;
88
use React\Http\HttpServer;
99
use React\Http\Io\IniUtil;
10+
use React\Http\Io\StreamingServer;
11+
use React\Http\Middleware\InactiveConnectionTimeoutMiddleware;
1012
use React\Http\Middleware\StreamingRequestMiddleware;
1113
use React\Promise;
1214
use React\Promise\Deferred;
@@ -251,6 +253,19 @@ function (ServerRequestInterface $request) use (&$streaming) {
251253
$this->assertEquals(true, $streaming);
252254
}
253255

256+
public function testIdleConnectionWillBeClosedAfterConfiguredTimeout()
257+
{
258+
$this->connection->expects($this->once())->method('close');
259+
260+
$loop = Factory::create();
261+
$http = new HttpServer($loop, new InactiveConnectionTimeoutMiddleware(0.1), $this->expectCallableNever());
262+
263+
$http->listen($this->socket);
264+
$this->socket->emit('connection', array($this->connection));
265+
266+
$loop->run();
267+
}
268+
254269
public function testForwardErrors()
255270
{
256271
$exception = new \Exception();
@@ -433,7 +448,7 @@ public function testConstructServerWithMemoryLimitDoesLimitConcurrency()
433448

434449
public function testConstructFiltersOutConfigurationMiddlewareBefore()
435450
{
436-
$http = new HttpServer(new StreamingRequestMiddleware(), function () { });
451+
$http = new HttpServer(new InactiveConnectionTimeoutMiddleware(0), new StreamingRequestMiddleware(), function () { });
437452

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

tests/Io/StreamingServerTest.php

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

61+
public function testIdleConnectionWillBeClosedAfterConfiguredTimeout()
62+
{
63+
$this->connection->expects($this->once())->method('close');
64+
65+
$loop = Factory::create();
66+
$server = new StreamingServer($loop, $this->expectCallableNever(), 0.1);
67+
68+
$server->listen($this->socket);
69+
$this->socket->emit('connection', array($this->connection));
70+
71+
$loop->run();
72+
}
73+
6174
public function testRequestEventIsEmitted()
6275
{
6376
$server = new StreamingServer(Loop::get(), $this->expectCallableOnce());
@@ -3228,9 +3241,9 @@ public function testNewConnectionWillInvokeParserTwiceAfterInvokingRequestHandle
32283241
// pretend parser just finished parsing
32293242
$server->handleRequest($this->connection, $request);
32303243

3231-
$this->assertCount(2, $this->connection->listeners('close'));
3244+
$this->assertCount(3, $this->connection->listeners('close'));
32323245
$body->end();
3233-
$this->assertCount(1, $this->connection->listeners('close'));
3246+
$this->assertCount(3, $this->connection->listeners('close'));
32343247
}
32353248

32363249
private function createGetRequest()

0 commit comments

Comments
 (0)