Repository navigation
Expand file tree
/
Copy pathCoroutineServer.php
More file actions
235 lines (209 loc) · 9.4 KB
/
Copy pathCoroutineServer.php
File metadata and controls
235 lines (209 loc) · 9.4 KB
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact [email protected]
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
namespace Hyperf\Server;
use Hyperf\Contract\ConfigInterface;
use Hyperf\Contract\MiddlewareInitializerInterface;
use Hyperf\Coordinator\Constants;
use Hyperf\Coordinator\CoordinatorManager;
use Hyperf\Coroutine\Waiter;
use Hyperf\Engine\SafeSocket;
use Hyperf\Server\Event\AllCoroutineServersClosed;
use Hyperf\Server\Event\CoroutineServerStart;
use Hyperf\Server\Event\CoroutineServerStop;
use Hyperf\Server\Event\MainCoroutineServerStart;
use Hyperf\Server\Exception\RuntimeException;
use Psr\Container\ContainerInterface;
use Psr\EventDispatcher\EventDispatcherInterface;
use Psr\Log\LoggerInterface;
use Swoole\Coroutine;
use Swoole\Coroutine\Http\Server as HttpServer;
use Swoole\Coroutine\Server;
use function Hyperf\Coroutine\run;
use function Hyperf\Support\swoole_hook_flags;
class CoroutineServer implements ServerInterface
{
protected ?ServerConfig $config = null;
protected null|HttpServer|Server $server = null;
/**
* @var callable
*/
protected $handler;
protected bool $mainServerStarted = false;
private Waiter $waiter;
public function __construct(
protected ContainerInterface $container,
protected LoggerInterface $logger,
protected EventDispatcherInterface $eventDispatcher
) {
$this->waiter = new Waiter(-1);
}
public function init(ServerConfig $config): ServerInterface
{
$this->config = $config;
return $this;
}
public function start(): void
{
$this->writePid();
run(function () {
$this->initServer($this->config);
$servers = ServerManager::list();
$config = $this->config->toArray();
foreach ($servers as $name => [$type, $server]) {
Coroutine::create(function () use ($name, $server, $config) {
if (! $this->mainServerStarted) {
$this->mainServerStarted = true;
$this->eventDispatcher->dispatch(new MainCoroutineServerStart($name, $server, $config));
CoordinatorManager::until(Constants::WORKER_START)->resume();
}
$this->eventDispatcher->dispatch(new CoroutineServerStart($name, $server, $config));
$server->start();
$this->eventDispatcher->dispatch(new CoroutineServerStop($name, $server));
CoordinatorManager::until(Constants::WORKER_EXIT)->resume();
});
}
if (CoordinatorManager::until(Constants::WORKER_EXIT)->yield()) {
$this->closeAll($servers);
}
}, swoole_hook_flags());
}
public function getServer(): HttpServer|Server
{
return $this->server;
}
protected function closeAll(array $servers = []): void
{
/**
* @var HttpServer|Server $server
*/
foreach ($servers as [$type, $server]) {
$server->shutdown();
}
$this->eventDispatcher->dispatch(new AllCoroutineServersClosed());
}
protected function initServer(ServerConfig $config): void
{
$servers = $config->getServers();
foreach ($servers as $server) {
if (! $server instanceof Port) {
continue;
}
$name = $server->getName();
$type = $server->getType();
$host = $server->getHost();
$port = $server->getPort();
$callbacks = array_replace($config->getCallbacks(), $server->getCallbacks());
$this->server = $this->makeServer($type, $host, $port);
$settings = array_replace($config->getSettings(), $server->getSettings());
$this->server->set($settings);
$this->bindServerCallbacks($type, $name, $callbacks, $server);
ServerManager::add($name, [$type, $this->server, $callbacks]);
}
}
protected function bindServerCallbacks(int $type, string $name, array $callbacks, Port $port): void
{
switch ($type) {
case ServerInterface::SERVER_HTTP:
if (isset($callbacks[Event::ON_REQUEST])) {
[$handler, $method] = $this->getCallbackMethod(Event::ON_REQUEST, $callbacks);
if ($handler instanceof MiddlewareInitializerInterface) {
$handler->initCoreMiddleware($name);
}
if ($this->server instanceof HttpServer) {
$this->server->handle('/', static function ($request, $response) use ($handler, $method) {
Coroutine::create(static fn () => $handler->{$method}($request, $response));
});
}
}
return;
case ServerInterface::SERVER_WEBSOCKET:
if (isset($callbacks[Event::ON_HAND_SHAKE])) {
[$handler, $method] = $this->getCallbackMethod(Event::ON_HAND_SHAKE, $callbacks);
if ($handler instanceof MiddlewareInitializerInterface) {
$handler->initCoreMiddleware($name);
}
if ($this->server instanceof HttpServer) {
$this->server->handle('/', [$handler, $method]);
}
}
return;
case ServerInterface::SERVER_BASE:
if (isset($callbacks[Event::ON_RECEIVE])) {
[$connectHandler, $connectMethod] = $this->getCallbackMethod(Event::ON_CONNECT, $callbacks);
[$receiveHandler, $receiveMethod] = $this->getCallbackMethod(Event::ON_RECEIVE, $callbacks);
[$closeHandler, $closeMethod] = $this->getCallbackMethod(Event::ON_CLOSE, $callbacks);
if ($receiveHandler instanceof MiddlewareInitializerInterface) {
$receiveHandler->initCoreMiddleware($name);
}
if ($this->server instanceof Server) {
$this->server->handle(function (Server\Connection $connection) use ($connectHandler, $connectMethod, $receiveHandler, $receiveMethod, $closeHandler, $closeMethod, $port) {
$socket = $connection->exportSocket();
$fd = $socket->fd;
$options = $port->getOptions();
if ($options && $options->getSendChannelCapacity() > 0) {
$socket = new SafeSocket($socket, $options->getSendChannelCapacity(), false, $this->logger);
$connection = new Connection($socket);
}
if ($connectHandler && $connectMethod) {
$this->waiter->wait(static function () use ($connectHandler, $connectMethod, $connection, $fd) {
$connectHandler->{$connectMethod}($connection, $fd);
});
}
while (true) {
$data = $socket->recvPacket();
if (empty($data)) {
if ($closeHandler && $closeMethod) {
$this->waiter->wait(static function () use ($closeHandler, $closeMethod, $connection, $fd) {
$closeHandler->{$closeMethod}($connection, $fd);
});
}
$socket->close();
break;
}
// One coroutine at a time, consistent with other servers
$this->waiter->wait(static function () use ($receiveHandler, $receiveMethod, $connection, $data, $fd) {
$receiveHandler->{$receiveMethod}($connection, $fd, 0, $data);
});
}
});
}
}
return;
}
throw new RuntimeException('Server type is invalid or the server callback does not exists.');
}
protected function getCallbackMethod(string $callback, array $callbacks): array
{
$handler = $method = null;
if (isset($callbacks[$callback])) {
[$class, $method] = $callbacks[$callback];
$handler = $this->container->get($class);
}
return [$handler, $method];
}
protected function makeServer($type, $host, $port): HttpServer|Server
{
return match ($type) {
ServerInterface::SERVER_HTTP,
ServerInterface::SERVER_WEBSOCKET => new HttpServer($host, $port, false, true),
ServerInterface::SERVER_BASE => new Server($host, $port, false, true),
default => throw new RuntimeException('Server type is invalid.'),
};
}
private function writePid(): void
{
$config = $this->container->get(ConfigInterface::class);
$file = $config->get('server.settings.pid_file');
if ($file) {
file_put_contents($file, getmypid());
}
}
}