Compare commits

...
7 Commits
Author SHA1 Message Date
as2252258 01d0c01703 eee 2026-07-20 11:15:46 +08:00
as2252258 276ea63b54 eee 2026-07-15 09:54:34 +08:00
as2252258 39bdb9f5c9 eee 2026-07-15 09:52:12 +08:00
as2252258 136f360fec eee 2026-07-15 09:42:08 +08:00
as2252258 6ad9d5d0da eee 2026-07-14 22:53:12 +08:00
as2252258 d3ca24c4c5 Build hot reload artifacts before worker restart 2026-07-10 17:13:20 +08:00
as2252258 ca68418e0d eee 2026-07-10 15:57:44 +08:00
6 changed files with 272 additions and 11 deletions
+63 -4
View File
@@ -7,6 +7,7 @@ use Kiri\Di\Inject\Container;
use Kiri\Error\StdoutLogger; use Kiri\Error\StdoutLogger;
use Kiri\Events\EventProvider; use Kiri\Events\EventProvider;
use Kiri\Router\Router; use Kiri\Router\Router;
use Kiri\Router\RouteArtifactState;
use Kiri\Server\Events\OnWorkerStart; use Kiri\Server\Events\OnWorkerStart;
use Kiri\Server\Processes\AbstractProcess; use Kiri\Server\Processes\AbstractProcess;
use Kiri\Server\Processes\OnProcessInterface; use Kiri\Server\Processes\OnProcessInterface;
@@ -62,7 +63,10 @@ class FileWatcher extends AbstractProcess implements OnProcessInterface
public function __construct() public function __construct()
{ {
$this->watchPaths = config('servers.reload.listen', []); $this->watchPaths = config('servers.reload.listen', []);
$this->excludePatterns = config('servers.reload.scan.skip_patterns', []); $this->excludePatterns = array_values(array_unique(array_merge(
['/vendor/', '/tests/', '/cache/', '/node_modules/', '/storage/', '/.git/', '/.idea/'],
config('servers.reload.scan.skip_patterns', [])
)));
$this->extensions = config('servers.reload.scan.extensions', ['php']); $this->extensions = config('servers.reload.scan.extensions', ['php']);
di(EventProvider::class)->on(OnWorkerStart::class, [di(Router::class), 'scan_build_route']); di(EventProvider::class)->on(OnWorkerStart::class, [di(Router::class), 'scan_build_route']);
@@ -236,8 +240,10 @@ class FileWatcher extends AbstractProcess implements OnProcessInterface
private function isExcluded(string $path): bool private function isExcluded(string $path): bool
{ {
$path = '/' . trim(str_replace('\\', '/', $path), '/') . '/';
foreach ($this->excludePatterns as $pattern) { foreach ($this->excludePatterns as $pattern) {
if (strpos($path, $pattern) !== false) { $pattern = '/' . trim(str_replace('\\', '/', (string)$pattern), '/') . '/';
if ($pattern !== '//' && strpos($path, $pattern) !== false) {
return true; return true;
} }
} }
@@ -298,16 +304,69 @@ class FileWatcher extends AbstractProcess implements OnProcessInterface
} }
di(HotReloadState::class)->store($changedFiles); di(HotReloadState::class)->store($changedFiles);
di(StdoutLogger::class)->println('detected file changes, reloading server: ' . $preview); di(StdoutLogger::class)->println('detected file changes, building hot reload artifacts: ' . $preview);
if (!$this->buildChangedFiles($changedFiles)) {
di(StdoutLogger::class)->println('hot reload build failed, keep old workers running');
return;
}
if (!$this->reloadWorkers()) { if (!$this->reloadWorkers()) {
di(StdoutLogger::class)->println('reload server failed: master pid not found or signal failed'); di(StdoutLogger::class)->println('reload server failed: Server->reload() failed, and master pid fallback not found or signal failed');
} }
} finally { } finally {
$this->reloading = false; $this->reloading = false;
} }
} }
private function buildChangedFiles(array $changedFiles): bool
{
$entry = $this->detectConsoleEntry();
if ($entry === null) {
di(StdoutLogger::class)->println('hot reload build failed: entry script not found');
return false;
}
$artifactType = defined('ROUTER_TYPE_HTTP') ? ROUTER_TYPE_HTTP : 'http';
$artifactState = di(RouteArtifactState::class);
$artifactState->clearBuild($artifactType);
$php = PHP_BINARY ?: 'php';
$command = escapeshellarg($php) . ' ' . escapeshellarg($entry) . ' sw:file-build';
$output = [];
$returnCode = 0;
exec($command . ' 2>&1', $output, $returnCode);
foreach ($output as $line) {
if ($line !== '') {
di(StdoutLogger::class)->println('[file-build] ' . $line);
}
}
if ($returnCode !== 0) {
return false;
}
return $artifactState->coversChangedFiles($artifactType, $changedFiles);
}
private function detectConsoleEntry(): ?string
{
$candidates = [
$_SERVER['SCRIPT_FILENAME'] ?? '',
defined('APP_PATH') ? APP_PATH . 'kiri.php' : '',
defined('APP_PATH') ? APP_PATH . 'bin/kiri' : '',
defined('APP_PATH') ? APP_PATH . 'artisan' : '',
];
foreach ($candidates as $candidate) {
if (is_string($candidate) && $candidate !== '' && is_file($candidate)) {
return $candidate;
}
}
return null;
}
private function invalidateChangedFiles(array $changedFiles): void private function invalidateChangedFiles(array $changedFiles): void
{ {
if (!function_exists('opcache_invalidate')) { if (!function_exists('opcache_invalidate')) {
+1 -1
View File
@@ -128,7 +128,7 @@ class HotReload extends AbstractProcess
$this->clear(); $this->clear();
if (!$this->reloadWorkers()) { if (!$this->reloadWorkers()) {
di(StdoutLogger::class)->println('reload server failed: master pid not found or signal failed'); di(StdoutLogger::class)->println('reload server failed: Server->reload() failed, and master pid fallback not found or signal failed');
} }
$this->addListen(); $this->addListen();
+79 -6
View File
@@ -2,16 +2,24 @@
namespace Kiri\Server\Abstracts; namespace Kiri\Server\Abstracts;
use Kiri\Error\StdoutLogger;
use Kiri\Server\ServerInterface;
use Swoole\Process; use Swoole\Process;
trait ReloadWorkers trait ReloadWorkers
{ {
private static ?int $cachedMasterPid = null;
/** /**
* @return void * @return void
*/ */
private function reloadWorkers(): bool private function reloadWorkers(): bool
{ {
if ($this->reloadByServerInstance()) {
return true;
}
$pid = $this->getMasterPid(); $pid = $this->getMasterPid();
if ($pid === null) { if ($pid === null) {
return false; return false;
@@ -20,16 +28,34 @@ trait ReloadWorkers
return Process::kill($pid, SIGUSR1); return Process::kill($pid, SIGUSR1);
} }
private function reloadByServerInstance(): bool
{
try {
di(StdoutLogger::class)->println('[file-build] Reload worker.');
$server = di(ServerInterface::class) ;
return $server->reload() !== false;
} catch (\Throwable) {
return false;
}
}
private function getMasterPid(): ?int private function getMasterPid(): ?int
{ {
if (self::$cachedMasterPid !== null && $this->isCachedMasterPid(self::$cachedMasterPid)) {
return self::$cachedMasterPid;
}
self::$cachedMasterPid = null;
$pidFilePid = $this->getPidFileMasterPid();
if ($pidFilePid !== null) {
self::$cachedMasterPid = $pidFilePid;
return $pidFilePid;
}
$processes = $this->listProcesses(); $processes = $this->listProcesses();
$candidates = []; $candidates = [];
$pidFile = function_exists('storage') ? storage('.swoole.pid') : '';
if (is_file($pidFile)) {
$candidates[] = (int)trim((string)file_get_contents($pidFile));
}
foreach ($processes as $process) { foreach ($processes as $process) {
if ($this->isMasterProcessCommand($process['command'])) { if ($this->isMasterProcessCommand($process['command'])) {
$candidates[] = (int)$process['pid']; $candidates[] = (int)$process['pid'];
@@ -41,6 +67,7 @@ trait ReloadWorkers
|> array_unique(...) |> array_unique(...)
|> array_values(...) as $pid) { |> array_values(...) as $pid) {
if ($this->isProcessAlive($pid) && $this->isMasterPid($pid, $processes)) { if ($this->isProcessAlive($pid) && $this->isMasterPid($pid, $processes)) {
self::$cachedMasterPid = $pid;
return $pid; return $pid;
} }
} }
@@ -48,6 +75,52 @@ trait ReloadWorkers
return null; return null;
} }
private function isCachedMasterPid(int $pid): bool
{
if (!$this->isProcessAlive($pid)) {
return false;
}
$pidFilePid = $this->readPidFile();
if ($pidFilePid === $pid && $this->isSameAppProcess($pid)) {
return true;
}
$command = $this->readProcessCommand($pid);
return $command !== '' && $this->isMasterProcessCommand($command) && $this->isSameAppProcess($pid);
}
private function getPidFileMasterPid(): ?int
{
$pid = $this->readPidFile();
if ($pid === null || !$this->isProcessAlive($pid) || !$this->isSameAppProcess($pid)) {
return null;
}
return $pid;
}
private function readPidFile(): ?int
{
$pidFile = function_exists('storage') ? storage('.swoole.pid') : '';
if ($pidFile === '' || !is_file($pidFile)) {
return null;
}
$pid = (int)trim((string)file_get_contents($pidFile));
return $pid > 1 ? $pid : null;
}
private function readProcessCommand(int $pid): string
{
$cmdline = @file_get_contents('/proc/' . $pid . '/cmdline');
if (is_string($cmdline) && $cmdline !== '') {
return trim(str_replace("\0", ' ', $cmdline));
}
return '';
}
private function isMasterPid(int $pid, array $processes): bool private function isMasterPid(int $pid, array $processes): bool
{ {
foreach ($processes as $process) { foreach ($processes as $process) {
@@ -61,7 +134,7 @@ trait ReloadWorkers
private function listProcesses(): array private function listProcesses(): array
{ {
$lines = []; $lines = [];
exec('ps -eo pid=,ppid=,args=', $lines); exec('ps -eo pid=,ppid=,args= 2>/dev/null', $lines);
$processes = []; $processes = [];
foreach ($lines as $line) { foreach ($lines as $line) {
+72
View File
@@ -0,0 +1,72 @@
<?php
declare(strict_types=1);
namespace Kiri\Server;
use Kiri\Di\HotReloadState;
use Kiri\Router\RouteArtifactState;
use Kiri\Router\Router;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Throwable;
class FileBuildCommand extends Command
{
protected function configure(): void
{
$this->setName('sw:file-build')
->setDescription('build hot reload artifacts for changed files');
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
defined('ROUTER_TYPE_HTTP') or define('ROUTER_TYPE_HTTP', 'http');
putenv('KIRI_FILE_BUILD=1');
$changedFiles = di(HotReloadState::class)->peek();
$startedAt = microtime(true);
try {
$syntaxError = $this->lintChangedFiles($changedFiles);
if ($syntaxError !== null) {
$output->writeln('<error>file build failed: ' . $syntaxError . '</error>');
return Command::FAILURE;
}
di(Router::class)->scan_build_route();
di(HotReloadState::class)->store($changedFiles);
di(RouteArtifactState::class)->markBuild(ROUTER_TYPE_HTTP, $changedFiles);
$elapsed = round((microtime(true) - $startedAt) * 1000, 2);
$output->writeln(sprintf('file build complete: %d changed files, %sms', count($changedFiles), $elapsed));
return Command::SUCCESS;
} catch (Throwable $throwable) {
if (class_exists('Kiri')) {
\Kiri::getLogger()->json_log($throwable);
}
$output->writeln('<error>file build failed: ' . $throwable->getMessage() . '</error>');
return Command::FAILURE;
} finally {
putenv('KIRI_FILE_BUILD');
}
}
private function lintChangedFiles(array $changedFiles): ?string
{
foreach ($changedFiles as $file) {
if (!is_string($file) || !str_ends_with($file, '.php') || !is_file($file)) {
continue;
}
$output = [];
$returnCode = 0;
exec(escapeshellarg(PHP_BINARY ?: 'php') . ' -l ' . escapeshellarg($file) . ' 2>&1', $output, $returnCode);
if ($returnCode !== 0) {
return implode("\n", $output);
}
}
return null;
}
}
+55
View File
@@ -134,6 +134,9 @@ class ServerCommand extends Command
{ {
$this->asyncServer->addProcess(config('process', [])); $this->asyncServer->addProcess(config('process', []));
$hotReload = \config('servers.reload.hot', false) === true; $hotReload = \config('servers.reload.hot', false) === true;
if ($hotReload && !$this->buildHotReloadArtifacts()) {
throw new Exception('Hot reload artifact build failed.');
}
if ($hotReload) { if ($hotReload) {
$this->asyncServer->addProcess([FileWatcher::class]); $this->asyncServer->addProcess([FileWatcher::class]);
} }
@@ -147,4 +150,56 @@ class ServerCommand extends Command
return 1; return 1;
} }
/**
* 热更模式下不要在 Master 进程扫描业务类;先用独立 CLI 进程构建路由 artifact
* Worker 启动/重载时直接导入 artifact,避免多个 Worker 同时全量扫描导致 OOM。
* @return bool
*/
private function buildHotReloadArtifacts(): bool
{
$entry = $this->detectConsoleEntry();
if ($entry === null) {
\Kiri::getLogger()->println('hot reload build failed: entry script not found');
return false;
}
$php = PHP_BINARY ?: 'php';
$command = escapeshellarg($php) . ' ' . escapeshellarg($entry) . ' sw:file-build';
$output = [];
$returnCode = 0;
exec($command . ' 2>&1', $output, $returnCode);
foreach ($output as $line) {
if ($line !== '') {
\Kiri::getLogger()->println('[file-build] ' . $line);
}
}
return $returnCode === 0;
}
/**
* @return string|null
*/
private function detectConsoleEntry(): ?string
{
$candidates = [
$_SERVER['SCRIPT_FILENAME'] ?? '',
defined('APP_PATH') ? APP_PATH . 'kiri.php' : '',
defined('APP_PATH') ? APP_PATH . 'bin/kiri' : '',
defined('APP_PATH') ? APP_PATH . 'artisan' : '',
];
foreach ($candidates as $candidate) {
if (is_string($candidate) && $candidate !== '' && is_file($candidate)) {
return $candidate;
}
}
return null;
}
} }
+2
View File
@@ -21,8 +21,10 @@ class ServerProviders extends Providers
public function onImport(): void public function onImport(): void
{ {
$server = $this->container->get(ServerCommand::class); $server = $this->container->get(ServerCommand::class);
$builder = $this->container->get(FileBuildCommand::class);
$console = $this->container->get(Application::class); $console = $this->container->get(Application::class);
$console->addCommand($server); $console->addCommand($server);
$console->addCommand($builder);
} }
} }