Lines 85.71% 12 / 14
Functions and Methods 66.66% 2 / 3
Classes and Traits 0.00% 0 / 1
Name Lines Functions and Methods CRAP Classes and Traits
ReloadCheck 85.71% 12 / 14 66.66% 2 / 3 8.19 0.00% 0 / 1
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 runReloadCheck 71.42% 5 / 7 0.00% 0 / 1 4.37
 buildCommand 100.00% 6 / 6 100.00% 1 / 1 3
1<?php
2
3declare(strict_types=1);
4
5namespace Stewart\Runtime\Broker\Reload;
6
7use Amp\Cancellation;
8use Amp\CancelledException;
9use JsonException;
10use Stewart\Contracts\Exception\StewartException;
11use Stewart\Contracts\Time\Duration;
12use Stewart\Runtime\Broker\DaemonLaunchOptions;
13use Stewart\Runtime\Broker\Deploy\ExternalCommandRunner;
14use Stewart\Runtime\Exception\DeployException;
15
16final readonly class ReloadCheck
17{
18    private const string COMMAND = 'reload:check';
19
20    private const int CHECK_TIMEOUT_SECONDS = 120;
21
22    private const string UNEXPLAINED_FAILURE = 'reload:check failed without saying why';
23
24    // An Xdebug session per reload would stall the check under make debug.
25    private const array CHECK_ENVIRONMENT = ['XDEBUG_MODE' => 'off'];
26
27    public function __construct(
28        private ExternalCommandRunner $commands,
29        private ReloadCheckReportCodec $reports,
30        private DaemonLaunchOptions $launch,
31        private string $stewartConsoleScript,
32    ) {}
33
34    /** @throws CancelledException */
35    public function runReloadCheck(Cancellation $cancellation): ReloadCheckReport
36    {
37        try {
38            $result = $this->commands->runCommand($this->buildCommand(), Duration::seconds(self::CHECK_TIMEOUT_SECONDS), $cancellation, self::CHECK_ENVIRONMENT);
39        } catch (DeployException $e) {
40            return ReloadCheckReport::failed([$e->getMessage()]);
41        }
42
43        try {
44            return $this->reports->decodeReport(trim($result->output));
45        } catch (JsonException|StewartException) {
46            $reason = $result->findFirstErrorLine();
47
48            return ReloadCheckReport::failed([$reason === '' ? self::UNEXPLAINED_FAILURE : $reason]);
49        }
50    }
51
52    /** @return non-empty-list<string> */
53    private function buildCommand(): array
54    {
55        $command = [\PHP_BINARY, $this->stewartConsoleScript, self::COMMAND, '--no-ansi'];
56
57        if ($this->launch->configFile !== null) {
58            $command[] = '--config=' . $this->launch->configFile;
59        }
60
61        foreach ($this->launch->selection->onlyIds ?? [] as $appId) {
62            $command[] = '--only=' . $appId->value;
63        }
64
65        return $command;
66    }
67}