Lines 90.47% 19 / 21
Functions and Methods 75.00% 3 / 4
Classes and Traits 0.00% 0 / 1
Name Lines Functions and Methods CRAP Classes and Traits
RegistryRefresher 90.47% 19 / 21 75.00% 3 / 4 8.06 0.00% 0 / 1
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 scheduleRefreshFor 100.00% 4 / 4 100.00% 1 / 1 2
 startRefresh 84.61% 11 / 13 0.00% 0 / 1 3.03
 refreshAndBroadcast 100.00% 3 / 3 100.00% 1 / 1 2
1<?php
2
3declare(strict_types=1);
4
5namespace Stewart\Runtime\Broker;
6
7use Psr\Log\LoggerInterface;
8use Stewart\Contracts\Event\HaEvent;
9use Stewart\Contracts\Time\Duration;
10use Stewart\Support\Time\TimerHandle;
11use Stewart\Support\Time\Timers;
12use Throwable;
13
14use function Amp\async;
15
16final class RegistryRefresher
17{
18    private const array REFRESHING_EVENT_TYPES = [
19        'area_registry_updated',
20        'floor_registry_updated',
21        'label_registry_updated',
22        'device_registry_updated',
23        'entity_registry_updated',
24    ];
25
26    private const int QUIET_PERIOD_MILLISECONDS = 1000;
27
28    private ?TimerHandle $pendingRefresh = null;
29
30    private bool $refreshing = false;
31
32    private bool $refreshRequestedWhileRefreshing = false;
33
34    public function __construct(
35        private readonly HaSession $session,
36        private readonly WorkerSlotRegistry $slots,
37        private readonly Timers $timers,
38        private readonly GeneratedCodeDrift $drift,
39        private readonly LoggerInterface $logger,
40    ) {}
41
42    public function scheduleRefreshFor(HaEvent $event): void
43    {
44        if (!\in_array($event->type, self::REFRESHING_EVENT_TYPES, true)) {
45            return;
46        }
47
48        $this->pendingRefresh?->cancel();
49        $this->pendingRefresh = $this->timers->startTimer(Duration::milliseconds(self::QUIET_PERIOD_MILLISECONDS), $this->startRefresh(...));
50    }
51
52    private function startRefresh(): void
53    {
54        $this->pendingRefresh = null;
55
56        if ($this->refreshing) {
57            $this->refreshRequestedWhileRefreshing = true;
58
59            return;
60        }
61
62        $this->refreshing = true;
63
64        async(function (): void {
65            try {
66                do {
67                    $this->refreshRequestedWhileRefreshing = false;
68                    $this->refreshAndBroadcast();
69                } while ($this->refreshRequestedWhileRefreshing);
70            } catch (Throwable $e) {
71                $this->logger->error('Failed refreshing the Home Assistant registry', ['exception' => $e]);
72            } finally {
73                $this->refreshing = false;
74            }
75        })->ignore();
76    }
77
78    private function refreshAndBroadcast(): void
79    {
80        if ($this->session->refreshRegistry()) {
81            $this->slots->broadcast($this->session->snapshotRegistry()->toRegistrySnapshot());
82            $this->drift->recheckGeneratedCode();
83        }
84    }
85}