-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathApiCall.php
More file actions
320 lines (289 loc) · 9.7 KB
/
ApiCall.php
File metadata and controls
320 lines (289 loc) · 9.7 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
<?php
namespace Typesence;
use \Typesence\Lib\Node;
use \Typesence\Lib\Configuration;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\RequestException;
use \Typesence\Exceptions\ServerError;
use \Typesence\Exceptions\ObjectNotFound;
use \Typesence\Exceptions\RequestMalformed;
use \Typesence\Exceptions\HTTPStatus0Error;
use \Typesence\Exceptions\ServiceUnavailable;
use \Typesence\Exceptions\RequestUnauthorized;
use \Typesence\Exceptions\ObjectAlreadyExists;
use \Typesence\Exceptions\ObjectUnprocessable;
use \Typesence\Exceptions\TypesenseClientError;
/**
* Class ApiCall
*
* @package \Typesence
* @date 4/5/20
* @author Abdullah Al-Faqeir <abdullah@devloops.net>
*/
class ApiCall
{
private const API_KEY_HEADER_NAME = 'X-TYPESENSE-API-KEY';
/**
* @var \GuzzleHttp\Client
*/
private \GuzzleHttp\Client $client;
/**
* @var \Typesence\Lib\Configuration
*/
private Configuration $config;
/**
* @var array|\Typesence\Lib\Node[]
*/
private static array $nodes;
/**
* @var \Typesence\Lib\Node|null
*/
private static ?Node $nearestNode;
/**
* @var int
*/
private int $nodeIndex;
/**
* ApiCall constructor.
*
* @param \Typesence\Lib\Configuration $config
*/
public function __construct(Configuration $config)
{
$this->config = $config;
$this->client = new \GuzzleHttp\Client();
self::$nodes = $this->config->getNodes();
self::$nearestNode = $this->config->getNearestNode();
$this->nodeIndex = 0;
$this->initializeNodes();
}
/**
* Initialize Nodes
*/
private function initializeNodes(): void
{
if (self::$nearestNode !== null) {
$this->setNodeHealthCheck(self::$nearestNode, true);
}
foreach (self::$nodes as &$node) {
$this->setNodeHealthCheck($node, true);
}
}
/**
* @param string $endPoint
* @param array $params
* @param bool $asJson
*
* @return string|array
* @throws \Typesence\Exceptions\TypesenseClientError
* @throws \Exception|\GuzzleHttp\Exception\GuzzleException
*/
public function get(string $endPoint, array $params, bool $asJson = true)
{
return $this->makeRequest('get', $endPoint, $asJson, [
'data' => $params ?? [],
]);
}
/**
* @param string $endPoint
* @param mixed $body
*
* @param bool $asJson
*
* @return array|string
* @throws \Typesence\Exceptions\TypesenseClientError
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function post(string $endPoint, $body, bool $asJson = true): array
{
return $this->makeRequest('post', $endPoint, $asJson, [
'data' => $body ?? [],
]);
}
/**
* @param string $endPoint
* @param array $body
*
* @return array
* @throws \Typesence\Exceptions\TypesenseClientError|\GuzzleHttp\Exception\GuzzleException
*/
public function put(string $endPoint, array $body): array
{
return $this->makeRequest('put', $endPoint, true, [
'data' => $body ?? [],
]);
}
/**
* @param string $endPoint
*
* @return array
* @throws \Typesence\Exceptions\TypesenseClientError|\GuzzleHttp\Exception\GuzzleException
*/
public function delete(string $endPoint): array
{
return $this->makeRequest('delete', $endPoint, true, []);
}
/**
* Makes the actual http request, along with retries
*
* @param string $method
* @param string $endPoint
* @param bool $asJson
* @param array $options
*
* @return string|array
* @throws \Typesence\Exceptions\TypesenseClientError|\GuzzleHttp\Exception\GuzzleException
* @throws \Exception
*/
private function makeRequest(string $method, string $endPoint, bool $asJson, array $options)
{
$numRetries = 0;
$last_exception = null;
while ($numRetries < $this->config->getNumRetries() + 1) {
$numRetries++;
$node = $this->getNode();
try {
$url = $node->url().$endPoint;
$reqOp = $this->getRequestOptions();
if (isset($options['data'])) {
if ($method === 'get') {
$reqOp['query'] = http_build_query($options['data']);
} elseif (is_string($options['data'])) {
$reqOp['body'] = $options['data'];
} else {
$reqOp['json'] = $options['data'];
}
}
$response = $this->client->request($method, $url, $reqOp);
$statusCode = $response->getStatusCode();
if (0 < $statusCode && $statusCode < 500) {
$this->setNodeHealthCheck($node, true);
}
if (!(200 <= $statusCode && $statusCode < 300)) {
$errorMessage = json_decode($response->getBody()
->getContents(), true, 512, JSON_THROW_ON_ERROR)['message'] ?? 'API error.';
throw $this->getException($statusCode)
->setMessage($errorMessage);
}
return $asJson ? json_decode($response->getBody()
->getContents(), true, 512, JSON_THROW_ON_ERROR) : $response->getBody()
->getContents();
} catch (ClientException $exception) {
if ($exception->getResponse()
->getStatusCode() === 408) {
continue;
}
$this->setNodeHealthCheck($node, false);
throw $this->getException($exception->getResponse()
->getStatusCode())
->setMessage($exception->getMessage());
} catch (RequestException $exception) {
$this->setNodeHealthCheck($node, false);
throw $this->getException($exception->getResponse()
->getStatusCode())
->setMessage($exception->getMessage());
} catch (TypesenseClientError $exception) {
$this->setNodeHealthCheck($node, false);
throw $exception;
} catch (\Exception $exception) {
$this->setNodeHealthCheck($node, false);
$last_exception = $exception;
sleep($this->config->getRetryIntervalSeconds());
}
}
if ($last_exception) {
throw $last_exception;
}
}
/**
* @return array
*/
private function getRequestOptions(): array
{
return [
'headers' => [
self::API_KEY_HEADER_NAME => $this->config->getApiKey(),
],
'connect_timeout' => $this->config->getConnectionTimeoutSeconds(),
];
}
/**
* @param \Typesence\Lib\Node $node
*
* @return bool
*/
private function nodeDueForHealthCheck(Node $node): bool
{
$currentTimestamp = time();
$checkNode = ($currentTimestamp - $node->getLastAccessTs()) > $this->config->getHealthCheckIntervalSeconds();
if ($checkNode) {
//
}
return $checkNode;
}
/**
* @param \Typesence\Lib\Node $node
* @param bool $isHealthy
*/
public function setNodeHealthCheck(Node $node, bool $isHealthy): void
{
$node->setHealthy($isHealthy);
$node->setLastAccessTs(time());
}
/**
* Returns a healthy host from the pool in a round-robin fashion
* Might return an unhealthy host periodically to check for recovery.
*
* @return \Typesence\Lib\Node
*/
public function getNode(): Lib\Node
{
if (self::$nearestNode !== null) {
if (self::$nearestNode->isHealthy() || $this->nodeDueForHealthCheck(self::$nearestNode)) {
return self::$nearestNode;
}
}
$i = 0;
while ($i < count(self::$nodes)) {
$i++;
$node = self::$nodes[$this->nodeIndex];
$this->nodeIndex = ($this->nodeIndex + 1) % count(self::$nodes);
if ($node->isHealthy() || $this->nodeDueForHealthCheck($node)) {
return $node;
}
}
/**
* None of the nodes are marked healthy, but some of them could have become healthy since last health check.
* So we will just return the next node.
*/
return self::$nodes[$this->nodeIndex];
}
/**
* @param int $httpCode
*
* @return \Typesence\Exceptions\TypesenseClientError
*/
public function getException(int $httpCode): TypesenseClientError
{
switch ($httpCode) {
case 0:
return new HTTPStatus0Error();
case 400:
return new RequestMalformed();
case 401:
return new RequestUnauthorized();
case 404:
return new ObjectNotFound();
case 409:
return new ObjectAlreadyExists();
case 422:
return new ObjectUnprocessable();
case 500:
return new ServerError();
case 503:
return new ServiceUnavailable();
default:
return new TypesenseClientError();
}
}
}