1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace ReactInspector; |
4
|
|
|
|
5
|
|
|
use React\EventLoop\LoopInterface; |
6
|
|
|
use React\EventLoop\TimerInterface; |
7
|
|
|
use Rx\DisposableInterface; |
8
|
|
|
use Rx\Observable; |
9
|
|
|
use Rx\ObserverInterface; |
10
|
|
|
use Rx\Subject\Subject; |
11
|
|
|
use function ApiClients\Tools\Rx\observableFromArray; |
12
|
|
|
|
13
|
|
|
final class Metrics extends Subject implements MetricsStreamInterface |
14
|
|
|
{ |
15
|
|
|
private LoopInterface $loop; |
16
|
|
|
|
17
|
|
|
private float $interval; |
18
|
|
|
|
19
|
|
|
private ?TimerInterface $timer = null; |
20
|
|
|
|
21
|
|
|
/** @var array<int, CollectorInterface> */ |
22
|
|
|
private array $collectors = []; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* @param array<int, CollectorInterface> $collectors |
26
|
|
|
*/ |
27
|
|
|
public function __construct(LoopInterface $loop, float $interval, CollectorInterface ...$collectors) |
28
|
|
|
{ |
29
|
|
|
$this->loop = $loop; |
30
|
|
|
$this->interval = $interval; |
31
|
|
|
$this->collectors = $collectors; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
public function removeObserver(ObserverInterface $observer): bool |
35
|
|
|
{ |
36
|
|
|
$return = parent::removeObserver($observer); |
37
|
|
|
if (! $this->hasObservers()) { |
38
|
|
|
if ($this->timer instanceof TimerInterface) { |
39
|
1 |
|
$this->loop->cancelTimer($this->timer); |
40
|
|
|
$this->timer = null; |
41
|
1 |
|
} |
42
|
1 |
|
|
43
|
1 |
|
foreach ($this->collectors as $index => $instance) { |
44
|
1 |
|
$instance->cancel(); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
$this->collectors = []; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
return $return; |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
protected function _subscribe(ObserverInterface $observer): DisposableInterface |
54
|
|
|
{ |
55
|
|
|
if ($this->timer === null) { |
56
|
|
|
$collect = function (): void { |
57
|
|
|
observableFromArray($this->collectors)->flatMap(static function (CollectorInterface $collector): Observable { |
58
|
|
|
return $collector->collect(); |
59
|
|
|
})->subscribe(function (Metric $metric): void { |
60
|
|
|
$this->onNext($metric); |
61
|
|
|
}); |
62
|
1 |
|
}; |
63
|
|
|
$this->timer = $this->loop->addPeriodicTimer($this->interval, $collect); |
64
|
1 |
|
$collect(); |
65
|
|
|
} |
66
|
|
|
|
67
|
1 |
|
return parent::_subscribe($observer); |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|