Repository navigation
Expand file tree
/
Copy pathGrpcClient.php
More file actions
378 lines (328 loc) · 11.2 KB
/
Copy pathGrpcClient.php
File metadata and controls
378 lines (328 loc) · 11.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact [email protected]
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
namespace Hyperf\GrpcClient;
use Hyperf\Coroutine\Channel\Pool as ChannelPool;
use Hyperf\Coroutine\Coroutine;
use Hyperf\Engine\Channel;
use Hyperf\Grpc\StatusCode;
use Hyperf\GrpcClient\Exception\GrpcClientException;
use InvalidArgumentException;
use RuntimeException;
use Swoole\Coroutine\Http2\Client as SwooleHttp2Client;
use Swoole\Http2\Response;
class GrpcClient
{
public const GRPC_DEFAULT_TIMEOUT = 3.0;
private string $host;
private int $port;
private array $options = [];
private float $timeout;
private bool $sendYield = false;
private bool $ssl = false;
/**
* The main coroutine id of the client.
*/
private int $mainCoroutineId = 0;
private ?SwooleHttp2Client $httpClient = null;
private int $recvCoroutineId = 0;
private int $sendCoroutineId = 0;
/**
* The hashMap of channels [streamId => response channel].
* @var Channel[]
*/
private array $recvChannelMap = [];
private int $waitStatus = Status::WAIT_PENDDING;
private ?Channel $waitYield = null;
/**
* The channel to proxy send data from all of the coroutine.
*/
private ?Channel $sendChannel = null;
/**
* The channel to get the current send stream id (as ret val).
*/
private ?Channel $sendResultChannel = null;
public function __construct(private ChannelPool $channelPool)
{
}
public function set(string $hostname, array $options = [])
{
$parts = parse_url($hostname);
if (! $parts || ! isset($parts['host']) || ! $parts['port']) {
throw new InvalidArgumentException("The hostname {$hostname} is illegal!");
}
$this->host = $parts['host'];
$this->port = (int) $parts['port'];
$defaultOptions = [
'timeout' => self::GRPC_DEFAULT_TIMEOUT,
'send_yield' => false,
'ssl' => false,
'ssl_host_name' => '',
'credentials' => null,
];
$this->options = $options + $defaultOptions;
$this->timeout = &$this->options['timeout'];
$this->sendYield = &$this->options['send_yield'];
$this->ssl = $this->options['ssl'] || $this->options['ssl_host_name'];
}
public function start(): bool
{
if ($this->recvCoroutineId !== 0 || $this->sendCoroutineId !== 0) { // Client already started
return true;
}
if (! Coroutine::inCoroutine()) {
throw new RuntimeException('Client must be started in coroutine.');
}
if (! $this->getHttpClient()->connect()) {
throw new GrpcClientException('Connect failed, error=' . $this->getHttpClient()->errMsg, $this->getHttpClient()->errCode);
}
$this->mainCoroutineId = Coroutine::id();
$this->runReceiveCoroutine();
$this->runSendCoroutine();
return true;
}
public function close($yield = false): bool
{
return $this->wait(Status::WAIT_CLOSE_FORCE, $yield);
}
public function closeRecv()
{
if ($this->waitStatus) {
$shouldKill = true;
} else {
$shouldKill = ! $this->getHttpClient()->connect();
}
if ($shouldKill) {
// Set `connected` of http client to `false`
$this->getHttpClient()->close();
}
// Clear the receive channel map
if (! empty($this->recvChannelMap)) {
foreach ($this->recvChannelMap as $channel) {
// If this channel has pending pop, we should push 'false' to negate the pop.
// Otherwise we should release it directly.
while ($channel->stats()['consumer_num'] !== 0) {
$channel->push(-1);
}
$this->channelPool->release($channel);
}
$this->recvChannelMap = [];
}
return $shouldKill;
}
public function isConnected(): bool
{
return (bool) $this->httpClient?->connected;
}
public function isStreamExist(int $streamId): bool
{
return isset($this->recvChannelMap[$streamId]);
}
public function isRunning(): bool
{
return $this->recvCoroutineId > 0 && ($this->sendYield === false || $this->sendCoroutineId > 0);
}
public function getHttpClient(): SwooleHttp2Client
{
if (! $this->httpClient instanceof SwooleHttp2Client) {
$this->httpClient = $this->buildHttp2Client();
}
return $this->httpClient;
}
/**
* Open a stream and return the id.
* @param mixed $data
*/
public function openStream(
string $path,
$data = '',
string $method = '',
bool $usePipelineRead = false,
array $metadata = []
): int {
$request = new Request($path);
if ($data) {
$request->data = $data;
}
$request->headers = $request->headers + $metadata;
$request->pipeline = true;
if ($usePipelineRead) {
$request->usePipelineRead = true;
}
return $this->send($request);
}
public function send(Request $request): int
{
if (! $this->isConnected()) {
return 0;
}
if ($this->sendYield === true) {
$this->sendChannel->push($request);
$streamId = $this->sendResultChannel->pop();
} else {
$streamId = $this->getHttpClient()->send($request);
}
if ($streamId === false) {
throw new GrpcClientException('Failed to send the request to server', StatusCode::INTERNAL);
}
if ($streamId > 0) {
$this->recvChannelMap[$streamId] = $this->channelPool->get();
}
return $streamId;
}
public function write(int $streamId, $data, bool $end = false)
{
if ($this->sendYield === true) {
return $this->sendChannel->push([$streamId, $data, $end])
&& $this->sendResultChannel->pop();
}
return $this->getHttpClient()->write($streamId, $data, $end);
}
public function recv(int $streamId, ?float $timeout = null)
{
if (! $this->isConnected() || $streamId <= 0 || ! $this->isStreamExist($streamId)) {
return false;
}
$channel = $this->recvChannelMap[$streamId] ?? null;
if ($channel instanceof Channel) {
$response = $channel->pop($timeout === null ? $this->timeout : $timeout);
if ($response === -1) {
unset($this->recvChannelMap[$streamId]);
return false;
}
// Unset recvChannelMap arfter recv
if (($response === false && $channel->errCode === SWOOLE_CHANNEL_TIMEOUT) || ($response instanceof Response && ! $response->pipeline)) {
unset($this->recvChannelMap[$streamId]);
if (! $channel->isEmpty()) {
$channel->pop();
}
$this->channelPool->push($channel);
}
return $response;
}
return false;
}
public function getErrCode(): int
{
return $this->httpClient ? $this->httpClient->errCode : 0;
}
public function ping(): bool
{
return $this->getHttpClient()->ping();
}
/**
* @param bool|float $yield
*/
private function wait(int $type, $yield = true): bool
{
if (! $this->isConnected()) {
return false;
}
$this->waitStatus = $type;
if ($this->waitStatus === Status::WAIT_CLOSE) {
return $this->yield($yield);
}
$this->getHttpClient()->close();
$result = $this->sendYield ? $this->sendChannel->push(0) : true;
if ($result === true) {
$this->yield($yield);
}
return $result;
}
/**
* @param bool|float $yield
*/
private function yield($yield = true)
{
$yield = $yield === true ? -1 : $yield;
if ($yield) {
$this->waitYield = $this->channelPool->get();
return $this->waitYield->pop($yield);
}
}
private function runReceiveCoroutine()
{
// Receive wait
Coroutine::create(function () {
$this->recvCoroutineId = Coroutine::id();
// Start the receive loop
while (true) {
$response = $this->getHttpClient()->recv();
if ($response !== false) {
$streamId = $response->streamId;
if (! $this->isStreamExist($streamId)) {
continue;
}
// Force close.
if ($this->waitStatus === Status::WAIT_CLOSE_FORCE) {
if ($this->closeRecv()) {
break;
}
}
$channel = $this->recvChannelMap[$streamId];
$channel->push($response);
// If wait status is equal to WAIT_CLOSE, and no coroutine is waiting, then break the recv loop.
if ($this->waitStatus === Status::WAIT_CLOSE && empty($this->recvChannelMap)) {
break;
}
} else {
if ($this->ping()) {
continue;
}
// If no response, then close all the connection.
if ($this->closeRecv()) {
break;
}
}
}
// The receive coroutine is closed, notity the status to main coroutine.
if ($this->waitYield instanceof Channel) {
$this->waitYield->push(true);
$this->channelPool->release($this->waitYield);
$this->waitYield = null;
}
// Reset the properties.
$this->recvCoroutineId = 0;
$this->mainCoroutineId = 0;
$this->waitStatus = Status::WAIT_PENDDING;
$this->waitYield = null;
});
}
private function runSendCoroutine()
{
if (! $this->sendYield) {
return;
}
Coroutine::create(function () {
$this->sendCoroutineId = Coroutine::id();
$this->sendChannel = $this->channelPool->get();
$this->sendResultChannel = $this->channelPool->get();
while (true) {
$data = $this->sendChannel->pop();
if ($data === 0) {
break;
}
if ($data instanceof Request) {
$result = $this->getHttpClient()->send($data);
} else {
$result = $this->getHttpClient()->write(...$data);
}
$this->sendResultChannel->push($result);
}
$this->sendCoroutineId = 0;
});
}
private function buildHttp2Client(): SwooleHttp2Client
{
$httpClient = new SwooleHttp2Client($this->host, $this->port, $this->ssl);
$httpClient->set($this->options);
return $httpClient;
}
}