Compare commits

..

No commits in common. "main" and "v1.1.5" have entirely different histories.
main ... v1.1.5

15 changed files with 331 additions and 1025 deletions

View File

@ -12,8 +12,6 @@
执行
```bash
composer config repositories.php-rpc-doc vcs git@git.int.haowumc.com:composer/php-rpc-doc.git
composer require itxq/api-doc-php
composer config repositories.php-json-rpc vcs git@git.int.haowumc.com:composer/php-json-rpc.git
composer require paidian/json-rpc:dev-master
```

View File

@ -7,8 +7,8 @@
"illuminate/support": "^5.5",
"illuminate/http": "^5.5",
"monolog/monolog": "^1.24",
"influxdb/influxdb-php": "^1.14",
"itxq/api-doc-php": "^1.1"
"itxq/api-doc-php": "^1.1",
"influxdb/influxdb-php": "^1.14"
},
"autoload": {
"psr-4": {
@ -16,5 +16,9 @@
}
},
"require-dev": {
},
"api-doc-php": {
"type": "vcs",
"url": "git@git.int.haowumc.com:composer/php-rpc-doc.git"
}
}

978
composer.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -45,9 +45,5 @@ return [
'local' => true,
'base_uri' => env('RPC_PAYMENT_URI','http://payapi.dev.haowumc.com'),
],
'wx-server' => [
'local' => true,
'base_uri' => env('RPC_WX_SERVER_URI', 'http://sapi.in.haowumc.com'),
],
],
];

View File

@ -7,7 +7,6 @@ use JsonRpc\Exception\RpcServerException;
use JsonRpc\Server\JsonRpcBase;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
use Psr\Log\LoggerInterface;
class Client extends JsonRpc
{
@ -28,11 +27,6 @@ class Client extends JsonRpc
*/
protected $http;
/**
* @var LoggerInterface
*/
protected $logger;
/**
* which server rpc call choose
* @var array
@ -45,11 +39,6 @@ class Client extends JsonRpc
$this->id = 1;
}
public function setLogger($logger)
{
$this->logger = $logger;
}
/**
*
* @param $k
@ -60,7 +49,7 @@ class Client extends JsonRpc
$this->server_config = $this->config['client'][$k];
$default = [
'timeout' => 60,
'timeout' => 3,
'allow_redirects' => false,
];
@ -71,11 +60,10 @@ class Client extends JsonRpc
/**
* @param $name
* @param $arguments
* @param $options []
* @throws RpcServerException
* @return array
*/
public function call($name, $arguments, $options = [])
public function call($name, $arguments)
{
$payload = [
'jsonrpc' => '2.0',
@ -83,7 +71,7 @@ class Client extends JsonRpc
'params' => $arguments,
'id' => $this->id(),
];
return $this->post($payload, $options);
return $this->post($payload);
}
/**
@ -102,25 +90,21 @@ class Client extends JsonRpc
* @throws RpcServerException
* @return array
*/
protected function post($payload, $options = [])
protected function post($payload)
{
$uri = 'rpc/json-rpc-v2.json?app=' . $this->config['app'];
$requestId = isset($_SERVER['HTTP_X_REQUEST_ID']) ? $_SERVER['HTTP_X_REQUEST_ID'] : 'nginx-config-err';
try {
$headers = [
'X-Client-App' => $this->config['app'],
'X-Request-Id' => $requestId,
];
$this->logger && $this->logger->info("client_request", array_merge($this->server_config, $payload));
$resp = $this->http->request('POST', $uri, array_merge([
app('rpc.logger')->info("client_request", array_merge($this->server_config, $payload));
$resp = $this->http->request('POST', 'rpc/json-rpc-v2.json', [
'headers' => $headers,
'json' => $payload,
], $options));
]);
} catch (ServerException $e) {
$ex = new RpcServerException(self::ErrorMsg[JsonRpc::Rpc_Error_Internal_Error], JsonRpc::Rpc_Error_Internal_Error);
if (function_exists('env') && env("APP_DEBUG") == true) {
if (env("APP_DEBUG") == true) {
$resp = $e->getResponse();
$ex->setResponse($e->getResponse());
}
throw $ex;
@ -128,7 +112,7 @@ class Client extends JsonRpc
try {
$body = \GuzzleHttp\json_decode($resp->getBody(), true);
$this->logger && $this->logger->info("client_response", $body);
app('rpc.logger')->info("client_response", $body);
if (empty($body)) {
throw new RpcServerException('http response empty', JsonRpc::Rpc_Error_System_Error);
}
@ -141,9 +125,9 @@ class Client extends JsonRpc
return $body['result'];
} catch (\InvalidArgumentException $e) {
$this->logger && $this->logger->error('client_decode_error', array_merge($this->server_config, $payload));
app('rpc.logger')->error('client_decode_error', array_merge($this->server_config, $payload));
$ex = new RpcServerException($e->getMessage(), JsonRpc::Rpc_Error_Parse_Error);
if (function_exists('env') && env("APP_DEBUG") == true) {
if (env("APP_DEBUG") == true) {
$ex->setResponse($resp);
}
throw $ex;

View File

@ -40,7 +40,7 @@ class Security
*/
private function isClientIPPermitted($ip)
{
if (app()->environment('develop', 'local')) {
if (!app()->environment('production', 'staging')) {
return true;
}

View File

@ -6,7 +6,6 @@ use Closure;
use GuzzleHttp\Client;
use Illuminate\Http\JsonResponse;
use InfluxDB\Database;
use InfluxDB\Exception;
use InfluxDB\Point;
/**
@ -40,24 +39,20 @@ class TunnelMiddleware
{
//过滤tool返回结果
if ($response instanceof JsonResponse) {
if (app()->environment('develop', 'production') && env('RPC_MONITOR_SWITCH') == 1) {
if (app()->environment('dev')) {
$content = $response->getOriginalContent();
$status = isset($content['error']) ? $content['error']['code'] : 200;
$client = new \InfluxDB\Client("influxdb-svc", 8086, '', '', false, false, 1, 1);
$client = new \InfluxDB\Client("10.0.1.67");
$database = $client->selectDB('rpc_monitor');
$points = array(
new Point(
'monitor',
1,
['app' => env('APP_NAME'), 'status' => $status, 'env' => app()->environment()],
['status_value' => $status == 200 ? $status : -$status]
['content' => $request->getContent()]
)
);
try {
$database->writePoints($points, Database::PRECISION_SECONDS);
} catch (Exception $exception) {
app('log')->error('influxdb-write-wrong', ['code' => $exception->getCode(),'message' => $exception->getMessage()]);
}
app('rpc.logger')->info('record to influxdb', ['rs' => $database->writePoints($points, Database::PRECISION_SECONDS)]);
}
}

View File

@ -11,10 +11,7 @@ use Monolog\Logger;
class BaseServiceProvider extends ServiceProvider
{
protected $logger;
public function boot()
{
public function boot(){
Request::setTrustedProxies([
//pod network
'172.20.0.0/16',
@ -32,26 +29,26 @@ class BaseServiceProvider extends ServiceProvider
protected function setupConfig()
{
$source = realpath(__DIR__ . '/../../config/rpc.php');
$this->app->configure('rpc');
// if ($this->app instanceof LaravelApplication && $this->app->runningInConsole()) {
// $this->publishes([$source => config_path('rpc.php')], 'rpc');
// } elseif ($this->app instanceof LumenApplication) {
// $this->app->configure('rpc');
// }
// var_dump($this->app instanceof LumenApplication); // false
// exit();
$this->mergeConfigFrom($source, 'rpc');
if ($this->app instanceof LaravelApplication && $this->app->runningInConsole()) {
$this->publishes([$source => config_path('rpc.php')], 'rpc');
} elseif ($this->app instanceof LumenApplication) {
$this->app->configure('rpc');
}
$this->mergeConfigFrom($source, 'rpc');
}
public function register()
{
$this->setupConfig();
$this->logger = new Logger('RPC.LOGGER');
$this->app->singleton("rpc.logger", function () {
$config = config('rpc');
$stream = new StreamHandler($config['log_path']);
$stream->setFormatter(new $config['log_formatter']());
$this->logger->pushHandler($stream);
$logger = new Logger('RPC.LOGGER');
return $logger->pushHandler($stream);
});
}
}

View File

@ -16,19 +16,18 @@ class ClientServiceProvider extends BaseServiceProvider
public function register()
{
parent::register();
$this->app->configure('rpc');
$config = config('rpc');
if (!is_array($config)) {
throw new RpcServerException("Application's Rpc Client Config Undefind", 500);
}
$this->app->singleton('rpc', function () use ($config) {
$client = new Client($config);
$client->setLogger($this->logger);
return $client;
return new Client($config);
});
foreach ($config['client'] as $k => $item) {
$this->app->singleton('rpc.' . $k, function () use ($k, $config) {
return (new Client($config))->endpoint($k);
$this->app->singleton('rpc.' . $k, function () use ($k) {
return app('rpc')->endpoint($k);
});
}
}

View File

@ -40,7 +40,6 @@ class LumenServerServiceProvider extends BaseServiceProvider
}
$callback = function () use ($config) {
$server = new JsonRpcServer($config);
$server->setLogger($this->logger);
return $server->handler();
};

View File

@ -6,7 +6,6 @@ namespace JsonRpc\Server;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use JsonRpc\JsonRpc;
use Psr\Log\LoggerInterface;
class JsonRpcServer extends JsonRpc
{
@ -14,19 +13,13 @@ class JsonRpcServer extends JsonRpc
* @var Request
*/
public $request;
/**
* @var LoggerInterface
*/
protected $logger;
/**
* @var array 配置
* @var config 配置
*/
protected $config;
/**
* @var array rpc.server.map rpc方法
* @var rpc.server.map rpc方法
*/
protected $map;
@ -37,15 +30,11 @@ class JsonRpcServer extends JsonRpc
$this->map = $config['map'];
}
public function setLogger($logger){
$this->logger = $logger;
}
public function handler()
{
if ($this->request->getContentType() != 'json') {
return $this->error(self::Rpc_Error_Invalid_Request);
}
// if ($this->request->getContentType() != 'json') {
// return $this->error(self::Rpc_Error_Invalid_Request);
// }
try {
@ -67,9 +56,9 @@ class JsonRpcServer extends JsonRpc
return $this->error(self::Rpc_Error_Invalid_Params);
}
$this->request->attributes->add(['tunnel_method' => $method, 'tunnel_params' => $params]);
$this->logger && $this->logger->info('server', [$id, $class, $method, $params]);
app('rpc.logger')->info('server', [$id, $class,$method, $params]);
$ret = call_user_func_array([(new $class($id, $this->request)), $function], $params);
$this->logger && $this->logger->info('server_result', [$id, $ret]);
app('rpc.logger')->info('server_result', [$id, $ret]);
return JsonResponse::create($ret);
@ -78,11 +67,6 @@ class JsonRpcServer extends JsonRpc
}
}
/**
* 处理json rpc post body
* @param $data
* @return array
*/
protected function parseJson($data)
{
$data = \GuzzleHttp\json_decode($data, true);
@ -92,23 +76,36 @@ class JsonRpcServer extends JsonRpc
return [$method, $params, $id];
}
/**
* 根据method解析出对应的class
* @param $method
* @return array|mixed
*/
protected function parseMethodWithMap($method)
{
return isset($this->map[$method]) ? $this->map[$method] : ['', ''];
}
/**
* 检查调用方式是否足够
* @param $class
* @param $method
* @param $parameters
* @return bool
* thisis
* @param string $method 参数名称
* @return array 返回结果
*/
// protected function parseMethod($method)
// {
// $method = explode('.', $method);
//
// if (count($method) < 2) {
// return ['', ''];
// }
//
// $function = array_pop($method);
// $class = 'Rpc' . ucwords(array_pop($method));
//
// foreach ($method as $one) {
// $class = ucwords($one) . '\\' . $class;
// }
//
// $class = "App\Rpc\\$class";
// return [$class, $function];
// }
protected function isEnoughParameter($class, $method, $parameters)
{
$r = new \ReflectionMethod($class, $method);

View File

@ -4,7 +4,6 @@ namespace JsonRpc\Server;
use Illuminate\Http\Request;
use Illuminate\View\Factory;
use itxq\apidoc\BootstrapApiDoc;
use JsonRpc\Exception\RpcServerException;
use Monolog\Logger;
@ -51,24 +50,10 @@ class JsonRpcTool
);
}
}
$methods = [];
foreach ($this->config['map'] as $key => $item) {
if (!in_array($item[0], $methods)) {
$methods[] = $item[0];
}
}
$config = [
'class' => $methods,
'filter_method' => [],
];
$api = new BootstrapApiDoc($config);
$data = $api->getApiDocTmp();
$methods = $this->getMethods();
$view->share('data',json_encode($data));
$view->share('method', $method);
$view->share('endpoint', $this->getEndpoint());
$view->share('methods', $methods);
$view->share('method', $method);
$view->share('params', json_encode($params, JSON_PRETTY_PRINT));
foreach ($methods as $name => $class) {

View File

@ -21,7 +21,7 @@
<nav class="col-md-3 d-none d-md-block bg-light sidebar">
<div class="sidebar-sticky">
<ul id="nav-content" class="nav flex-column">
<ul class="nav flex-column">
<li class="nav-item">
<a class="nav-link active" href="/rpc/doc.html">
<span data-feather="home"></span>
@ -55,6 +55,7 @@
{{--</div>--}}
</div>
<div class="form-row">
<div class="form-group col-md-12">
<label for="inputAddress">Method</label>
<select class="form-control" id="method" name="method">
@ -63,52 +64,16 @@
@endforeach
</select>
</div>
<div class="table-item col-md-12">
<p class="table-title">
<span class="btn btn-xs btn-info">请求参数</span>
</p>
<table id="paramRequird" class="table">
<tr>
<td>参数</td>
<td>类型</td>
<td>描述</td>
<td>默认值</td>
<td>是否必须</td>
</tr>
</table>
</div>
<div class="table-item col-md-12">
<p class="table-title">
<span class="btn btn-xs btn-info">返回参数</span>
</p>
<table id="returnRequird" class="table">
<tr>
<td>参数</td>
<td>类型</td>
<td>描述</td>
<td>默认值</td>
<td>是否必须</td>
</tr>
</table>
</div>
<div class="table-item col-md-12">
<p class="table-title">
<span class="btn btn-xs btn-info">状态码说明</span>
</p>
<table id="codeRequird" class="table">
</table>
</div>
</div>
<div>
</div>
<div class="form-row">
<div class="form-group col-md-12">
<label for="inputAddress">Paramsjson 数组)</label>
<div id="editor" style="height: 300px">{{$params}}</div>
<input type="hidden" name="params" id="params" value="{{$params}}">
</div>
</div>
<button id="submit-btn" type="submit" class="btn btn-primary">Request</button>
<button type="submit" class="btn btn-primary">Request</button>
</form>
<div class="row col-md-12">
@if( !empty($error) )
@ -142,106 +107,13 @@
<script src="https://cdn.bootcss.com/highlight.js/9.13.1/highlight.min.js"></script>
<script src="https://cdn.bootcss.com/highlight.js/9.13.1/languages/json.min.js"></script>
<script src="https://cdn.bootcss.com/ace/1.4.2/ace.js"></script>
<script type="text/javascript">
<script>
var editor = ace.edit("editor");
var params = <?php echo $params; ?>;
var data = <?php echo $data; ?>;
var error_empty = <?php echo isset($error) ? 0 : 1; ?>;
console.log(params)
editor.setTheme("ace/theme/monokai");
editor.session.setMode("ace/mode/json");
editor.on('change', function (e) {
$('#params').val(editor.getValue())
})
$(document).ready(function(){
intTable();
var valKey =$("#method option:first-child").text();
var data = <?php echo $data; ?>;
var methodArray = data[valKey];
changeTable(methodArray);
if (error_empty > 0) {
var storage = window.localStorage;
var valKey = $("#method").find("option:selected").text();
var d = JSON.stringify(params);
storage.setItem(valKey, d);
}
changeNavShow()
});
$('#method').on('change', function() {
var valKey = $("#method").find("option:selected").text();
var methodArray = data[valKey];
intTable()
changeTable(methodArray)
})
function intTable() {
$("#paramRequird").empty();
$("#returnRequird").empty();
$("#codeRequird").empty();
var html1 = "<tr><td>参数</td><td>类型</td><td>描述</td><td>默认值</td><td>是否必须</td></tr>";
var html2 = "<tr><td>参数</td><td>类型</td><td>描述</td>/tr>";
var html3 = "<tr><td>状态码</td><td>描述</td></tr>";
$(html1).appendTo("#paramRequird");
$(html2).appendTo("#returnRequird");
$(html3).appendTo("#codeRequird");
}
function changeTable(params) {
params.param.map(function (val, index) {
var $trTemp = $("<tr></tr>");
//往行里面追加 td单元格
$trTemp.append("<td>"+ val.param_name +"</td>");
$trTemp.append("<td>"+ val.param_type +"</td>");
$trTemp.append("<td>"+ val.param_title +"</td>");
$trTemp.append("<td>"+ val.param_default +"</td>");
$trTemp.append("<td>"+ val.param_require +"</td>");
$trTemp.appendTo("#paramRequird");
})
params.return.map(function (val, index) {
var $trTemp = $("<tr></tr>");
//往行里面追加 td单元格
$trTemp.append("<td>"+ val.return_name +"</td>");
$trTemp.append("<td>"+ val.return_type +"</td>");
$trTemp.append("<td>"+ val.return_title +"</td>");
$trTemp.appendTo("#returnRequird");
})
params.code.map(function (val, index) {
var $trTemp = $("<tr></tr>");
//往行里面追加 td单元格
$trTemp.append("<td>"+ val.code +"</td>");
$trTemp.append("<td>"+ val.content +"</td>");
$trTemp.appendTo("#codeRequird");
})
}
function changeLocoal(params) {
var storage=window.localStorage;
var valKey = $("#method").find("option:selected").text();
var data=editor.getValue();
var d=JSON.stringify(data).replaceAll("\r|\n|\\s", "");
storage.setItem(valKey,d);
}
function changeNavShow(){
var storage=window.localStorage;
for(var i=0;i<storage.length;i++){
var key=storage.key(i);
var $trTemp = $('<li class="nav-item"></li>');
$trTemp.append('<a class="nav-link">'+ key +'</a>');
$trTemp.appendTo("#nav-content");
$trTemp.attr('methond',key)
}
}
$('#nav-content').on('click','.nav-item', function(){
var activeKey = $(this).attr('methond');
var param = localStorage.getItem(activeKey)
$('.nav-item').removeClass('bg-info');
$(this).addClass('bg-info');
$("#method").val(activeKey);
var methodArray = data[activeKey];
intTable();
changeTable(methodArray);
$('#params').val(param);
editor.setValue(param)
})
</script>
<script>hljs.initHighlightingOnLoad();</script>
</body>

View File

@ -1,25 +0,0 @@
<?php
include_once dirname(__DIR__) . '/vendor/autoload.php';
$client = new \JsonRpc\Client([
'app' => 'abc',
'client' => [
'default' => [
'base_uri' => 'http://localhost:8080',
]
],
]);
$client->endpoint('default');
$json = json_encode([
'order_id' => '123',
'user_id' => '456',
]);
try {
$res = $client->call('topic.produce', ['abc', $json]);
var_dump($res);
} catch (Exception $e) {
var_dump($e->getCode(),$e->getMessage());
}

View File

@ -1,19 +1,8 @@
<?php
include_once dirname(__DIR__).'/vendor/autoload.php';
$client = new \JsonRpc\Client([
'app' => 'abc',
'client' => [
'default' => [
'base_uri' => 'http://localhost:8080',
]
],
]);
$client = new \JsonRpc\Client();
$client->endpoint('default');
try {
$res = $client->call('math.subtract',['12','23',500]);
} catch (Exception $e) {
var_dump($e->getMessage());
}
var_dump($res);