Lines 97.14% 34 / 35
Methods 87.50% 7 / 8
Classes 0.00% 0 / 1
Name Lines Methods CRAP
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 recordWorkerReady 100.00% 2 / 2 100.00% 1 / 1 1
 recordWorkerQuarantined 100.00% 2 / 2 100.00% 1 / 1 1
 scheduleOnceWorkersSettle 100.00% 7 / 7 100.00% 1 / 1 4
 restartAfterReload 100.00% 5 / 5 100.00% 1 / 1 1
 reconcileIfDue 90.00% 9 / 10 0.00% 0 / 1 5.03
 haveAllWorkersSettled 100.00% 1 / 1 100.00% 1 / 1 1
 buildReconcile 100.00% 7 / 7 100.00% 1 / 1 4
23final class ExposureReconciler
24{
25    private const int GRACE_SECONDS_AFTER_WORKERS_SETTLE = 30;
26
27    /** @var array<int, AppIdCollection> */
28    private array $runningAppsByWorker = [];
29
30    private bool $graceStarted = false;
31
32    private ?TimerHandle $grace = null;
33
34    private bool $due = false;
35
36    public function __construct(
37        private readonly AppTopology $topology,
38        private readonly ExposureLink $exposures,
39        private readonly HaClient $client,
40        private readonly ComponentTracker $tracker,
41        private readonly ExposeConfig $expose,
42        private readonly Timers $timers,
43        private readonly LoggerInterface $logger,
44    ) {}
45
46    public function recordWorkerReady(WorkerId $workerId, AppIdCollection $runningApps): void
47    {
48        $this->runningAppsByWorker[$workerId->value] = $runningApps;
49        $this->scheduleOnceWorkersSettle();
50    }
51
52    public function recordWorkerQuarantined(WorkerId $workerId): void
53    {
54        $this->runningAppsByWorker[$workerId->value] = AppIdCollection::empty();
55        $this->scheduleOnceWorkersSettle();
56    }
57
58    public function scheduleOnceWorkersSettle(): void
59    {
60        if (!$this->expose->prune || $this->graceStarted || !$this->haveAllWorkersSettled()) {
61            return;
62        }
63
64        $this->graceStarted = true;
65        $this->grace = $this->timers->startTimer(Duration::seconds(self::GRACE_SECONDS_AFTER_WORKERS_SETTLE), function (): void {
66            $this->due = true;
67            $this->reconcileIfDue();
68        });
69    }
70
71    public function restartAfterReload(): void
72    {
73        $this->grace?->cancel();
74        $this->grace = null;
75        $this->runningAppsByWorker = [];
76        $this->graceStarted = false;
77        $this->due = false;
78    }
79
80    public function reconcileIfDue(): void
81    {
82        if (!$this->due || !$this->tracker->isActive()) {
83            return;
84        }
85
86        $this->due = false;
87
88        try {
89            $removed = $this->client->reconcileExposedEntities($this->buildReconcile());
90        } catch (HaClientException $e) {
91            $this->due = true;
92            $this->logger->debug('Pruning exposed entities waits for the next stewart integration session', ['exception' => $e]);
93
94            return;
95        }
96
97        if (!$removed->isEmpty()) {
98            $this->logger->info('Removed exposed entities that no app exposes any more', ['entities' => $removed->toStrings()]);
99        }
100    }
101
102    private function haveAllWorkersSettled(): bool
103    {
104        return !$this->topology->getWorkerSlots()->containsWhere(fn(WorkerSlot $slot): bool => !isset($this->runningAppsByWorker[$slot->workerId->value]));
105    }
106
107    private function buildReconcile(): ExposedEntityReconcile
108    {
109        $keptApps = [];
110
111        foreach ($this->topology->getWorkerSlots() as $slot) {
112            $runningApps = $this->runningAppsByWorker[$slot->workerId->value] ?? AppIdCollection::empty();
113
114            foreach ($slot->listAppIds() as $appId) {
115                if (!$runningApps->containsId($appId)) {
116                    $keptApps[] = $appId;
117                }
118            }
119        }
120
121        return new ExposedEntityReconcile($this->expose->instance, $this->exposures->listKeptAddresses(), AppIdCollection::fromList($keptApps));
122    }
123}