Lines
85.71%
18 / 21
Functions and Methods
80.00%
4 / 5
Classes and Traits
0.00%
0 / 1
| Name | Lines | Functions and Methods | CRAP | Classes and Traits | ||||||
|---|---|---|---|---|---|---|---|---|---|---|
| SignalHandlers | 85.71% | 18 / 21 | 80.00% | 4 / 5 | 10.29 | 0.00% | 0 / 1 | |||
| __construct | 100.00% | 1 / 1 | 100.00% | 1 / 1 | 1 | |||||
| install | 70.00% | 7 / 10 | 0.00% | 0 / 1 | 3.24 | |||||
| removeAll | 100.00% | 3 / 3 | 100.00% | 1 / 1 | 2 | |||||
| handleStopSignal | 100.00% | 4 / 4 | 100.00% | 1 / 1 | 2 | |||||
| handleReloadSignal | 100.00% | 3 / 3 | 100.00% | 1 / 1 | 2 | |||||
| 1 | <?php | |
| 2 | ||
| 3 | declare(strict_types=1); | |
| 4 | ||
| 5 | namespace Stewart\Runtime\Broker; | |
| 6 | ||
| 7 | use Closure; | |
| 8 | use Psr\Log\LoggerInterface; | |
| 9 | use Revolt\EventLoop; | |
| 10 | use Stewart\Runtime\Broker\Reload\ReloadCoordinator; | |
| 11 | use Stewart\Runtime\Broker\Reload\ReloadRequestOutcome; | |
| 12 | use Stewart\Runtime\Broker\Reload\ReloadTrigger; | |
| 13 | ||
| 14 | final class SignalHandlers | |
| 15 | { | |
| 16 | /** @var list<string> */ | |
| 17 | private array $watchers = []; | |
| 18 | ||
| 19 | public function __construct( | |
| 20 | private readonly BrokerRun $run, | |
| 21 | private readonly ReloadCoordinator $reloads, | |
| 22 | private readonly LoggerInterface $logger, | |
| 23 | ) {} | |
| 24 | ||
| 25 | public function install(): void | |
| 26 | { | |
| 27 | /** @var array<int, Closure(): void> $handlers */ | |
| 28 | $handlers = [ | |
| 29 | \SIGTERM => $this->handleStopSignal(...), | |
| 30 | \SIGINT => $this->handleStopSignal(...), | |
| 31 | \SIGHUP => $this->handleReloadSignal(...), | |
| 32 | ]; | |
| 33 | ||
| 34 | foreach ($handlers as $signal => $handler) { | |
| 35 | try { | |
| 36 | $this->watchers[] = EventLoop::unreference(EventLoop::onSignal($signal, $handler)); | |
| 37 | } catch (EventLoop\UnsupportedFeatureException) { | |
| 38 | $this->logger->warning('Signal handling unavailable; shutdown will not be graceful.'); | |
| 39 | ||
| 40 | return; | |
| 41 | } | |
| 42 | } | |
| 43 | } | |
| 44 | ||
| 45 | public function removeAll(): void | |
| 46 | { | |
| 47 | foreach ($this->watchers as $watcher) { | |
| 48 | EventLoop::cancel($watcher); | |
| 49 | } | |
| 50 | ||
| 51 | $this->watchers = []; | |
| 52 | } | |
| 53 | ||
| 54 | private function handleStopSignal(): void | |
| 55 | { | |
| 56 | if ($this->run->isStopping()) { | |
| 57 | $this->run->killWorkersNow(); | |
| 58 | ||
| 59 | return; | |
| 60 | } | |
| 61 | ||
| 62 | $this->run->stop('signal'); | |
| 63 | } | |
| 64 | ||
| 65 | private function handleReloadSignal(): void | |
| 66 | { | |
| 67 | $outcome = $this->reloads->requestReload(ReloadTrigger::Signal); | |
| 68 | ||
| 69 | if ($outcome !== ReloadRequestOutcome::Started) { | |
| 70 | $this->logger->info('Reload signal ignored', ['reason' => $outcome->describeOutcome()]); | |
| 71 | } | |
| 72 | } | |
| 73 | } |