Skip to content

Commit 3398ca8

Browse files
committed
Close inactive requests
This builds on top of #405 and further builds out #423 by also close connections with inactive requests.
1 parent e76a58b commit 3398ca8

File tree

7 files changed

+312
-200
lines changed

7 files changed

+312
-200
lines changed

src/HttpServer.php

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,10 @@
55
use Evenement\EventEmitter;
66
use React\EventLoop\Loop;
77
use React\EventLoop\LoopInterface;
8+
use React\Http\Io\Clock;
89
use React\Http\Io\IniUtil;
910
use React\Http\Io\MiddlewareRunner;
11+
use React\Http\Io\RequestHeaderParser;
1012
use React\Http\Io\StreamingServer;
1113
use React\Http\Middleware\InactiveConnectionTimeoutMiddleware;
1214
use React\Http\Middleware\LimitConcurrentRequestsMiddleware;
@@ -259,7 +261,8 @@ public function __construct($requestHandlerOrLoop)
259261
return !($handler instanceof StreamingRequestMiddleware) && !($handler instanceof InactiveConnectionTimeoutMiddleware);
260262
});
261263

262-
$this->streamingServer = new StreamingServer($loop, new MiddlewareRunner($middleware), $idleConnectTimeout);
264+
$clock = new Clock($loop);
265+
$this->streamingServer = new StreamingServer(new MiddlewareRunner($middleware), new RequestHeaderParser($loop, $clock, $idleConnectTimeout), $clock);
263266

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

src/Io/RequestHeaderParser.php

Lines changed: 35 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
use Evenement\EventEmitter;
66
use Psr\Http\Message\ServerRequestInterface;
7+
use React\EventLoop\LoopInterface;
78
use React\Http\Message\Response;
89
use React\Http\Message\ServerRequest;
910
use React\Socket\ConnectionInterface;
@@ -24,23 +25,53 @@ class RequestHeaderParser extends EventEmitter
2425
{
2526
private $maxSize = 8192;
2627

28+
/**
29+
* @var LoopInterface
30+
*/
31+
private $loop;
32+
2733
/** @var Clock */
2834
private $clock;
2935

36+
/**
37+
* @var float
38+
*/
39+
private $idleConnectionTimeout;
40+
3041
/** @var array<string|int,array<string,string>> */
3142
private $connectionParams = array();
3243

33-
public function __construct(Clock $clock)
44+
/**
45+
* @param LoopInterface $loop
46+
* @param float $idleConnectionTimeout
47+
*/
48+
public function __construct(LoopInterface $loop, Clock $clock, $idleConnectionTimeout)
3449
{
50+
$this->loop = $loop;
3551
$this->clock = $clock;
52+
$this->idleConnectionTimeout = $idleConnectionTimeout;
3653
}
3754

3855
public function handle(ConnectionInterface $conn)
3956
{
57+
$loop = $this->loop;
58+
$idleConnectionTimeout = $this->idleConnectionTimeout;
59+
$that = $this;
60+
$idleConnectionTimeoutHandler = function () use ($that, $conn) {
61+
$that->emit('error', array(
62+
new \RuntimeException('Request timed out', Response::STATUS_REQUEST_TIMEOUT),
63+
$conn
64+
));
65+
$conn->close();
66+
};
67+
$timer = $loop->addTimer($idleConnectionTimeout, $idleConnectionTimeoutHandler);
68+
$conn->on('close', function () use ($loop, &$timer) {
69+
$loop->cancelTimer($timer);
70+
});
4071
$buffer = '';
4172
$maxSize = $this->maxSize;
42-
$that = $this;
43-
$conn->on('data', $fn = function ($data) use (&$buffer, &$fn, $conn, $maxSize, $that) {
73+
$conn->on('data', $fn = function ($data) use (&$buffer, &$fn, $conn, $maxSize, $that, $loop, &$timer, $idleConnectionTimeout, $idleConnectionTimeoutHandler) {
74+
$loop->cancelTimer($timer);
4475
// append chunk of data to buffer and look for end of request headers
4576
$buffer .= $data;
4677
$endOfHeader = \strpos($buffer, "\r\n\r\n");
@@ -59,6 +90,7 @@ public function handle(ConnectionInterface $conn)
5990

6091
// ignore incomplete requests
6192
if ($endOfHeader === false) {
93+
$timer = $loop->addTimer($idleConnectionTimeout, $idleConnectionTimeoutHandler);
6294
return;
6395
}
6496

src/Io/StreamingServer.php

Lines changed: 10 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,8 @@
55
use Evenement\EventEmitter;
66
use Psr\Http\Message\ResponseInterface;
77
use Psr\Http\Message\ServerRequestInterface;
8-
use React\EventLoop\LoopInterface;
98
use React\Http\Message\Response;
109
use React\Http\Message\ServerRequest;
11-
use React\Http\Middleware\InactiveConnectionTimeoutMiddleware;
1210
use React\Promise;
1311
use React\Promise\PromiseInterface;
1412
use React\Socket\ConnectionInterface;
@@ -29,7 +27,7 @@
2927
* object in return:
3028
*
3129
* ```php
32-
* $server = new StreamingServer($loop, function (ServerRequestInterface $request) {
30+
* $server = new StreamingServer(function (ServerRequestInterface $request) {
3331
* return new Response(
3432
* Response::STATUS_OK,
3533
* array(
@@ -54,7 +52,7 @@
5452
* in order to start a plaintext HTTP server like this:
5553
*
5654
* ```php
57-
* $server = new StreamingServer($loop, $handler);
55+
* $server = new StreamingServer($handler);
5856
*
5957
* $socket = new React\Socket\SocketServer('0.0.0.0:8080', array(), $loop);
6058
* $server->listen($socket);
@@ -98,23 +96,19 @@ final class StreamingServer extends EventEmitter
9896
* connections in order to then parse incoming data as HTTP.
9997
* See also [listen()](#listen) for more details.
10098
*
101-
* @param LoopInterface $loop
10299
* @param callable $requestHandler
103100
* @param float $idleConnectTimeout
104101
* @see self::listen()
105102
*/
106-
public function __construct(LoopInterface $loop, $requestHandler, $idleConnectTimeout = InactiveConnectionTimeoutMiddleware::DEFAULT_TIMEOUT)
103+
public function __construct($requestHandler, RequestHeaderParser $parser, Clock $clock)
107104
{
108105
if (!\is_callable($requestHandler)) {
109106
throw new \InvalidArgumentException('Invalid request handler given');
110107
}
111108

112-
$this->loop = $loop;
113-
$this->idleConnectionTimeout = $idleConnectTimeout;
114-
115109
$this->callback = $requestHandler;
116-
$this->clock = new Clock($loop);
117-
$this->parser = new RequestHeaderParser($this->clock);
110+
$this->clock = $clock;
111+
$this->parser = $parser;
118112

119113
$that = $this;
120114
$this->parser->on('headers', function (ServerRequestInterface $request, ConnectionInterface $conn) use ($that) {
@@ -141,27 +135,7 @@ public function __construct(LoopInterface $loop, $requestHandler, $idleConnectTi
141135
*/
142136
public function listen(ServerInterface $socket)
143137
{
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);
138+
$socket->on('connection', array($this->parser, 'handle'));
165139
}
166140

167141
/** @internal */
@@ -379,7 +353,7 @@ public function handleResponse(ConnectionInterface $connection, ServerRequestInt
379353

380354
// either wait for next request over persistent connection or end connection
381355
if ($persist) {
382-
$this->handle($connection);
356+
$this->parser->handle($connection);
383357
} else {
384358
$connection->end();
385359
}
@@ -400,10 +374,10 @@ public function handleResponse(ConnectionInterface $connection, ServerRequestInt
400374
// write streaming body and then wait for next request over persistent connection
401375
if ($persist) {
402376
$body->pipe($connection, array('end' => false));
403-
$that = $this;
404-
$body->on('end', function () use ($connection, $that, $body) {
377+
$parser = $this->parser;
378+
$body->on('end', function () use ($connection, $parser, $body) {
405379
$connection->removeListener('close', array($body, 'close'));
406-
$that->handle($connection);
380+
$parser->handle($connection);
407381
});
408382
} else {
409383
$body->pipe($connection);

src/Middleware/InactiveConnectionTimeoutMiddleware.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,9 @@
2828
*/
2929
final class InactiveConnectionTimeoutMiddleware
3030
{
31+
/**
32+
* @internal
33+
*/
3134
const DEFAULT_TIMEOUT = 60;
3235

3336
/**
@@ -50,6 +53,7 @@ public function __invoke(ServerRequestInterface $request, $next)
5053

5154
/**
5255
* @return float
56+
* @internal
5357
*/
5458
public function getTimeout()
5559
{

tests/HttpServerTest.php

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -62,10 +62,18 @@ public function testConstructWithoutLoopAssignsLoopAutomatically()
6262
$ref->setAccessible(true);
6363
$clock = $ref->getValue($streamingServer);
6464

65+
$ref = new \ReflectionProperty($streamingServer, 'parser');
66+
$ref->setAccessible(true);
67+
$parser = $ref->getValue($streamingServer);
68+
6569
$ref = new \ReflectionProperty($clock, 'loop');
6670
$ref->setAccessible(true);
6771
$loop = $ref->getValue($clock);
6872

73+
$ref = new \ReflectionProperty($parser, 'loop');
74+
$ref->setAccessible(true);
75+
$loop = $ref->getValue($parser);
76+
6977
$this->assertInstanceOf('React\EventLoop\LoopInterface', $loop);
7078
}
7179

@@ -263,13 +271,12 @@ public function testIdleConnectionWillBeClosedAfterConfiguredTimeout()
263271
{
264272
$this->connection->expects($this->once())->method('close');
265273

266-
$loop = Factory::create();
267-
$http = new HttpServer($loop, new InactiveConnectionTimeoutMiddleware(0.1), $this->expectCallableNever());
274+
$http = new HttpServer(Loop::get(), new InactiveConnectionTimeoutMiddleware(0.1), $this->expectCallableNever());
268275

269276
$http->listen($this->socket);
270277
$this->socket->emit('connection', array($this->connection));
271278

272-
$loop->run();
279+
Loop::run();
273280
}
274281

275282
public function testForwardErrors()

0 commit comments

Comments
 (0)