1 | <?php |
||
2 | /** |
||
3 | * RPC client base |
||
4 | * User: moyo |
||
5 | * Date: 27/09/2017 |
||
6 | * Time: 6:14 PM |
||
7 | */ |
||
8 | |||
9 | namespace Carno\RPC; |
||
10 | |||
11 | use function Carno\Coroutine\ctx; |
||
12 | use Carno\RPC\Chips\HChains; |
||
13 | use Carno\RPC\Chips\NamedKit; |
||
14 | use Carno\RPC\Contracts\Client\Cluster; |
||
15 | use Carno\RPC\Contracts\Client\Remapping; |
||
16 | use Carno\RPC\Exception\ClientInitializingException; |
||
17 | use Carno\RPC\Protocol\Request; |
||
18 | use Carno\RPC\Protocol\Response; |
||
19 | use Google\Protobuf\Internal\Message; |
||
20 | use Closure; |
||
21 | |||
22 | abstract class Client |
||
23 | { |
||
24 | use NamedKit, HChains; |
||
25 | |||
26 | /** |
||
27 | * @var Closure |
||
28 | */ |
||
29 | private $invoker = null; |
||
30 | |||
31 | /** |
||
32 | * Client constructor. |
||
33 | * @param Cluster $clustering |
||
34 | * @param Remapping $remapping |
||
35 | */ |
||
36 | final public function __construct(Cluster $clustering = null, Remapping $remapping = null) |
||
37 | { |
||
38 | $serv = $this->namedServer(static::class); |
||
39 | |||
40 | if ($remapping && $remapping->configured($serv)) { |
||
41 | $this->invoker = $remapping->dispatcher()->handler(); |
||
42 | } elseif ($clustering) { |
||
43 | $clustering->joining($serv); |
||
44 | $this->invoker = Client::layers()->handler(); |
||
45 | } else { |
||
46 | throw new ClientInitializingException; |
||
47 | } |
||
48 | } |
||
49 | |||
50 | /** |
||
51 | * @param string $server |
||
52 | * @param string $service |
||
53 | * @param string $method |
||
54 | * @param Message $request |
||
55 | * @param Message $response |
||
56 | * @return Message |
||
57 | */ |
||
58 | final protected function request( |
||
59 | string $server, |
||
60 | string $service, |
||
61 | string $method, |
||
62 | Message $request, |
||
63 | Message $response |
||
64 | ) { |
||
65 | $rpc = |
||
66 | (new Request($server, $service, $method)) |
||
67 | ->setJsonc(false) |
||
68 | ->setPayload($request->serializeToString()) |
||
69 | ; |
||
70 | |||
71 | /** |
||
72 | * @var Response $resp |
||
73 | */ |
||
74 | $resp = yield ($this->invoker)($rpc, clone yield ctx()); |
||
0 ignored issues
–
show
Bug
Best Practice
introduced
by
![]() |
|||
75 | |||
76 | $response->mergeFromString($resp->getPayload()); |
||
77 | |||
78 | return $response; |
||
79 | } |
||
80 | } |
||
81 |