GrpcClient.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  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\Nacos;
  12. use Exception;
  13. use Hyperf\Codec\Json;
  14. use Hyperf\Contract\IPReaderInterface;
  15. use Hyperf\Contract\StdoutLoggerInterface;
  16. use Hyperf\Coordinator\Constants;
  17. use Hyperf\Coordinator\CoordinatorManager;
  18. use Hyperf\Engine\Http\V2\Request;
  19. use Hyperf\Grpc\Parser;
  20. use Hyperf\Http2Client\Client;
  21. use Hyperf\Nacos\Exception\ConnectToServerFailedException;
  22. use Hyperf\Nacos\Exception\RequestException;
  23. use Hyperf\Nacos\Protobuf\Any;
  24. use Hyperf\Nacos\Protobuf\ListenContext;
  25. use Hyperf\Nacos\Protobuf\ListenHandler\NamingPushRequestHandler;
  26. use Hyperf\Nacos\Protobuf\ListenHandlerInterface;
  27. use Hyperf\Nacos\Protobuf\Metadata;
  28. use Hyperf\Nacos\Protobuf\Payload;
  29. use Hyperf\Nacos\Protobuf\Request\ConfigBatchListenRequest;
  30. use Hyperf\Nacos\Protobuf\Request\ConfigQueryRequest;
  31. use Hyperf\Nacos\Protobuf\Request\ConnectionSetupRequest;
  32. use Hyperf\Nacos\Protobuf\Request\HealthCheckRequest;
  33. use Hyperf\Nacos\Protobuf\Request\RequestInterface;
  34. use Hyperf\Nacos\Protobuf\Request\ServerCheckRequest;
  35. use Hyperf\Nacos\Protobuf\Response\ConfigChangeBatchListenResponse;
  36. use Hyperf\Nacos\Protobuf\Response\ConfigChangeNotifyRequest;
  37. use Hyperf\Nacos\Protobuf\Response\ConfigQueryResponse;
  38. use Hyperf\Nacos\Protobuf\Response\NotifySubscriberRequest;
  39. use Hyperf\Nacos\Protobuf\Response\Response;
  40. use Hyperf\Nacos\Protobuf\ServiceInfo;
  41. use Hyperf\Nacos\Provider\AccessToken;
  42. use Hyperf\Support\Network;
  43. use Psr\Container\ContainerInterface;
  44. use Psr\Http\Message\ResponseInterface;
  45. use Psr\Log\LoggerInterface;
  46. use Throwable;
  47. use function Hyperf\Coroutine\go;
  48. class GrpcClient
  49. {
  50. use AccessToken;
  51. protected array $listeners = [];
  52. protected ?Client $client = null;
  53. protected ?LoggerInterface $logger = null;
  54. /**
  55. * @var array<string, ListenContext>
  56. */
  57. protected array $configListenContexts = [];
  58. /**
  59. * @var array<string, ?ListenHandlerInterface>
  60. */
  61. protected array $configListenHandlers = [];
  62. /**
  63. * @var array<string, ServiceInfo>
  64. */
  65. protected array $namingListenContexts = [];
  66. /**
  67. * @var array<string, ?ListenHandlerInterface>
  68. */
  69. protected array $namingListenHandlers = [];
  70. protected int $streamId;
  71. public function __construct(
  72. protected Application $app,
  73. protected Config $config,
  74. protected ContainerInterface $container,
  75. protected string $namespaceId = '',
  76. protected string $module = 'config',
  77. ) {
  78. if ($this->container->has(StdoutLoggerInterface::class)) {
  79. $this->logger = $this->container->get(StdoutLoggerInterface::class);
  80. }
  81. $this->reconnect();
  82. }
  83. public function request(RequestInterface $request, ?Client $client = null): Response
  84. {
  85. $payload = new Payload([
  86. 'metadata' => new Metadata($this->getMetadata($request)),
  87. 'body' => new Any([
  88. 'value' => Json::encode($request->getValue()),
  89. ]),
  90. ]);
  91. $client ??= $this->client;
  92. $response = $client->request(
  93. new Request('/Request/request', 'POST', Parser::serializeMessage($payload), $this->grpcDefaultHeaders())
  94. );
  95. return Response::jsonDeSerialize($response->getBody());
  96. }
  97. public function write(int $streamId, RequestInterface $request, ?Client $client = null): bool
  98. {
  99. $payload = new Payload([
  100. 'metadata' => new Metadata($this->getMetadata($request)),
  101. 'body' => new Any([
  102. 'value' => Json::encode($request->getValue()),
  103. ]),
  104. ]);
  105. $client ??= $this->client;
  106. return $client->write($streamId, Parser::serializeMessage($payload));
  107. }
  108. public function listenConfig(string $group, string $dataId, ListenHandlerInterface $callback, string $md5 = ''): void
  109. {
  110. $listenContext = new ListenContext($this->namespaceId, $group, $dataId, $md5);
  111. $this->configListenContexts[$listenContext->toKeyString()] = $listenContext;
  112. $this->configListenHandlers[$listenContext->toKeyString()] = $callback;
  113. }
  114. public function listenNaming(string $clusters, string $group, string $service, ListenHandlerInterface $callback): void
  115. {
  116. $serviceInfo = new ServiceInfo($service, $group, $clusters);
  117. if ($context = $this->namingListenContexts[$serviceInfo->toKeyString()] ?? null) {
  118. $callback->handle(new NotifySubscriberRequest(['requestId' => '', 'module' => 'naming', 'serviceInfo' => $context]));
  119. $this->namingListenHandlers[$serviceInfo->toKeyString()] = $callback;
  120. return;
  121. }
  122. $this->namingListenContexts[$serviceInfo->toKeyString()] = $serviceInfo;
  123. $this->namingListenHandlers[$serviceInfo->toKeyString()] = $callback;
  124. }
  125. public function listen(): void
  126. {
  127. $request = new ConfigBatchListenRequest(true, array_values($this->configListenContexts));
  128. $response = $this->request($request);
  129. if ($response instanceof ConfigChangeBatchListenResponse) {
  130. $changedConfigs = $response->changedConfigs;
  131. foreach ($changedConfigs as $changedConfig) {
  132. $this->handleConfig($changedConfig->tenant, $changedConfig->group, $changedConfig->dataId);
  133. }
  134. }
  135. }
  136. protected function reconnect(): void
  137. {
  138. $this->client && $this->client->close();
  139. $this->client = new Client(
  140. $this->config->getHost() . ':' . ($this->config->getPort() + 1000),
  141. [
  142. 'heartbeat' => null,
  143. ]
  144. );
  145. if ($this->logger) {
  146. $this->client->setLogger($this->logger);
  147. }
  148. $this->serverCheck();
  149. $this->streamId = $this->bindStreamCall();
  150. $this->healthCheck();
  151. }
  152. protected function healthCheck()
  153. {
  154. go(function () {
  155. $client = $this->client;
  156. $heartbeat = $this->config->getGrpc()['heartbeat'];
  157. while ($heartbeat > 0 && $client->inLoop()) {
  158. if (CoordinatorManager::until(Constants::WORKER_EXIT)->yield($heartbeat)) {
  159. break;
  160. }
  161. $res = $this->request(new HealthCheckRequest(), $client);
  162. if ($res->errorCode !== 0) {
  163. $this->logger?->error('Health check failed, the result is ' . (string) $res);
  164. }
  165. }
  166. });
  167. }
  168. protected function ip(): string
  169. {
  170. if ($this->container->has(IPReaderInterface::class)) {
  171. return $this->container->get(IPReaderInterface::class)->read();
  172. }
  173. return Network::ip();
  174. }
  175. protected function bindStreamCall(): int
  176. {
  177. $id = $this->client->send(new Request('/BiRequestStream/requestBiStream', 'POST', '', $this->grpcDefaultHeaders(), true));
  178. go(function () use ($id) {
  179. $client = $this->client;
  180. while (true) {
  181. try {
  182. if (! $client->inLoop()) {
  183. break;
  184. }
  185. $response = $client->recv($id, -1);
  186. $response = Response::jsonDeSerialize($response->getBody());
  187. match (true) {
  188. $response instanceof ConfigChangeNotifyRequest => $this->handleConfig(
  189. $response->tenant,
  190. $response->group,
  191. $response->dataId,
  192. $response
  193. ),
  194. $response instanceof NotifySubscriberRequest => $this->handleNaming($response),
  195. };
  196. $this->listen();
  197. } catch (Throwable $e) {
  198. ! $this->isWorkerExit() && $this->logger->error((string) $e);
  199. }
  200. }
  201. if (! $this->isWorkerExit()) {
  202. $this->reconnect();
  203. $this->listen();
  204. }
  205. });
  206. $request = new ConnectionSetupRequest($this->namespaceId, $this->module);
  207. $this->write($id, $request);
  208. return $id;
  209. }
  210. protected function handleConfig(string $tenant, string $group, string $dataId, ?ConfigChangeNotifyRequest $request = null): void
  211. {
  212. $response = $this->request(new ConfigQueryRequest($tenant, $group, $dataId));
  213. $key = ListenContext::getKeyString($tenant, $group, $dataId);
  214. if ($response instanceof ConfigQueryResponse) {
  215. if (isset($this->configListenContexts[$key])) {
  216. $this->configListenContexts[$key]->md5 = $response->getMd5();
  217. $this->configListenHandlers[$key]?->handle($response);
  218. }
  219. if ($request && $ack = $this->configListenHandlers[$key]?->ack($request)) {
  220. $this->write($this->streamId, $ack);
  221. }
  222. }
  223. }
  224. protected function handleNaming(NotifySubscriberRequest $response): void
  225. {
  226. $serviceInfo = $response->serviceInfo;
  227. $key = $serviceInfo->toKeyString();
  228. if (! isset($this->namingListenContexts[$key])) {
  229. $this->namingListenContexts[$key] = $serviceInfo;
  230. }
  231. if ($serviceInfo->lastRefTime > $this->namingListenContexts[$key]->lastRefTime) {
  232. $this->namingListenContexts[$key] = $serviceInfo;
  233. }
  234. if ($handler = $this->namingListenHandlers[$key] ?? null) {
  235. $handler->handle($response);
  236. $this->write($this->streamId, $handler->ack($response));
  237. } else {
  238. $this->write($this->streamId, (new NamingPushRequestHandler(fn () => null))->ack($response));
  239. }
  240. }
  241. /**
  242. * @deprecated since 3.1, use handleNaming instead.
  243. */
  244. protected function hanldeNaming(NotifySubscriberRequest $response)
  245. {
  246. $this->handleNaming($response);
  247. }
  248. protected function serverCheck(): bool
  249. {
  250. $request = new ServerCheckRequest();
  251. while (true) {
  252. try {
  253. $response = $this->request($request);
  254. if ($response->errorCode !== 0) {
  255. $this->logger?->error('Nacos check server failed.');
  256. if (CoordinatorManager::until(Constants::WORKER_EXIT)->yield(5)) {
  257. break;
  258. }
  259. continue;
  260. }
  261. return true;
  262. } catch (Exception $exception) {
  263. $this->logger?->error((string) $exception);
  264. if (CoordinatorManager::until(Constants::WORKER_EXIT)->yield(5)) {
  265. break;
  266. }
  267. }
  268. }
  269. throw new ConnectToServerFailedException('the nacos server is not ready to work in 30 seconds, connect to server failed');
  270. }
  271. private function isWorkerExit(): bool
  272. {
  273. return CoordinatorManager::until(Constants::WORKER_EXIT)->isClosing();
  274. }
  275. private function getMetadata(RequestInterface $request): array
  276. {
  277. if ($token = $this->getAccessToken()) {
  278. return [
  279. 'type' => $request->getType(),
  280. 'clientIp' => $this->ip(),
  281. 'headers' => [
  282. 'accessToken' => $token,
  283. ],
  284. ];
  285. }
  286. return [
  287. 'type' => $request->getType(),
  288. 'clientIp' => $this->ip(),
  289. ];
  290. }
  291. private function grpcDefaultHeaders(): array
  292. {
  293. return [
  294. 'content-type' => 'application/grpc+proto',
  295. 'te' => 'trailers',
  296. 'user-agent' => 'Nacos-Hyperf-Client:v3.1',
  297. ];
  298. }
  299. private function handleResponse(ResponseInterface $response): array
  300. {
  301. $statusCode = $response->getStatusCode();
  302. $contents = (string) $response->getBody();
  303. if ($statusCode !== 200) {
  304. throw new RequestException($contents, $statusCode);
  305. }
  306. return Json::decode($contents);
  307. }
  308. }