TcpServer.php 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  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\JsonRpc;
  12. use Hyperf\Context\ResponseContext;
  13. use Hyperf\Contract\ConfigInterface;
  14. use Hyperf\Contract\PackerInterface;
  15. use Hyperf\Contract\StdoutLoggerInterface;
  16. use Hyperf\ExceptionHandler\ExceptionHandlerDispatcher;
  17. use Hyperf\HttpMessage\Server\Request as Psr7Request;
  18. use Hyperf\HttpMessage\Server\Response as Psr7Response;
  19. use Hyperf\HttpMessage\Uri\Uri;
  20. use Hyperf\HttpServer\Contract\CoreMiddlewareInterface;
  21. use Hyperf\JsonRpc\Exception\BadRequestException;
  22. use Hyperf\JsonRpc\Exception\Handler\TcpExceptionHandler;
  23. use Hyperf\Rpc\Protocol;
  24. use Hyperf\Rpc\ProtocolManager;
  25. use Hyperf\RpcServer\RequestDispatcher;
  26. use Hyperf\RpcServer\Server;
  27. use Hyperf\Server\Exception\InvalidArgumentException;
  28. use Hyperf\Server\ServerManager;
  29. use Psr\Container\ContainerInterface;
  30. use Swoole\Server\Port;
  31. use Swow\Psr7\Message\ResponsePlusInterface;
  32. use Swow\Psr7\Message\ServerRequestPlusInterface;
  33. use function Hyperf\Support\make;
  34. class TcpServer extends Server
  35. {
  36. protected ?ResponseBuilder $responseBuilder = null;
  37. protected ?PackerInterface $packer = null;
  38. protected ProtocolManager $protocolManager;
  39. protected array $serverConfig = [];
  40. public function __construct(
  41. ContainerInterface $container,
  42. RequestDispatcher $dispatcher,
  43. ExceptionHandlerDispatcher $exceptionDispatcher,
  44. ProtocolManager $protocolManager,
  45. StdoutLoggerInterface $logger
  46. ) {
  47. parent::__construct($container, $dispatcher, $exceptionDispatcher, $logger);
  48. $this->protocolManager = $protocolManager;
  49. }
  50. public function initCoreMiddleware(string $serverName): void
  51. {
  52. $this->initServerConfig($serverName);
  53. $this->initProtocol();
  54. parent::initCoreMiddleware($serverName);
  55. }
  56. protected function initProtocol()
  57. {
  58. $protocol = 'jsonrpc';
  59. if ($this->isLengthCheck()) {
  60. $protocol = 'jsonrpc-tcp-length-check';
  61. }
  62. $this->protocol = new Protocol($this->container, $this->protocolManager, $protocol, $this->serverConfig);
  63. $this->packer = $this->protocol->getPacker();
  64. $this->responseBuilder = make(ResponseBuilder::class, [
  65. 'dataFormatter' => $this->protocol->getDataFormatter(),
  66. 'packer' => $this->packer,
  67. ]);
  68. }
  69. protected function isLengthCheck(): bool
  70. {
  71. return boolval($this->serverConfig['settings']['open_length_check'] ?? false);
  72. }
  73. protected function initServerConfig(string $serverName): array
  74. {
  75. $servers = $this->container->get(ConfigInterface::class)->get('server.servers', []);
  76. foreach ($servers as $server) {
  77. if ($server['name'] === $serverName) {
  78. return $this->serverConfig = $server;
  79. }
  80. }
  81. throw new InvalidArgumentException(sprintf('Server name %s is invalid.', $serverName));
  82. }
  83. protected function createCoreMiddleware(): CoreMiddlewareInterface
  84. {
  85. return new CoreMiddleware($this->container, $this->protocol, $this->responseBuilder, $this->serverName);
  86. }
  87. protected function buildResponse(int $fd, $server): ResponsePlusInterface
  88. {
  89. return (new Psr7Response())->setAttribute('fd', $fd)->setAttribute('server', $server);
  90. }
  91. protected function buildRequest(int $fd, int $reactorId, string $data): ServerRequestPlusInterface
  92. {
  93. return $this->buildJsonRpcRequest($fd, $reactorId, $this->packer->unpack($data) ?? ['jsonrpc' => '2.0']);
  94. }
  95. protected function buildJsonRpcRequest(int $fd, int $reactorId, array $data)
  96. {
  97. if (! isset($data['method'])) {
  98. $data['method'] = '';
  99. }
  100. if (! isset($data['params'])) {
  101. $data['params'] = [];
  102. }
  103. /** @var Port $port */
  104. [, $port] = ServerManager::get($this->serverName);
  105. $uri = (new Uri())->setPath($data['method'])->setHost($port->host)->setPort($port->port);
  106. $request = (new Psr7Request('POST', $uri))->setAttribute('fd', $fd)
  107. ->setAttribute('fromId', $reactorId)
  108. ->setAttribute('data', $data)
  109. ->setAttribute('request_id', $data['id'] ?? null)
  110. ->setParsedBody($data['params']);
  111. $this->getContext()->setData($data['context'] ?? []);
  112. if (! isset($data['jsonrpc'])) {
  113. ResponseContext::set($this->responseBuilder->buildErrorResponse($request, ResponseBuilder::INVALID_REQUEST));
  114. throw new BadRequestException();
  115. }
  116. return $request;
  117. }
  118. protected function getDefaultExceptionHandler(): array
  119. {
  120. return [
  121. TcpExceptionHandler::class,
  122. ];
  123. }
  124. }