Lines 100.00% 12 / 12
Functions and Methods 100.00% 1 / 1
Classes and Traits 100.00% 1 / 1
Name Lines Functions and Methods CRAP Classes and Traits
ConnectionMetricSource 100.00% 12 / 12 100.00% 1 / 1 3 100.00% 1 / 1
 collectMetrics 100.00% 12 / 12 100.00% 1 / 1 3
1<?php
2
3declare(strict_types=1);
4
5namespace Stewart\Runtime\Metrics\Source;
6
7use Stewart\Runtime\Control\Protocol\Status\RuntimeSnapshot;
8use Stewart\Runtime\Lifecycle\ConnectionPhase;
9use Stewart\Runtime\Metrics\Exposition\MetricFamily;
10use Stewart\Runtime\Metrics\Exposition\MetricLabels;
11use Stewart\Runtime\Metrics\Exposition\MetricType;
12use Stewart\Runtime\Metrics\RuntimeMetricSource;
13
14final readonly class ConnectionMetricSource implements RuntimeMetricSource
15{
16    /** @return list<MetricFamily> */
17    public function collectMetrics(RuntimeSnapshot $snapshot): array
18    {
19        $connection = $snapshot->connection;
20        $phases = new MetricFamily('stewart_ha_connection_phase', 'Home Assistant connection phase; 1 for the current one.', MetricType::Gauge);
21
22        foreach (ConnectionPhase::cases() as $phase) {
23            $phases->recordSample(MetricLabels::fromLabel('phase', $phase->value), $phase === $connection->phase);
24        }
25
26        $lastOutage = new MetricFamily('stewart_ha_last_outage_seconds', 'Length of the last Home Assistant outage.', MetricType::Gauge);
27
28        if ($connection->lastOutage !== null) {
29            $lastOutage->recordSample(MetricLabels::none(), $connection->lastOutage->toSeconds());
30        }
31
32        return [
33            $phases,
34            MetricFamily::createWithSample('stewart_ha_reconnects_total', 'Home Assistant reconnects since the daemon started.', MetricType::Counter, MetricLabels::none(), $connection->reconnects),
35            $lastOutage,
36        ];
37    }
38}