Lines 92.22% 166 / 180
Functions and Methods 75.00% 21 / 28
Classes and Traits 0.00% 0 / 1
Name Lines Functions and Methods CRAP Classes and Traits
HaConnection 92.22% 166 / 180 75.00% 21 / 28 78.72 0.00% 0 / 1
 __construct 100.00% 3 / 3 100.00% 1 / 1 1
 connect 100.00% 27 / 27 100.00% 1 / 1 5
 flushEvents 100.00% 1 / 1 100.00% 1 / 1 1
 send 100.00% 6 / 6 100.00% 1 / 1 2
 subscribeEvents 100.00% 8 / 8 100.00% 1 / 1 2
 unsubscribeEvents 100.00% 2 / 2 100.00% 1 / 1 1
 sendIgnoringResult 100.00% 1 / 1 100.00% 1 / 1 1
 onDisconnect 100.00% 1 / 1 100.00% 1 / 1 1
 isConnected 100.00% 1 / 1 100.00% 1 / 1 1
 close 100.00% 7 / 7 100.00% 1 / 1 1
 openSocket 66.66% 4 / 6 0.00% 0 / 1 3.33
 defaultConnector 100.00% 13 / 13 100.00% 1 / 1 2
 sendAndAwaitResponse 94.44% 17 / 18 0.00% 0 / 1 4.00
 authenticate 78.94% 15 / 19 0.00% 0 / 1 7.46
 declareSupportedFeatures 100.00% 2 / 2 100.00% 1 / 1 1
 receiveMessage 100.00% 2 / 2 100.00% 1 / 1 1
 receiveLoop 100.00% 8 / 8 100.00% 1 / 1 5
 handleConnectionLost 83.33% 10 / 12 0.00% 0 / 1 4.07
 decodeMessageBatchOrLog 100.00% 4 / 4 100.00% 1 / 1 2
 dispatchMessage 71.42% 5 / 7 0.00% 0 / 1 5.58
 dispatchEvent 100.00% 6 / 6 100.00% 1 / 1 4
 convertCloseToLoss 100.00% 4 / 4 100.00% 1 / 1 5
 assertSuccess 87.50% 7 / 8 0.00% 0 / 1 6.07
 encodeMessage 33.33% 1 / 3 0.00% 0 / 1 3.19
 decodeMessage 100.00% 1 / 1 100.00% 1 / 1 1
 decodeMessageBatch 100.00% 4 / 4 100.00% 1 / 1 4
 decodeJsonPayload 100.00% 3 / 3 100.00% 1 / 1 2
 requireObjectMessage 100.00% 3 / 3 100.00% 1 / 1 2
1<?php
2
3declare(strict_types=1);
4
5namespace Stewart\Client\Connection;
6
7use Amp\Cancellation;
8use Amp\CancelledException;
9use Amp\CompositeCancellation;
10use Amp\DeferredCancellation;
11use Amp\Websocket\Client\Rfc6455ConnectionFactory;
12use Amp\Websocket\Client\Rfc6455Connector;
13use Amp\Websocket\Client\WebsocketConnection;
14use Amp\Websocket\Client\WebsocketConnector;
15use Amp\Websocket\Client\WebsocketHandshake;
16use Amp\Websocket\Parser\Rfc6455ParserFactory;
17use Amp\Websocket\PeriodicHeartbeatQueue;
18use Amp\Websocket\WebsocketCloseCode;
19use Amp\Websocket\WebsocketCloseInfo;
20use Closure;
21use JsonException;
22use Psr\Log\LoggerInterface;
23use Psr\Log\NullLogger;
24use Stewart\Client\Connection\Command\Authenticate;
25use Stewart\Client\Connection\Command\DeclareSupportedFeatures;
26use Stewart\Client\Connection\Command\HaCommand;
27use Stewart\Client\Connection\Command\SubscriptionCommand;
28use Stewart\Client\Connection\Command\UnsubscribeEvents;
29use Stewart\Client\Exception\HaClientError;
30use Stewart\Client\Exception\HaClientException;
31use Stewart\Support\Json\JsonDecoder;
32use Stewart\Support\Json\JsonEncoder;
33use Stewart\Support\Json\JsonShape;
34use Stewart\Support\Time\Deadlines;
35use Throwable;
36
37use function Amp\async;
38
39/** @internal */
40final class HaConnection
41{
42    private const string UNAUTHORIZED_ERROR_CODE = 'unauthorized';
43
44    private ?WebsocketConnection $socket = null;
45
46    private readonly MessageCorrelator $correlator;
47
48    /** @var array<int, Closure(array<string, mixed>): void> */
49    private array $eventHandlers = [];
50
51    public private(set) ?string $haVersion = null;
52
53    private ?DeferredCancellation $connecting = null;
54
55    /** @var (Closure(HaClientException): void)|null */
56    private ?Closure $onDisconnect = null;
57
58    private EventDelivery $events;
59
60    private ?WebsocketConnector $connector;
61
62    public function __construct(
63        private readonly ConnectionConfig $config,
64        private readonly Deadlines $deadlines,
65        private readonly LoggerInterface $logger = new NullLogger(),
66        ?WebsocketConnector $connector = null,
67    ) {
68        $this->connector = $connector;
69        $this->correlator = new MessageCorrelator();
70        $this->events = new EventDelivery($config->eventBufferLimit, $logger);
71    }
72
73    public function connect(): void
74    {
75        if ($this->socket !== null) {
76            $this->close();
77        }
78
79        $this->logger->debug('Connecting to Home Assistant', ['url' => (string) $this->config->url]);
80
81        $this->connecting = $connecting = new DeferredCancellation();
82        $cancellation = new CompositeCancellation(
83            $connecting->getCancellation(),
84            $this->deadlines->timeout($this->config->connectTimeout),
85        );
86
87        try {
88            $socket = $this->openSocket($cancellation);
89
90            try {
91                $this->authenticate($socket, $cancellation);
92                $this->declareSupportedFeatures($socket);
93            } catch (Throwable $e) {
94                $socket->close();
95
96                throw $e;
97            }
98        } catch (CancelledException $e) {
99            throw $connecting->isCancelled()
100                ? HaClientException::createForReason(HaClientError::ClosedLocally, phase: 'it was being established')
101                : HaClientException::createForReason(
102                    HaClientError::ConnectTimedOut,
103                    $e,
104                    url: (string) $this->config->url,
105                    timeout: (string) $this->config->connectTimeout,
106                );
107        } finally {
108            $this->connecting = null;
109        }
110
111        $this->socket = $socket;
112        $this->events = new EventDelivery($this->config->eventBufferLimit, $this->logger);
113
114        async(fn() => $this->receiveLoop($socket))->ignore();
115    }
116
117    public function flushEvents(): void
118    {
119        $this->events->flush();
120    }
121
122    /** @return array<array-key, mixed> */
123    public function send(HaCommand $command): array
124    {
125        $response = $this->sendAndAwaitResponse($this->correlator->nextId(), $command);
126        self::assertSuccess($response, $command);
127
128        $result = $response['result'] ?? null;
129
130        return \is_array($result)
131            ? $result
132            : throw HaClientException::protocolViolation(\sprintf('a non-object result for %s', $command->describe()));
133    }
134
135    /** @param Closure(array<string, mixed>): void $handler */
136    public function subscribeEvents(SubscriptionCommand $command, Closure $handler): int
137    {
138        $id = $this->correlator->nextId();
139        $this->eventHandlers[$id] = $handler;
140
141        try {
142            self::assertSuccess($this->sendAndAwaitResponse($id, $command), $command);
143        } catch (Throwable $e) {
144            unset($this->eventHandlers[$id]);
145
146            throw $e;
147        }
148
149        $this->logger->debug('Subscribed to Home Assistant events', ['command' => $command->describe(), 'id' => $id]);
150
151        return $id;
152    }
153
154    public function unsubscribeEvents(int $subscriptionId): void
155    {
156        unset($this->eventHandlers[$subscriptionId]);
157
158        $this->sendIgnoringResult(new UnsubscribeEvents($subscriptionId));
159    }
160
161    public function sendIgnoringResult(HaCommand $command): void
162    {
163        self::assertSuccess($this->sendAndAwaitResponse($this->correlator->nextId(), $command), $command);
164    }
165
166    /** @param Closure(HaClientException): void $handler */
167    public function onDisconnect(Closure $handler): void
168    {
169        $this->onDisconnect = $handler;
170    }
171
172    public function isConnected(): bool
173    {
174        return $this->socket !== null;
175    }
176
177    public function close(): void
178    {
179        $this->connecting?->cancel();
180
181        $socket = $this->socket;
182        $this->socket = null;
183        $this->eventHandlers = [];
184
185        $this->events->close();
186        $this->correlator->failAll(HaClientException::createForReason(HaClientError::ClosedLocally, phase: 'commands were waiting for an answer'));
187
188        $socket?->close();
189    }
190
191    private function openSocket(Cancellation $cancellation): WebsocketConnection
192    {
193        $this->connector ??= $this->defaultConnector();
194
195        try {
196            return $this->connector->connect(new WebsocketHandshake($this->config->url->reveal()), $cancellation);
197        } catch (CancelledException $e) {
198            throw $e;
199        } catch (Throwable $e) {
200            throw HaClientException::createForReason(HaClientError::ConnectFailed, $e, url: (string) $this->config->url);
201        }
202    }
203
204    private function defaultConnector(): WebsocketConnector
205    {
206        $interval = $this->config->heartbeatInterval;
207
208        return new Rfc6455Connector(
209            connectionFactory: new Rfc6455ConnectionFactory(
210                heartbeatQueue: $interval === null
211                    ? null
212                    : new PeriodicHeartbeatQueue(max(1, $this->config->heartbeatMissedLimit), max(1, (int) round($interval->toSeconds()))),
213                parserFactory: new Rfc6455ParserFactory(
214                    // json_decode() rejects invalid UTF-8 anyway.
215                    validateUtf8: false,
216                    messageSizeLimit: $this->config->messageSizeLimit,
217                    frameSizeLimit: $this->config->frameSizeLimit,
218                ),
219            ),
220        );
221    }
222
223    /** @return array<string, mixed> */
224    private function sendAndAwaitResponse(int $id, HaCommand $command): array
225    {
226        $socket = $this->socket ?? throw HaClientException::createForReason(HaClientError::NotConnected);
227        $description = $command->describe();
228        $payload = self::encodeMessage([...$command->toMessage(), 'id' => $id], $description);
229        $future = $this->correlator->expect($id);
230
231        try {
232            try {
233                $socket->sendText($payload);
234            } catch (Throwable $e) {
235                // A close or drop during the send already failed this command with the real cause.
236                if ($future->isComplete()) {
237                    $future->await();
238                }
239
240                throw HaClientException::createForReason(HaClientError::SendFailed, $e, command: $description);
241            }
242
243            return $future->await($this->deadlines->timeout($this->config->commandTimeout));
244        } catch (CancelledException $e) {
245            throw HaClientException::createForReason(
246                HaClientError::CommandTimedOut,
247                $e,
248                command: $description,
249                timeout: (string) $this->config->commandTimeout,
250            );
251        } finally {
252            $this->correlator->forget($id);
253        }
254    }
255
256    private function authenticate(WebsocketConnection $socket, Cancellation $cancellation): void
257    {
258        $greeting = $this->receiveMessage($socket, $cancellation);
259
260        if (($greeting['type'] ?? null) !== 'auth_required') {
261            throw HaClientException::createForReason(
262                HaClientError::UnexpectedGreeting,
263                receivedType: \is_scalar($greeting['type'] ?? null) ? (string) $greeting['type'] : 'nothing',
264            );
265        }
266
267        $this->haVersion = \is_string($greeting['ha_version'] ?? null) ? $greeting['ha_version'] : 'unknown';
268
269        $socket->sendText(self::encodeMessage(new Authenticate($this->config->token)->toMessage(), 'auth'));
270
271        $response = $this->receiveMessage($socket, $cancellation);
272
273        if (($response['type'] ?? null) !== 'auth_ok') {
274            throw HaClientException::createForReason(
275                HaClientError::TokenRejected,
276                reason: \is_string($response['message'] ?? null) ? $response['message'] : 'no reason given',
277            );
278        }
279
280        $this->haVersion = \is_string($response['ha_version'] ?? null) ? $response['ha_version'] : $this->haVersion;
281
282        $this->logger->info('Authenticated with Home Assistant', [
283            'url' => (string) $this->config->url,
284            'ha_version' => $this->haVersion,
285        ]);
286    }
287
288    // The answer is not awaited: a refusal only means Home Assistant keeps sending one message per frame.
289    private function declareSupportedFeatures(WebsocketConnection $socket): void
290    {
291        $command = new DeclareSupportedFeatures();
292
293        $socket->sendText(self::encodeMessage([...$command->toMessage(), 'id' => $this->correlator->nextId()], $command->describe()));
294    }
295
296    /** @return array<string, mixed> */
297    private function receiveMessage(WebsocketConnection $socket, Cancellation $cancellation): array
298    {
299        $message = $socket->receive($cancellation) ?? throw HaClientException::createForReason(HaClientError::ClosedDuringAuthentication);
300
301        return self::decodeMessage($message->buffer());
302    }
303
304    private function receiveLoop(WebsocketConnection $socket): void
305    {
306        try {
307            while (($message = $socket->receive()) !== null) {
308                foreach ($this->decodeMessageBatchOrLog($message->buffer()) as $decoded) {
309                    $this->dispatchMessage($decoded);
310                }
311            }
312
313            $lost = self::convertCloseToLoss($socket->getCloseInfo());
314        } catch (Throwable $e) {
315            $lost = $e instanceof HaClientException ? $e : HaClientException::connectionDropped('socket failed: ' . $e->getMessage(), $e);
316        }
317
318        $this->handleConnectionLost($socket, $lost);
319        $socket->close();
320    }
321
322    private function handleConnectionLost(WebsocketConnection $socket, HaClientException $lost): void
323    {
324        if ($this->socket !== $socket) {
325            return;
326        }
327
328        $this->socket = null;
329        $this->eventHandlers = [];
330        $this->events->close();
331        $abandoned = $this->correlator->failAll($lost);
332
333        $this->logger->warning($lost->getMessage(), ['abandoned_commands' => $abandoned]);
334
335        if ($this->onDisconnect === null) {
336            return;
337        }
338
339        try {
340            ($this->onDisconnect)($lost);
341        } catch (Throwable $e) {
342            $this->logger->error('Disconnect handler failed', ['exception' => $e]);
343        }
344    }
345
346    /** @return list<array<string, mixed>> */
347    private function decodeMessageBatchOrLog(string $payload): array
348    {
349        try {
350            return self::decodeMessageBatch($payload);
351        } catch (HaClientException $e) {
352            $this->logger->error('Failed handling a Home Assistant message', ['exception' => $e]);
353
354            return [];
355        }
356    }
357
358    /** @param array<string, mixed> $message */
359    private function dispatchMessage(array $message): void
360    {
361        $id = $message['id'] ?? null;
362
363        if (!\is_int($id)) {
364            return;
365        }
366
367        match ($message['type'] ?? null) {
368            'result' => $this->correlator->resolve($id, $message),
369            'event' => $this->dispatchEvent($id, $message),
370            default => null,
371        };
372    }
373
374    /** @param array<string, mixed> $message */
375    private function dispatchEvent(int $id, array $message): void
376    {
377        $handler = $this->eventHandlers[$id] ?? null;
378        $event = $message['event'] ?? null;
379
380        if ($handler === null || !\is_array($event)) {
381            return;
382        }
383
384        if ($this->events->enqueue($handler, JsonShape::treatKeysAsStrings($event)) === EnqueueOutcome::Full) {
385            throw HaClientException::createForReason(HaClientError::EventBacklogExceeded, limit: $this->config->eventBufferLimit);
386        }
387    }
388
389    // amphp reports its own parser's size check as a close by the peer, so the code decides that case.
390    private static function convertCloseToLoss(WebsocketCloseInfo $close): HaClientException
391    {
392        $reason = $close->getReason();
393
394        return match (true) {
395            $close->getCode() === WebsocketCloseCode::MESSAGE_TOO_LARGE => HaClientException::createForReason(HaClientError::MessageTooLarge),
396            $close->isByPeer() => HaClientException::connectionDropped($reason === '' ? 'closed by Home Assistant' : 'closed by Home Assistant: ' . $reason),
397            default => HaClientException::connectionDropped(ltrim(\sprintf('%s (close code %d)', $reason, $close->getCode()))),
398        };
399    }
400
401    /** @param array<string, mixed> $response */
402    private static function assertSuccess(array $response, HaCommand $command): void
403    {
404        if (($response['success'] ?? false) === true) {
405            return;
406        }
407
408        $error = \is_array($response['error'] ?? null) ? $response['error'] : [];
409        $message = \is_string($error['message'] ?? null) ? $error['message'] : 'unknown error';
410        $code = \is_scalar($error['code'] ?? null) ? (string) $error['code'] : null;
411
412        throw $code === self::UNAUTHORIZED_ERROR_CODE
413            ? HaClientException::createForReason(HaClientError::CommandUnauthorized, command: $command->describe(), detail: $message, errorCode: $code)
414            : HaClientException::createForReason(HaClientError::CommandRejected, command: $command->describe(), detail: $message, errorCode: $code);
415    }
416
417    /** @param array<string, mixed> $message */
418    private static function encodeMessage(array $message, string $description): string
419    {
420        try {
421            return JsonEncoder::encodeToJson($message);
422        } catch (JsonException $e) {
423            throw HaClientException::commandUnencodable($description, $e);
424        }
425    }
426
427    /** @return array<string, mixed> */
428    private static function decodeMessage(string $payload): array
429    {
430        return self::requireObjectMessage(self::decodeJsonPayload($payload));
431    }
432
433    // With coalesce_messages, Home Assistant sends the messages it queued as one JSON array.
434    /** @return list<array<string, mixed>> */
435    private static function decodeMessageBatch(string $payload): array
436    {
437        $decoded = self::decodeJsonPayload($payload);
438
439        return \is_array($decoded) && $decoded !== [] && array_is_list($decoded)
440            ? array_map(self::requireObjectMessage(...), $decoded)
441            : [self::requireObjectMessage($decoded)];
442    }
443
444    private static function decodeJsonPayload(string $payload): mixed
445    {
446        try {
447            return JsonDecoder::decodeJson($payload);
448        } catch (JsonException $e) {
449            throw HaClientException::protocolViolation('a message that is not JSON', $e);
450        }
451    }
452
453    /** @return array<string, mixed> */
454    private static function requireObjectMessage(mixed $decoded): array
455    {
456        if (!\is_array($decoded)) {
457            throw HaClientException::protocolViolation('a non-object message');
458        }
459
460        return JsonShape::treatKeysAsStrings($decoded);
461    }
462}