modify plugin name

This commit is contained in:
2022-06-16 17:38:23 +08:00
parent 8f9de7a508
commit 6371d5271e
4 changed files with 334 additions and 311 deletions
+1 -1
View File
@@ -4,7 +4,7 @@ namespace PHPSTORM_META {
// Reflect // Reflect
use Kiri\Di\Container; use Kiri\Di\Container;
use Psr\Container\ContainerInterface; use Kiri\Di\ContainerInterface;
override(ContainerInterface::get(0), map('@')); override(ContainerInterface::get(0), map('@'));
override(Container::get(0), map('@')); override(Container::get(0), map('@'));
+103
View File
@@ -0,0 +1,103 @@
<?php
namespace Kiri\Rpc;
use Exception;
use Kiri;
use Kiri\Abstracts\Component;
use Kiri\Consul\Agent;
use Psr\Container\ContainerExceptionInterface;
use Kiri\Di\ContainerInterface;
use Psr\Container\NotFoundExceptionInterface;
use Swoole\Coroutine;
class Consul extends Component
{
public Agent $agent;
private array $config = [];
/**
* @param ContainerInterface $container
* @param array $settings
* @param array $config
* @throws Exception
*/
public function __construct(public ContainerInterface $container, array $settings, array $config = [])
{
parent::__construct($config);
$this->config = $settings;
}
/**
* @return void
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function init(): void
{
$this->agent = $this->container->get(Agent::class);
}
/**
* @return void
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function deregister()
{
if (env('environmental') != Kiri::WORKER && env('environmental_workerId') != 0) {
return;
}
$agent = $this->container->get(Agent::class);
$this->logger->debug("disconnect consul.");
$agent->service->deregister($this->config['ID']);
$agent->checks->deregister($this->config['Check']['CheckId']);
}
/**
* @return void
*/
public function service_health(): void
{
$info = $this->agent->service->service_health($this->config['ID']);
if ($info->getStatusCode() == 200) {
return;
}
$this->agent->service->register($this->config);
}
public function watches()
{
}
/**
* @return void
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function register(): void
{
$this->deregister();
$data = $this->agent->service->register($this->config);
if ($data->getStatusCode() != 200) {
$this->logger->error($data->getBody());
}
}
}
+209 -243
View File
@@ -26,7 +26,7 @@ use Kiri\Server\Events\OnTaskerStart;
use Kiri\Server\Events\OnWorkerExit; use Kiri\Server\Events\OnWorkerExit;
use Kiri\Server\Events\OnWorkerStart; use Kiri\Server\Events\OnWorkerStart;
use Psr\Container\ContainerExceptionInterface; use Psr\Container\ContainerExceptionInterface;
use Psr\Container\ContainerInterface; use Kiri\Di\ContainerInterface;
use Psr\Container\NotFoundExceptionInterface; use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Message\ServerRequestInterface;
use ReflectionException; use ReflectionException;
@@ -42,289 +42,255 @@ class RpcJsonp extends Component implements OnConnectInterface, OnReceiveInterfa
{ {
private int $timerId = -1; private array $consul = [];
/** /**
* @param ContainerInterface $container * @param ContainerInterface $container
* @param Router $router * @param Router $router
* @param Annotation $annotation * @param Annotation $annotation
* @param DataGrip $dataGrip * @param DataGrip $dataGrip
* @param RpcManager $manager * @param RpcManager $manager
* @param RouterCollector $collector * @param RouterCollector $collector
* @param EventProvider $eventProvider * @param EventProvider $eventProvider
* @param array $config * @param array $config
* @throws Exception * @throws Exception
*/ */
public function __construct(public ContainerInterface $container, public function __construct(public ContainerInterface $container,
public Router $router, public Router $router,
public Annotation $annotation, public Annotation $annotation,
public DataGrip $dataGrip, public DataGrip $dataGrip,
public RpcManager $manager, public RpcManager $manager,
public RouterCollector $collector, public RouterCollector $collector,
public EventProvider $eventProvider, public EventProvider $eventProvider,
array $config = []) array $config = [])
{ {
parent::__construct($config); parent::__construct($config);
} }
/** /**
* @return void * @return void
* @throws ReflectionException * @throws ReflectionException|ConfigException
*/ */
public function init(): void public function init(): void
{ {
$this->eventProvider->on(OnBeforeShutdown::class, [$this, 'onBeforeShutdown']); $this->eventProvider->on(OnBeforeShutdown::class, [$this, 'onBeforeShutdown']);
scan_directory(APP_PATH . 'rpc', 'app\Rpc');
scan_directory(APP_PATH . 'rpc', 'app\Rpc'); $this->consul = Config::get('rpc.consul', null);
if (!empty($this->consul)) {
$this->eventProvider->on(OnWorkerStart::class, [$this, 'consulWatches']); $this->eventProvider->on(OnServerBeforeStart::class, [$this, 'register']);
$this->eventProvider->on(OnWorkerExit::class, [$this, 'onWorkerExit']); }
$this->eventProvider->on(OnServerBeforeStart::class, [$this, 'register']); $this->collector = $this->dataGrip->get('rpc');
}
$this->collector = $this->dataGrip->get('rpc');
}
/** /**
* @param OnBeforeShutdown $beforeShutdown * @param OnBeforeShutdown $beforeShutdown
* @return void * @return void
* @throws ContainerExceptionInterface * @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface|ConfigException * @throws NotFoundExceptionInterface
*/ */
public function onBeforeShutdown(OnBeforeShutdown $beforeShutdown): void public function onBeforeShutdown(OnBeforeShutdown $beforeShutdown): void
{ {
if (env('environmental_workerId') != 0) { if (env('environmental') != Kiri::WORKER && env('environmental_workerId') != 0) {
return; return;
} }
$agent = $this->container->get(Agent::class); $agent = $this->container->get(Agent::class);
$value = Config::get("rpc.consul", []);
if (empty($value)) {
return;
}
$this->logger->debug("disconnect consul."); $this->logger->debug("disconnect consul.");
$agent->service->deregister($value['ID']); $agent->service->deregister($this->consul['ID']);
$agent->checks->deregister($value['Check']['CheckId']); $agent->checks->deregister($this->consul['Check']['CheckId']);
} }
/**
* @param OnWorkerStart|OnTaskerStart $server
* @throws ConfigException
*/
public function consulWatches(OnWorkerStart|OnTaskerStart $server)
{
if ($server->workerId != 0) {
return;
}
$async_time = (int)Config::get('consul.async_time', 1000);
$this->timerId = Timer::tick($async_time, static function () {
Kiri::getDi()->get(RpcManager::class)->tick();
});
}
/**
* @param OnWorkerExit $exit
* @return void
*/
public function onWorkerExit(OnWorkerExit $exit): void
{
if ($this->timerId) {
Timer::clear($this->timerId);
}
}
/** /**
* @param OnServerBeforeStart $server * @param OnServerBeforeStart $server
* @throws ConfigException * @throws ConfigException
*/ */
public function register(OnServerBeforeStart $server) public function register(OnServerBeforeStart $server)
{ {
$consumers = Config::get("rpc.consumers", []); $consumers = Config::get("rpc.consumers", []);
if (!empty($consumers)) { if (!empty($consumers)) {
$manager = Kiri::getDi()->get(RpcManager::class);
foreach ($consumers as $service => $consumer) { foreach ($consumers as $service => $consumer) {
$manager->add($service, $consumer); $this->manager->add($service, $consumer);
} }
} }
$this->manager->register(); $this->manager->register($this->consul);
} }
/** /**
* @param Server $server * @param Server $server
* @param int $fd * @param int $fd
*/ */
public function onConnect(Server $server, int $fd): void public function onConnect(Server $server, int $fd): void
{ {
// TODO: Implement onConnect() method. // TODO: Implement onConnect() method.
} }
/** /**
* @param Server $server * @param Server $server
* @param int $fd * @param int $fd
* @param int $reactor_id * @param int $reactor_id
* @param string $data * @param string $data
*/ */
public function onReceive(Server $server, int $fd, int $reactor_id, string $data): void public function onReceive(Server $server, int $fd, int $reactor_id, string $data): void
{ {
$data = json_decode($data, true); try {
if (is_null($data)) { $data = json_decode($data, true);
$this->failure(-32700, 'Parse error语法解析错误'); if (!is_array($data)) {
} else if (!isset($data['jsonrpc']) || !isset($data['method']) || $data['jsonrpc'] != '2.0') { throw new Exception('Parse error语法解析错误', -32700);
$this->failure(-32600, 'Invalid Request无效请求'); }
} else { if (!isset($data['jsonrpc']) || !isset($data['method']) || $data['jsonrpc'] != '2.0') {
$this->batchDispatch($server, $fd, $data); throw new Exception('Invalid Request无效请求', -32600);
} }
} $server->send($fd, $this->batchDispatch($data));
} catch (\Throwable $throwable) {
$this->logger->error('JsonRpc: ' . $throwable->getMessage());
$server->send($fd, $this->failure(-32700, 'Parse error语法解析错误'));
}
}
/** /**
* @param Server $server * @param array $data
* @param int $fd * @return string|bool
* @param array $data */
* @return void private function batchDispatch(array $data): string|bool
*/ {
private function batchDispatch(Server $server, int $fd, array $data): void if (isset($data['jsonrpc'])) {
{ $result = $this->dispatch($data);
if (isset($data['jsonrpc'])) { if (!isset($data['id'])) {
$dispatch = $this->dispatch($data); $result = [1];
if (!isset($data['id'])) { }
$dispatch = [1]; } else {
} $channel = new Channel($total = count($data));
$result = json_encode($dispatch, JSON_UNESCAPED_UNICODE); foreach ($data as $datum) {
} else { $this->_execute($channel, $datum);
$channel = new Channel($total = count($data)); }
foreach ($data as $datum) { $result = [];
$this->_execute($channel, $datum); for ($i = 0; $i < $total; $i++) {
} $result[] = $channel->pop();
$result = []; }
for ($i = 0; $i < $total; $i++) { }
$result[] = $channel->pop(); return json_encode($result, JSON_UNESCAPED_UNICODE);
} }
$result = json_encode($result, JSON_UNESCAPED_UNICODE);
}
$server->send($fd, $result);
}
/** /**
* @param $channel * @param $channel
* @param $datum * @param $datum
*/ */
private function _execute($channel, $datum) private function _execute($channel, $datum)
{ {
Coroutine::create(function () use ($channel, $datum) { Coroutine::create(function () use ($channel, $datum) {
if (empty($datum) || !isset($datum['jsonrpc'])) { if (empty($datum) || !isset($datum['jsonrpc'])) {
$channel->push($this->failure(-32700, 'Parse error语法解析错误')); $channel->push($this->failure(-32700, 'Parse error语法解析错误'));
} else if (!isset($datum['method'])) { } else if (!isset($datum['method'])) {
$channel->push($this->failure(-32700, 'Parse error语法解析错误')); $channel->push($this->failure(-32700, 'Parse error语法解析错误'));
} else { } else {
$dispatch = $this->dispatch($datum); $dispatch = $this->dispatch($datum);
if (!isset($dispatch['id'])) { if (!isset($dispatch['id'])) {
$dispatch = [1]; $dispatch = [1];
} }
$channel->push($dispatch); $channel->push($dispatch);
} }
}); });
} }
/** /**
* @param $data * @param $data
* @return array * @return array
*/ */
private function dispatch($data): array private function dispatch($data): array
{ {
try { try {
$handler = $this->collector->find($data['service'], 'GET'); $handler = $this->collector->find($data['service'], 'GET');
if (is_integer($handler) || is_null($handler)) { if (is_integer($handler) || is_null($handler)) {
throw new Exception('Handler not found', -32601); throw new Exception('Handler not found', -32601);
} }
$controller = $this->container->get($handler->callback[0]); $controller = $this->container->get($handler->callback[0]);
if (!method_exists($controller, $data['method'])) { if (!method_exists($controller, $data['method'])) {
throw new Exception('Method not found', -32601); throw new Exception('Method not found', -32601);
} }
$params = $this->container->getMethodParameters($controller::class, $data['method']); $params = $this->container->getArgs($controller::class, $data['method']);
Context::setContext(RequestInterface::class, $this->createServerRequest($params)); Context::setContext(RequestInterface::class, $this->createServerRequest($params));
return $this->handler($controller, $data['method'], $params); return $this->handler($controller, $data['method'], $params);
} catch (\Throwable $throwable) { } catch (\Throwable $throwable) {
$code = $throwable->getCode() == 0 ? -32603 : $throwable->getCode(); $code = $throwable->getCode() == 0 ? -32603 : $throwable->getCode();
return $this->failure($code, jTraceEx($throwable), [], $data['id'] ?? null); return $this->failure($code, jTraceEx($throwable), [], $data['id'] ?? null);
} }
} }
/** /**
* @param $params * @param $params
* @return ServerRequestInterface * @return ServerRequestInterface
* @throws Exception * @throws Exception
*/ */
private function createServerRequest($params): ServerRequestInterface private function createServerRequest($params): ServerRequestInterface
{ {
return (new ServerRequest())->withParsedBody($params); return (new ServerRequest())->withParsedBody($params);
} }
/** /**
* @param $controller * @param $controller
* @param string $method * @param string $method
* @param $params * @param $params
* @return array * @return array
*/ */
#[ArrayShape([])] #[ArrayShape([])]
private function handler($controller, string $method, $params): array private function handler($controller, string $method, $params): array
{ {
$result = call_user_func([$controller, $method], ...$params); $result = call_user_func([$controller, $method], ...$params);
return [ return [
'jsonrpc' => '2.0', 'jsonrpc' => '2.0',
'result' => $result, 'result' => $result,
'id' => $data['id'] ?? null 'id' => $data['id'] ?? null
]; ];
} }
/** /**
* @param $code * @param $code
* @param $message * @param $message
* @param array $data * @param array $data
* @param null $id * @param null $id
* @return array * @return array
*/ */
#[ArrayShape([])] #[ArrayShape([])]
protected function failure($code, $message, array $data = [], $id = null): array protected function failure($code, $message, array $data = [], $id = null): array
{ {
$error = [ $error = [
'jsonrpc' => '2.0', 'jsonrpc' => '2.0',
'error' => [ 'error' => [
'code' => $code, 'code' => $code,
'message' => $message, 'message' => $message,
'data' => $data 'data' => $data
] ]
]; ];
if (!is_null($id)) { if (!is_null($id)) {
$error['id'] = $id; $error['id'] = $id;
} }
return $error; return $error;
} }
/** /**
* @param \Swoole\WebSocket\Server $server * @param \Swoole\WebSocket\Server $server
* @param int $fd * @param int $fd
* @return void * @return void
*/ */
public function onClose(\Swoole\WebSocket\Server $server, int $fd): void public function onClose(\Swoole\WebSocket\Server $server, int $fd): void
{ {
// TODO: Implement onClose() method. // TODO: Implement onClose() method.
} }
} }
+10 -56
View File
@@ -11,51 +11,20 @@ use Kiri\Consul\Agent;
use Kiri\Consul\Health; use Kiri\Consul\Health;
use Kiri\Message\Handler\Router; use Kiri\Message\Handler\Router;
/**
* class RpcManager
*/
class RpcManager extends Component class RpcManager extends Component
{ {
/** /**
* @var array * @var Health
*/ */
private array $_rpc = [];
#[Inject(Health::class)] #[Inject(Health::class)]
public Health $health; public Health $health;
/**
* @return void
* @throws Kiri\Exception\ConfigException
*/
public function reRegister(): void
{
$service = Kiri::getDi()->get(Agent::class);
$config = Config::get("rpc.consul", null, true);
$info = $service->service->service_health($config['ID']);
if ($info->getStatusCode() == 200) {
return;
}
$service->service->register($config);
}
/**
* @throws Exception
*/
public function tick(): void
{
try {
$this->reRegister();
} catch (\Throwable $throwable) {
$this->logger->error(error_trigger_format($throwable));
}
}
/** /**
* @param $serviceName * @param $serviceName
* @return array|null * @return array|null
@@ -89,30 +58,15 @@ class RpcManager extends Component
/** /**
* @return array * @param array $config
*/
public function doneList(): array
{
$array = [];
foreach ($this->_rpc as $list) {
$array[] = $list;
}
return $array;
}
/**
* @return void * @return void
* @throws Kiri\Exception\ConfigException
*/ */
public function register(): void public function register(array $config): void
{ {
$agent = Kiri::getDi()->get(Agent::class); $agent = Kiri::getDi()->get(Agent::class);
$agent->checks->deregister($config['ID']);
$list = Config::get("rpc.consul", null, true); $agent->service->deregister($config['ID']);
$data = $agent->service->register($config);
$agent->service->deregister($list['ID']);
$data = $agent->service->register($list);
if ($data->getStatusCode() != 200) { if ($data->getStatusCode() != 200) {
$this->logger->error($data->getBody()); $this->logger->error($data->getBody());
} }