1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
|
4
|
|
|
namespace TechDeCo\ElasticApmAgent\Client; |
5
|
|
|
|
6
|
|
|
use Countable; |
7
|
|
|
use Http\Promise\Promise; |
8
|
|
|
use Psr\Http\Message\ResponseInterface; |
9
|
|
|
use Psr\Log\LoggerInterface; |
10
|
|
|
use TechDeCo\ElasticApmAgent\Exception\ClientException; |
11
|
|
|
use Throwable; |
12
|
|
|
use function array_filter; |
13
|
|
|
use function count; |
14
|
|
|
|
15
|
|
|
final class PromiseCollection implements Countable |
16
|
|
|
{ |
17
|
|
|
/** |
18
|
|
|
* @var LoggerInterface |
19
|
|
|
*/ |
20
|
|
|
private $logger; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* @var Promise[] |
24
|
|
|
*/ |
25
|
|
|
private $promiseList = []; |
26
|
|
|
|
27
|
10 |
|
public function __construct(LoggerInterface $logger) |
28
|
|
|
{ |
29
|
10 |
|
$this->logger = $logger; |
30
|
10 |
|
} |
31
|
|
|
|
32
|
9 |
|
public function add(Promise $promise): void |
33
|
|
|
{ |
34
|
9 |
|
$this->promiseList[] = $promise; |
35
|
9 |
|
} |
36
|
|
|
|
37
|
10 |
|
public function count(): int |
38
|
|
|
{ |
39
|
10 |
|
return count($this->promiseList); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* @return Throwable[] |
44
|
|
|
*/ |
45
|
4 |
|
public function resolveAll(): array |
46
|
|
|
{ |
47
|
4 |
|
$exceptionList = []; |
48
|
4 |
|
foreach ($this->promiseList as $index => $promise) { |
49
|
4 |
|
$exceptionList[] = $this->resolve($index + 1, $promise); |
50
|
|
|
} |
51
|
|
|
|
52
|
4 |
|
$this->promiseList = []; |
53
|
|
|
|
54
|
4 |
|
return array_filter($exceptionList); |
55
|
|
|
} |
56
|
|
|
|
57
|
4 |
|
private function resolve(int $promiseCount, Promise $promise): ?Throwable |
58
|
|
|
{ |
59
|
|
|
try { |
60
|
4 |
|
$this->logger->debug('Waiting for response on request #' . $promiseCount); |
61
|
4 |
|
$this->verifyResponse($promise->wait()); |
62
|
2 |
|
$this->logger->debug('Successful response on request #' . $promiseCount); |
63
|
3 |
|
} catch (Throwable $e) { |
64
|
3 |
|
$this->logger->error('Encountered error in response for request #' . $promiseCount, [ |
65
|
3 |
|
'exception' => $e, |
66
|
3 |
|
'message' => $e->getMessage(), |
67
|
|
|
]); |
68
|
|
|
|
69
|
3 |
|
return $e; |
70
|
|
|
} |
71
|
|
|
|
72
|
2 |
|
return null; |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
/** |
76
|
|
|
* @throws ClientException |
77
|
|
|
*/ |
78
|
4 |
|
private function verifyResponse(ResponseInterface $response): void |
79
|
|
|
{ |
80
|
4 |
|
$status = $response->getStatusCode(); |
81
|
|
|
|
82
|
4 |
|
if ($status >= 400 && $status < 500) { |
83
|
1 |
|
throw ClientException::fromResponse('Bad request', $response); |
84
|
|
|
} |
85
|
3 |
|
if ($status >= 500) { |
86
|
2 |
|
throw ClientException::fromResponse('APM internal server error', $response); |
87
|
|
|
} |
88
|
2 |
|
} |
89
|
|
|
} |
90
|
|
|
|