Skip to content

Commit

Permalink
fix client call with multi params
Browse files Browse the repository at this point in the history
  • Loading branch information
zhanglei28 committed Oct 30, 2024
1 parent 1f69666 commit dbc36df
Show file tree
Hide file tree
Showing 6 changed files with 67 additions and 59 deletions.
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -37,3 +37,7 @@ agent.pid
# debugger
.gdb*
/tests/MockServer/log.txt

composer.phar
composer.lock
.phpunit.cache/
39 changes: 15 additions & 24 deletions phpunit.xml
Original file line number Diff line number Diff line change
@@ -1,25 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
bootstrap="tests/bootstrap.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
>
<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">./src/</directory>
<exclude>
<directory suffix=".php">./src/Motan/PB</directory>
</exclude>
</whitelist>
</filter>
<testsuites>
<testsuite name="Package Test Suite">
<directory suffix=".php">./tests/</directory>
</testsuite>
</testsuites>
</phpunit>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" backupGlobals="false" bootstrap="tests/bootstrap.php" colors="true" processIsolation="false" stopOnFailure="false" xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/10.5/phpunit.xsd" cacheDirectory=".phpunit.cache" backupStaticProperties="false">
<testsuites>
<testsuite name="Package Test Suite">
<directory suffix=".php">./tests/</directory>
</testsuite>
</testsuites>
<source>
<include>
<directory suffix=".php">./src/</directory>
</include>
<exclude>
<directory suffix=".php">./src/Motan/PB</directory>
</exclude>
</source>
</phpunit>
21 changes: 13 additions & 8 deletions src/Motan/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,9 @@ public function __construct(URL $url_obj = NULL)
try {
$mesh_isalive = $connection->buildConnection($agent_addr);
} catch (\Exception $e) {
error_log("weibo-mesh isn't alive " . $e->getMessage() );
error_log("weibo-mesh isn't alive " . $e->getMessage());
}
if ($mesh_isalive){
if ($mesh_isalive) {
$this->_url_obj->setEndpoint(Constants::ENDPOINT_AGENT);
$this->_endpoint = new Agent($this->_url_obj);
$this->_endpoint->setConnectionObj($connection);
Expand Down Expand Up @@ -78,7 +78,8 @@ public function setConnectionTimeOut($time_out)
$this->_endpoint->setConnectionTimeOut($time_out);
}

public function getEndPoint() {
public function getEndPoint()
{
return $this->_endpoint;
}

Expand Down Expand Up @@ -132,8 +133,11 @@ public function __call($name, $arguments)
{
$request_id = $request_args = $request_header = NULL;
isset($arguments[0]) && !empty($arguments[0]) && $request_args = $arguments[0];
if (!is_array($request_args)) { // single parameter
$request_args = array($request_args);
}
$request = new \Motan\Request($this->_url_obj->getService(),
$name, ...[$request_args]);
$name, ...$request_args);
$request->addHeaders($this->_url_obj->getHeaders());
isset($arguments[1]) && !empty($arguments[1]) && $request->addHeaders($arguments[1]);
isset($arguments[2]) && !empty($arguments[2]) && $request->setRequestId($arguments[2]);
Expand Down Expand Up @@ -164,20 +168,21 @@ public function __call($name, $arguments)
/**
* multiCall calls a method on multiple backend.
* @param URL[] $url_objs array of backend URL object.
* @param string $method RPC method name.
* @param mixed ...$args arguments will pass to method.
* @param string $method RPC method name.
* @param mixed ...$args arguments will pass to method.
* @return array arary of called result, index 0 is the first response of $url_objs.
* @throws \Exception, you should try to catch it.
*/
public function multiCall(array $url_objs,string $method, ...$args) {
public function multiCall(array $url_objs, string $method, ...$args)
{
if (empty($url_objs)) {
return [];
}

$request_objs = [];
foreach ($url_objs as $url_obj) {
$request = new \Motan\Request($url_obj->getService(),
$method, ...$args);
$method, ...$args);
$request->addHeaders($url_obj->getHeaders());
$request->setGroup($url_obj->getGroup());
$request_objs[] = $request;
Expand Down
39 changes: 21 additions & 18 deletions src/Motan/Endpointer.php
Original file line number Diff line number Diff line change
Expand Up @@ -106,15 +106,16 @@ protected function _buildConnection()
return $this->_connection = $this->_connection_obj->getConnection();
}

public function setConnectionObj(Connection $conn_obj) {
public function setConnectionObj(Connection $conn_obj)
{
$this->_connection_obj = $conn_obj;
$this->_connection = $this->_connection_obj->getConnection();
}

public function doUpload(\Motan\Request $request)
{
$this->_buildConnection();
if( !$this->_connection) {
if (!$this->_connection) {
throw new \Exception("Connection has gone away!");
}

Expand Down Expand Up @@ -151,7 +152,7 @@ public function doUpload(\Motan\Request $request)
$sent = @fwrite($this->_connection, $buffer, $length);
if ($sent === false) {
$stream_meta = stream_get_meta_data($this->_connection);
if($stream_meta['timed_out'] == TRUE) {
if ($stream_meta['timed_out'] == TRUE) {
throw new \Exception('Write to remote timeout.');
} else {
throw new \Exception('Unknow error when write to remote. Stream detail:' . var_export($stream_meta, TRUE));
Expand All @@ -175,7 +176,7 @@ public function doUpload(\Motan\Request $request)
$sent += @fwrite($this->_connection, $buff);
}
if ($sent != $file_size) {
throw new \Exception("upload fail, need to upload:${file_size}, but only uploaded:${sent}" . var_export(stream_get_meta_data($this->_connection), TRUE));
throw new \Exception("upload fail, need to upload:{$file_size}, but only uploaded:{$sent}" . var_export(stream_get_meta_data($this->_connection), TRUE));
}
@fclose($in);

Expand Down Expand Up @@ -219,13 +220,13 @@ protected function _doHTTPCall(\Motan\Request $request)
$status_code = \curl_getinfo($ch, CURLINFO_HTTP_CODE);
$exception = NULL;
if ($status_code == 0) {
$exception = new \Exception("bad request to httpcalling error, url is ${url}");
$exception = new \Exception("bad request to httpcalling error, url is {$url}");
}
if ($status_code >= 400) {
$exception = new \Exception("back to httpcalling error, url is ${url}");
$exception = new \Exception("back to httpcalling error, url is {$url}");
}
$request_id = $request->getRequestId();
$raw_header = \Motan\Protocol\Motan::buildResponseHeader($request_id,SERIALIZE_SIMPLE, $status_code);
$raw_header = \Motan\Protocol\Motan::buildResponseHeader($request_id, SERIALIZE_SIMPLE, $status_code);
$metadata['M_p'] = $request->getService();
$metadata['M_m'] = $request->getMethod();
$metadata['M_g'] = $request->getGroup();
Expand Down Expand Up @@ -283,11 +284,11 @@ protected function _doSend(\Motan\Request $request)
{
// aquires seialization type from request itself.
// notice: $request_seria is a string typed flag.
$request_seria=$request->getSerialization();
$request_seria = $request->getSerialization();
// create seialization object from $request_seria.
$serialization=empty($request_seria)?$this->_url_obj->getSerialization():$request_seria;
$serialization = empty($request_seria) ? $this->_url_obj->getSerialization() : $request_seria;
// if create fail, using $this->_serializer as default serializer.
$serializer=empty($request_seria)?$this->_serializer:$request->getSerializer();
$serializer = empty($request_seria) ? $this->_serializer : $request->getSerializer();

if ($this->_url_obj->getUrlType() == Constants::REQ_URL_TYPE_RESTY
|| FALSE !== strpos($request->getMethod(), '/')) {
Expand All @@ -305,10 +306,10 @@ protected function _doSend(\Motan\Request $request)
throw new \Exception("Couldn't get correct group.");
}
}
if( !$this->_connection) {
if (!$this->_connection) {
throw new \Exception("Connection has gone away!");
}
if(!is_null($request->getRequestArgs())){
if (!is_null($request->getRequestArgs())) {
$req_body = $serializer->serializeMulti(...$request->getRequestArgs());
}

Expand Down Expand Up @@ -341,22 +342,24 @@ protected function _doRecv($resp_obj = NULL)
return $this->_parseRespMsg($resp_msg, $resp_obj);
}

protected function _doRecvRespMsg() {
protected function _doRecvRespMsg()
{
return $this->_connection_obj->read();
}

protected function _parseRespMsg($resp_msg, $resp_obj = NULL) {
protected function _parseRespMsg($resp_msg, $resp_obj = NULL)
{
$resp_body = $resp_msg->getBody();
if ($resp_msg->getHeader()->isGzip()) {
$resp_body = zlib_decode($resp_body);
}
// aquires seialization type from response header.
$resp_seria=$resp_msg->getHeader()->getSerialize();
$resp_seria = $resp_msg->getHeader()->getSerialize();
// create seialization object from $resp_seria.
// notice: $resp_seria is a int typed flag.
$serializer=Utils::getSerializer($resp_seria);
$serializer = Utils::getSerializer($resp_seria);
// if create fail, using $this->_serializer as default serializer.
empty($serializer)&&$serializer=$this->_serializer;
empty($serializer) && $serializer = $this->_serializer;

$res = $exception = NULL;
$res = $serializer->deserialize($resp_obj, $resp_body);
Expand Down Expand Up @@ -429,7 +432,7 @@ public function doMultiCall($request_objs)
$respMsg = $this->_doRecvRespMsg();
$requestId = $respMsg->getHeader()->getRequestId();
$resp_obj = isset($requests[$requestId]) ? $requests[$requestId]->getRespSerializerObj() : null;
$resp= $this->_parseRespMsg($respMsg, $resp_obj);
$resp = $this->_parseRespMsg($respMsg, $resp_obj);
} catch (\Exception $e) {
array_push($multi_exceptions, $e);
continue;
Expand Down
10 changes: 5 additions & 5 deletions src/Motan/Transport/Connection.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,11 @@

/**
* TCP Connection for PHP 5.6+
*
*
* <pre>
* TCP 连接
* </pre>
*
*
* @author idevz <[email protected]>
* @version V1.0 [created at: 2016-11-18]
*/
Expand Down Expand Up @@ -74,14 +74,14 @@ private function _initConnection()
}
}
if (!$connection) {
throw new \Exception("Connect to $this->_connection_addr fail, err_code:${err_code},err_msg:${err_msg} ");
throw new \Exception("Connect to $this->_connection_addr fail, err_code:{$err_code},err_msg:{$err_msg} ");
}
$this->_connection = $connection;
$this->_setStreamOpt();
return true;
}

private function _setStreamOpt()
private function _setStreamOpt()
{
if (!is_resource($this->_connection)) {
return false;
Expand All @@ -102,7 +102,7 @@ public function write($buffer)
$sent = @fwrite($this->_connection, $buffer, $length);
if ($sent === false) {
$stream_meta = stream_get_meta_data($this->_connection);
if($stream_meta['timed_out'] == TRUE) {
if ($stream_meta['timed_out'] == TRUE) {
throw new \Exception('Write to remote timeout.');
} else {
throw new \Exception('Unknow error when write to remote. Stream detail:' . var_export($stream_meta, TRUE));
Expand Down
13 changes: 9 additions & 4 deletions tests/Motan/ClientTest.php
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
<?php

namespace Motan;
define('DEFAULT_TEST_URL', 'motan2://127.0.0.1:9981/com.weibo.HelloMTService?group=motan-demo-rpc');

Expand All @@ -19,7 +20,7 @@ class ClientTest extends \PHPUnit\Framework\TestCase
* Sets up the fixture, for example, opens a network connection.
* This method is called before a test is executed.
*/
protected function setUp() : void
protected function setUp(): void
{
$url = new URL(DEFAULT_TEST_URL);
$url->setConnectionTimeOut(50000);
Expand All @@ -31,7 +32,7 @@ protected function setUp() : void
* Tears down the fixture, for example, closes a network connection.
* This method is called after a test is executed.
*/
protected function tearDown() : void
protected function tearDown(): void
{
}

Expand Down Expand Up @@ -77,7 +78,7 @@ public function testGetResponseMetadata()
*/
public function testGetResponseException()
{
$this->object->doCall('HelloX', 222, 123, 124, ['string','arr']);
$this->object->doCall('HelloX', 222, 123, 124, ['string', 'arr']);
$rs = $this->object->getResponseException();
$this->assertEquals('{"errcode":500,"errmsg":"method HelloX is not found in provider.","errtype":1}', $rs);
}
Expand All @@ -91,7 +92,7 @@ public function testGetResponse()
$params = "testmsg";
$this->object->doCall('Hello', $params);
$rs = $this->object->getResponse();
$this->assertObjectHasAttribute('_type',$rs);
$this->assertObjectHasProperty('_type', $rs);
$this->assertEquals(MSG_TYPE_RESPONSE, $rs->getType());
}

Expand All @@ -115,6 +116,10 @@ public function test__call()
$params = "testmsg";
$rs = $this->object->Hello($params);
$this->assertEquals("hello testmsg", $rs);

// use array params(for multi params)
$rs = $this->object->Hello([$params]);
$this->assertEquals("hello testmsg", $rs);
}

/**
Expand Down

0 comments on commit dbc36df

Please sign in to comment.