Compare commits

..

13 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
18 changed files with 267 additions and 177 deletions
+2 -2
View File
@@ -92,7 +92,7 @@ class AsyncServer extends Component implements ServerInterface
$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);
return $service;
}
@@ -106,7 +106,7 @@ class AsyncServer extends Component implements ServerInterface
*/
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_ENABLE_REUSE_PORT] = true;
$settings[Constant::OPTION_PID_FILE] = storage('.swoole.pid');
+3 -3
View File
@@ -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);
}
}
@@ -168,4 +168,4 @@ class HotReload extends AbstractProcess
}
}
}
}
}
+19 -7
View File
@@ -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();
}
}
+2 -2
View File
@@ -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);
}
}
+1 -1
View File
@@ -30,7 +30,7 @@ class OnPipeMessage extends Server
}
call_user_func([$message, 'process'], $server, $src_worker_id);
} catch (\Throwable $throwable) {
Kiri::getLogger()->error(throwable($throwable));
\Kiri::getLogger()->json_log($throwable, ['src_worker_id' => $src_worker_id, 'message' => $message]);
}
}
+115 -111
View File
@@ -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)->waite();
$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);
}
}
}
+1 -1
View File
@@ -133,7 +133,7 @@ abstract class AbstractProcess implements OnProcessInterface
Coroutine::set($array);
Coroutine::create(fn() => $this->coroutineWaitSignal());
} else {
pcntl_signal(SIGTERM | SIGINT | SIGUSR1, [$this, 'pointWaitSignal']);
$process::signal(SIGTERM | SIGINT | SIGUSR1, [$this, 'pointWaitSignal']);
}
return $this;
}
+2 -2
View File
@@ -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;
}
}
}
+5 -15
View File
@@ -33,6 +33,7 @@ class ServerCommand extends Command
{
#[Container(State::class)]
public State $state;
@@ -64,17 +65,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 +114,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);
@@ -141,13 +131,13 @@ class ServerCommand extends Command
*/
protected function start(InputInterface $input): int
{
$this->asyncServer->addProcess(config('processes', []));
if (\config('reload.hot', false) === true) {
$this->asyncServer->addProcess(config('process', []));
if (\config('servers.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->initCoreServers(config('servers.server', []), (int)$input->getOption('daemon'));
$this->asyncServer->start();
return 1;
}
+1 -1
View File
@@ -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);
}
}
+1 -1
View File
@@ -21,7 +21,7 @@ class State extends Component
*/
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 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)
{
}
}
+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;
}
+14 -10
View File
@@ -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,22 +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[0] = Kiri::getDi()->get($handler[0]);
return call_user_func($handler, $task_id, $src_worker_id, $params);
$handler = Kiri::getDi()->make($handler, $params);
if (!($handler instanceof OnTaskInterface)) {
throw new \Exception('Task process must implements ' . OnTaskInterface::class);
}
$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
View File
@@ -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
View File
@@ -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;
}
+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": {
"php": ">=8.0",
"php": ">=8.4",
"ext-json": "*",
"composer-runtime-api": "^2.0",
"psr/http-server-middleware": "^1.0",