Lines 100.00% 12 / 12
Functions and Methods 100.00% 2 / 2
Classes and Traits 100.00% 1 / 1
Name Lines Functions and Methods CRAP Classes and Traits
StatusWatch 100.00% 12 / 12 100.00% 2 / 2 7 100.00% 1 / 1
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 watchStatus 100.00% 11 / 11 100.00% 1 / 1 6
1<?php
2
3declare(strict_types=1);
4
5namespace Stewart\Runtime\Console;
6
7use Amp\ByteStream\StreamException;
8use Amp\Cancellation;
9use Amp\CancelledException;
10use Closure;
11use Stewart\Contracts\Exception\StewartException;
12use Stewart\Contracts\Time\Duration;
13use Stewart\Runtime\Control\Protocol\Status\RuntimeSnapshot;
14use Stewart\Runtime\Exception\ControlError;
15use Stewart\Runtime\Exception\ControlException;
16use Stewart\Support\Time\Deadlines;
17
18final readonly class StatusWatch
19{
20    // A daemon that is down or restarting comes back; a wrong token, address or protocol does not.
21    private const array PASSING_FAILURES = [ControlError::BrokerHungUp, ControlError::RequestTimedOut];
22
23    public function __construct(private Deadlines $deadlines) {}
24
25    /**
26     * @param Closure(): RuntimeSnapshot $fetchSnapshot
27     * @param Closure(RuntimeSnapshot): void $drawFrame
28     * @param Closure(string): void $drawUnreachable
29     * @throws StewartException
30     */
31    public function watchStatus(Closure $fetchSnapshot, Closure $drawFrame, Closure $drawUnreachable, Duration $interval, Cancellation $stop): void
32    {
33        while (!$stop->isRequested()) {
34            try {
35                $drawFrame($fetchSnapshot());
36            } catch (StreamException|CancelledException $e) {
37                $drawUnreachable($e->getMessage());
38            } catch (ControlException $e) {
39                if (!\in_array($e->reason, self::PASSING_FAILURES, true)) {
40                    throw $e;
41                }
42
43                $drawUnreachable($e->getMessage());
44            }
45
46            try {
47                $this->deadlines->delay($interval, $stop);
48            } catch (CancelledException) {
49                return;
50            }
51        }
52    }
53}