|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* Service invoker |
|
4
|
|
|
* User: moyo |
|
5
|
|
|
* Date: 25/09/2017 |
|
6
|
|
|
* Time: 4:57 PM |
|
7
|
|
|
*/ |
|
8
|
|
|
|
|
9
|
|
|
namespace Carno\RPC\Handlers; |
|
10
|
|
|
|
|
11
|
|
|
use Carno\Chain\Layered; |
|
12
|
|
|
use function Carno\Coroutine\async; |
|
13
|
|
|
use Carno\Coroutine\Context; |
|
14
|
|
|
use function Carno\Coroutine\race; |
|
15
|
|
|
use function Carno\Coroutine\timeout; |
|
16
|
|
|
use Carno\Promise\Promised; |
|
17
|
|
|
use Carno\RPC\Options; |
|
18
|
|
|
use Carno\RPC\Service\Dispatcher; |
|
19
|
|
|
use Carno\RPC\Protocol\Request; |
|
20
|
|
|
use Carno\RPC\Protocol\Response; |
|
21
|
|
|
use Throwable; |
|
22
|
|
|
|
|
23
|
|
|
class ServiceInvoker implements Layered |
|
24
|
|
|
{ |
|
25
|
|
|
/** |
|
26
|
|
|
* @var Dispatcher |
|
27
|
|
|
*/ |
|
28
|
|
|
private $dispatcher = null; |
|
29
|
|
|
|
|
30
|
|
|
/** |
|
31
|
|
|
* @var Options |
|
32
|
|
|
*/ |
|
33
|
|
|
private $options = null; |
|
34
|
|
|
|
|
35
|
|
|
/** |
|
36
|
|
|
* ServiceInvoker constructor. |
|
37
|
|
|
* @param Dispatcher $dispatcher |
|
38
|
|
|
* @param Options $options |
|
39
|
|
|
*/ |
|
40
|
|
|
public function __construct(Dispatcher $dispatcher, Options $options = null) |
|
41
|
|
|
{ |
|
42
|
|
|
$this->dispatcher = $dispatcher; |
|
43
|
|
|
$this->options = $options ?? new Options; |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
|
|
/** |
|
47
|
|
|
* @param Request $request |
|
48
|
|
|
* @param Context $ctx |
|
49
|
|
|
* @return Promised |
|
50
|
|
|
*/ |
|
51
|
|
|
public function inbound($request, Context $ctx) : Promised |
|
52
|
|
|
{ |
|
53
|
|
|
return race(async(function ($request) { |
|
54
|
|
|
return $this->dispatcher->invoke($request); |
|
55
|
|
|
}, $ctx, $request), timeout($this->options->ttExec)); |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
/** |
|
59
|
|
|
* @param Response $response |
|
60
|
|
|
* @param Context $ctx |
|
61
|
|
|
* @return Response |
|
62
|
|
|
*/ |
|
63
|
|
|
public function outbound($response, Context $ctx) : Response |
|
64
|
|
|
{ |
|
65
|
|
|
return $response; |
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
|
|
/** |
|
69
|
|
|
* @param Throwable $e |
|
70
|
|
|
* @param Context $ctx |
|
71
|
|
|
* @return void |
|
72
|
|
|
* @throws Throwable |
|
73
|
|
|
*/ |
|
74
|
|
|
public function exception(Throwable $e, Context $ctx) : void |
|
75
|
|
|
{ |
|
76
|
|
|
throw $e; |
|
77
|
|
|
} |
|
78
|
|
|
} |
|
79
|
|
|
|