CoroutineServer.php 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * @link https://www.hyperf.io
  7. * @document https://hyperf.wiki
  8. * @contact group@hyperf.io
  9. * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
  10. */
  11. namespace Hyperf\Server;
  12. use Hyperf\Contract\ConfigInterface;
  13. use Hyperf\Contract\MiddlewareInitializerInterface;
  14. use Hyperf\Coordinator\Constants;
  15. use Hyperf\Coordinator\CoordinatorManager;
  16. use Hyperf\Coroutine\Waiter;
  17. use Hyperf\Engine\SafeSocket;
  18. use Hyperf\Server\Event\AllCoroutineServersClosed;
  19. use Hyperf\Server\Event\CoroutineServerStart;
  20. use Hyperf\Server\Event\CoroutineServerStop;
  21. use Hyperf\Server\Event\MainCoroutineServerStart;
  22. use Hyperf\Server\Exception\RuntimeException;
  23. use Psr\Container\ContainerInterface;
  24. use Psr\EventDispatcher\EventDispatcherInterface;
  25. use Psr\Log\LoggerInterface;
  26. use Swoole\Coroutine;
  27. use Swoole\Coroutine\Http\Server as HttpServer;
  28. use Swoole\Coroutine\Server;
  29. use function Hyperf\Coroutine\run;
  30. use function Hyperf\Support\swoole_hook_flags;
  31. class CoroutineServer implements ServerInterface
  32. {
  33. protected ?ServerConfig $config = null;
  34. protected null|HttpServer|Server $server = null;
  35. /**
  36. * @var callable
  37. */
  38. protected $handler;
  39. protected bool $mainServerStarted = false;
  40. private Waiter $waiter;
  41. public function __construct(
  42. protected ContainerInterface $container,
  43. protected LoggerInterface $logger,
  44. protected EventDispatcherInterface $eventDispatcher
  45. ) {
  46. $this->waiter = new Waiter(-1);
  47. }
  48. public function init(ServerConfig $config): ServerInterface
  49. {
  50. $this->config = $config;
  51. return $this;
  52. }
  53. public function start(): void
  54. {
  55. $this->writePid();
  56. run(function () {
  57. $this->initServer($this->config);
  58. $servers = ServerManager::list();
  59. $config = $this->config->toArray();
  60. foreach ($servers as $name => [$type, $server]) {
  61. Coroutine::create(function () use ($name, $server, $config) {
  62. if (! $this->mainServerStarted) {
  63. $this->mainServerStarted = true;
  64. $this->eventDispatcher->dispatch(new MainCoroutineServerStart($name, $server, $config));
  65. CoordinatorManager::until(Constants::WORKER_START)->resume();
  66. }
  67. $this->eventDispatcher->dispatch(new CoroutineServerStart($name, $server, $config));
  68. $server->start();
  69. $this->eventDispatcher->dispatch(new CoroutineServerStop($name, $server));
  70. CoordinatorManager::until(Constants::WORKER_EXIT)->resume();
  71. });
  72. }
  73. if (CoordinatorManager::until(Constants::WORKER_EXIT)->yield()) {
  74. $this->closeAll($servers);
  75. }
  76. }, swoole_hook_flags());
  77. }
  78. public function getServer(): HttpServer|Server
  79. {
  80. return $this->server;
  81. }
  82. protected function closeAll(array $servers = []): void
  83. {
  84. /**
  85. * @var HttpServer|Server $server
  86. */
  87. foreach ($servers as [$type, $server]) {
  88. $server->shutdown();
  89. }
  90. $this->eventDispatcher->dispatch(new AllCoroutineServersClosed());
  91. }
  92. protected function initServer(ServerConfig $config): void
  93. {
  94. $servers = $config->getServers();
  95. foreach ($servers as $server) {
  96. if (! $server instanceof Port) {
  97. continue;
  98. }
  99. $name = $server->getName();
  100. $type = $server->getType();
  101. $host = $server->getHost();
  102. $port = $server->getPort();
  103. $callbacks = array_replace($config->getCallbacks(), $server->getCallbacks());
  104. $this->server = $this->makeServer($type, $host, $port);
  105. $settings = array_replace($config->getSettings(), $server->getSettings());
  106. $this->server->set($settings);
  107. $this->bindServerCallbacks($type, $name, $callbacks, $server);
  108. ServerManager::add($name, [$type, $this->server, $callbacks]);
  109. }
  110. }
  111. protected function bindServerCallbacks(int $type, string $name, array $callbacks, Port $port): void
  112. {
  113. switch ($type) {
  114. case ServerInterface::SERVER_HTTP:
  115. if (isset($callbacks[Event::ON_REQUEST])) {
  116. [$handler, $method] = $this->getCallbackMethod(Event::ON_REQUEST, $callbacks);
  117. if ($handler instanceof MiddlewareInitializerInterface) {
  118. $handler->initCoreMiddleware($name);
  119. }
  120. if ($this->server instanceof HttpServer) {
  121. $this->server->handle('/', static function ($request, $response) use ($handler, $method) {
  122. Coroutine::create(static fn () => $handler->{$method}($request, $response));
  123. });
  124. }
  125. }
  126. return;
  127. case ServerInterface::SERVER_WEBSOCKET:
  128. if (isset($callbacks[Event::ON_HAND_SHAKE])) {
  129. [$handler, $method] = $this->getCallbackMethod(Event::ON_HAND_SHAKE, $callbacks);
  130. if ($handler instanceof MiddlewareInitializerInterface) {
  131. $handler->initCoreMiddleware($name);
  132. }
  133. if ($this->server instanceof HttpServer) {
  134. $this->server->handle('/', [$handler, $method]);
  135. }
  136. }
  137. return;
  138. case ServerInterface::SERVER_BASE:
  139. if (isset($callbacks[Event::ON_RECEIVE])) {
  140. [$connectHandler, $connectMethod] = $this->getCallbackMethod(Event::ON_CONNECT, $callbacks);
  141. [$receiveHandler, $receiveMethod] = $this->getCallbackMethod(Event::ON_RECEIVE, $callbacks);
  142. [$closeHandler, $closeMethod] = $this->getCallbackMethod(Event::ON_CLOSE, $callbacks);
  143. if ($receiveHandler instanceof MiddlewareInitializerInterface) {
  144. $receiveHandler->initCoreMiddleware($name);
  145. }
  146. if ($this->server instanceof Server) {
  147. $this->server->handle(function (Server\Connection $connection) use ($connectHandler, $connectMethod, $receiveHandler, $receiveMethod, $closeHandler, $closeMethod, $port) {
  148. $socket = $connection->exportSocket();
  149. $fd = $socket->fd;
  150. $options = $port->getOptions();
  151. if ($options && $options->getSendChannelCapacity() > 0) {
  152. $socket = new SafeSocket($socket, $options->getSendChannelCapacity(), false, $this->logger);
  153. $connection = new Connection($socket);
  154. }
  155. if ($connectHandler && $connectMethod) {
  156. $this->waiter->wait(static function () use ($connectHandler, $connectMethod, $connection, $fd) {
  157. $connectHandler->{$connectMethod}($connection, $fd);
  158. });
  159. }
  160. while (true) {
  161. $data = $socket->recvPacket();
  162. if (empty($data)) {
  163. if ($closeHandler && $closeMethod) {
  164. $this->waiter->wait(static function () use ($closeHandler, $closeMethod, $connection, $fd) {
  165. $closeHandler->{$closeMethod}($connection, $fd);
  166. });
  167. }
  168. $socket->close();
  169. break;
  170. }
  171. // One coroutine at a time, consistent with other servers
  172. $this->waiter->wait(static function () use ($receiveHandler, $receiveMethod, $connection, $data, $fd) {
  173. $receiveHandler->{$receiveMethod}($connection, $fd, 0, $data);
  174. });
  175. }
  176. });
  177. }
  178. }
  179. return;
  180. }
  181. throw new RuntimeException('Server type is invalid or the server callback does not exists.');
  182. }
  183. protected function getCallbackMethod(string $callback, array $callbacks): array
  184. {
  185. $handler = $method = null;
  186. if (isset($callbacks[$callback])) {
  187. [$class, $method] = $callbacks[$callback];
  188. $handler = $this->container->get($class);
  189. }
  190. return [$handler, $method];
  191. }
  192. protected function makeServer($type, $host, $port): HttpServer|Server
  193. {
  194. return match ($type) {
  195. ServerInterface::SERVER_HTTP,
  196. ServerInterface::SERVER_WEBSOCKET => new HttpServer($host, $port, false, true),
  197. ServerInterface::SERVER_BASE => new Server($host, $port, false, true),
  198. default => throw new RuntimeException('Server type is invalid.'),
  199. };
  200. }
  201. private function writePid(): void
  202. {
  203. $config = $this->container->get(ConfigInterface::class);
  204. $file = $config->get('server.settings.pid_file');
  205. if ($file) {
  206. file_put_contents($file, getmypid());
  207. }
  208. }
  209. }