Lines 93.60% 205 / 219
Functions and Methods 65.00% 13 / 20
Classes and Traits 0.00% 0 / 1
Name Lines Functions and Methods CRAP Classes and Traits
StatusRenderer 93.60% 205 / 219 65.00% 13 / 20 77.51 0.00% 0 / 1
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 render 100.00% 8 / 8 100.00% 1 / 1 2
 renderDaemonTable 100.00% 22 / 22 100.00% 1 / 1 1
 renderWorkerTable 100.00% 21 / 21 100.00% 1 / 1 7
 renderAppTable 100.00% 24 / 24 100.00% 1 / 1 2
 renderSubscriptionTable 100.00% 15 / 15 100.00% 1 / 1 3
 renderScheduleTable 100.00% 12 / 12 100.00% 1 / 1 3
 formatAppState 83.33% 5 / 6 0.00% 0 / 1 4.07
 renderFailureTable 100.00% 6 / 6 100.00% 1 / 1 3
 describeConnection 100.00% 7 / 7 100.00% 1 / 1 3
 describeReconnects 66.66% 2 / 3 0.00% 0 / 1 2.15
 describeComponent 100.00% 12 / 12 100.00% 1 / 1 9
 describeStoreHealth 62.50% 5 / 8 0.00% 0 / 1 6.32
 describeMqtt 93.33% 14 / 15 0.00% 0 / 1 9.02
 describeDeploy 88.23% 15 / 17 0.00% 0 / 1 3.01
 describeReload 72.72% 8 / 11 0.00% 0 / 1 5.51
 describeGeneratedCode 100.00% 7 / 7 100.00% 1 / 1 4
 formatCalls 100.00% 7 / 7 100.00% 1 / 1 3
 formatLatency 100.00% 6 / 6 100.00% 1 / 1 5
 renderTable 72.72% 8 / 11 0.00% 0 / 1 2.08
1<?php
2
3declare(strict_types=1);
4
5namespace Stewart\Runtime\Console;
6
7use Stewart\Client\Component\ComponentProtocol;
8use Stewart\Contracts\Time\Instant;
9use Stewart\Runtime\Control\Protocol\Status\AppStatus;
10use Stewart\Runtime\Control\Protocol\Status\ComponentStatus;
11use Stewart\Runtime\Control\Protocol\Status\ConnectionState;
12use Stewart\Runtime\Control\Protocol\Status\DeployStatus;
13use Stewart\Runtime\Control\Protocol\Status\GeneratedCodeStatus;
14use Stewart\Runtime\Control\Protocol\Status\MqttStatus;
15use Stewart\Runtime\Control\Protocol\Status\RegistrationInfo;
16use Stewart\Runtime\Control\Protocol\Status\ReloadStatus;
17use Stewart\Runtime\Control\Protocol\Status\RuntimeSnapshot;
18use Stewart\Runtime\Control\Protocol\Status\ScheduleStatus;
19use Stewart\Runtime\Control\Protocol\Status\WorkerStatus;
20use Stewart\Runtime\Lifecycle\ComponentState;
21use Stewart\Runtime\Model\HaCallOutcome;
22use Stewart\Store\StoreHealth;
23use Symfony\Component\Console\Helper\Table;
24use Symfony\Component\Console\Output\OutputInterface;
25
26final readonly class StatusRenderer
27{
28    private const float LATENCY_QUANTILE = 0.95;
29
30    private const int SHORT_COMMIT_LENGTH = 7;
31
32    public function __construct(private StatusFormatter $formatter) {}
33
34    public function render(OutputInterface $output, RuntimeSnapshot $snapshot, StatusView $view = StatusView::Overview): void
35    {
36        // The daemon's clock, so skew between a remote daemon and this CLI does not distort ages.
37        $now = $snapshot->takenAt;
38
39        $this->renderDaemonTable($output, $snapshot, $now);
40        $this->renderWorkerTable($output, $snapshot, $now);
41        $this->renderAppTable($output, $snapshot, $now);
42
43        if ($view === StatusView::AppDetail) {
44            $this->renderSubscriptionTable($output, $snapshot, $now);
45            $this->renderScheduleTable($output, $snapshot, $now);
46        }
47
48        $this->renderFailureTable($output, $snapshot, $now);
49    }
50
51    private function renderDaemonTable(OutputInterface $output, RuntimeSnapshot $snapshot, Instant $now): void
52    {
53        $daemon = $snapshot->daemon;
54        $connection = $snapshot->connection;
55        $broker = $snapshot->broker;
56
57        $this->renderTable($output, 'Daemon', ['', ''], [
58            ['version', $daemon->version],
59            ['pid', (string) $daemon->pid],
60            ['up', $this->formatter->formatDuration($now->elapsedSince($daemon->startedAt))],
61            ['memory', $this->formatter->formatBytes($daemon->memoryBytes)],
62            ['home assistant', $this->describeConnection($snapshot, $now)],
63            ['reconnects', $this->describeReconnects($connection)],
64            ['component', $this->describeComponent($snapshot->component, $now)],
65            ['store', $this->describeStoreHealth($snapshot->store, $now)],
66            ['mqtt', $this->describeMqtt($snapshot->mqtt, $now)],
67            ['deploy', $this->describeDeploy($snapshot->deploy, $now)],
68            ['reload', $this->describeReload($snapshot->reload, $now)],
69            ['generated', $this->describeGeneratedCode($snapshot->generated, $now)],
70            ['entities', (string) $daemon->entities],
71            ['time zone', $daemon->timeZone],
72            ['workers', \sprintf('%d live of %d', $broker->liveWorkers, $broker->workers)],
73            ['HA calls', \sprintf('%d in flight, %d refused', $broker->inFlightHaCalls, $broker->refusedHaCalls)],
74            ['routing', \sprintf('%d subscriptions, %d patterns, cache %d hits / %d misses', $broker->routing->subscriptions, $broker->routing->patterns, $broker->routing->cacheHits, $broker->routing->cacheMisses)],
75        ]);
76    }
77
78    private function renderWorkerTable(OutputInterface $output, RuntimeSnapshot $snapshot, Instant $now): void
79    {
80        $this->renderTable(
81            $output,
82            'Workers',
83            ['worker', 'phase', 'pid', 'ready', 'apps', 'lag', 'memory', 'pong', 'missed', 'restarts', 'queued', 'dropped', 'batches', 'calls'],
84            array_map(fn(WorkerStatus $w): array => [
85                (string) $w->workerId,
86                $w->phase->value . ($w->restartDueAt === null ? '' : ' ' . $this->formatter->formatTimeUntil($w->restartDueAt, $now)),
87                $w->pid === null ? '-' : (string) $w->pid,
88                $this->formatter->formatYesNo($w->ready),
89                implode(', ', $w->appIds),
90                $this->formatter->formatElapsed($w->loopLag),
91                $this->formatter->formatBytes($w->memoryBytes),
92                $this->formatter->formatTimeAgo($w->lastPongAt, $now),
93                (string) $w->missedProbes,
94                $w->restarts === 0 ? '0' : \sprintf('%d (%d since start)', $w->restartsInWindow, $w->restarts),
95                $w->outbox === null ? '-' : (string) $w->outbox->queued,
96                $w->outbox === null ? '-' : (string) $w->outbox->dropped,
97                $w->outbox === null ? '-' : \sprintf('%d (%d coalesced)', $w->outbox->stateBatchesSent, $w->outbox->coalescedStateChanges),
98                (string) $w->inFlightHaCalls,
99            ], $snapshot->workers),
100        );
101    }
102
103    private function renderAppTable(OutputInterface $output, RuntimeSnapshot $snapshot, Instant $now): void
104    {
105        $this->renderTable(
106            $output,
107            'Apps',
108            ['app', 'worker', 'state', 'reported', 'last handled', 'next run', 'subs', 'schedules', 'exposed', 'delivered', 'dropped', 'suppressed', 'runs', 'publishes', 'calls ok/failed', 'p95', 'failures'],
109            array_map(fn(AppStatus $app): array => [
110                $app->id,
111                $app->workerId === null ? '-' : (string) $app->workerId,
112                $this->formatAppState($app, $now),
113                $this->formatter->formatTimeAgo($app->reportedAt, $now),
114                $this->formatter->formatTimeAgo($app->lastHandledAt, $now),
115                $this->formatter->formatNextRun($app->nextRunAt, $now),
116                (string) $app->subscriptions,
117                (string) $app->schedules,
118                (string) $app->exposedEntities,
119                (string) $app->counters->delivered,
120                (string) $app->counters->subscriptionDropped,
121                (string) $app->counters->suppressed,
122                (string) $app->counters->scheduleRuns,
123                (string) $app->counters->publishes,
124                $this->formatCalls($app),
125                $this->formatLatency($app),
126                (string) $app->counters->failures,
127            ], $snapshot->apps),
128        );
129    }
130
131    private function renderSubscriptionTable(OutputInterface $output, RuntimeSnapshot $snapshot, Instant $now): void
132    {
133        $namesApps = \count($snapshot->apps) > 1;
134
135        $this->renderTable(
136            $output,
137            'Subscriptions',
138            [...($namesApps ? ['app'] : []), 'kind', 'match', 'received', 'handled', 'dropped', 'last handled'],
139            array_map(fn(RegistrationInfo $subscription): array => [
140                ...($namesApps ? [$subscription->appId] : []),
141                $subscription->kind->value,
142                $subscription->selector,
143                (string) $subscription->received,
144                (string) $subscription->handled,
145                (string) $subscription->dropped,
146                $this->formatter->formatTimeAgo($subscription->lastHandledAt, $now),
147            ], $snapshot->subscriptions),
148        );
149    }
150
151    private function renderScheduleTable(OutputInterface $output, RuntimeSnapshot $snapshot, Instant $now): void
152    {
153        $namesApps = \count($snapshot->apps) > 1;
154
155        $this->renderTable(
156            $output,
157            'Schedules',
158            [...($namesApps ? ['app'] : []), 'schedule', 'next run', 'last run'],
159            array_map(fn(ScheduleStatus $schedule): array => [
160                ...($namesApps ? [$schedule->appId] : []),
161                $schedule->description,
162                $this->formatter->formatNextRun($schedule->nextRunAt, $now),
163                $this->formatter->formatTimeAgo($schedule->lastRunAt, $now),
164            ], $snapshot->schedules),
165        );
166    }
167
168    private function formatAppState(AppStatus $app, Instant $now): string
169    {
170        $state = $app->state === null ? 'unknown' : $app->state->value;
171
172        if ($app->pause !== null) {
173            return \sprintf('%s (paused by %s %s)', $state, $app->pause->source->value, $this->formatter->formatTimeAgo($app->pause->since, $now));
174        }
175
176        if ($app->configPauseOverride !== null) {
177            return \sprintf('%s (resumed by %s %s over config)', $state, $app->configPauseOverride->source->value, $this->formatter->formatTimeAgo($app->configPauseOverride->since, $now));
178        }
179
180        return $state;
181    }
182
183    private function renderFailureTable(OutputInterface $output, RuntimeSnapshot $snapshot, Instant $now): void
184    {
185        $rows = [];
186
187        foreach ($snapshot->apps as $app) {
188            $failure = $app->lastFailure;
189
190            if ($failure !== null) {
191                $rows[] = [$app->id, $this->formatter->formatTimeAgo($failure->at, $now), $failure->phase->value, $failure->reason ?? '-', $failure->message];
192            }
193        }
194
195        $this->renderTable($output, 'Failures', ['app', 'when', 'phase', 'reason', 'message'], $rows);
196    }
197
198    private function describeConnection(RuntimeSnapshot $snapshot, Instant $now): string
199    {
200        $connection = $snapshot->connection;
201        $description = $connection->phase->value;
202
203        if ($connection->since !== null) {
204            $description .= ' since ' . $this->formatter->formatTimeAgo($connection->since, $now);
205        }
206
207        if ($snapshot->daemon->haVersion !== null) {
208            $description .= ', version ' . $snapshot->daemon->haVersion;
209        }
210
211        return $description;
212    }
213
214    private function describeReconnects(ConnectionState $connection): string
215    {
216        if ($connection->lastOutage === null) {
217            return (string) $connection->reconnects;
218        }
219
220        return \sprintf('%d, last outage %s', $connection->reconnects, $this->formatter->formatDuration($connection->lastOutage));
221    }
222
223    private function describeComponent(?ComponentStatus $component, Instant $now): string
224    {
225        if ($component === null) {
226            return 'unknown';
227        }
228
229        $description = \sprintf('%s since %s', str_replace('_', ' ', $component->state->value), $this->formatter->formatTimeAgo($component->since, $now));
230
231        if ($component->version !== null) {
232            $description .= ', version ' . $component->version;
233        }
234
235        return match ($component->state) {
236            ComponentState::Missing => $description . ', not installed in Home Assistant or not loaded yet',
237            ComponentState::ProtocolMismatch => \sprintf('%s, protocol %d where Stewart speaks %d', $description, $component->protocol ?? 0, ComponentProtocol::VERSION),
238            ComponentState::Refused => $description . ', see the daemon log',
239            ComponentState::Replaced => \sprintf('%s, another Stewart uses expose.instance "%s"', $description, $component->instance),
240            ComponentState::Disabled => $description . ', expose.enabled is off',
241            ComponentState::Unchecked, ComponentState::Active => $description,
242        };
243    }
244
245    private function describeStoreHealth(?StoreHealth $health, Instant $now): string
246    {
247        if ($health === null) {
248            return 'not configured';
249        }
250
251        $state = $health->available ? 'up' : 'down';
252
253        if ($health->lastFailure === null) {
254            return $state;
255        }
256
257        return $health->lastFailureAt === null
258            ? \sprintf('%s, last failure: %s', $state, $health->lastFailure)
259            : \sprintf('%s, last failure %s: %s', $state, $this->formatter->formatTimeAgo($health->lastFailureAt, $now), $health->lastFailure);
260    }
261
262    private function describeMqtt(?MqttStatus $mqtt, Instant $now): string
263    {
264        if ($mqtt === null) {
265            return 'not configured';
266        }
267
268        $description = $mqtt->phase->value;
269
270        if ($mqtt->since !== null) {
271            $description .= ' since ' . $this->formatter->formatTimeAgo($mqtt->since, $now);
272        }
273
274        if ($mqtt->lastError !== null) {
275            $description .= ': ' . $mqtt->lastError;
276        }
277
278        if ($mqtt->reconnects > 0) {
279            $description .= \sprintf(', %d %s', $mqtt->reconnects, $mqtt->reconnects === 1 ? 'reconnect' : 'reconnects');
280        }
281
282        if ($mqtt->lastOutage !== null) {
283            $description .= ', last outage ' . $this->formatter->formatDuration($mqtt->lastOutage);
284        }
285
286        if ($mqtt->outboundQueued > 0) {
287            $description .= \sprintf(', %d queued', $mqtt->outboundQueued);
288        }
289
290        $dropped = $mqtt->countDropped();
291
292        return $dropped === 0 ? $description : \sprintf('%s, %d dropped', $description, $dropped);
293    }
294
295    private function describeDeploy(?DeployStatus $deploy, Instant $now): string
296    {
297        if ($deploy === null) {
298            return 'not polling';
299        }
300
301        $description = \sprintf(
302            '%s, polled %s',
303            substr($deploy->commit, 0, self::SHORT_COMMIT_LENGTH),
304            $this->formatter->formatTimeAgo($deploy->lastPolledAt, $now),
305        );
306
307        if ($deploy->lastFailure === null) {
308            return $description;
309        }
310
311        return \sprintf(
312            '%s, %d rejected, last %s %s: %s',
313            $description,
314            $deploy->failures,
315            substr($deploy->lastFailure->commit, 0, self::SHORT_COMMIT_LENGTH),
316            $this->formatter->formatTimeAgo($deploy->lastFailure->failedAt, $now),
317            $deploy->lastFailure->reason,
318        );
319    }
320
321    private function describeReload(?ReloadStatus $reload, Instant $now): string
322    {
323        if ($reload?->underway === true) {
324            return 'underway';
325        }
326
327        $last = $reload?->last;
328
329        if ($last === null) {
330            return 'never';
331        }
332
333        $description = \sprintf('%s %s', $last->outcome->describeOutcome(), $this->formatter->formatTimeAgo($last->finishedAt, $now));
334
335        if ($last->error !== null) {
336            $description .= ': ' . $last->error;
337        }
338
339        if ($last->settingsNeedingRestart !== []) {
340            $description .= '; restart to apply ' . implode(', ', $last->settingsNeedingRestart);
341        }
342
343        return $description;
344    }
345
346    private function describeGeneratedCode(?GeneratedCodeStatus $generated, Instant $now): string
347    {
348        if ($generated === null) {
349            return 'not generated';
350        }
351
352        if (!$generated->hasCurrentFormat()) {
353            return \sprintf('format %d, expected %d; run stewart generate', $generated->format, $generated->expectedFormat);
354        }
355
356        if ($generated->hasDrift()) {
357            return \sprintf('%d added, %d removed; run stewart generate', \count($generated->added), \count($generated->removed));
358        }
359
360        return 'up to date, checked ' . $this->formatter->formatTimeAgo($generated->checkedAt, $now);
361    }
362
363    private function formatCalls(AppStatus $app): string
364    {
365        $succeeded = 0;
366        $failed = 0;
367
368        foreach ($app->haCalls as $stats) {
369            if ($stats->outcome->isFailure()) {
370                $failed += $stats->count;
371            } else {
372                $succeeded += $stats->count;
373            }
374        }
375
376        return \sprintf('%d/%d', $succeeded, $failed);
377    }
378
379    private function formatLatency(AppStatus $app): string
380    {
381        foreach ($app->haCalls as $stats) {
382            if ($stats->outcome !== HaCallOutcome::Succeeded || $stats->latency === null) {
383                continue;
384            }
385
386            $bound = $stats->latency->quantileBoundMs(self::LATENCY_QUANTILE);
387            $last = max(0, ...$stats->latency->boundsMs);
388
389            return $bound === null ? \sprintf('> %d ms', $last) : \sprintf('≤ %d ms', $bound);
390        }
391
392        return '-';
393    }
394
395    /**
396     * @param list<string> $headers
397     * @param list<list<string>> $rows
398     */
399    private function renderTable(OutputInterface $output, string $title, array $headers, array $rows): void
400    {
401        $output->writeln('<info>' . $title . '</info>');
402
403        if ($rows === []) {
404            $output->writeln('  (none)');
405            $output->writeln('');
406
407            return;
408        }
409
410        new Table($output)
411            ->setStyle('compact')
412            ->setHeaders($headers)
413            ->setRows($rows)
414            ->render();
415        $output->writeln('');
416    }
417}