fix(daemons): reload the servers list on a 5-second timer

Once the signals daemon had run its first settings check, it called
ServerRepository::getAll(true) - a SELECT * FROM servers against MAIN - on
every pass of a loop that sleeps 250 ms: up to 240 reads a minute from every
node. The watchdog and the cache handler tied the reload to the settings
interval instead (10-60 s), so their view of the cluster could be a minute
stale.

DaemonTrait::serversRefreshDue()/refreshServers() reload at most every five
seconds, and the three daemons use it: 12 reads a minute, never more than
five seconds stale (SignalsLoopQueryRateTest). Phase 0 of the MAIN <-> LB
API plan.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Es8UhyPS8MNjuYTagqfGWi
This commit is contained in:
Claude
2026-09-25 09:28:03 +00:00
parent c1e8a8639f
commit b41f7b72b7
5 changed files with 101 additions and 5 deletions
+3 -2
View File
@@ -7,7 +7,6 @@ use XcVm\Cli\DaemonTrait;
use XcVm\Core\Config\SettingsManager;
use XcVm\Core\Config\SettingsRepository;
use XcVm\Domain\Line\LineService;
use XcVm\Domain\Server\ServerRepository;
use XcVm\Infrastructure\Signal\SignalQueue;
/**
@@ -58,9 +57,11 @@ class CacheHandlerCommand implements CommandInterface {
break;
}
if ($this->serversRefreshDue()) {
$this->refreshServers();
}
if ($this->shouldRefreshSettings()) {
SettingsManager::set(SettingsRepository::getAll(true));
ServerRepository::getAll(true);
if (!SettingsManager::get('enable_cache')) {
echo "Cache disabled! Break.\n";
break;
+4 -2
View File
@@ -57,8 +57,10 @@ class SignalsCommand implements CommandInterface {
if (!$this->refreshOrBreak()) {
break;
}
if ($this->rLastCheck) {
$rServers = ServerRepository::getAll(true);
// Was every pass (four times a second): a `SELECT * FROM servers`
// against MAIN from every node, all day.
if ($this->serversRefreshDue()) {
$rServers = $this->refreshServers();
}
// Stop if Redis required but dead. checkRedisHealth() catches
+4 -1
View File
@@ -80,6 +80,10 @@ class WatchdogCommand implements CommandInterface {
$this->attemptRedisRestart();
}
if ($this->serversRefreshDue()) {
$rServers = $this->refreshServers();
}
if ($this->shouldRefreshSettings()) {
if (!ProcessManager::isNginxRunning()) {
echo "Not running! Break.\n";
@@ -89,7 +93,6 @@ class WatchdogCommand implements CommandInterface {
echo "File changed! Break.\n";
break;
}
$rServers = ServerRepository::getAll(true);
SettingsManager::set(SettingsRepository::getAll(true));
ConnectionTracker::getCapacity(true);
ConnectionTracker::getCapacity(false);
+29
View File
@@ -5,6 +5,7 @@ namespace XcVm\Cli;
use XcVm\Core\Config\SettingsManager;
use XcVm\Core\Config\SettingsRepository;
use XcVm\Core\Process\ProcessManager;
use XcVm\Domain\Server\ServerRepository;
use XcVm\Infrastructure\Redis\RedisManager;
/**
@@ -30,6 +31,9 @@ trait DaemonTrait {
/** @var int Интервал обновления настроек (секунды) */
protected $rRefreshInterval = 60;
/** @var int|null When the servers list was last reloaded from the DB. */
protected $rServersRefreshedAt = null;
/** @var resource|null Файловый lock для singleton-демона */
protected $rDaemonLockHandle;
@@ -74,6 +78,31 @@ trait DaemonTrait {
/**
* Проверить нужно ли обновить настройки (по таймеру).
*/
/**
* Reload the servers list at most this often. Often enough that routing,
* ports and node state are never more than five seconds stale; rare
* enough that a tight loop does not re-read `servers` on every pass.
*/
protected function serversRefreshInterval(): int {
return 5;
}
/** Is the servers list due for a reload? */
protected function serversRefreshDue(?int $rNow = null): bool {
return $this->rServersRefreshedAt === null
|| ($rNow ?? time()) - $this->rServersRefreshedAt >= $this->serversRefreshInterval();
}
/**
* Reload the servers list from the DB (which also rewrites its cache).
*
* @return array<int, array<string, mixed>>
*/
protected function refreshServers(): array {
$this->rServersRefreshedAt = time();
return ServerRepository::getAll(true);
}
protected function shouldRefreshSettings(): bool {
return !$this->rLastCheck || $this->rRefreshInterval <= time() - $this->rLastCheck;
}
+61
View File
@@ -0,0 +1,61 @@
<?php
use PHPUnit\Framework\TestCase;
use XcVm\Cli\DaemonTrait;
/**
* The signals daemon re-read `servers` (a SELECT * against MAIN) on every
* pass of its loop once it had run a settings check — four times a second on
* every node. Persistent loops now reload the servers list on a five-second
* timer shared through DaemonTrait.
*/
final class SignalsLoopQueryRateTest extends TestCase {
private function daemon(): object {
return new class {
use DaemonTrait;
public function due(?int $rNow): bool {
return $this->serversRefreshDue($rNow);
}
public function markRefreshed(int $rAt): void {
$this->rServersRefreshedAt = $rAt;
}
};
}
public function testReloadAtMostEveryFiveSeconds(): void {
$rDaemon = $this->daemon();
$this->assertTrue($rDaemon->due(1000), 'first pass loads');
$rDaemon->markRefreshed(1000);
$this->assertFalse($rDaemon->due(1000));
$this->assertFalse($rDaemon->due(1004));
$this->assertTrue($rDaemon->due(1005));
}
public function testAQuarterSecondLoopReadsServersTwelveTimesAMinuteNotTwoHundredForty(): void {
$rDaemon = $this->daemon();
$rReads = 0;
for ($rTick = 0; $rTick < 240; $rTick++) { // one minute at usleep(250000)
$rNow = 1000 + intdiv($rTick, 4);
if ($rDaemon->due($rNow)) {
$rReads++;
$rDaemon->markRefreshed($rNow);
}
}
$this->assertSame(12, $rReads);
}
/** @dataProvider daemons */
public function testDaemonsUseTheTimer(string $rFile): void {
$rSource = (string) file_get_contents(dirname(__DIR__, 2) . '/src/Cli/Commands/' . $rFile);
$this->assertStringContainsString('$this->serversRefreshDue()', $rSource);
$this->assertStringNotContainsString('ServerRepository::getAll(true)', $rSource);
}
/** @return array<string, array{string}> */
public static function daemons(): array {
return ['signals' => ['SignalsCommand.php'], 'watchdog' => ['WatchdogCommand.php'], 'cache handler' => ['CacheHandlerCommand.php']];
}
}