Lines 98.55% 68 / 69
Functions and Methods 88.88% 8 / 9
Classes and Traits 0.00% 0 / 1
Name Lines Functions and Methods CRAP Classes and Traits
ConnectionChecks 98.55% 68 / 69 88.88% 8 / 9 27 0.00% 0 / 1
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 runConnectionChecks 90.00% 9 / 10 0.00% 0 / 1 4.02
 checkHttpListeners 100.00% 14 / 14 100.00% 1 / 1 6
 checkHomeAssistant 100.00% 8 / 8 100.00% 1 / 1 3
 checkConnectedHomeAssistant 100.00% 10 / 10 100.00% 1 / 1 2
 checkIntegrationIfEnabled 100.00% 5 / 5 100.00% 1 / 1 3
 checkLocation 100.00% 4 / 4 100.00% 1 / 1 2
 checkIntegration 100.00% 10 / 10 100.00% 1 / 1 3
 checkStore 100.00% 7 / 7 100.00% 1 / 1 3
1<?php
2
3declare(strict_types=1);
4
5namespace Stewart\Runtime\Console\Doctor;
6
7use Stewart\Client\Component\ComponentProtocol;
8use Stewart\Client\Component\ComponentVersion;
9use Stewart\Client\Connection\ConnectionConfig;
10use Stewart\Client\Exception\HaClientException;
11use Stewart\Client\HaClient;
12use Stewart\Client\HaClientFactory;
13use Stewart\Client\HaConfig;
14use Stewart\Contracts\Exception\StewartException;
15use Stewart\Contracts\Exception\StoreException;
16use Stewart\Runtime\Config\ConfigLoader;
17use Stewart\Runtime\Config\ExposeConfig;
18use Stewart\Runtime\Config\HttpConfig;
19use Stewart\Runtime\Config\PersistenceConfig;
20use Stewart\Runtime\Config\ProjectRoot;
21use Stewart\Runtime\Logging\LoggerFactory;
22use Stewart\Runtime\Model\LogLevel;
23use Stewart\Store\Exception\StoreSetupException;
24use Stewart\Store\StoreBackendConnector;
25use Stewart\Store\StoreTiming;
26
27final readonly class ConnectionChecks
28{
29    private const string ENVIRONMENT_FILE = '.env';
30
31    public function __construct(
32        private ConfigLoader $configs,
33        private ProjectRoot $projectRoot,
34        private HaClientFactory $haClients,
35        private StoreBackendConnector $storeBackends,
36        private LoggerFactory $loggers,
37    ) {}
38
39    /** @return list<DoctorFinding> */
40    public function runConnectionChecks(?string $configPath): array
41    {
42        $environmentFile = is_file($this->projectRoot->resolvePath(self::ENVIRONMENT_FILE))
43            ? new DoctorFinding('.env', DoctorOutcome::Pass, 'found')
44            : new DoctorFinding('.env', DoctorOutcome::Warn, 'missing; `make env` creates it, unless the environment sets everything');
45
46        try {
47            $config = $this->configs->loadConfig($configPath);
48        } catch (StewartException $e) {
49            return [$environmentFile, new DoctorFinding('config', DoctorOutcome::Fail, $e->getMessage())];
50        }
51
52        $configFile = $this->configs->findMissingDefaultFile($configPath) === null
53            ? new DoctorFinding('config', DoctorOutcome::Pass, 'loads')
54            : new DoctorFinding('config', DoctorOutcome::Pass, 'loads from the environment; there is no stewart.yaml');
55
56        return [$environmentFile, $configFile, ...$this->checkHttpListeners($config->http), ...$this->checkHomeAssistant($config->homeAssistant, $config->expose), $this->checkStore($config->persistence)];
57    }
58
59    /** @return list<DoctorFinding> */
60    private function checkHttpListeners(HttpConfig $http): array
61    {
62        $listeners = array_filter([
63            'probe' => $http->listen,
64            'admin' => $http->admin->listen,
65            'metrics' => $http->metrics->listen,
66        ]);
67
68        if ($listeners === []) {
69            return [];
70        }
71
72        try {
73            $http->requireValidListeners();
74        } catch (StewartException $e) {
75            return [new DoctorFinding('http', DoctorOutcome::Fail, $e->getMessage())];
76        }
77
78        $described = [];
79
80        foreach ($listeners as $role => $address) {
81            $described[] = $role === 'metrics' && $http->metrics->token === null ? \sprintf('%s %s (no token)', $role, $address) : \sprintf('%s %s', $role, $address);
82        }
83
84        return [new DoctorFinding('http', DoctorOutcome::Pass, implode(', ', $described))];
85    }
86
87    /** @return list<DoctorFinding> */
88    private function checkHomeAssistant(?ConnectionConfig $connection, ExposeConfig $expose): array
89    {
90        if ($connection === null) {
91            return [new DoctorFinding('connection', DoctorOutcome::Skip, 'set STEWART_HOME_ASSISTANT__URL and STEWART_HOME_ASSISTANT__TOKEN in .env')];
92        }
93
94        $client = $this->haClients->createClient($connection, $this->loggers->createStdoutLogger(LogLevel::Error));
95
96        try {
97            $client->connect();
98
99            return $this->checkConnectedHomeAssistant($client, $connection, $expose);
100        } catch (HaClientException $e) {
101            return [new DoctorFinding('connection', DoctorOutcome::Fail, $e->getMessage())];
102        } finally {
103            $client->close();
104        }
105    }
106
107    /**
108     * @return list<DoctorFinding>
109     * @throws HaClientException
110     */
111    private function checkConnectedHomeAssistant(HaClient $client, ConnectionConfig $connection, ExposeConfig $expose): array
112    {
113        $user = $client->fetchCurrentUser();
114        $userName = $user->name ?? $user->id;
115
116        return [
117            new DoctorFinding('connection', DoctorOutcome::Pass, \sprintf('Home Assistant %s at %s', $client->getHaVersion() ?? 'of unknown version', $connection->url)),
118            $user->isAdmin
119                ? new DoctorFinding('token', DoctorOutcome::Pass, \sprintf('belongs to %s, an administrator', $userName))
120                : new DoctorFinding('token', DoctorOutcome::Fail, \sprintf('belongs to %s, who is not an administrator; Stewart needs one to receive every event', $userName)),
121            $this->checkLocation($client->getConfig()),
122            $this->checkIntegrationIfEnabled($client, $user->isAdmin, $expose),
123        ];
124    }
125
126    /** @throws HaClientException */
127    private function checkIntegrationIfEnabled(HaClient $client, bool $asAdministrator, ExposeConfig $expose): DoctorFinding
128    {
129        if (!$expose->enabled) {
130            return new DoctorFinding('integration', DoctorOutcome::Skip, 'expose.enabled is off');
131        }
132
133        return $asAdministrator
134            ? $this->checkIntegration($client->findComponentVersion())
135            : new DoctorFinding('integration', DoctorOutcome::Skip, 'only an administrator token can ask for it');
136    }
137
138    private function checkLocation(HaConfig $haConfig): DoctorFinding
139    {
140        $location = $haConfig->location;
141
142        return $location === null
143            ? new DoctorFinding('location', DoctorOutcome::Warn, 'Home Assistant has none, so sun schedules fail; set it under Settings → System → General')
144            : new DoctorFinding('location', DoctorOutcome::Pass, \sprintf('%.4f, %.4f', $location->latitude, $location->longitude));
145    }
146
147    private function checkIntegration(?ComponentVersion $version): DoctorFinding
148    {
149        if ($version === null) {
150            return new DoctorFinding('integration', DoctorOutcome::Warn, 'not installed; apps need it only to expose entities');
151        }
152
153        return $version->isCompatible()
154            ? new DoctorFinding('integration', DoctorOutcome::Pass, 'version ' . $version->componentVersion)
155            : new DoctorFinding('integration', DoctorOutcome::Fail, \sprintf(
156                'version %s speaks protocol %d, Stewart speaks %d; install the integration of the same version as Stewart',
157                $version->componentVersion,
158                $version->protocol,
159                ComponentProtocol::VERSION,
160            ));
161    }
162
163    private function checkStore(PersistenceConfig $persistence): DoctorFinding
164    {
165        $url = $persistence->url;
166
167        if ($url === null) {
168            return new DoctorFinding('store', DoctorOutcome::Skip, 'persistence.url is not set, so apps that take a Store do not start');
169        }
170
171        try {
172            $this->storeBackends->connectToBackend($url, new StoreTiming($persistence->timeout, $persistence->recoveryInterval))->probe();
173        } catch (StoreException|StoreSetupException $e) {
174            return new DoctorFinding('store', DoctorOutcome::Fail, $e->getMessage());
175        }
176
177        return new DoctorFinding('store', DoctorOutcome::Pass, 'answers at ' . $url);
178    }
179}