Repository navigation
Expand file tree
/
Copy pathClient.php
More file actions
142 lines (128 loc) · 4.83 KB
/
Copy pathClient.php
File metadata and controls
142 lines (128 loc) · 4.83 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
<?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\ConfigApollo;
use Closure;
use Exception;
use Hyperf\Contract\ConfigInterface;
use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Coroutine\Parallel;
use Psr\Http\Message\ResponseInterface;
use RuntimeException;
class Client implements ClientInterface
{
protected array $cache = [];
public function __construct(
protected Option $option,
protected Closure $httpClientFactory,
protected ConfigInterface $config,
protected StdoutLoggerInterface $logger
) {
}
public function pull(): array
{
$namespaces = $this->config->get('config_center.drivers.apollo.namespaces');
return $this->parallelPull($namespaces);
}
public function getOption(): Option
{
return $this->option;
}
public function parallelPull(array $namespaces): array
{
$option = $this->option;
$parallel = new Parallel();
$httpClientFactory = $this->httpClientFactory;
foreach ($namespaces as $namespace) {
$parallel->add(function () use ($option, $httpClientFactory, $namespace) {
$client = $httpClientFactory();
if (! $client instanceof \GuzzleHttp\Client) {
throw new RuntimeException('Invalid http client.');
}
$cacheKey = $option->buildCacheKey($namespace);
$releaseKey = $this->getReleaseKey($cacheKey);
$query = [
'ip' => $option->getClientIp(),
'releaseKey' => $releaseKey,
];
$timestamp = $this->getTimestamp();
$headers = [
'Authorization' => $this->getAuthorization($timestamp, parse_url($option->buildBaseUrl(), PHP_URL_PATH) . $namespace . '?' . http_build_query($query)),
'Timestamp' => $timestamp,
];
$response = $client->get($option->buildBaseUrl() . $namespace, [
'query' => $query,
'headers' => $headers,
]);
if ($response->getStatusCode() === 200 && str_contains($response->getHeaderLine('content-type'), 'application/json')) {
$body = json_decode((string) $response->getBody(), true);
$result = $body['configurations'] ?? [];
$this->cache[$cacheKey] = [
'releaseKey' => $body['releaseKey'] ?? '',
'configurations' => $result,
];
} else {
// Status code is 304 or Connection Failed, use the previous config value
$result = $this->cache[$cacheKey]['configurations'] ?? [];
if ($response->getStatusCode() !== 304) {
$this->logger->error('Connect to Apollo server failed');
}
}
return $result;
}, $namespace);
}
return $parallel->wait();
}
public function longPulling(array $notifications): ?ResponseInterface
{
$httpClientFactory = $this->httpClientFactory;
$client = $httpClientFactory([
'timeout' => 60,
]);
if (! $client instanceof \GuzzleHttp\Client) {
throw new RuntimeException('Invalid http client.');
}
try {
$uri = $this->option->buildLongPullingBaseUrl();
return $client->get($uri, [
'query' => [
'appId' => $this->option->getAppid(),
'cluster' => $this->option->getCluster(),
'notifications' => json_encode(array_values($notifications)),
],
]);
} catch (Exception) {
// Do nothing
return null;
}
}
protected function getReleaseKey(string $cacheKey): ?string
{
return $this->cache[$cacheKey]['releaseKey'] ?? null;
}
private function hasSecret(): bool
{
return ! empty($this->option->getSecret());
}
private function getTimestamp(): string
{
[$usec, $sec] = explode(' ', microtime());
return sprintf('%.0f', (floatval($usec) + floatval($sec)) * 1000);
}
private function getAuthorization(string $timestamp, string $pathWithQuery): string
{
if (! $this->hasSecret()) {
return '';
}
$toSignature = $timestamp . "\n" . $pathWithQuery;
$signature = base64_encode(hash_hmac('sha1', $toSignature, $this->option->getSecret(), true));
return sprintf('Apollo %s:%s', $this->option->getAppid(), $signature);
}
}