Lines 73.41% 58 / 79
Functions and Methods 66.66% 8 / 12
Classes and Traits 0.00% 0 / 1
Name Lines Functions and Methods CRAP Classes and Traits
StatusCommand 73.41% 58 / 79 66.66% 8 / 12 55.71 0.00% 0 / 1
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 configure 100.00% 6 / 6 100.00% 1 / 1 1
 execute 66.66% 16 / 24 0.00% 0 / 1 5.93
 fetchFocusedSnapshot 100.00% 11 / 11 100.00% 1 / 1 4
 writeSnapshot 100.00% 4 / 4 100.00% 1 / 1 2
 drawWatchFrame 0.00% 0 / 5 0.00% 0 / 1 6
 drawOutage 0.00% 0 / 6 0.00% 0 / 1 12
 clearScreen 0.00% 0 / 2 0.00% 0 / 1 6
 reportProbe 100.00% 6 / 6 100.00% 1 / 1 3
 readAppIdsArgument 100.00% 2 / 2 100.00% 1 / 1 2
 findWatchInterval 100.00% 6 / 6 100.00% 1 / 1 5
 findProbeOption 100.00% 6 / 6 100.00% 1 / 1 4
1<?php
2
3declare(strict_types=1);
4
5namespace Stewart\Runtime\Console;
6
7use Amp\ByteStream\StreamException;
8use Amp\CancelledException;
9use Amp\NullCancellation;
10use Stewart\Contracts\App\AppId;
11use Stewart\Contracts\Exception\IdentifierException;
12use Stewart\Contracts\Exception\StewartException;
13use Stewart\Contracts\Time\Duration;
14use Stewart\Runtime\Config\ConfigLoader;
15use Stewart\Runtime\Control\Client\ControlClient;
16use Stewart\Runtime\Control\Client\ControlTarget;
17use Stewart\Runtime\Control\Client\ControlTargetResolver;
18use Stewart\Runtime\Control\Protocol\Codec\FrameCodec;
19use Stewart\Runtime\Control\Protocol\Frame\SnapshotFrame;
20use Stewart\Runtime\Control\Protocol\Status\AppStatus;
21use Stewart\Runtime\Control\Protocol\Status\RuntimeSnapshot;
22use Stewart\Runtime\Exception\AppException;
23use Stewart\Runtime\Exception\ConfigurationError;
24use Stewart\Runtime\Exception\ConfigurationException;
25use Stewart\Runtime\Health\ProbeKind;
26use Stewart\Runtime\Health\ReadinessCheck;
27use Stewart\Runtime\Model\ResourceScope;
28use Stewart\Support\Text\ClosestNameFinder;
29use Symfony\Component\Console\Attribute\AsCommand;
30use Symfony\Component\Console\Command\Command;
31use Symfony\Component\Console\Input\InputArgument;
32use Symfony\Component\Console\Input\InputInterface;
33use Symfony\Component\Console\Input\InputOption;
34use Symfony\Component\Console\Output\ConsoleOutputInterface;
35use Symfony\Component\Console\Output\OutputInterface;
36use Throwable;
37
38#[AsCommand(name: self::NAME, description: 'Show what the running daemon is doing')]
39final class StatusCommand extends ControlCommand
40{
41    public const string NAME = 'status';
42
43    private const string DEFAULT_WATCH_INTERVAL = '2s';
44
45    // Cursor home, then clear to the end, as watch(1) redraws; the output is often taller than the terminal.
46    private const string CLEAR_SCREEN = "\e[H\e[J";
47
48    public function __construct(
49        ConfigLoader $config,
50        ControlTargetResolver $targets,
51        private readonly ControlClient $client,
52        private readonly StatusRenderer $renderer,
53        private readonly FrameCodec $codec,
54        private readonly ReadinessCheck $readiness,
55        private readonly StatusWatch $watch,
56        private readonly ClosestNameFinder $names,
57    ) {
58        parent::__construct($config, $targets);
59    }
60
61    protected function configure(): void
62    {
63        parent::configure();
64        $this
65            ->addArgument('apps', InputArgument::IS_ARRAY | InputArgument::OPTIONAL, 'Show only these apps, with their subscriptions and schedules')
66            ->addOption('json', null, InputOption::VALUE_NONE, 'Print the snapshot as the wire JSON instead of tables')
67            ->addOption('probe', null, InputOption::VALUE_REQUIRED, 'liveness or readiness: print one line and exit 0 or 1, for health checks')
68            ->addOption('watch', null, InputOption::VALUE_OPTIONAL, 'Redraw every interval, like 5s, until Ctrl-C; every 2s when given alone', false);
69    }
70
71    protected function execute(InputInterface $input, OutputInterface $output): int
72    {
73        try {
74            $appIds = $this->readAppIdsArgument($input);
75            $interval = $this->findWatchInterval($input);
76            $probe = $this->findProbeOption($input, $appIds, $interval);
77            $target = $this->resolveControlTarget($input);
78            $timeout = $this->parseTimeoutOption($input);
79            $json = (bool) $input->getOption('json');
80            $view = $appIds === [] ? StatusView::Overview : StatusView::AppDetail;
81
82            if ($interval !== null) {
83                $this->watch->watchStatus(
84                    fn(): RuntimeSnapshot => $this->fetchFocusedSnapshot($target, $timeout, $appIds),
85                    fn(RuntimeSnapshot $snapshot) => $this->drawWatchFrame($output, $snapshot, $json, $view, $interval),
86                    fn(string $outage) => $this->drawOutage($output, $outage, $json, $interval),
87                    $interval,
88                    new NullCancellation(),
89                );
90
91                return Command::SUCCESS;
92            }
93
94            $snapshot = $this->fetchFocusedSnapshot($target, $timeout, $appIds);
95        } catch (StewartException|StreamException|CancelledException $e) {
96            $output->writeln('<error>' . $e->getMessage() . '</error>');
97
98            return Command::FAILURE;
99        }
100
101        if ($probe !== null) {
102            return $this->reportProbe($output, $probe, $snapshot);
103        }
104
105        $this->writeSnapshot($output, $snapshot, $json, $view);
106
107        return Command::SUCCESS;
108    }
109
110    /**
111     * @param list<AppId> $appIds
112     * @throws StewartException|Throwable
113     */
114    private function fetchFocusedSnapshot(ControlTarget $target, Duration $timeout, array $appIds): RuntimeSnapshot
115    {
116        $snapshot = $this->client->fetchSnapshot($target, $timeout);
117
118        if ($appIds === []) {
119            return $snapshot;
120        }
121
122        $knownIds = array_values(array_filter(
123            array_map(static fn(AppStatus $app): string => $app->id, $snapshot->apps),
124            static fn(string $id): bool => ResourceScope::tryFromWireValue($id)?->isShared() !== true,
125        ));
126
127        foreach ($appIds as $appId) {
128            if (!\in_array($appId->value, $knownIds, true)) {
129                throw AppException::unknown($appId, $this->names->findClosestName($appId->value, $knownIds));
130            }
131        }
132
133        return $snapshot->withOnlyApps(array_map(static fn(AppId $appId): string => $appId->value, $appIds));
134    }
135
136    private function writeSnapshot(OutputInterface $output, RuntimeSnapshot $snapshot, bool $json, StatusView $view): void
137    {
138        if ($json) {
139            $output->write($this->codec->encodeFrame(new SnapshotFrame($snapshot)));
140
141            return;
142        }
143
144        $this->renderer->render($output, $snapshot, $view);
145    }
146
147    private function drawWatchFrame(OutputInterface $output, RuntimeSnapshot $snapshot, bool $json, StatusView $view, Duration $interval): void
148    {
149        if (!$json) {
150            $this->clearScreen($output);
151            $output->writeln(\sprintf('<comment>Every %s; Ctrl-C stops.</comment>', $interval));
152            $output->writeln('');
153        }
154
155        $this->writeSnapshot($output, $snapshot, $json, $view);
156    }
157
158    private function drawOutage(OutputInterface $output, string $outage, bool $json, Duration $interval): void
159    {
160        $notice = \sprintf('Stewart is not reachable, retrying every %s: %s', $interval, $outage);
161
162        if ($json) {
163            ($output instanceof ConsoleOutputInterface ? $output->getErrorOutput() : $output)->writeln($notice);
164
165            return;
166        }
167
168        $this->clearScreen($output);
169        $output->writeln('<comment>' . $notice . '</comment>');
170    }
171
172    private function clearScreen(OutputInterface $output): void
173    {
174        if ($output->isDecorated()) {
175            $output->write(self::CLEAR_SCREEN);
176        }
177    }
178
179    private function reportProbe(OutputInterface $output, ProbeKind $probe, RuntimeSnapshot $snapshot): int
180    {
181        if ($probe === ProbeKind::Liveness) {
182            $output->writeln('alive');
183
184            return Command::SUCCESS;
185        }
186
187        $verdict = $this->readiness->assessSnapshot($snapshot);
188        $output->writeln($verdict->describeVerdict());
189
190        return $verdict->isReady() ? Command::SUCCESS : Command::FAILURE;
191    }
192
193    /**
194     * @return list<AppId>
195     * @throws IdentifierException
196     */
197    private function readAppIdsArgument(InputInterface $input): array
198    {
199        $ids = $input->getArgument('apps');
200
201        return \is_array($ids) ? array_map(static fn(string $id): AppId => new AppId($id), array_values(array_filter($ids, \is_string(...)))) : [];
202    }
203
204    /** @throws StewartException */
205    private function findWatchInterval(InputInterface $input): ?Duration
206    {
207        $watch = $input->getOption('watch');
208
209        if ($watch === false) {
210            return null;
211        }
212
213        $raw = \is_string($watch) && $watch !== '' ? $watch : self::DEFAULT_WATCH_INTERVAL;
214        $interval = Duration::parse($raw);
215
216        return $interval->isLongerThan(Duration::zero()) ? $interval : throw ConfigurationException::valueInvalid($raw, 'a --watch interval longer than 0s');
217    }
218
219    /**
220     * @param list<AppId> $appIds
221     * @throws ConfigurationException
222     */
223    private function findProbeOption(InputInterface $input, array $appIds, ?Duration $interval): ?ProbeKind
224    {
225        $probe = $this->nonEmptyStringOption($input, 'probe');
226
227        if ($probe === null) {
228            return null;
229        }
230
231        if ($appIds !== [] || $interval !== null) {
232            throw ConfigurationException::createForReason(ConfigurationError::OptionsConflict, option: '--probe', conflicting: 'app IDs or --watch');
233        }
234
235        return ProbeKind::parse($probe);
236    }
237}