Lines
100.00%
22 / 22
Methods
100.00%
4 / 4
Classes
100.00%
1 / 1
| Name | Lines | Methods | CRAP | ||||
|---|---|---|---|---|---|---|---|
| __construct | 100.00% | 1 / 1 | 100.00% | 1 / 1 | 1 | ||
| handledMessageClass | 100.00% | 1 / 1 | 100.00% | 1 / 1 | 1 | ||
| handle | 100.00% | 14 / 14 | 100.00% | 1 / 1 | 3 | ||
| dispatchRestored | 100.00% | 6 / 6 | 100.00% | 1 / 1 | 1 | ||
| 18 | final readonly class StateResyncedHandler implements BrokerMessageHandler | |
| 19 | { | |
| 20 | public function __construct( | |
| 21 | private StateCacheSync $stateCacheSync, | |
| 22 | private ConnectionStatus $connection, | |
| 23 | private LocalDispatcher $dispatcher, | |
| 24 | private Clock $clock, | |
| 25 | private LoggerInterface $logger, | |
| 26 | ) {} | |
| 27 | ||
| 28 | public function handledMessageClass(): string | |
| 29 | { | |
| 30 | return StateResynced::class; | |
| 31 | } | |
| 32 | ||
| 33 | /** @param StateResynced $message */ | |
| 34 | public function handle(BrokerMessage $message): void | |
| 35 | { | |
| 36 | // Before the revision check, so a stale resync also ends the outage. | |
| 37 | $outageEnded = $this->connection->markRestored(); | |
| 38 | ||
| 39 | if (!$this->stateCacheSync->isOlderThan($message->revision)) { | |
| 40 | if ($outageEnded) { | |
| 41 | $this->dispatchRestored($this->clock->getNow(), $message, 0); | |
| 42 | } | |
| 43 | ||
| 44 | return; | |
| 45 | } | |
| 46 | ||
| 47 | $restoredAt = $this->clock->getNow(); | |
| 48 | $reconstructed = $this->stateCacheSync->replaceWithResyncedStates($message->states->collection, $message->revision, $restoredAt); | |
| 49 | ||
| 50 | $this->dispatcher->dispatchStateChanges($reconstructed); | |
| 51 | ||
| 52 | $this->logger->info('State rebuilt after losing Home Assistant', [ | |
| 53 | 'entities' => $this->stateCacheSync->countEntities(), | |
| 54 | 'outage' => (string) $message->outage, | |
| 55 | 'reconstructed_changes' => \count($reconstructed), | |
| 56 | ]); | |
| 57 | ||
| 58 | $this->dispatchRestored($restoredAt, $message, \count($reconstructed)); | |
| 59 | } | |
| 60 | ||
| 61 | private function dispatchRestored(Instant $restoredAt, StateResynced $message, int $reconstructedChanges): void | |
| 62 | { | |
| 63 | $this->dispatcher->dispatchConnection(new ConnectionRestored( | |
| 64 | restoredAt: $restoredAt, | |
| 65 | entityCount: $this->stateCacheSync->countEntities(), | |
| 66 | outage: $message->outage, | |
| 67 | reconstructedChanges: $reconstructedChanges, | |
| 68 | )); | |
| 69 | } | |
| 70 | } |