-
Notifications
You must be signed in to change notification settings - Fork 99
/
Server.php
114 lines (95 loc) · 2.96 KB
/
Server.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
<?php
namespace Laravel\Reverb\Servers\Reverb\Http;
use Illuminate\Support\Str;
use Laravel\Reverb\Loggers\Log;
use Laravel\Reverb\Servers\Reverb\Concerns\ClosesConnections;
use OverflowException;
use Psr\Http\Message\RequestInterface;
use React\EventLoop\Loop;
use React\EventLoop\LoopInterface;
use React\Socket\ConnectionInterface;
use React\Socket\ServerInterface;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Throwable;
class Server
{
use ClosesConnections;
/**
* Create a new Http server instance.
*/
public function __construct(protected ServerInterface $socket, protected Router $router, protected int $maxRequestSize, protected ?LoopInterface $loop = null)
{
gc_disable();
$this->loop = $loop ?: Loop::get();
$this->loop->addPeriodicTimer(30, fn () => gc_collect_cycles());
// Register __invoke handler for this class to receive new connections...
$socket->on('connection', $this);
}
/**
* Start the Http server
*/
public function start(): void
{
$this->loop->run();
}
/**
* Handle an incoming request.
*/
protected function handleRequest(string $message, Connection $connection): void
{
if ($connection->isConnected()) {
return;
}
if (($request = $this->createRequest($message, $connection)) === null) {
return;
}
$connection->connect();
try {
$this->router->dispatch($request, $connection);
} catch (HttpException $e) {
$this->close($connection, $e->getStatusCode(), $e->getMessage());
} catch (Throwable $e) {
Log::error($e->getMessage());
$this->close($connection, 500, 'Internal server error.');
}
}
/**
* Create a Psr7 request from the incoming message.
*/
protected function createRequest(string $message, Connection $connection): ?RequestInterface
{
try {
$request = Request::from($message, $connection, $this->maxRequestSize);
} catch (OverflowException $e) {
$this->close($connection, 413, 'Payload too large.');
} catch (Throwable $e) {
$this->close($connection, 400, 'Bad request.');
}
return $request ?? null;
}
/**
* Stop the Http server
*/
public function stop(): void
{
$this->loop->stop();
$this->socket->close();
}
/**
* Invoke the server with a new connection instance.
*/
public function __invoke(ConnectionInterface $connection): void
{
$connection = new Connection($connection);
$connection->on('data', function ($data) use ($connection) {
$this->handleRequest($data, $connection);
});
}
/**
* Determine whether the server has TLS support.
*/
public function isSecure(): bool
{
return Str::startsWith($this->socket->getAddress(), 'tls://');
}
}