Lines 84.61% 33 / 39
Methods 71.42% 5 / 7
Classes 0.00% 0 / 1
Name Lines Methods CRAP
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 handleRequest 84.21% 16 / 19 0.00% 0 / 1 6.14
 answerRoute 100.00% 8 / 8 100.00% 1 / 1 8
 describeMissingEndpoint 100.00% 3 / 3 100.00% 1 / 1 2
 selectFailureStatus 100.00% 3 / 3 100.00% 1 / 1 4
 respondWithFailure 25.00% 1 / 4 0.00% 0 / 1 3.69
 respond 100.00% 1 / 1 100.00% 1 / 1 1
29final readonly class AdminRequestHandler implements RequestHandler
30{
31    private const array JSON_HEADERS = ['content-type' => 'application/json', 'cache-control' => 'no-store'];
32
33    private const string METRICS_PATH = '/metrics';
34
35    public function __construct(
36        private RuntimeAdmin $admin,
37        private AdminApiCodec $codec,
38        private LoggerInterface $logger,
39        private BearerTokenCheck $tokens,
40        private UnauthorizedRequestWarnings $refusals,
41    ) {}
42
43    public function handleRequest(Request $request): Response
44    {
45        if (!$this->tokens->admitsRequest($request)) {
46            $this->refusals->recordRefusedRequest($request);
47
48            return $this->respondWithFailure(HttpStatus::UNAUTHORIZED, new RequestFailed('unauthorized', 'A valid bearer token is required.'), ['www-authenticate' => 'Bearer']);
49        }
50
51        $path = $request->getUri()->getPath();
52        $route = AdminRoute::fromPath($path);
53
54        if ($route === null) {
55            return $this->respondWithFailure(HttpStatus::NOT_FOUND, new RequestFailed('not_found', $this->describeMissingEndpoint($path)));
56        }
57
58        if (!$route->allowsMethod($request->getMethod())) {
59            return $this->respondWithFailure(
60                HttpStatus::METHOD_NOT_ALLOWED,
61                new RequestFailed('method_not_allowed', \sprintf('%s does not accept %s.', $path, $request->getMethod())),
62                ['allow' => implode(', ', $route->action->listAllowedMethods())],
63            );
64        }
65
66        try {
67            return $this->respond(HttpStatus::OK, $this->answerRoute($route));
68        } catch (StewartException $e) {
69            return $this->respondWithFailure($this->selectFailureStatus($e->reason), new RequestFailed((string) $e->reason->value, $e->getMessage()));
70        } catch (Throwable $e) {
71            $this->logger->error('Could not answer the admin request', ['path' => $path, 'exception' => $e]);
72
73            return $this->respondWithFailure(HttpStatus::INTERNAL_SERVER_ERROR, new RequestFailed('internal_error', 'The admin request failed; the daemon log has the cause.'));
74        }
75    }
76
77    /** @throws StewartException */
78    private function answerRoute(AdminRoute $route): AdminAppList|AdminAppView|CommandResult
79    {
80        return match ($route->action) {
81            AdminAction::ListApps => new AdminAppList(array_map(AdminAppView::fromAppStatus(...), $this->admin->listHostedAppStatuses())),
82            AdminAction::ShowApp => AdminAppView::fromAppStatus($this->admin->requireAppStatus(new AppId((string) $route->resourceId))),
83            AdminAction::PauseApp => $this->admin->pauseApp(new AppId((string) $route->resourceId), AppPauseSource::Http),
84            AdminAction::ResumeApp => $this->admin->resumeApp(new AppId((string) $route->resourceId), AppPauseSource::Http),
85            AdminAction::ResetApp => $this->admin->resetApp(new AppId((string) $route->resourceId), AppPauseSource::Http),
86            AdminAction::RestartWorker => $this->admin->restartWorker((string) $route->resourceId),
87            AdminAction::Reload => $this->admin->reload(ReloadTrigger::Http),
88        };
89    }
90
91    private function describeMissingEndpoint(string $path): string
92    {
93        // Scrapers still pointed at the admin port learn where the metrics went in 2.0.
94        return $path === self::METRICS_PATH
95            ? 'Metrics are served on the http.metrics.listen port, not the admin port.'
96            : \sprintf('No admin endpoint at %s.', $path);
97    }
98
99    private function selectFailureStatus(ExceptionReason $reason): int
100    {
101        return match ($reason) {
102            AppError::Unknown, IdentifierError::AppIdInvalid, IdentifierError::AppIdTooLong, WorkerError::Unknown => HttpStatus::NOT_FOUND,
103            AppError::Disabled, WorkerError::ShuttingDown => HttpStatus::CONFLICT,
104            default => HttpStatus::INTERNAL_SERVER_ERROR,
105        };
106    }
107
108    /** @param array<non-empty-string, string> $headers */
109    private function respondWithFailure(int $status, RequestFailed $failure, array $headers = []): Response
110    {
111        try {
112            return $this->respond($status, $failure, $headers);
113        } catch (Throwable $e) {
114            $this->logger->error('Could not encode the admin failure', ['exception' => $e]);
115
116            return new Response($status, $headers);
117        }
118    }
119
120    /**
121     * @param array<non-empty-string, string> $headers
122     * @throws Throwable
123     */
124    private function respond(int $status, AdminAppList|AdminAppView|CommandResult|RequestFailed $body, array $headers = []): Response
125    {
126        return new Response($status, [...self::JSON_HEADERS, ...$headers], $this->codec->encodeResponse($body));
127    }
128}