|
1
|
|
|
<?php declare(strict_types=1); |
|
2
|
|
|
|
|
3
|
|
|
namespace ReactInspector\Http\Middleware\Printer; |
|
4
|
|
|
|
|
5
|
|
|
use Psr\Http\Message\ResponseInterface; |
|
6
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
|
7
|
|
|
use React\Cache\ArrayCache; |
|
8
|
|
|
use React\Cache\CacheInterface; |
|
9
|
|
|
use React\Promise\PromiseInterface; |
|
10
|
|
|
use ReactInspector\Metric; |
|
11
|
|
|
use ReactInspector\MetricsStreamInterface; |
|
12
|
|
|
use ReactInspector\Printer\Printer; |
|
13
|
|
|
use RingCentral\Psr7\Response; |
|
14
|
|
|
use function assert; |
|
15
|
|
|
|
|
16
|
|
|
final class PrinterMiddleware |
|
17
|
|
|
{ |
|
18
|
|
|
private const TTL = 120; |
|
19
|
|
|
|
|
20
|
|
|
private Printer $printer; |
|
21
|
|
|
|
|
22
|
|
|
private CacheInterface $metrics; |
|
23
|
|
|
|
|
24
|
|
|
/** @var array<string, string> */ |
|
25
|
|
|
private array $metricsList = []; |
|
26
|
|
|
|
|
27
|
|
|
public function __construct(Printer $printer, MetricsStreamInterface $metricsStream) |
|
28
|
|
|
{ |
|
29
|
|
|
$this->printer = $printer; |
|
30
|
|
|
$this->metrics = new ArrayCache(); |
|
31
|
|
|
$metricsStream->subscribe(function (Metric $metric): void { |
|
32
|
|
|
$this->metrics->set($metric->config()->name(), $metric, self::TTL); |
|
33
|
|
|
$this->metricsList[$metric->config()->name()] = $metric->config()->name(); |
|
34
|
|
|
}); |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
|
|
public function __invoke(ServerRequestInterface $request): PromiseInterface |
|
38
|
|
|
{ |
|
39
|
|
|
/** @psalm-suppress TooManyTemplateParams */ |
|
40
|
|
|
return $this->metrics->getMultiple($this->metricsList)->then(function (array $metrics): ResponseInterface { |
|
41
|
|
|
$body = ''; |
|
42
|
|
|
|
|
43
|
|
|
foreach ($metrics as $metric) { |
|
44
|
|
|
assert($metric instanceof Metric); |
|
45
|
|
|
$body .= $this->printer->print($metric); |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
return new Response(200, [], $body); |
|
49
|
|
|
}); |
|
50
|
|
|
} |
|
51
|
|
|
} |
|
52
|
|
|
|