Lines
70.00%
7 / 10
Functions and Methods
50.00%
1 / 2
Classes and Traits
0.00%
0 / 1
| Name | Lines | Functions and Methods | CRAP | Classes and Traits | ||||||
|---|---|---|---|---|---|---|---|---|---|---|
| MetricsRequestHandler | 70.00% | 7 / 10 | 50.00% | 1 / 2 | 5.68 | 0.00% | 0 / 1 | |||
| __construct | 100.00% | 1 / 1 | 100.00% | 1 / 1 | 1 | |||||
| handleRequest | 66.66% | 6 / 9 | 0.00% | 0 / 1 | 4.59 | |||||
| 1 | <?php | |
| 2 | ||
| 3 | declare(strict_types=1); | |
| 4 | ||
| 5 | namespace Stewart\Runtime\Http; | |
| 6 | ||
| 7 | use Amp\Http\HttpStatus; | |
| 8 | use Amp\Http\Server\Request; | |
| 9 | use Amp\Http\Server\RequestHandler; | |
| 10 | use Amp\Http\Server\Response; | |
| 11 | use Psr\Log\LoggerInterface; | |
| 12 | use Stewart\Runtime\Metrics\PrometheusTextEncoder; | |
| 13 | use Stewart\Runtime\Metrics\RuntimeMetricsExporter; | |
| 14 | use Throwable; | |
| 15 | ||
| 16 | final readonly class MetricsRequestHandler implements RequestHandler | |
| 17 | { | |
| 18 | private const array RESPONSE_HEADERS = ['content-type' => PrometheusTextEncoder::CONTENT_TYPE, 'cache-control' => 'no-store']; | |
| 19 | ||
| 20 | private const string METRICS_PATH = '/metrics'; | |
| 21 | ||
| 22 | public function __construct( | |
| 23 | private RuntimeMetricsExporter $metrics, | |
| 24 | private BearerTokenCheck $tokens, | |
| 25 | private UnauthorizedRequestWarnings $refusals, | |
| 26 | private LoggerInterface $logger, | |
| 27 | ) {} | |
| 28 | ||
| 29 | public function handleRequest(Request $request): Response | |
| 30 | { | |
| 31 | if (!$this->tokens->admitsRequest($request)) { | |
| 32 | $this->refusals->recordRefusedRequest($request); | |
| 33 | ||
| 34 | return new Response(HttpStatus::UNAUTHORIZED, ['www-authenticate' => 'Bearer']); | |
| 35 | } | |
| 36 | ||
| 37 | if ($request->getUri()->getPath() !== self::METRICS_PATH) { | |
| 38 | return new Response(HttpStatus::NOT_FOUND); | |
| 39 | } | |
| 40 | ||
| 41 | try { | |
| 42 | return new Response(HttpStatus::OK, self::RESPONSE_HEADERS, $this->metrics->exportMetrics()); | |
| 43 | } catch (Throwable $e) { | |
| 44 | $this->logger->error('Could not export the metrics', ['exception' => $e]); | |
| 45 | ||
| 46 | return new Response(HttpStatus::INTERNAL_SERVER_ERROR); | |
| 47 | } | |
| 48 | } | |
| 49 | } |