Compare commits

...

79 Commits

Author SHA1 Message Date
as2252258 eeb925b5b9 eee 2025-12-31 00:19:28 +08:00
as2252258 59042c0110 eee 2025-12-23 19:04:18 +08:00
as2252258 7c459cc9bc eee 2025-12-23 19:03:21 +08:00
as2252258 968cdbd11a eee 2025-12-18 15:39:40 +08:00
as2252258 37b59c8536 eee 2025-07-16 14:54:35 +08:00
as2252258 9376a73628 eee 2025-07-14 17:55:15 +08:00
as2252258 eebaf63999 eee 2025-07-14 15:34:37 +08:00
as2252258 e399837dad eee 2025-07-11 15:04:25 +08:00
as2252258 7b8a43f94f eee 2025-07-11 14:56:17 +08:00
as2252258 c0f8133926 eee 2025-07-11 14:51:53 +08:00
as2252258 f533d3262b eee 2025-07-11 14:44:06 +08:00
as2252258 c767a1745a eee 2025-07-11 11:50:54 +08:00
as2252258 251e05dbf7 eee 2024-12-27 22:34:17 +08:00
as2252258 5defd5fb30 eee 2024-12-27 21:53:16 +08:00
as2252258 95f52b58fd eee 2024-12-27 18:32:55 +08:00
as2252258 0a97c9b29a eee 2024-12-27 18:30:35 +08:00
as2252258 3336573b4d eee 2024-12-27 18:29:06 +08:00
as2252258 44187c2354 eee 2024-12-27 18:26:49 +08:00
as2252258 a058f3ed99 eee 2024-12-27 18:21:30 +08:00
as2252258 faff485006 eee 2024-12-27 17:59:52 +08:00
as2252258 e2b012126a eee 2024-12-27 17:58:52 +08:00
as2252258 b36e21d8ee eee 2024-11-19 09:12:45 +08:00
as2252258 d191296ecc eee 2024-11-19 09:12:29 +08:00
as2252258 03825dcb09 eee 2024-11-19 09:10:12 +08:00
as2252258 d500bb78c8 eee 2024-11-18 17:32:49 +08:00
as2252258 e2cac499b6 eee 2024-11-18 17:30:21 +08:00
as2252258 bb557a9aa9 eee 2024-11-18 17:15:22 +08:00
as2252258 89cc6a04eb eee 2024-11-18 17:09:12 +08:00
as2252258 91e5c4d66a eee 2024-11-18 17:07:57 +08:00
as2252258 7e5301f02a eee 2024-11-18 17:05:21 +08:00
as2252258 f76f4c02b6 eee 2024-11-18 16:59:10 +08:00
as2252258 2afe84694d eee 2024-11-18 16:55:55 +08:00
as2252258 8f80811da6 eee 2024-11-18 16:51:24 +08:00
as2252258 e46ad90c46 eee 2024-11-18 16:50:22 +08:00
as2252258 4172349872 eee 2024-11-18 16:46:31 +08:00
as2252258 0849870234 eee 2024-11-18 16:42:28 +08:00
as2252258 9fcd47ecd1 eee 2024-11-18 16:40:55 +08:00
as2252258 3bfcaf8236 eee 2024-11-18 16:39:59 +08:00
as2252258 23110643e0 eee 2024-11-18 16:35:37 +08:00
as2252258 d9980e9e1b eee 2024-11-18 16:05:10 +08:00
as2252258 a580607ec8 eee 2024-11-18 16:03:49 +08:00
as2252258 1e5fe2412a eee 2024-11-18 14:39:26 +08:00
as2252258 2be7134ea6 eee 2024-11-18 14:34:42 +08:00
as2252258 125dd9e5b2 eee 2024-11-18 14:31:26 +08:00
as2252258 7fa1110a50 eee 2024-11-18 14:29:47 +08:00
as2252258 b23c7eff83 eee 2024-11-18 14:29:19 +08:00
as2252258 2e86a73187 eee 2024-11-18 14:28:41 +08:00
as2252258 263b4d53eb eee 2024-11-18 14:19:31 +08:00
as2252258 ddf25de2c5 eee 2024-11-18 14:17:02 +08:00
as2252258 54c34ccf8f eee 2024-11-18 14:16:03 +08:00
as2252258 ad9f536c90 eee 2024-11-18 14:15:17 +08:00
as2252258 c068c2db4f eee 2024-11-18 14:14:15 +08:00
as2252258 c4bca4f88e eee 2024-11-18 14:13:47 +08:00
as2252258 f6a00d89c1 eee 2024-11-18 14:00:51 +08:00
as2252258 7f93ab046b eee 2024-11-18 13:53:50 +08:00
as2252258 64514b069e eee 2024-11-18 13:45:19 +08:00
as2252258 e669d80bb9 eee 2024-11-18 13:43:38 +08:00
as2252258 b3777a64e3 eee 2024-11-18 13:42:12 +08:00
as2252258 f858cecf1a eee 2024-11-18 13:40:23 +08:00
as2252258 e0eda4b42c eee 2024-11-18 12:23:58 +08:00
as2252258 b54d956a2d eee 2024-11-18 12:22:49 +08:00
as2252258 bce6870538 eee 2024-11-18 12:21:33 +08:00
as2252258 ab1a18a886 eee 2024-11-18 12:19:26 +08:00
as2252258 26bd43510e eee 2024-11-18 12:13:09 +08:00
as2252258 cb73717c7f eee 2024-11-18 12:11:11 +08:00
as2252258 7360a8107b eee 2024-11-18 12:07:24 +08:00
as2252258 cc98a527cd eee 2024-11-18 12:06:53 +08:00
as2252258 694bde36d9 eee 2024-11-18 11:50:13 +08:00
as2252258 bbae787d4b eee 2024-11-18 11:49:49 +08:00
as2252258 dc15054c86 eee 2024-11-18 11:46:39 +08:00
as2252258 787f035d62 eee 2024-11-18 11:45:31 +08:00
as2252258 09ec4eb9c3 eee 2024-11-18 11:43:08 +08:00
as2252258 60d08ccaca eee 2024-11-18 11:42:02 +08:00
as2252258 8c5eefb9a7 eee 2024-11-18 11:38:27 +08:00
as2252258 9cb6db5e26 eee 2024-11-18 11:32:40 +08:00
as2252258 82ff5c5d42 eee 2024-11-18 11:27:05 +08:00
as2252258 a5378658ee eee 2024-11-18 11:24:08 +08:00
as2252258 ac629ece15 eee 2024-09-29 09:01:39 +08:00
as2252258 42794168b5 eee 2024-09-29 09:01:03 +08:00
18 changed files with 507 additions and 180 deletions
+2 -2
View File
@@ -92,7 +92,7 @@ class AsyncServer extends Component implements ServerInterface
$config->events[Constant::SHUTDOWN] = [OnServer::class, 'onShutdown']; $config->events[Constant::SHUTDOWN] = [OnServer::class, 'onShutdown'];
} }
$this->event($this->server, array_merge(\config('server.events', []), $config->events)); $this->event($this->server, array_merge(\config('servers.server.events', []), $config->events));
$this->container->bind(ServerInterface::class, $this->server); $this->container->bind(ServerInterface::class, $this->server);
return $service; return $service;
} }
@@ -106,7 +106,7 @@ class AsyncServer extends Component implements ServerInterface
*/ */
protected function systemConfig(SConfig $config, int $daemon): array protected function systemConfig(SConfig $config, int $daemon): array
{ {
$settings = array_merge(\config('server.settings', []), $config->settings); $settings = array_merge(\config('servers.server.settings', []), $config->settings);
$settings[Constant::OPTION_DAEMONIZE] = (bool)$daemon; $settings[Constant::OPTION_DAEMONIZE] = (bool)$daemon;
$settings[Constant::OPTION_ENABLE_REUSE_PORT] = true; $settings[Constant::OPTION_ENABLE_REUSE_PORT] = true;
$settings[Constant::OPTION_PID_FILE] = storage('.swoole.pid'); $settings[Constant::OPTION_PID_FILE] = storage('.swoole.pid');
+171
View File
@@ -0,0 +1,171 @@
<?php
namespace Kiri\Server\Abstracts;
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\ServerInterface;
use Psr\Log\LoggerInterface;
use Swoole\Event;
use Swoole\Process;
use Kiri\Server\Processes\AbstractProcess;
class HotReload extends AbstractProcess
{
/**
* @var mixed
*/
protected mixed $pipe;
/**
* @var LoggerInterface|StdoutLogger
*/
#[Container(LoggerInterface::class)]
public StdoutLogger|LoggerInterface $logger;
/**
* @var bool
*/
protected bool $enable_coroutine = false;
/**
* @var array
*/
protected array $watches = [];
/**
* @var bool
*/
protected bool $enable_queue = false;
/**
* @var bool
*/
protected bool $reloading = false;
/**
* @throws \Exception
*/
public function __construct()
{
di(EventProvider::class)->on(OnWorkerStart::class, [di(Router::class), 'scan_build_route']);
}
/**
* @return string
*/
public function getName(): string
{
return 'hotReload';
}
/**
* @return void
*/
public function onSigterm(): void
{
// TODO: Implement onSigterm() method.
$this->stop();
}
/**
* @param ?Process $process
*/
public function process(Process|null $process): void
{
$this->pipe = inotify_init();
$this->addListen();
Event::add($this->pipe, function () use ($process) {
$read = inotify_read($this->pipe);
if (count($read) > 0) {
$this->reload();
}
});
Event::cycle(function (): void {
if ($this->isStop()) {
Event::exit();
}
});
Event::wait();
}
/**
* @return void
*/
public function reload(): void
{
if ($this->reloading) {
return;
}
$this->reloading = true;
di(StdoutLogger::class)->println('reloading server[' . \config('site.id', 'system-service') . '], please waite.');
$this->clear();
di(ServerInterface::class)->reload();
$this->addListen();
$this->reloading = false;
}
/**
* @return void
*/
protected function addListen(): void
{
foreach (config('servers.reload.listen') as $value) {
$this->readDirectory($value);
}
}
/**
* @return void
*/
protected function clear(): void
{
$this->watches = [];
}
/**
* @param string $directory
* @return void
*/
public function readFile(string $directory): void
{
if (str_ends_with($directory, '.php') === true) {
inotify_add_watch($this->pipe, $directory, IN_MODIFY | IN_MOVE | IN_CREATE | IN_DELETE);
}
}
/**
* @param string $directory
* @return void
*/
public function readDirectory(string $directory): void
{
foreach (glob($directory . '/*') as $data) {
if (is_dir($data)) {
$this->readDirectory($data);
} else {
$this->readFile($data);
}
}
}
}
+19 -7
View File
@@ -4,6 +4,8 @@
namespace Kiri\Server\Abstracts; namespace Kiri\Server\Abstracts;
use Kiri\Error\StdoutLogger;
/** /**
* Class Server * Class Server
* @package Server\Abstracts * @package Server\Abstracts
@@ -11,12 +13,22 @@ namespace Kiri\Server\Abstracts;
abstract class Server abstract class Server
{ {
/** /**
* Server constructor. * Server constructor.
* @throws * @throws
*/ */
public function __construct() public function __construct()
{ {
} }
/**
* @return StdoutLogger
*/
protected function getLogger(): StdoutLogger
{
return \Kiri::getLogger();
}
} }
+2 -2
View File
@@ -21,7 +21,7 @@ trait TraitServer
*/ */
public function onSignal(): void public function onSignal(): void
{ {
$signal = \config('signal', []); $signal = \config('servers.signal', []);
$this->onPcntlSignal(SIGINT, [$this, 'onSigint']); $this->onPcntlSignal(SIGINT, [$this, 'onSigint']);
foreach ($signal as $sig => $value) { foreach ($signal as $sig => $value) {
if (is_array($value) && is_string($value[0])) { if (is_array($value) && is_string($value[0])) {
@@ -46,7 +46,7 @@ trait TraitServer
Kiri::getLogger()->alert('Pid ' . getmypid() . ' get signo ' . $no); Kiri::getLogger()->alert('Pid ' . getmypid() . ' get signo ' . $no);
$this->shutdown(); $this->shutdown();
} catch (\Throwable $exception) { } catch (\Throwable $exception) {
error($exception); \Kiri::getLogger()->json_log($exception);
} }
} }
+11 -6
View File
@@ -2,6 +2,7 @@
namespace Kiri\Server\Handler; namespace Kiri\Server\Handler;
use Kiri;
use Kiri\Server\Abstracts\Server; use Kiri\Server\Abstracts\Server;
use Kiri\Server\Contract\OnPipeMessageInterface; use Kiri\Server\Contract\OnPipeMessageInterface;
@@ -20,13 +21,17 @@ class OnPipeMessage extends Server
*/ */
public function onPipeMessage(\Swoole\Server $server, int $src_worker_id, mixed $message): void public function onPipeMessage(\Swoole\Server $server, int $src_worker_id, mixed $message): void
{ {
if (is_string($message)) { try {
$message = unserialize($message); if (is_string($message)) {
$message = unserialize($message);
}
if (!is_object($message) || !($message instanceof OnPipeMessageInterface)) {
return;
}
call_user_func([$message, 'process'], $server, $src_worker_id);
} catch (\Throwable $throwable) {
\Kiri::getLogger()->json_log($throwable, ['src_worker_id' => $src_worker_id, 'message' => $message]);
} }
if (!is_object($message) || !($message instanceof OnPipeMessageInterface)) {
return;
}
call_user_func([$message, 'process'], $server, $src_worker_id);
} }
+125 -101
View File
@@ -3,7 +3,10 @@
namespace Kiri\Server\Handler; namespace Kiri\Server\Handler;
use Kiri; use Kiri;
use Kiri\Abstracts\CoordinatorManager;
use Kiri\Coordinator;
use Kiri\Core\Help; use Kiri\Core\Help;
use Kiri\Di\Inject\Container;
use Kiri\Events\EventDispatch; use Kiri\Events\EventDispatch;
use Kiri\Server\Events\OnAfterWorkerStart; use Kiri\Server\Events\OnAfterWorkerStart;
use Kiri\Server\Events\OnBeforeWorkerStart; use Kiri\Server\Events\OnBeforeWorkerStart;
@@ -12,6 +15,7 @@ use Kiri\Server\Events\OnWorkerError;
use Kiri\Server\Events\OnWorkerExit; use Kiri\Server\Events\OnWorkerExit;
use Kiri\Server\Events\OnWorkerStart; use Kiri\Server\Events\OnWorkerStart;
use Kiri\Server\Events\OnWorkerStop; use Kiri\Server\Events\OnWorkerStop;
use Psr\Http\Message\RequestInterface;
use Swoole\Server; use Swoole\Server;
use Swoole\Timer; use Swoole\Timer;
use Throwable; use Throwable;
@@ -25,120 +29,140 @@ use function config;
class OnServerWorker extends Kiri\Server\Abstracts\Server class OnServerWorker extends Kiri\Server\Abstracts\Server
{ {
/**
* @return void /**
*/ * @var EventDispatch
public function init(): void */
{ #[Container(EventDispatch::class)]
on(OnBeforeWorkerStart::class, [$this, 'onWorkerNameAlias']); public EventDispatch $dispatch;
}
/** /**
* @param OnBeforeWorkerStart $workerStart * @return void
* @return void */
*/ public function init(): void
public function onWorkerNameAlias(OnBeforeWorkerStart $workerStart): void {
{ on(OnBeforeWorkerStart::class, [$this, 'onWorkerNameAlias']);
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 Server $server * @param OnBeforeWorkerStart $workerStart
* @param int $workerId * @return void
* @return void */
* @throws public function onWorkerNameAlias(OnBeforeWorkerStart $workerStart): void
*/ {
public function onWorkerStart(Server $server, int $workerId): void if ($workerStart->workerId < $workerStart->server->setting['worker_num']) {
{ $this->processName($workerStart->server, 'Worker');
$dispatch = Kiri::getDi()->get(EventDispatch::class); set_env('environmental', Kiri::WORKER);
$dispatch->dispatch(new OnBeforeWorkerStart($server, $workerId)); } else {
if ($workerId < $server->setting['worker_num']) { $this->processName($workerStart->server, 'Tasker');
$dispatch->dispatch(new OnWorkerStart($server, $workerId)); set_env('environmental', Kiri::TASK);
} else { }
$dispatch->dispatch(new OnTaskerStart($server, $workerId)); set_env('environmental_worker_id', $workerStart->workerId);
} }
$dispatch->dispatch(new OnAfterWorkerStart($server, $workerId));
}
/** /**
* @param Server $server * @param Server $server
* @param string $prefix * @param int $workerId
* @return void * @return void
*/ * @throws
protected function processName(Server $server, string $prefix): void */
{ public function onWorkerStart(Server $server, int $workerId): void
Kiri::setProcessName(sprintf($prefix . '[%d]', $server->worker_pid)); {
} try {
$this->dispatch->dispatch(new OnBeforeWorkerStart($server, $workerId));
if ($workerId < $server->setting['worker_num']) {
CoordinatorManager::utility(Coordinator::WORKER_START)->waite();
$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 Server $server
* @param int $workerId * @param string $prefix
* @throws * @return void
*/ */
public function onWorkerStop(Server $server, int $workerId): void protected function processName(Server $server, string $prefix): void
{ {
event(new OnWorkerStop($server, $workerId)); Kiri::setProcessName(sprintf($prefix . '[%d]', $server->worker_pid));
Timer::clearAll(); }
}
/** /**
* @param Server $server * @param Server $server
* @param int $workerId * @param int $workerId
* @throws * @throws
*/ */
public function onWorkerExit(Server $server, int $workerId): void public function onWorkerStop(Server $server, int $workerId): void
{ {
event(new OnWorkerExit($server, $workerId)); event(new OnWorkerStop($server, $workerId));
} Timer::clearAll();
}
/** /**
* @param Server $server * @param Server $server
* @param int $worker_id * @param int $workerId
* @param int $worker_pid * @throws
* @param int $exit_code */
* @param int $signal public function onWorkerExit(Server $server, int $workerId): void
* @throws {
*/ event(new OnWorkerExit($server, $workerId));
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);
$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));
error($message);
$this->system_mail($message);
}
/** /**
* @param $messageContent * @param Server $server
* @throws * @param int $worker_id
*/ * @param int $worker_pid
protected function system_mail($messageContent): void * @param int $exit_code
{ * @param int $signal
try { * @throws
$email = config('email', ['enable' => false]); */
if (!empty($email) && ($email['enable'] ?? false)) { public function onWorkerError(Server $server, int $worker_id, int $worker_pid, int $exit_code, int $signal): void
Help::sendEmail($email, 'Service Error', $messageContent); {
} event(new OnWorkerError($server, $worker_id, $worker_pid, $exit_code, $signal));
} catch (Throwable $e) {
error($e, ['email']); 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());
}
$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) {
\Kiri::getLogger()->json_log($e);
}
}
} }
+16 -11
View File
@@ -5,6 +5,8 @@ namespace Kiri\Server\Processes;
use Swoole\Coroutine; use Swoole\Coroutine;
use Swoole\Process; use Swoole\Process;
use const SIGHUP;
use const SIGTERM;
/** /**
* *
@@ -125,26 +127,29 @@ abstract class AbstractProcess implements OnProcessInterface
{ {
$this->process = $process; $this->process = $process;
if ($this->enable_coroutine) { if ($this->enable_coroutine) {
Coroutine::set([ $array['enable_deadlock_check'] = false;
'enable_deadlock_check' => false, $array['deadlock_check_disable_trace'] = false;
'deadlock_check_disable_trace' => false, $array['exit_condition'] = [$this, 'exit_condition'];
'exit_condition' => function () { Coroutine::set($array);
return Coroutine::stats()['coroutine_num'] === 0; Coroutine::create(fn() => $this->coroutineWaitSignal());
}
]);
Coroutine::create(fn () => $this->coroutineWaitSignal());
} else { } else {
pcntl_signal(SIGTERM, [$this, 'pointWaitSignal']); $process::signal(SIGTERM | SIGINT | SIGUSR1, [$this, 'pointWaitSignal']);
} }
return $this; return $this;
} }
public function exit_condition(): bool
{
return Coroutine::stats()['coroutine_num'] === 0;
}
/** /**
* @param $data * @param $signal
* @return void * @return void
*/ */
public function pointWaitSignal($data): void public function pointWaitSignal($signal): void
{ {
$this->stop = true; $this->stop = true;
+1 -1
View File
@@ -40,7 +40,7 @@ trait TraitProcess
private function genProcess(AbstractProcess $name): Process private function genProcess(AbstractProcess $name): Process
{ {
return new Process(function (Process $process) use ($name) { 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->onShutdown($process)->process($process);
}, },
$name->getRedirectStdinAndStdout(), $name->getRedirectStdinAndStdout(),
+41 -17
View File
@@ -6,16 +6,21 @@ namespace Kiri\Server;
use Exception; use Exception;
use Kiri; use Kiri;
use Kiri\Server\Events\OnWorkerStart;
use Kiri\Events\EventProvider;
use Kiri\Events\EventDispatch; use Kiri\Events\EventDispatch;
use Kiri\Router\Router; use Kiri\Router\Router;
use Kiri\Server\Abstracts\AsyncServer; use Kiri\Server\Abstracts\AsyncServer;
use Kiri\Server\Events\OnShutdown; use Kiri\Server\Events\OnShutdown;
use Psr\Container\ContainerInterface;
use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Output\OutputInterface;
use function config; use function config;
use Kiri\Server\Abstracts\HotReload;
use Kiri\Di\Inject\Container;
defined('ROUTER_TYPE_HTTP') or define('ROUTER_TYPE_HTTP', 'http'); defined('ROUTER_TYPE_HTTP') or define('ROUTER_TYPE_HTTP', 'http');
defined('PID_PATH') or define('PID_PATH', APP_PATH . 'storage/server.pid'); defined('PID_PATH') or define('PID_PATH', APP_PATH . 'storage/server.pid');
@@ -28,18 +33,36 @@ class ServerCommand extends Command
{ {
#[Container(State::class)]
public State $state; public State $state;
/** /**
* @param string|null $name * @var ContainerInterface
* @throws Exception
*/ */
public function __construct(string $name = null) #[Container(ContainerInterface::class)]
{ public ContainerInterface $container;
parent::__construct($name);
$this->state = Kiri::getDi()->get(State::class);
} /**
* @var AsyncServer
*/
#[Container(AsyncServer::class)]
public AsyncServer $asyncServer;
/**
* @var EventDispatch
*/
#[Container(EventDispatch::class)]
public EventDispatch $eventDispatch;
/**
* @var EventProvider
*/
#[Container(EventProvider::class)]
public EventProvider $eventProvider;
/** /**
@@ -91,13 +114,12 @@ class ServerCommand extends Command
*/ */
protected function stop(): int protected function stop(): int
{ {
$configs = config('server', []); $configs = config('servers.server', []);
$instances = Kiri::getDi()->get(AsyncServer::class)->sortService($configs['ports'] ?? []); $instances = $this->asyncServer->sortService($configs['ports'] ?? []);
foreach ($instances as $config) { foreach ($instances as $config) {
$this->state->exit($config->port); $this->state->exit($config->port);
} }
$dispatch = Kiri::getDi()->get(EventDispatch::class); $this->eventDispatch->dispatch(new OnShutdown());
$dispatch->dispatch(new OnShutdown());
return 1; return 1;
} }
@@ -109,12 +131,14 @@ class ServerCommand extends Command
*/ */
protected function start(InputInterface $input): int protected function start(InputInterface $input): int
{ {
$manager = Kiri::getDi()->get(AsyncServer::class); $this->asyncServer->addProcess(config('process', []));
$router = Kiri::getDi()->get(Router::class); if (\config('servers.reload.hot', false) === true) {
$router->scan_build_route(); $this->asyncServer->addProcess([HotReload::class]);
$manager->addProcess(config('processes', [])); } else {
$manager->initCoreServers(config('server', []), (int)$input->getOption('daemon')); di(Router::class)->scan_build_route();
$manager->start(); }
$this->asyncServer->initCoreServers(config('servers.server', []), (int)$input->getOption('daemon'));
$this->asyncServer->start();
return 1; return 1;
} }
+1 -1
View File
@@ -23,6 +23,6 @@ class ServerProviders extends Providers
$server = $this->container->get(ServerCommand::class); $server = $this->container->get(ServerCommand::class);
$console = $this->container->get(Application::class); $console = $this->container->get(Application::class);
$console->add($server); $console->addCommand($server);
} }
} }
+1 -1
View File
@@ -21,7 +21,7 @@ class State extends Component
*/ */
public function init(): void public function init(): void
{ {
$this->servers = config('server.ports'); $this->servers = config('servers.server.ports');
} }
+7 -7
View File
@@ -6,12 +6,12 @@ class OnTaskFinish
{ {
/** /**
* @param int $task_id * @param int $task_id
* @param mixed $data * @param mixed $data
*/ */
public function __construct(int $task_id, mixed $data) public function __construct(public int $task_id, public mixed $data)
{ {
} }
} }
+17
View File
@@ -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
View File
@@ -24,7 +24,7 @@ class Task
*/ */
public function __construct() public function __construct()
{ {
$exception = \config('exception.task'); $exception = \config('servers.task.exception');
if (!in_array(ExceptionHandlerInterface::class, class_implements($exception))) { if (!in_array(ExceptionHandlerInterface::class, class_implements($exception))) {
$exception = ExceptionHandlerDispatcher::class; $exception = ExceptionHandlerDispatcher::class;
} }
@@ -67,20 +67,26 @@ class Task
* @param int $task_id * @param int $task_id
* @param int $src_worker_id * @param int $src_worker_id
* @param mixed $data * @param mixed $data
* @return mixed * @return void
* @throws * @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 { try {
$data = json_decode($data, true); [$handler, $params] = [$data[0], $data[1]];
if (is_null($data)) {
return null; $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) { } 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);
} }
} }
+30 -4
View File
@@ -2,22 +2,50 @@
namespace Kiri\Server\Task; namespace Kiri\Server\Task;
use Exception;
use Kiri\Server\ServerInterface; use Kiri\Server\ServerInterface;
class TaskExecute implements TaskInterface 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 mixed $data
* @param float $timeout * @param float $timeout
* @param int $dstWorkerId * @param int $dstWorkerId
* @return mixed * @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); $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); return $server->taskWaitMulti($tasks, $timeout);
} }
} }
+21 -8
View File
@@ -7,11 +7,24 @@ interface TaskInterface
/** /**
* @param array $tasks * @param string $handler
* @param float $timeout * @param mixed $data
* @return false|array * @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 * @param array $tasks
@@ -20,12 +33,12 @@ interface TaskInterface
*/ */
public function taskCo(array $tasks, float $timeout = 0.5): false|array; public function taskCo(array $tasks, float $timeout = 0.5): false|array;
/** /**
* @param mixed $data * @param array $tasks
* @param float $timeout * @param float $timeout
* @param int $dstWorkerId * @return false|array
* @return mixed
*/ */
public function taskWait(mixed $data, float $timeout = 0.5, int $dstWorkerId = -1): mixed; public function taskWaitMulti(array $tasks, float $timeout = 0.5): false|array;
} }
+24
View File
@@ -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
View File
@@ -9,7 +9,7 @@
} }
], ],
"require": { "require": {
"php": ">=8.0", "php": ">=8.4",
"ext-json": "*", "ext-json": "*",
"composer-runtime-api": "^2.0", "composer-runtime-api": "^2.0",
"psr/http-server-middleware": "^1.0", "psr/http-server-middleware": "^1.0",