Lines 95.23% 100 / 105
Methods 76.19% 16 / 21
Classes 0.00% 0 / 1
Name Lines Methods CRAP
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 open 93.33% 14 / 15 0.00% 0 / 1 2.00
 close 100.00% 4 / 4 100.00% 1 / 1 1
 isOpen 100.00% 1 / 1 100.00% 1 / 1 1
 isConnected 100.00% 1 / 1 100.00% 1 / 1 2
 snapshotStateCache 100.00% 3 / 3 100.00% 1 / 1 2
 snapshotRegistry 100.00% 4 / 4 100.00% 1 / 1 2
 refreshRegistry 87.50% 7 / 8 0.00% 0 / 1 4.03
 countEntities 100.00% 1 / 1 100.00% 1 / 1 1
 getTimeZone 100.00% 1 / 1 100.00% 1 / 1 1
 getHaVersion 0.00% 0 / 1 0.00% 0 / 1 2
 getHaUserId 100.00% 1 / 1 100.00% 1 / 1 1
 getLocation 100.00% 1 / 1 100.00% 1 / 1 1
 listEntityIds 100.00% 1 / 1 100.00% 1 / 1 1
 connectSubscribeAndSeed 100.00% 22 / 22 100.00% 1 / 1 2
 onStateUpdated 100.00% 6 / 6 100.00% 1 / 1 2
 onEventFired 66.66% 2 / 3 0.00% 0 / 1 3.33
 onTriggerFired 100.00% 3 / 3 100.00% 1 / 1 4
 onTriggerRejected 100.00% 2 / 2 100.00% 1 / 1 1
 onDisconnected 91.66% 11 / 12 0.00% 0 / 1 4.01
 reconnectAfterOutage 100.00% 14 / 14 100.00% 1 / 1 3
31final class WebsocketHaSession implements HaSession
32{
33    private HaSessionListener $listener;
34
35    private int $revision = 0;
36
37    private bool $open = false;
38
39    private readonly DeferredCancellation $stop;
40
41    private bool $reconnecting = false;
42
43    private bool $establishing = false;
44
45    /** @var array<string, StateUpdate> */
46    private array $pendingUpdates = [];
47
48    private ?HaSiteSettings $siteSettings = null;
49
50    private ?string $haUserId = null;
51
52    private ?StateCacheSnapshot $stateCacheSnapshot = null;
53
54    private ?RegistryCacheSnapshot $registryCacheSnapshot = null;
55
56    public function __construct(
57        private readonly HaClient $client,
58        private readonly Reconnector $reconnector,
59        private readonly LoggerInterface $logger,
60        private readonly Clock $clock,
61        private readonly StateCache $states,
62        private readonly RegistryCache $registry,
63        private readonly HaTriggerLink $triggers,
64        private readonly ComponentSession $componentSession,
65        private readonly ExposureLink $exposures,
66    ) {
67        $this->stop = new DeferredCancellation();
68    }
69
70    public function open(HaSessionListener $listener): void
71    {
72        $this->listener = $listener;
73        $this->open = true;
74        $this->triggers->onTriggerFired($this->onTriggerFired(...));
75        $this->triggers->onTriggerRejected($this->onTriggerRejected(...));
76        $this->exposures->onEntitySynced($listener->exposedEntitySynced(...));
77        $this->exposures->onEntityCommanded($listener->exposedEntityCommanded(...));
78
79        $this->reconnector->retryUntilConnected($this->connectSubscribeAndSeed(...), $this->stop->getCancellation());
80
81        if (!$this->isOpen()) {
82            return;
83        }
84
85        $this->client->onDisconnect($this->onDisconnected(...));
86
87        $this->logger->info('Connected to Home Assistant', [
88            'ha_version' => $this->client->getHaVersion(),
89            'entities' => $this->states->count(),
90            'time_zone' => $this->getTimeZone()->getName(),
91        ]);
92    }
93
94    public function close(): void
95    {
96        $this->open = false;
97        $this->stop->cancel();
98        $this->componentSession->markLinkLost();
99        $this->client->close();
100    }
101
102    private function isOpen(): bool
103    {
104        return $this->open;
105    }
106
107    public function isConnected(): bool
108    {
109        return $this->open && !$this->reconnecting;
110    }
111
112    public function snapshotStateCache(): StateCacheSnapshot
113    {
114        if ($this->stateCacheSnapshot?->revision !== $this->revision) {
115            $this->stateCacheSnapshot = new StateCacheSnapshot(EntityStatesFragment::fromCollection($this->states->getAllStates()), $this->revision);
116        }
117
118        return $this->stateCacheSnapshot;
119    }
120
121    public function snapshotRegistry(): RegistryCacheSnapshot
122    {
123        $revision = $this->registry->getRevision();
124
125        if ($this->registryCacheSnapshot?->revision !== $revision) {
126            $this->registryCacheSnapshot = new RegistryCacheSnapshot(RegistryFragment::fromRegistry($this->registry->getIndexedRegistry()), $revision);
127        }
128
129        return $this->registryCacheSnapshot;
130    }
131
132    public function refreshRegistry(): bool
133    {
134        if (!$this->isConnected() || $this->establishing) {
135            return false;
136        }
137
138        try {
139            $registry = $this->client->getRegistry();
140        } catch (HaClientException $e) {
141            $this->logger->warning('Could not refresh the Home Assistant registry; the previous one stays', ['exception' => $e]);
142
143            return false;
144        }
145
146        $this->registry->replaceAsNextRevision($registry);
147
148        return true;
149    }
150
151    public function countEntities(): int
152    {
153        return $this->states->count();
154    }
155
156    public function getTimeZone(): DateTimeZone
157    {
158        return $this->siteSettings->timeZone ?? new DateTimeZone('UTC');
159    }
160
161    public function getHaVersion(): ?string
162    {
163        return $this->client->getHaVersion();
164    }
165
166    public function getHaUserId(): ?string
167    {
168        return $this->haUserId;
169    }
170
171    public function getLocation(): ?GeoLocation
172    {
173        return $this->siteSettings?->location;
174    }
175
176    public function listEntityIds(): array
177    {
178        return $this->states->listEntityIds()->toStrings();
179    }
180
181    private function connectSubscribeAndSeed(): void
182    {
183        // Subscribe before seeding and buffer updates in between, so no update is lost.
184        $this->triggers->markLinkLost();
185        $this->componentSession->markLinkLost();
186        $this->client->close();
187        $this->client->connect();
188        $this->establishing = true;
189
190        try {
191            $this->client->subscribeStateUpdatesAndEvents($this->onStateUpdated(...), $this->onEventFired(...));
192            $this->triggers->resubscribeAll();
193            $this->componentSession->openSession();
194            $this->siteSettings ??= $this->client->getSiteSettings();
195            $this->haUserId ??= $this->client->getCurrentUserId();
196            $states = $this->client->getStates();
197            $registry = $this->client->getRegistry();
198            $this->client->flushEvents();
199
200            $this->establishing = false;
201            $this->registry->replaceAsNextRevision($registry);
202            $this->states->replaceAll($states);
203
204            foreach ($this->pendingUpdates as $update) {
205                $this->states->applyUpdate($update);
206            }
207
208            ++$this->revision;
209        } finally {
210            $this->establishing = false;
211            $this->pendingUpdates = [];
212        }
213
214        $this->componentSession->startRelinkingUnlessSettled();
215    }
216
217    private function onStateUpdated(StateUpdate $update): void
218    {
219        if ($this->establishing) {
220            $this->pendingUpdates[$update->entityId->value] = $update;
221
222            return;
223        }
224
225        $this->states->applyUpdate($update);
226        ++$this->revision;
227
228        $this->listener->stateUpdated($update);
229    }
230
231    private function onEventFired(HaEvent $event): void
232    {
233        // Dropped until the state cache is rebuilt; handlers would read pre-outage state.
234        if ($this->establishing || $this->reconnecting) {
235            return;
236        }
237
238        $this->listener->eventFired($event);
239    }
240
241    private function onTriggerFired(TriggerSpec $spec, TriggerEvent $event): void
242    {
243        if ($this->establishing || $this->reconnecting) {
244            return;
245        }
246
247        $this->listener->triggerFired($spec, $event->firedAt === null ? $event->withFiredAt($this->clock->getNow()) : $event);
248    }
249
250    private function onTriggerRejected(TriggerSpec $spec, string $reason): void
251    {
252        $this->logger->error('Home Assistant rejected a trigger subscription', ['platforms' => $spec->listPlatforms(), 'reason' => $reason]);
253
254        $this->listener->triggerRejected($spec, $reason);
255    }
256
257    private function onDisconnected(HaClientException $lost): void
258    {
259        if (!$this->open || $this->reconnecting) {
260            return;
261        }
262
263        $this->triggers->markLinkLost();
264        $this->componentSession->markLinkLost();
265
266        $this->reconnecting = true;
267        $startedAt = $this->clock->getMonotonicTime();
268
269        $this->listener->connectionLost($lost->getMessage(), $this->clock->getNow());
270
271        async(function () use ($startedAt): void {
272            try {
273                $this->reconnectAfterOutage($startedAt);
274            } catch (Throwable $e) {
275                $this->logger->error('Failed handling a Home Assistant reconnect', ['exception' => $e]);
276            }
277        })->ignore();
278    }
279
280    private function reconnectAfterOutage(MonotonicTime $startedAt): void
281    {
282        try {
283            $this->reconnector->retryUntilConnected($this->connectSubscribeAndSeed(...), $this->stop->getCancellation());
284        } catch (Throwable $e) {
285            $this->reconnecting = false;
286            $this->listener->connectionFailed($e);
287
288            return;
289        }
290
291        $this->reconnecting = false;
292
293        if (!$this->isOpen()) {
294            return;
295        }
296
297        $outage = $this->clock->getMonotonicTime()->elapsedSince($startedAt);
298
299        $this->logger->info('Reconnected to Home Assistant', [
300            'outage' => (string) $outage,
301            'entities' => $this->states->count(),
302        ]);
303
304        $this->listener->reconnected($outage);
305    }
306}