Compare commits
36 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 908c8719d3 | |||
| 69b845d924 | |||
| d9c8344a29 | |||
| ced9f89ebe | |||
| ee487649fa | |||
| 0cdb100180 | |||
| a9f1afb866 | |||
| 853a9661bc | |||
| 2d4951b0dd | |||
| e819fe9ba4 | |||
| 9e1e16dca9 | |||
| 77cf882f2e | |||
| eeb925b5b9 | |||
| 59042c0110 | |||
| 7c459cc9bc | |||
| 968cdbd11a | |||
| 37b59c8536 | |||
| 9376a73628 | |||
| eebaf63999 | |||
| e399837dad | |||
| 7b8a43f94f | |||
| c0f8133926 | |||
| f533d3262b | |||
| c767a1745a | |||
| 251e05dbf7 | |||
| 5defd5fb30 | |||
| 95f52b58fd | |||
| 0a97c9b29a | |||
| 3336573b4d | |||
| 44187c2354 | |||
| a058f3ed99 | |||
| faff485006 | |||
| e2b012126a | |||
| b36e21d8ee | |||
| d191296ecc | |||
| 03825dcb09 |
+135
-133
@@ -23,164 +23,166 @@ use Swoole\Server;
|
||||
class AsyncServer extends Component implements ServerInterface
|
||||
{
|
||||
|
||||
use TraitServer;
|
||||
use TraitProcess;
|
||||
use TraitServer;
|
||||
use TraitProcess;
|
||||
|
||||
|
||||
/**
|
||||
* @var Server|null
|
||||
*/
|
||||
private ?Server $server = null;
|
||||
/**
|
||||
* @var Server|null
|
||||
*/
|
||||
private ?Server $server = null;
|
||||
|
||||
|
||||
/**
|
||||
* @param array $service
|
||||
* @param int $daemon
|
||||
* @return void
|
||||
* @throws
|
||||
*/
|
||||
public function initCoreServers(array $service, int $daemon = 0): void
|
||||
{
|
||||
$service = $this->createBaseServer($this->genConfigService($service), $daemon);
|
||||
if (isset($this->server->setting[Constant::OPTION_TASK_WORKER_NUM])) {
|
||||
$this->container->get(Task::class)->initTaskWorker($this->server);
|
||||
}
|
||||
/**
|
||||
* @param array $service
|
||||
* @param int $daemon
|
||||
* @return void
|
||||
* @throws
|
||||
*/
|
||||
public function initCoreServers(array $service, int $daemon = 0): void
|
||||
{
|
||||
$service = $this->createBaseServer($this->genConfigService($service), $daemon);
|
||||
if (isset($this->server->setting[Constant::OPTION_TASK_WORKER_NUM])) {
|
||||
$this->container->get(Task::class)->initTaskWorker($this->server);
|
||||
}
|
||||
|
||||
foreach ($this->_process as $process) $this->server->addProcess($process);
|
||||
foreach ($service as $value) $this->addListener($value);
|
||||
foreach ($this->_process as $process)
|
||||
$this->server->addProcess($process);
|
||||
foreach ($service as $value)
|
||||
$this->addListener($value);
|
||||
|
||||
$this->provider->on(OnServerBeforeStart::class, [$this, 'onSignal']);
|
||||
}
|
||||
$this->provider->on(OnServerBeforeStart::class, [$this, 'onSignal']);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
* @throws
|
||||
*/
|
||||
public function shutdown(): bool
|
||||
{
|
||||
$this->server->shutdown();
|
||||
/**
|
||||
* @return bool
|
||||
* @throws
|
||||
*/
|
||||
public function shutdown(): bool
|
||||
{
|
||||
$this->server->shutdown();
|
||||
|
||||
$this->dispatch->dispatch(new OnShutdown());
|
||||
$this->dispatch->dispatch(new OnShutdown);
|
||||
|
||||
return true;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param array $service
|
||||
* @param int $daemon
|
||||
* @return array
|
||||
* @throws ContainerExceptionInterface
|
||||
* @throws NotFindClassException
|
||||
* @throws NotFoundExceptionInterface
|
||||
*/
|
||||
private function createBaseServer(array $service, int $daemon = 0): array
|
||||
{
|
||||
$config = array_pop($service);
|
||||
/**
|
||||
* @param array $service
|
||||
* @param int $daemon
|
||||
* @return array
|
||||
* @throws ContainerExceptionInterface
|
||||
* @throws NotFindClassException
|
||||
* @throws NotFoundExceptionInterface
|
||||
*/
|
||||
private function createBaseServer(array $service, int $daemon = 0): array
|
||||
{
|
||||
$config = array_pop($service);
|
||||
|
||||
$match = $this->getServerClass($config->type);
|
||||
if (is_null($match)) {
|
||||
throw new NotFindClassException('Unknown server type ' . $config->type);
|
||||
}
|
||||
$match = $this->getServerClass($config->type);
|
||||
if (is_null($match)) {
|
||||
throw new NotFindClassException('Unknown server type ' . $config->type);
|
||||
}
|
||||
|
||||
$this->container->get(StdoutLogger::class)->println('Listen address ' . $config->host . '::' . $config->port);
|
||||
$this->container->get(StdoutLogger::class)->println('Listen address ' . $config->type . ' ' . $config->host . '::' . $config->port);
|
||||
|
||||
$this->server = new $match($config->host, $config->port, $config->mode, $config->socket);
|
||||
$this->server->set($this->systemConfig($config, $daemon));
|
||||
if (!isset($config->events[Constant::SHUTDOWN])) {
|
||||
$config->events[Constant::SHUTDOWN] = [OnServer::class, 'onShutdown'];
|
||||
}
|
||||
$this->server = new $match($config->host, $config->port, $config->mode, $config->socket);
|
||||
$this->server->set($this->systemConfig($config, $daemon));
|
||||
if (!isset($config->events[Constant::SHUTDOWN])) {
|
||||
$config->events[Constant::SHUTDOWN] = [OnServer::class, 'onShutdown'];
|
||||
}
|
||||
|
||||
$this->event($this->server, array_merge(\config('server.events', []), $config->events));
|
||||
$this->container->bind(ServerInterface::class, $this->server);
|
||||
return $service;
|
||||
}
|
||||
$this->event($this->server, array_merge(\config('servers.server.events', []), $config->events));
|
||||
$this->container->bind(ServerInterface::class, $this->server);
|
||||
return $service;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param SConfig $config
|
||||
* @param int $daemon
|
||||
* @return array
|
||||
* @throws
|
||||
*/
|
||||
protected function systemConfig(SConfig $config, int $daemon): array
|
||||
{
|
||||
$settings = array_merge(\config('server.settings', []), $config->settings);
|
||||
$settings[Constant::OPTION_DAEMONIZE] = (bool)$daemon;
|
||||
$settings[Constant::OPTION_ENABLE_REUSE_PORT] = true;
|
||||
$settings[Constant::OPTION_PID_FILE] = storage('.swoole.pid');
|
||||
if (!isset($settings[Constant::OPTION_PID_FILE])) {
|
||||
$settings[Constant::OPTION_LOG_FILE] = storage('system.log');
|
||||
}
|
||||
return $settings;
|
||||
}
|
||||
/**
|
||||
* @param SConfig $config
|
||||
* @param int $daemon
|
||||
* @return array
|
||||
* @throws
|
||||
*/
|
||||
protected function systemConfig(SConfig $config, int $daemon): array
|
||||
{
|
||||
$settings = array_merge(\config('servers.server.settings', []), $config->settings);
|
||||
$settings[Constant::OPTION_DAEMONIZE] = (bool)$daemon;
|
||||
$settings[Constant::OPTION_ENABLE_REUSE_PORT] = true;
|
||||
$settings[Constant::OPTION_PID_FILE] = storage('.swoole.pid');
|
||||
if (!isset($settings[Constant::OPTION_PID_FILE])) {
|
||||
$settings[Constant::OPTION_LOG_FILE] = storage('system.log');
|
||||
}
|
||||
return $settings;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param SConfig $config
|
||||
* @return void
|
||||
* @throws
|
||||
*/
|
||||
public function addListener(SConfig $config): void
|
||||
{
|
||||
$port = $this->server->addlistener($config->host, $config->port, $config->socket);
|
||||
if ($port === false) {
|
||||
throw new Exception('Listen port fail.' . swoole_last_error());
|
||||
}
|
||||
$port->set($this->resetSettings($config->type, $config->settings));
|
||||
$this->event($port, $config->getEvents());
|
||||
/**
|
||||
* @param SConfig $config
|
||||
* @return void
|
||||
* @throws
|
||||
*/
|
||||
public function addListener(SConfig $config): void
|
||||
{
|
||||
$port = $this->server->addlistener($config->host, $config->port, $config->socket);
|
||||
if ($port === false) {
|
||||
throw new Exception('Listen port fail.' . swoole_last_error());
|
||||
}
|
||||
$port->set($this->resetSettings($config->type, $config->settings));
|
||||
$this->event($port, $config->getEvents());
|
||||
|
||||
$this->container->get(StdoutLogger::class)->println('Listen address ' . $config->host . '::' . $config->port);
|
||||
}
|
||||
$this->container->get(StdoutLogger::class)->println('Listen address ' . $config->type . ' ' . $config->host . '::' . $config->port);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $type
|
||||
* @param array $settings
|
||||
* @return array
|
||||
* @throws
|
||||
*/
|
||||
private function resetSettings(string $type, array $settings): array
|
||||
{
|
||||
if ($type == Constant::SERVER_TYPE_HTTP && !isset($settings['open_http_protocol'])) {
|
||||
$settings['open_http_protocol'] = true;
|
||||
if (in_array($this->server->setting['dispatch_mode'], [2, 4])) {
|
||||
$settings['open_http2_protocol'] = true;
|
||||
}
|
||||
}
|
||||
if ($type == Constant::SERVER_TYPE_WEBSOCKET && !isset($settings['open_websocket_protocol'])) {
|
||||
$settings['open_websocket_protocol'] = true;
|
||||
}
|
||||
return $settings;
|
||||
}
|
||||
/**
|
||||
* @param string $type
|
||||
* @param array $settings
|
||||
* @return array
|
||||
* @throws
|
||||
*/
|
||||
private function resetSettings(string $type, array $settings): array
|
||||
{
|
||||
if ($type == Constant::SERVER_TYPE_HTTP && !isset($settings['open_http_protocol'])) {
|
||||
$settings['open_http_protocol'] = true;
|
||||
if (in_array($this->server->setting['dispatch_mode'], [2, 4])) {
|
||||
$settings['open_http2_protocol'] = true;
|
||||
}
|
||||
}
|
||||
if ($type == Constant::SERVER_TYPE_WEBSOCKET && !isset($settings['open_websocket_protocol'])) {
|
||||
$settings['open_websocket_protocol'] = true;
|
||||
}
|
||||
return $settings;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param Server\Port|Server $base
|
||||
* @param array $events
|
||||
* @return void
|
||||
* @throws
|
||||
*/
|
||||
private function event(Server\Port|Server $base, array $events): void
|
||||
{
|
||||
$container = $this->container;
|
||||
foreach ($events as $name => $event) {
|
||||
if (is_array($event) && is_string($event[0])) {
|
||||
$event[0] = $container->get($event[0]);
|
||||
}
|
||||
$base->on($name, $event);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* @param Server\Port|Server $base
|
||||
* @param array $events
|
||||
* @return void
|
||||
* @throws
|
||||
*/
|
||||
private function event(Server\Port|Server $base, array $events): void
|
||||
{
|
||||
$container = $this->container;
|
||||
foreach ($events as $name => $event) {
|
||||
if (is_array($event) && is_string($event[0])) {
|
||||
$event[0] = $container->get($event[0]);
|
||||
}
|
||||
$base->on($name, $event);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return void
|
||||
* @throws
|
||||
*/
|
||||
public function start(): void
|
||||
{
|
||||
$this->dispatch->dispatch(new OnServerBeforeStart());
|
||||
$this->server->start();
|
||||
}
|
||||
/**
|
||||
* @return void
|
||||
* @throws
|
||||
*/
|
||||
public function start(): void
|
||||
{
|
||||
$this->dispatch->dispatch(new OnServerBeforeStart);
|
||||
$this->server->start();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,446 @@
|
||||
<?php
|
||||
|
||||
namespace Kiri\Server\Abstracts;
|
||||
|
||||
use Kiri\Di\HotReloadState;
|
||||
use Kiri\Di\Inject\Container;
|
||||
use Kiri\Error\StdoutLogger;
|
||||
use Kiri\Events\EventProvider;
|
||||
use Kiri\Router\Router;
|
||||
use Kiri\Server\Events\OnWorkerStart;
|
||||
use Kiri\Server\Processes\AbstractProcess;
|
||||
use Kiri\Server\Processes\OnProcessInterface;
|
||||
use Kiri\Server\ServerInterface;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Swoole\Event;
|
||||
use Swoole\Process;
|
||||
|
||||
class FileWatcher extends AbstractProcess implements OnProcessInterface
|
||||
{
|
||||
protected mixed $pipe;
|
||||
|
||||
#[Container(LoggerInterface::class)]
|
||||
public StdoutLogger|LoggerInterface $logger;
|
||||
|
||||
protected bool $enable_coroutine = false;
|
||||
|
||||
protected array $watches = [];
|
||||
|
||||
protected bool $enable_queue = false;
|
||||
|
||||
protected bool $reloading = false;
|
||||
|
||||
private array $watchPaths = [];
|
||||
private array $excludePatterns = [];
|
||||
private array $extensions = ['php'];
|
||||
private string $strategy;
|
||||
private bool $running = false;
|
||||
|
||||
private $inotifyFd = null;
|
||||
private array $inotifyWatchMap = [];
|
||||
private $fswatchProcess = null;
|
||||
private array $fswatchPipes = [];
|
||||
private int $pollInterval = 2;
|
||||
private array $fileSnapshot = [];
|
||||
private $pollTimer = null;
|
||||
private $debounceTimer = null;
|
||||
private int $debounceMs = 200;
|
||||
|
||||
private const STRATEGY_INOTIFY = 'inotify';
|
||||
private const STRATEGY_FSWATCH = 'fswatch';
|
||||
private const STRATEGY_POLL = 'poll';
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->watchPaths = config('servers.reload.listen', []);
|
||||
$this->excludePatterns = config('servers.reload.scan.skip_patterns', []);
|
||||
$this->extensions = config('servers.reload.scan.extensions', ['php']);
|
||||
|
||||
di(EventProvider::class)->on(OnWorkerStart::class, [di(Router::class), 'scan_build_route']);
|
||||
|
||||
$this->strategy = $this->detectBestStrategy();
|
||||
}
|
||||
|
||||
public function getName(): string
|
||||
{
|
||||
return 'hotReload';
|
||||
}
|
||||
|
||||
public function onSigterm(): void
|
||||
{
|
||||
$this->stop();
|
||||
}
|
||||
|
||||
private function detectBestStrategy(): string
|
||||
{
|
||||
$forced = config('servers.reload.scan.strategy', 'auto');
|
||||
if (in_array($forced, [self::STRATEGY_INOTIFY, self::STRATEGY_FSWATCH, self::STRATEGY_POLL], true)) {
|
||||
return $forced;
|
||||
}
|
||||
|
||||
if ($this->isMountedWindowsPath()) {
|
||||
return $this->isFswatchAvailable() ? self::STRATEGY_FSWATCH : self::STRATEGY_POLL;
|
||||
}
|
||||
|
||||
if (extension_loaded('inotify')) {
|
||||
return self::STRATEGY_INOTIFY;
|
||||
}
|
||||
|
||||
if ($this->isFswatchAvailable()) {
|
||||
return self::STRATEGY_FSWATCH;
|
||||
}
|
||||
|
||||
return self::STRATEGY_POLL;
|
||||
}
|
||||
|
||||
private function isMountedWindowsPath(): bool
|
||||
{
|
||||
foreach ($this->watchPaths as $path) {
|
||||
$real = realpath($path) ?: (string)$path;
|
||||
$real = str_replace('\\', '/', $real);
|
||||
if (str_starts_with($real, '/mnt/')) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private function isFswatchAvailable(): bool
|
||||
{
|
||||
$output = [];
|
||||
$returnVar = 0;
|
||||
exec('which fswatch 2>/dev/null', $output, $returnVar);
|
||||
return $returnVar === 0 && !empty($output[0]);
|
||||
}
|
||||
|
||||
public function setDebounce(int $milliseconds): self
|
||||
{
|
||||
$this->debounceMs = $milliseconds;
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function setPollInterval(int $seconds): self
|
||||
{
|
||||
$this->pollInterval = $seconds;
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function process(Process|null $process): void
|
||||
{
|
||||
if ($this->running) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->running = true;
|
||||
|
||||
switch ($this->strategy) {
|
||||
case self::STRATEGY_INOTIFY:
|
||||
$this->startInotify();
|
||||
break;
|
||||
case self::STRATEGY_FSWATCH:
|
||||
$this->startFswatch();
|
||||
break;
|
||||
case self::STRATEGY_POLL:
|
||||
$this->startPolling();
|
||||
break;
|
||||
}
|
||||
|
||||
Event::wait();
|
||||
}
|
||||
|
||||
public function stop(): void
|
||||
{
|
||||
$this->running = false;
|
||||
|
||||
if ($this->inotifyFd && is_resource($this->inotifyFd)) {
|
||||
@Event::del($this->inotifyFd);
|
||||
@fclose($this->inotifyFd);
|
||||
$this->inotifyFd = null;
|
||||
}
|
||||
|
||||
if (isset($this->fswatchPipes[1]) && is_resource($this->fswatchPipes[1])) {
|
||||
@Event::del($this->fswatchPipes[1]);
|
||||
@fclose($this->fswatchPipes[1]);
|
||||
}
|
||||
|
||||
if (isset($this->fswatchPipes[2]) && is_resource($this->fswatchPipes[2])) {
|
||||
@fclose($this->fswatchPipes[2]);
|
||||
}
|
||||
|
||||
if ($this->fswatchProcess && is_resource($this->fswatchProcess)) {
|
||||
@proc_terminate($this->fswatchProcess);
|
||||
@proc_close($this->fswatchProcess);
|
||||
$this->fswatchProcess = null;
|
||||
}
|
||||
|
||||
if ($this->pollTimer) {
|
||||
\Swoole\Timer::clear($this->pollTimer);
|
||||
$this->pollTimer = null;
|
||||
}
|
||||
|
||||
if ($this->debounceTimer) {
|
||||
\Swoole\Timer::clear($this->debounceTimer);
|
||||
$this->debounceTimer = null;
|
||||
}
|
||||
|
||||
@Event::exit();
|
||||
}
|
||||
|
||||
private function isExcluded(string $path): bool
|
||||
{
|
||||
foreach ($this->excludePatterns as $pattern) {
|
||||
if (strpos($path, $pattern) !== false) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private function hasValidExtension(string $path): bool
|
||||
{
|
||||
if (empty($this->extensions)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$ext = pathinfo($path, PATHINFO_EXTENSION);
|
||||
return in_array($ext, $this->extensions, true);
|
||||
}
|
||||
|
||||
private function triggerCallback(array $changedFiles): void
|
||||
{
|
||||
$changedFiles = array_values(array_unique(array_filter($changedFiles, function ($file) {
|
||||
return !$this->isExcluded($file) && $this->hasValidExtension($file);
|
||||
})));
|
||||
|
||||
if (empty($changedFiles)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ($this->debounceTimer) {
|
||||
\Swoole\Timer::clear($this->debounceTimer);
|
||||
}
|
||||
|
||||
$this->debounceTimer = \Swoole\Timer::after($this->debounceMs, function () use ($changedFiles) {
|
||||
$this->debounceTimer = null;
|
||||
$this->reload($changedFiles);
|
||||
});
|
||||
}
|
||||
|
||||
private function reload(array $changedFiles): void
|
||||
{
|
||||
if ($this->reloading) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->reloading = true;
|
||||
|
||||
try {
|
||||
$preview = implode(', ', array_slice($changedFiles, 0, 3));
|
||||
if (count($changedFiles) > 3) {
|
||||
$preview .= ' ...';
|
||||
}
|
||||
|
||||
di(HotReloadState::class)->store($changedFiles);
|
||||
di(StdoutLogger::class)->println('detected file changes, reloading server: ' . $preview);
|
||||
|
||||
$server = di(ServerInterface::class);
|
||||
if (method_exists($server, 'reload')) {
|
||||
$server->reload();
|
||||
}
|
||||
} finally {
|
||||
$this->reloading = false;
|
||||
}
|
||||
}
|
||||
|
||||
private function startInotify(): void
|
||||
{
|
||||
$this->inotifyFd = inotify_init();
|
||||
stream_set_blocking($this->inotifyFd, false);
|
||||
|
||||
foreach ($this->watchPaths as $path) {
|
||||
$this->addInotifyWatchRecursive($path);
|
||||
}
|
||||
|
||||
Event::add($this->inotifyFd, function ($fd) {
|
||||
$events = inotify_read($fd);
|
||||
if ($events === false) {
|
||||
return;
|
||||
}
|
||||
|
||||
$changedFiles = [];
|
||||
foreach ($events as $event) {
|
||||
$wd = $event['wd'];
|
||||
$dir = $this->inotifyWatchMap[$wd] ?? '';
|
||||
$name = $event['name'] ?? '';
|
||||
$filePath = $name === '' ? $dir : $dir . '/' . $name;
|
||||
|
||||
if (($event['mask'] & IN_CREATE) && $filePath !== '' && is_dir($filePath) && !$this->isExcluded($filePath)) {
|
||||
$this->addInotifyWatchRecursive($filePath);
|
||||
}
|
||||
|
||||
if ($filePath !== '') {
|
||||
$changedFiles[] = $filePath;
|
||||
}
|
||||
}
|
||||
|
||||
$this->triggerCallback($changedFiles);
|
||||
});
|
||||
}
|
||||
|
||||
private function addInotifyWatchRecursive(string $path): void
|
||||
{
|
||||
if ($this->isExcluded($path)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (is_file($path)) {
|
||||
if ($this->hasValidExtension($path)) {
|
||||
$wd = inotify_add_watch($this->inotifyFd, $path, IN_MODIFY | IN_CREATE | IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
|
||||
$this->inotifyWatchMap[$wd] = dirname($path);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!is_dir($path)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$wd = inotify_add_watch($this->inotifyFd, $path, IN_MODIFY | IN_CREATE | IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
|
||||
$this->inotifyWatchMap[$wd] = $path;
|
||||
|
||||
$items = scandir($path);
|
||||
foreach ($items as $item) {
|
||||
if ($item === '.' || $item === '..') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$full = $path . '/' . $item;
|
||||
if (is_dir($full)) {
|
||||
$this->addInotifyWatchRecursive($full);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private function startFswatch(): void
|
||||
{
|
||||
$descriptorspec = [
|
||||
0 => ['pipe', 'r'],
|
||||
1 => ['pipe', 'w'],
|
||||
2 => ['pipe', 'w'],
|
||||
];
|
||||
|
||||
$excludeArgs = [];
|
||||
foreach ($this->excludePatterns as $pattern) {
|
||||
$excludeArgs[] = '--exclude';
|
||||
$excludeArgs[] = '.*' . preg_quote($pattern, '/') . '.*';
|
||||
}
|
||||
|
||||
$filterArgs = [];
|
||||
foreach ($this->extensions as $ext) {
|
||||
$filterArgs[] = '--include';
|
||||
$filterArgs[] = '\.' . $ext . '$';
|
||||
}
|
||||
|
||||
$cmd = 'fswatch -0 -r ' . implode(' ', array_merge($excludeArgs, $filterArgs)) . ' ' . implode(' ', array_map('escapeshellarg', $this->watchPaths));
|
||||
|
||||
$this->fswatchProcess = proc_open($cmd, $descriptorspec, $this->fswatchPipes);
|
||||
if (!is_resource($this->fswatchProcess)) {
|
||||
throw new \RuntimeException('Failed to start fswatch process');
|
||||
}
|
||||
|
||||
stream_set_blocking($this->fswatchPipes[1], false);
|
||||
|
||||
Event::add($this->fswatchPipes[1], function ($pipe) {
|
||||
$data = fread($pipe, 8192);
|
||||
if ($data === false || $data === '') {
|
||||
return;
|
||||
}
|
||||
|
||||
$files = explode("\0", trim($data, "\0"));
|
||||
$changedFiles = array_values(array_filter($files, function ($file) {
|
||||
return $file !== '';
|
||||
}));
|
||||
|
||||
$this->triggerCallback($changedFiles);
|
||||
});
|
||||
}
|
||||
|
||||
private function startPolling(): void
|
||||
{
|
||||
$this->buildFileSnapshot();
|
||||
|
||||
$intervalMs = $this->pollInterval * 1000;
|
||||
$this->pollTimer = \Swoole\Timer::tick($intervalMs, function () {
|
||||
$newSnapshot = [];
|
||||
$changedFiles = $this->compareSnapshots($newSnapshot);
|
||||
if (!empty($changedFiles)) {
|
||||
$this->triggerCallback($changedFiles);
|
||||
}
|
||||
|
||||
$this->fileSnapshot = $newSnapshot;
|
||||
});
|
||||
}
|
||||
|
||||
private function buildFileSnapshot(): void
|
||||
{
|
||||
$this->fileSnapshot = [];
|
||||
foreach ($this->watchPaths as $path) {
|
||||
$this->scanDirectory($path, $this->fileSnapshot);
|
||||
}
|
||||
}
|
||||
|
||||
private function scanDirectory(string $path, array &$snapshot): void
|
||||
{
|
||||
if ($this->isExcluded($path)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (is_file($path)) {
|
||||
if ($this->hasValidExtension($path)) {
|
||||
$snapshot[$path] = filemtime($path);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!is_dir($path)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$items = scandir($path);
|
||||
foreach ($items as $item) {
|
||||
if ($item === '.' || $item === '..') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$full = $path . '/' . $item;
|
||||
$this->scanDirectory($full, $snapshot);
|
||||
}
|
||||
}
|
||||
|
||||
private function compareSnapshots(array &$newSnapshot): array
|
||||
{
|
||||
$changed = [];
|
||||
|
||||
foreach ($this->watchPaths as $path) {
|
||||
$this->scanDirectory($path, $newSnapshot);
|
||||
}
|
||||
|
||||
foreach ($newSnapshot as $file => $mtime) {
|
||||
if (!isset($this->fileSnapshot[$file])) {
|
||||
$changed[] = $file;
|
||||
} elseif ($this->fileSnapshot[$file] !== $mtime) {
|
||||
$changed[] = $file;
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($this->fileSnapshot as $file => $mtime) {
|
||||
if (!isset($newSnapshot[$file])) {
|
||||
$changed[] = $file;
|
||||
}
|
||||
}
|
||||
|
||||
return $changed;
|
||||
}
|
||||
}
|
||||
@@ -113,7 +113,7 @@ class HotReload extends AbstractProcess
|
||||
}
|
||||
$this->reloading = true;
|
||||
|
||||
di(StdoutLogger::class)->println('reloading server[' . \config('id', 'system-service') . '], please waite.');
|
||||
di(StdoutLogger::class)->println('reloading server[' . \config('site.id', 'system-service') . '], please waite.');
|
||||
|
||||
$this->clear();
|
||||
di(ServerInterface::class)->reload();
|
||||
@@ -128,7 +128,7 @@ class HotReload extends AbstractProcess
|
||||
*/
|
||||
protected function addListen(): void
|
||||
{
|
||||
foreach (config('reload.listen') as $value) {
|
||||
foreach (config('servers.reload.listen') as $value) {
|
||||
$this->readDirectory($value);
|
||||
}
|
||||
}
|
||||
@@ -149,9 +149,7 @@ class HotReload extends AbstractProcess
|
||||
public function readFile(string $directory): void
|
||||
{
|
||||
if (str_ends_with($directory, '.php') === true) {
|
||||
$wd = inotify_add_watch($this->pipe, $directory, IN_MODIFY | IN_MOVE | IN_CREATE | IN_DELETE);
|
||||
|
||||
$this->watches[] = $wd;
|
||||
inotify_add_watch($this->pipe, $directory, IN_MODIFY | IN_MOVE | IN_CREATE | IN_DELETE);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -170,4 +168,4 @@ class HotReload extends AbstractProcess
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+19
-7
@@ -4,6 +4,8 @@
|
||||
namespace Kiri\Server\Abstracts;
|
||||
|
||||
|
||||
use Kiri\Error\StdoutLogger;
|
||||
|
||||
/**
|
||||
* Class Server
|
||||
* @package Server\Abstracts
|
||||
@@ -11,12 +13,22 @@ namespace Kiri\Server\Abstracts;
|
||||
abstract class Server
|
||||
{
|
||||
|
||||
/**
|
||||
* Server constructor.
|
||||
* @throws
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
}
|
||||
/**
|
||||
* Server constructor.
|
||||
* @throws
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return StdoutLogger
|
||||
*/
|
||||
protected function getLogger(): StdoutLogger
|
||||
{
|
||||
return \Kiri::getLogger();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ trait TraitServer
|
||||
*/
|
||||
public function onSignal(): void
|
||||
{
|
||||
$signal = \config('signal', []);
|
||||
$signal = \config('servers.signal', []);
|
||||
$this->onPcntlSignal(SIGINT, [$this, 'onSigint']);
|
||||
foreach ($signal as $sig => $value) {
|
||||
if (is_array($value) && is_string($value[0])) {
|
||||
@@ -46,7 +46,7 @@ trait TraitServer
|
||||
Kiri::getLogger()->alert('Pid ' . getmypid() . ' get signo ' . $no);
|
||||
$this->shutdown();
|
||||
} catch (\Throwable $exception) {
|
||||
error($exception);
|
||||
\Kiri::getLogger()->json_log($exception);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -102,7 +102,7 @@ trait TraitServer
|
||||
if ($port['type'] == Constant::SERVER_TYPE_WEBSOCKET) {
|
||||
array_unshift($array, $config);
|
||||
} else if ($port['type'] == Constant::SERVER_TYPE_HTTP) {
|
||||
if (!empty($array) && $array[0]['type'] == Constant::SERVER_TYPE_WEBSOCKET) {
|
||||
if (!empty($array) && $array[0]->type == Constant::SERVER_TYPE_WEBSOCKET) {
|
||||
$array[] = $config;
|
||||
} else {
|
||||
array_unshift($array, $config);
|
||||
|
||||
@@ -13,10 +13,11 @@ interface OnCloseInterface
|
||||
|
||||
/**
|
||||
* @param Server $server
|
||||
* @param int $fd
|
||||
* @param int $fd
|
||||
* @param int $reactorId
|
||||
* @return void
|
||||
*/
|
||||
public function onClose(Server $server, int $fd): void;
|
||||
public function onClose(Server $server, int $fd, int $reactorId): void;
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -10,9 +10,10 @@ interface OnConnectInterface
|
||||
|
||||
/**
|
||||
* @param Server $server
|
||||
* @param int $fd
|
||||
* @param int $fd
|
||||
* @param int $reactorId
|
||||
* @return void
|
||||
*/
|
||||
public function onConnect(Server $server, int $fd): void;
|
||||
public function onConnect(Server $server, int $fd, int $reactorId): void;
|
||||
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
namespace Kiri\Server\Contract;
|
||||
|
||||
use Swoole\WebSocket\Server;
|
||||
use Swoole\{WebSocket\Server};
|
||||
|
||||
interface OnDisconnectInterface
|
||||
{
|
||||
@@ -10,7 +10,7 @@ interface OnDisconnectInterface
|
||||
|
||||
/**
|
||||
* @param Server $server
|
||||
* @param int $fd
|
||||
* @param int $fd
|
||||
* @return void
|
||||
*/
|
||||
public function onDisconnect(Server $server, int $fd): void;
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
namespace Kiri\Server\Contract;
|
||||
|
||||
use Swoole\Server;
|
||||
use Swoole\WebSocket\Server;
|
||||
use Swoole\WebSocket\Frame;
|
||||
|
||||
interface OnMessageInterface
|
||||
@@ -11,7 +11,7 @@ interface OnMessageInterface
|
||||
|
||||
/**
|
||||
* @param Server $server
|
||||
* @param Frame $frame
|
||||
* @param Frame $frame
|
||||
* @return void
|
||||
*/
|
||||
public function onMessage(Server $server, Frame $frame): void;
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
namespace Kiri\Server\Contract;
|
||||
|
||||
use Swoole\Http\Request;
|
||||
use Swoole\Http\Server;
|
||||
use Swoole\WebSocket\Server;
|
||||
|
||||
interface OnOpenInterface
|
||||
{
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
namespace Kiri\Server\Contract;
|
||||
|
||||
|
||||
use Swoole\Server;
|
||||
|
||||
/**
|
||||
* Interface OnPipeMessageInterface
|
||||
* @package Server\Contract
|
||||
@@ -12,9 +14,12 @@ interface OnPipeMessageInterface
|
||||
{
|
||||
|
||||
/**
|
||||
*
|
||||
* @param Server $server
|
||||
* @param int $src_worker_id
|
||||
* @param mixed $message
|
||||
* @return void
|
||||
*/
|
||||
public function process(): void;
|
||||
public function onPipeMessage(Server $server, int $src_worker_id, mixed $message): void;
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,33 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Kiri\Server\Handler;
|
||||
|
||||
use Kiri\Server\Abstracts\Server;
|
||||
use Kiri\Server\Contract\OnPipeMessageInterface;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
class OnPipeMessage extends Server
|
||||
{
|
||||
|
||||
|
||||
/**
|
||||
* @param \Swoole\Server $server
|
||||
* @param int $src_worker_id
|
||||
* @param mixed $message
|
||||
* @throws
|
||||
*/
|
||||
public function onPipeMessage(\Swoole\Server $server, int $src_worker_id, mixed $message): void
|
||||
{
|
||||
if (is_string($message)) {
|
||||
$message = unserialize($message);
|
||||
}
|
||||
if (!is_object($message) || !($message instanceof OnPipeMessageInterface)) {
|
||||
return;
|
||||
}
|
||||
call_user_func([$message, 'process'], $server, $src_worker_id);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+115
-111
@@ -30,135 +30,139 @@ class OnServerWorker extends Kiri\Server\Abstracts\Server
|
||||
{
|
||||
|
||||
|
||||
/**
|
||||
* @var EventDispatch
|
||||
*/
|
||||
#[Container(EventDispatch::class)]
|
||||
public EventDispatch $dispatch;
|
||||
/**
|
||||
* @var EventDispatch
|
||||
*/
|
||||
#[Container(EventDispatch::class)]
|
||||
public EventDispatch $dispatch;
|
||||
|
||||
|
||||
/**
|
||||
* @return void
|
||||
*/
|
||||
public function init(): void
|
||||
{
|
||||
on(OnBeforeWorkerStart::class, [$this, 'onWorkerNameAlias']);
|
||||
}
|
||||
/**
|
||||
* @return void
|
||||
*/
|
||||
public function init(): void
|
||||
{
|
||||
on(OnBeforeWorkerStart::class, [$this, 'onWorkerNameAlias']);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param OnBeforeWorkerStart $workerStart
|
||||
* @return void
|
||||
*/
|
||||
public function onWorkerNameAlias(OnBeforeWorkerStart $workerStart): void
|
||||
{
|
||||
set_env('environmental_workerId', $workerStart->workerId);
|
||||
if ($workerStart->workerId < $workerStart->server->setting['worker_num']) {
|
||||
$this->processName($workerStart->server, 'Worker');
|
||||
set_env('environmental', Kiri::WORKER);
|
||||
} else {
|
||||
$this->processName($workerStart->server, 'Tasker');
|
||||
set_env('environmental', Kiri::TASK);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* @param OnBeforeWorkerStart $workerStart
|
||||
* @return void
|
||||
*/
|
||||
public function onWorkerNameAlias(OnBeforeWorkerStart $workerStart): void
|
||||
{
|
||||
if ($workerStart->workerId < $workerStart->server->setting['worker_num']) {
|
||||
$this->processName($workerStart->server, 'Worker');
|
||||
set_env('environmental', Kiri::WORKER);
|
||||
} else {
|
||||
$this->processName($workerStart->server, 'Tasker');
|
||||
set_env('environmental', Kiri::TASK);
|
||||
}
|
||||
set_env('environmental_worker_id', $workerStart->workerId);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param Server $server
|
||||
* @param int $workerId
|
||||
* @return void
|
||||
* @throws
|
||||
*/
|
||||
public function onWorkerStart(Server $server, int $workerId): void
|
||||
{
|
||||
$this->dispatch->dispatch(new OnBeforeWorkerStart($server, $workerId));
|
||||
if ($workerId < $server->setting['worker_num']) {
|
||||
CoordinatorManager::utility(Coordinator::WORKER_START)->waite();
|
||||
/**
|
||||
* @param Server $server
|
||||
* @param int $workerId
|
||||
* @return void
|
||||
* @throws
|
||||
*/
|
||||
public function onWorkerStart(Server $server, int $workerId): void
|
||||
{
|
||||
try {
|
||||
$this->dispatch->dispatch(new OnBeforeWorkerStart($server, $workerId));
|
||||
if ($workerId < $server->setting['worker_num']) {
|
||||
CoordinatorManager::utility(Coordinator::WORKER_START)->wait();
|
||||
|
||||
$this->dispatch->dispatch(new OnWorkerStart($server, $workerId));
|
||||
} else {
|
||||
$this->dispatch->dispatch(new OnTaskerStart($server, $workerId));
|
||||
}
|
||||
$this->dispatch->dispatch(new OnAfterWorkerStart($server, $workerId));
|
||||
}
|
||||
$this->dispatch->dispatch(new OnWorkerStart($server, $workerId));
|
||||
} else {
|
||||
$this->dispatch->dispatch(new OnTaskerStart($server, $workerId));
|
||||
}
|
||||
} catch (Throwable $exception) {
|
||||
\Kiri::getLogger()->json_log($exception);
|
||||
} finally {
|
||||
$this->dispatch->dispatch(new OnAfterWorkerStart($server, $workerId));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param Server $server
|
||||
* @param string $prefix
|
||||
* @return void
|
||||
*/
|
||||
protected function processName(Server $server, string $prefix): void
|
||||
{
|
||||
Kiri::setProcessName(sprintf($prefix . '[%d]', $server->worker_pid));
|
||||
}
|
||||
/**
|
||||
* @param Server $server
|
||||
* @param string $prefix
|
||||
* @return void
|
||||
*/
|
||||
protected function processName(Server $server, string $prefix): void
|
||||
{
|
||||
Kiri::setProcessName(sprintf($prefix . '[%d]', $server->worker_pid));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param Server $server
|
||||
* @param int $workerId
|
||||
* @throws
|
||||
*/
|
||||
public function onWorkerStop(Server $server, int $workerId): void
|
||||
{
|
||||
event(new OnWorkerStop($server, $workerId));
|
||||
Timer::clearAll();
|
||||
}
|
||||
/**
|
||||
* @param Server $server
|
||||
* @param int $workerId
|
||||
* @throws
|
||||
*/
|
||||
public function onWorkerStop(Server $server, int $workerId): void
|
||||
{
|
||||
event(new OnWorkerStop($server, $workerId));
|
||||
Timer::clearAll();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param Server $server
|
||||
* @param int $workerId
|
||||
* @throws
|
||||
*/
|
||||
public function onWorkerExit(Server $server, int $workerId): void
|
||||
{
|
||||
event(new OnWorkerExit($server, $workerId));
|
||||
}
|
||||
/**
|
||||
* @param Server $server
|
||||
* @param int $workerId
|
||||
* @throws
|
||||
*/
|
||||
public function onWorkerExit(Server $server, int $workerId): void
|
||||
{
|
||||
event(new OnWorkerExit($server, $workerId));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param Server $server
|
||||
* @param int $worker_id
|
||||
* @param int $worker_pid
|
||||
* @param int $exit_code
|
||||
* @param int $signal
|
||||
* @throws
|
||||
*/
|
||||
public function onWorkerError(Server $server, int $worker_id, int $worker_pid, int $exit_code, int $signal): void
|
||||
{
|
||||
event(new OnWorkerError($server, $worker_id, $worker_pid, $exit_code, $signal));
|
||||
/**
|
||||
* @param Server $server
|
||||
* @param int $worker_id
|
||||
* @param int $worker_pid
|
||||
* @param int $exit_code
|
||||
* @param int $signal
|
||||
* @throws
|
||||
*/
|
||||
public function onWorkerError(Server $server, int $worker_id, int $worker_pid, int $exit_code, int $signal): void
|
||||
{
|
||||
event(new OnWorkerError($server, $worker_id, $worker_pid, $exit_code, $signal));
|
||||
|
||||
debug_print_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT);
|
||||
debug_print_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT);
|
||||
|
||||
/** @var RequestInterface $context */
|
||||
$context = Kiri\Di\Context::get(RequestInterface::class);
|
||||
if (is_null($context)) {
|
||||
$message = sprintf('Worker#%d::%d error stop. signal %d, exit_code %d, msg %s', $worker_id, $worker_pid, $signal, $exit_code, swoole_strerror(swoole_last_error(), $signal));
|
||||
} else {
|
||||
$message = sprintf('Worker#%d::%d error stop. signal %d, exit_code %d, msg %s, method: %s, path: %s, query: %s', $worker_id, $worker_pid, $signal, $exit_code, swoole_strerror(swoole_last_error(), $signal),
|
||||
$context->getMethod(), $context->getUri()->getPath(), $context->getUri()->getQuery());
|
||||
}
|
||||
error($message . PHP_EOL);
|
||||
|
||||
$this->system_mail($message);
|
||||
}
|
||||
/** @var RequestInterface $context */
|
||||
$context = Kiri\Di\Context::get(RequestInterface::class);
|
||||
if (is_null($context)) {
|
||||
$message = sprintf('Worker#%d::%d error stop. signal %d, exit_code %d, msg %s', $worker_id, $worker_pid, $signal, $exit_code, swoole_strerror(swoole_last_error(), $signal));
|
||||
} else {
|
||||
$message = sprintf('Worker#%d::%d error stop. signal %d, exit_code %d, msg %s, method: %s, path: %s, query: %s', $worker_id, $worker_pid, $signal, $exit_code, swoole_strerror(swoole_last_error(), $signal),
|
||||
$context->getMethod(), $context->getUri()->getPath(), $context->getUri()->getQuery());
|
||||
}
|
||||
$this->getLogger()->println($message);
|
||||
$this->system_mail($message);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $messageContent
|
||||
* @throws
|
||||
*/
|
||||
protected function system_mail($messageContent): void
|
||||
{
|
||||
try {
|
||||
$email = config('email', ['enable' => false]);
|
||||
if (!empty($email) && ($email['enable'] ?? false)) {
|
||||
Help::sendEmail($email, 'Service Error', $messageContent);
|
||||
}
|
||||
} catch (Throwable $e) {
|
||||
error($e, ['email']);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* @param $messageContent
|
||||
* @throws
|
||||
*/
|
||||
protected function system_mail($messageContent): void
|
||||
{
|
||||
try {
|
||||
$email = config('email', ['enable' => false]);
|
||||
if (!empty($email) && ($email['enable'] ?? false)) {
|
||||
Help::sendEmail($email, 'Service Error', $messageContent);
|
||||
}
|
||||
} catch (Throwable $e) {
|
||||
\Kiri::getLogger()->json_log($e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -5,6 +5,8 @@ namespace Kiri\Server\Processes;
|
||||
|
||||
use Swoole\Coroutine;
|
||||
use Swoole\Process;
|
||||
use const SIGHUP;
|
||||
use const SIGTERM;
|
||||
|
||||
/**
|
||||
*
|
||||
@@ -125,26 +127,29 @@ abstract class AbstractProcess implements OnProcessInterface
|
||||
{
|
||||
$this->process = $process;
|
||||
if ($this->enable_coroutine) {
|
||||
Coroutine::set([
|
||||
'enable_deadlock_check' => false,
|
||||
'deadlock_check_disable_trace' => false,
|
||||
'exit_condition' => function () {
|
||||
return Coroutine::stats()['coroutine_num'] === 0;
|
||||
}
|
||||
]);
|
||||
Coroutine::create(fn () => $this->coroutineWaitSignal());
|
||||
$array['enable_deadlock_check'] = false;
|
||||
$array['deadlock_check_disable_trace'] = false;
|
||||
$array['exit_condition'] = [$this, 'exit_condition'];
|
||||
Coroutine::set($array);
|
||||
Coroutine::create(fn() => $this->coroutineWaitSignal());
|
||||
} else {
|
||||
pcntl_signal(SIGTERM, [$this, 'pointWaitSignal']);
|
||||
$process::signal(SIGTERM | SIGINT | SIGUSR1, [$this, 'pointWaitSignal']);
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
public function exit_condition(): bool
|
||||
{
|
||||
return Coroutine::stats()['coroutine_num'] === 0;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $data
|
||||
* @param $signal
|
||||
* @return void
|
||||
*/
|
||||
public function pointWaitSignal($data): void
|
||||
public function pointWaitSignal($signal): void
|
||||
{
|
||||
$this->stop = true;
|
||||
|
||||
|
||||
@@ -40,7 +40,7 @@ trait TraitProcess
|
||||
private function genProcess(AbstractProcess $name): Process
|
||||
{
|
||||
return new Process(function (Process $process) use ($name) {
|
||||
$process->name('[' . \config('id', 'system-service') . '].' . $name->getName() . '[' . $process->pid . ']');
|
||||
$process->name('[' . \config('site.id', 'system-service') . '].' . $name->getName() . '[' . $process->pid . ']');
|
||||
$name->onShutdown($process)->process($process);
|
||||
},
|
||||
$name->getRedirectStdinAndStdout(),
|
||||
@@ -66,4 +66,4 @@ trait TraitProcess
|
||||
{
|
||||
return $this->_process;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+21
-29
@@ -6,6 +6,7 @@ namespace Kiri\Server;
|
||||
|
||||
use Exception;
|
||||
use Kiri;
|
||||
use Kiri\Server\Abstracts\FileWatcher;
|
||||
use Kiri\Server\Events\OnWorkerStart;
|
||||
use Kiri\Events\EventProvider;
|
||||
use Kiri\Events\EventDispatch;
|
||||
@@ -33,6 +34,7 @@ class ServerCommand extends Command
|
||||
{
|
||||
|
||||
|
||||
#[Container(State::class)]
|
||||
public State $state;
|
||||
|
||||
|
||||
@@ -64,17 +66,6 @@ class ServerCommand extends Command
|
||||
public EventProvider $eventProvider;
|
||||
|
||||
|
||||
/**
|
||||
* @param string|null $name
|
||||
* @throws Exception
|
||||
*/
|
||||
public function __construct(string $name = null)
|
||||
{
|
||||
parent::__construct($name);
|
||||
$this->state = Kiri::getDi()->get(State::class);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return void
|
||||
*/
|
||||
@@ -124,7 +115,7 @@ class ServerCommand extends Command
|
||||
*/
|
||||
protected function stop(): int
|
||||
{
|
||||
$configs = config('server', []);
|
||||
$configs = config('servers.server', []);
|
||||
$instances = $this->asyncServer->sortService($configs['ports'] ?? []);
|
||||
foreach ($instances as $config) {
|
||||
$this->state->exit($config->port);
|
||||
@@ -134,22 +125,23 @@ class ServerCommand extends Command
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param InputInterface $input
|
||||
* @return int
|
||||
* @throws
|
||||
*/
|
||||
protected function start(InputInterface $input): int
|
||||
{
|
||||
$this->asyncServer->addProcess(config('processes', []));
|
||||
if (\config('reload.hot', false) === true) {
|
||||
$this->asyncServer->addProcess([HotReload::class]);
|
||||
} else {
|
||||
di(Router::class)->scan_build_route();
|
||||
}
|
||||
$this->asyncServer->initCoreServers(config('server', []), (int)$input->getOption('daemon'));
|
||||
$this->asyncServer->start();
|
||||
return 1;
|
||||
}
|
||||
/**
|
||||
* @param InputInterface $input
|
||||
* @return int
|
||||
* @throws
|
||||
*/
|
||||
protected function start(InputInterface $input): int
|
||||
{
|
||||
$this->asyncServer->addProcess(config('process', []));
|
||||
if (\config('servers.reload.hot', false) === true) {
|
||||
$this->asyncServer->addProcess([FileWatcher::class]);
|
||||
}
|
||||
// Master 进程在 fork 前完成首次扫描,Worker 启动时不再重复全量扫描
|
||||
// 避免每个 Worker 独立执行 opcache_compile_file + invalidateClasses 造成 OOM
|
||||
di(Router::class)->scan_build_route();
|
||||
$this->asyncServer->initCoreServers(config('servers.server', []), (int)$input->getOption('daemon'));
|
||||
$this->asyncServer->start();
|
||||
return 1;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+1
-1
@@ -23,6 +23,6 @@ class ServerProviders extends Providers
|
||||
$server = $this->container->get(ServerCommand::class);
|
||||
|
||||
$console = $this->container->get(Application::class);
|
||||
$console->add($server);
|
||||
$console->addCommand($server);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ class State extends Component
|
||||
*/
|
||||
public function init(): void
|
||||
{
|
||||
$this->servers = config('server.ports');
|
||||
$this->servers = config('servers.server.ports');
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -6,12 +6,12 @@ class OnTaskFinish
|
||||
{
|
||||
|
||||
|
||||
/**
|
||||
* @param int $task_id
|
||||
* @param mixed $data
|
||||
*/
|
||||
public function __construct(int $task_id, mixed $data)
|
||||
{
|
||||
}
|
||||
/**
|
||||
* @param int $task_id
|
||||
* @param mixed $data
|
||||
*/
|
||||
public function __construct(public int $task_id, public mixed $data)
|
||||
{
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
namespace Kiri\Server\Task;
|
||||
|
||||
interface OnTaskInterface
|
||||
{
|
||||
|
||||
|
||||
/**
|
||||
* @param int $task_id
|
||||
* @param int $src_worker_id
|
||||
* @return mixed
|
||||
*/
|
||||
public function process(int $task_id, int $src_worker_id): mixed;
|
||||
|
||||
|
||||
}
|
||||
+15
-9
@@ -24,7 +24,7 @@ class Task
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
$exception = \config('exception.task');
|
||||
$exception = \config('servers.task.exception');
|
||||
if (!in_array(ExceptionHandlerInterface::class, class_implements($exception))) {
|
||||
$exception = ExceptionHandlerDispatcher::class;
|
||||
}
|
||||
@@ -67,20 +67,26 @@ class Task
|
||||
* @param int $task_id
|
||||
* @param int $src_worker_id
|
||||
* @param mixed $data
|
||||
* @return mixed
|
||||
* @return void
|
||||
* @throws
|
||||
*/
|
||||
public function onTask(Server $server, int $task_id, int $src_worker_id, mixed $data): mixed
|
||||
public function onTask(Server $server, int $task_id, int $src_worker_id, mixed $data): void
|
||||
{
|
||||
try {
|
||||
$data = json_decode($data, true);
|
||||
if (is_null($data)) {
|
||||
return null;
|
||||
[$handler, $params] = [$data[0], $data[1]];
|
||||
|
||||
$handler = Kiri::getDi()->make($handler, $params);
|
||||
if (!($handler instanceof OnTaskInterface)) {
|
||||
throw new \Exception('Task process must implements ' . OnTaskInterface::class);
|
||||
}
|
||||
$data[0] = Kiri::getDi()->get($data[0]);
|
||||
return call_user_func($data, $task_id, $src_worker_id);
|
||||
|
||||
$response = call_user_func([$handler, 'process'], $task_id, $src_worker_id);
|
||||
} catch (\Throwable $throwable) {
|
||||
return $this->exception->emit($throwable, response());
|
||||
\Kiri::getLogger()->json_log($throwable, ['task_id' => $task_id, 'src_worker_id' => $src_worker_id, 'data' => $data]);
|
||||
|
||||
$response = throwable($throwable);
|
||||
} finally {
|
||||
$server->finish($response);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+31
-5
@@ -2,22 +2,50 @@
|
||||
|
||||
namespace Kiri\Server\Task;
|
||||
|
||||
use Exception;
|
||||
use Kiri\Server\ServerInterface;
|
||||
|
||||
class TaskExecute implements TaskInterface
|
||||
{
|
||||
|
||||
|
||||
/**
|
||||
* @param string $handler
|
||||
* @param mixed $data
|
||||
* @param int $dstWorkerId
|
||||
* @param callable|null $finishFinishCallback
|
||||
* @return void
|
||||
* @throws
|
||||
*/
|
||||
public function task(string $handler, mixed $data, int $dstWorkerId = -1, ?callable $finishFinishCallback = null): void
|
||||
{
|
||||
$array = class_implements($handler, true);
|
||||
if (!in_array(OnTaskInterface::class, $array, true)) {
|
||||
throw new Exception('Task is not implement OnTaskInterface');
|
||||
}
|
||||
$server = \Kiri::getDi()->get(ServerInterface::class);
|
||||
|
||||
$server->task([$handler, $data], $dstWorkerId, $finishFinishCallback);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $handler
|
||||
* @param mixed $data
|
||||
* @param float $timeout
|
||||
* @param int $dstWorkerId
|
||||
* @return mixed
|
||||
* @throws
|
||||
*/
|
||||
public function taskWait(mixed $data, float $timeout = 0.5, int $dstWorkerId = -1): mixed
|
||||
public function taskWait(string $handler, mixed $data, float $timeout = 0.5, int $dstWorkerId = -1): mixed
|
||||
{
|
||||
$array = class_implements($handler, true);
|
||||
if (!in_array(OnTaskInterface::class, $array, true)) {
|
||||
throw new Exception('Task is not implement OnTaskInterface');
|
||||
}
|
||||
$server = \Kiri::getDi()->get(ServerInterface::class);
|
||||
|
||||
return $server->taskwait($data, $timeout, $dstWorkerId);
|
||||
return $server->taskwait([$handler, $data], $timeout, $dstWorkerId);
|
||||
}
|
||||
|
||||
|
||||
@@ -45,6 +73,4 @@ class TaskExecute implements TaskInterface
|
||||
|
||||
return $server->taskWaitMulti($tasks, $timeout);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
+21
-8
@@ -7,11 +7,24 @@ interface TaskInterface
|
||||
|
||||
|
||||
/**
|
||||
* @param array $tasks
|
||||
* @param float $timeout
|
||||
* @return false|array
|
||||
* @param string $handler
|
||||
* @param mixed $data
|
||||
* @param int $dstWorkerId
|
||||
* @param callable|null $finishFinishCallback
|
||||
* @return void
|
||||
*/
|
||||
public function taskWaitMulti(array $tasks, float $timeout = 0.5): false|array;
|
||||
public function task(string $handler, mixed $data, int $dstWorkerId = -1, ?callable $finishFinishCallback = null): void;
|
||||
|
||||
|
||||
/**
|
||||
* @param string $handler
|
||||
* @param mixed $data
|
||||
* @param float $timeout
|
||||
* @param int $dstWorkerId
|
||||
* @return mixed
|
||||
*/
|
||||
public function taskWait(string $handler, mixed $data, float $timeout = 0.5, int $dstWorkerId = -1): mixed;
|
||||
|
||||
|
||||
/**
|
||||
* @param array $tasks
|
||||
@@ -20,12 +33,12 @@ interface TaskInterface
|
||||
*/
|
||||
public function taskCo(array $tasks, float $timeout = 0.5): false|array;
|
||||
|
||||
|
||||
/**
|
||||
* @param mixed $data
|
||||
* @param array $tasks
|
||||
* @param float $timeout
|
||||
* @param int $dstWorkerId
|
||||
* @return mixed
|
||||
* @return false|array
|
||||
*/
|
||||
public function taskWait(mixed $data, float $timeout = 0.5, int $dstWorkerId = -1): mixed;
|
||||
public function taskWaitMulti(array $tasks, float $timeout = 0.5): false|array;
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
namespace Kiri\Server\Task;
|
||||
|
||||
class TestTask implements OnTaskInterface
|
||||
{
|
||||
|
||||
|
||||
public function __construct($user, $friend)
|
||||
{
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param int $task_id
|
||||
* @param int $src_worker_id
|
||||
* @return int
|
||||
*/
|
||||
public function process(int $task_id, int $src_worker_id): int
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
}
|
||||
+1
-1
@@ -9,7 +9,7 @@
|
||||
}
|
||||
],
|
||||
"require": {
|
||||
"php": ">=8.0",
|
||||
"php": ">=8.5",
|
||||
"ext-json": "*",
|
||||
"composer-runtime-api": "^2.0",
|
||||
"psr/http-server-middleware": "^1.0",
|
||||
|
||||
Reference in New Issue
Block a user