diff --git a/kiri-actor/Actor.php b/kiri-actor/Actor.php index 82c6b4ab..a311760f 100644 --- a/kiri-actor/Actor.php +++ b/kiri-actor/Actor.php @@ -1,4 +1,5 @@ container->get(ActorManager::class); - while (!$this->isStop()) { - $read = json_decode($process->read(), true); - if (is_null($read) || !isset($read['category'])) { - continue; - } - $message = new ActorMessage($read['userId'], $read['event'], $read['body']); - switch ($read['category']) { - case ActorState::MESSAGE: - $actorManager->write($read['name'], $message); - break; - case ActorState::CREATE: - /** @var ActorInterface $actor */ - $actor = $this->container->create($read['class'], $read['constrict'], $read['config']); - $actorManager->addActor($actor); - break; - case ActorState::SHUTDOWN: - $actorManager->closeActor($read['name']); - break; - } - } - } - - - /** - * @return $this - */ - public function onSigterm(): static - { - pcntl_signal(SIGTERM, function () { - $this->onProcessStop(); - }); - return $this; - } - -} diff --git a/kiri-engine/Abstracts/AbstractServer.php b/kiri-engine/Abstracts/AbstractServer.php deleted file mode 100644 index 7c615ef4..00000000 --- a/kiri-engine/Abstracts/AbstractServer.php +++ /dev/null @@ -1,12 +0,0 @@ -get(Server::class); - } - - /** * @param string $name * @return mixed|null diff --git a/kiri-engine/Coordinator.php b/kiri-engine/Coordinator.php index 51a42941..9940347e 100644 --- a/kiri-engine/Coordinator.php +++ b/kiri-engine/Coordinator.php @@ -1,4 +1,6 @@ dispatch->dispatch(new OnShutdown()); + $this->dispatch->dispatch(new Kiri\Events\OnSystemError()); $this->sendError($message, $lastError['file'], $lastError['line']); } @@ -125,14 +118,13 @@ class ErrorHandler extends Component implements ErrorInterface * * @throws ContainerExceptionInterface * @throws NotFoundExceptionInterface - * @throws ReflectionException * @throws Exception */ public function exceptionHandler(\Throwable $exception) { $this->category = 'exception'; - $this->dispatch->dispatch(new OnAfterRequest()); + $this->dispatch->dispatch(new Kiri\Events\OnSystemError()); $this->sendError($exception->getMessage(), $exception->getFile(), $exception->getLine()); } @@ -158,7 +150,7 @@ class ErrorHandler extends Component implements ErrorInterface $this->logger->error('On error handler', [$data]); - $this->dispatch->dispatch(new OnAfterRequest()); + $this->dispatch->dispatch(new Kiri\Events\OnSystemError()); throw new \ErrorException($error[1], $error[0], 1, $error[2], $error[3]); } @@ -181,24 +173,7 @@ class ErrorHandler extends Component implements ErrorInterface return $data; } - - /** - * @return mixed - */ - public function getErrorMessage(): mixed - { - $message = $this->message; - $this->message = NULL; - return $message->getData(); - } - - /** - * @return bool - */ - public function getAsError(): bool - { - return $this->message !== NULL; - } + /** * @param $message diff --git a/kiri-engine/Error/LoggerAspect.php b/kiri-engine/Error/LoggerAspect.php deleted file mode 100644 index 6a9ddcd3..00000000 --- a/kiri-engine/Error/LoggerAspect.php +++ /dev/null @@ -1,53 +0,0 @@ -process(); - - $this->print_runtime($time); - - return $response; - } - - - /** - * @param $startTime - * @throws Exception - */ - private function print_runtime($startTime) - { - $request = Kiri::getDi()->get(RequestInterface::class); - $runTime = round(microtime(true) - $startTime, 6); - - $logger = Kiri::getDi()->get(LoggerInterface::class); - $logger->debug(sprintf('run %s use time %6f', $request->getUri()->__toString(), $runTime)); - } - -} diff --git a/kiri-engine/Error/StdoutLogger.php b/kiri-engine/Error/StdoutLogger.php index 61a41ae8..206c190e 100644 --- a/kiri-engine/Error/StdoutLogger.php +++ b/kiri-engine/Error/StdoutLogger.php @@ -1,5 +1,7 @@ */ private array $_connections = []; - /** - * @var WorkerStatus - */ - #[Inject(WorkerStatus::class)] - public WorkerStatus $status; - /** * @param $name diff --git a/kiri-engine/Pool/PoolItem.php b/kiri-engine/Pool/PoolItem.php index c81b92c0..b875c1c1 100644 --- a/kiri-engine/Pool/PoolItem.php +++ b/kiri-engine/Pool/PoolItem.php @@ -1,9 +1,9 @@ host = $config['host']; - $this->port = $config['port']; - $this->database = $config['databases']; - $this->auth = $config['auth']; - $this->prefix = $config['prefix']; - $this->timeout = $config['timeout']; - $this->read_timeout = $config['read_timeout']; - $this->pool = $config['pool']; - } - - - /** - * clear client heartbeat - */ - public function stopHeartbeatCheck(): void - { - $this->_timer = -1; - } - - - /** - * @param string $name - * @param array $arguments - * @return mixed - * @throws RedisConnectException|RedisException - */ - public function __call(string $name, array $arguments) - { - if (!method_exists($this, $name)) { - return $this->_pdo()->{$name}(...$arguments); - } - return $this->{$name}(...$arguments); - } - - - /** - * @return \Redis - * @throws Exception - * @throws RedisException - */ - public function _pdo(): \Redis - { - if (!($this->pdo instanceof \Redis) || !$this->pdo->ping('isOk')) { - $this->pdo = $this->newClient(); - } - return $this->pdo; - } - - - /** - * @return \Redis - * @throws Exception - */ - private function newClient(): \Redis - { - $redis = new \Redis(); - if (!$redis->connect($this->host, $this->port, $this->timeout)) { - throw new RedisConnectException(sprintf('The Redis Connect %s::%d Fail.', $this->host, $this->port)); - } - if (!empty($this->auth) && !$redis->auth($this->auth)) { - throw new RedisConnectException(sprintf('Redis Error: %s, Host %s, Auth %s', $redis->getLastError(), $this->host, $this->auth)); - } - if ($this->read_timeout < 0) { - $this->read_timeout = 0; - } - $redis->select($this->database); - if ($this->read_timeout > 0) { - $redis->setOption(\Redis::OPT_READ_TIMEOUT, $this->read_timeout); - } - $redis->setOption(\Redis::OPT_PREFIX, $this->prefix); - return $redis; - - } - -} diff --git a/kiri-engine/Reload/Inotify.php b/kiri-engine/Reload/Inotify.php deleted file mode 100644 index 75321790..00000000 --- a/kiri-engine/Reload/Inotify.php +++ /dev/null @@ -1,212 +0,0 @@ -isStop()) { - break; - } - sleep(1); - } - return; - } - $this->dirs = Config::get('reload.inotify', []); - $this->start(); - } - - - public function onSigterm(): static - { - pcntl_signal(SIGTERM, function () { - $this->isStop = true; - }); - return $this; - } - - - /** - * @return void - */ - public function error(): void - { - - } - - - /** - * @throws Exception - */ - public function start() - { - $this->inotify = inotify_init(); - $this->events = IN_MODIFY | IN_DELETE | IN_CREATE | IN_MOVE; - foreach ($this->dirs as $dir) { - if (!is_dir($dir)) continue; - $this->watch($dir); - } - Event::add($this->inotify, [$this, 'check']); - Event::cycle(function () { - if ($this->isStop()) { - Event::del($this->inotify); - } - }, true); - Event::wait(); - } - - - /** - * 开始监听 - * @throws Exception - */ - public function check() - { - if (!($events = inotify_read($this->inotify))) { - return; - } - if ($this->isReloading) { - return; - } - - $LISTEN_TYPE = [IN_CREATE, IN_DELETE, IN_MODIFY, IN_MOVED_TO, IN_MOVED_FROM]; - foreach ($events as $ev) { - if (!in_array($ev['mask'], $LISTEN_TYPE)) { - continue; - } - - //非重启类型 - if (str_ends_with($ev['name'], '.php')) { - if ($this->isReloading) { - break; - } - $this->isReloading = TRUE; - Timer::after(3000, fn() => $this->reload()); - } - } - } - - /** - * @throws Exception - */ - public function reload() - { - $swollen = \Kiri::getDi()->get(ServerInterface::class); - - $swollen->reload(); - - $this->clearWatch(); - foreach ($this->dirs as $root) { - $this->watch($root); - } - $this->isReloading = FALSE; - } - - - /** - * @throws Exception - */ - public function clearWatch() - { - foreach ($this->watchFiles as $wd) { - @inotify_rm_watch($this->inotify, $wd); - } - $this->watchFiles = []; - } - - - /** - * @param $dir - * @return bool - * @throws Exception - */ - public function watch($dir): bool - { - //目录不存在 - if (!is_dir($dir)) { - return $this->logger->addError("[$dir] is not a directory."); - } - //避免重复监听 - if (isset($this->watchFiles[$dir])) { - return FALSE; - } - - if (in_array($dir, self::IG_DIR)) { - return FALSE; - } - - $wd = @inotify_add_watch($this->inotify, $dir, $this->events); - $this->watchFiles[$dir] = $wd; - - $files = scandir($dir); - foreach ($files as $f) { - if ($f == '.' || $f == '..') { - continue; - } - $path = $dir . '/' . $f; - //递归目录 - if (is_dir($path)) { - $this->watch($path); - } else if (!str_ends_with($f, '.php')) { - continue; - } - //检测文件类型 - if (strstr($f, '.') == '.php') { - $wd = @inotify_add_watch($this->inotify, $path, $this->events); - $this->watchFiles[$path] = $wd; - } - } - return TRUE; - } -} diff --git a/kiri-engine/Reload/Scanner.php b/kiri-engine/Reload/Scanner.php deleted file mode 100644 index f28a86fe..00000000 --- a/kiri-engine/Reload/Scanner.php +++ /dev/null @@ -1,166 +0,0 @@ -dirs = Config::get('reload.inotify', []); - - $this->loadDirs(); - Timer::tick(3000, fn() => $this->loadDirs(true)); - } - - - /** - * @param bool $isReload - * @throws Exception - */ - private function loadDirs(bool $isReload = FALSE) - { - echo 'file tick ' . date('Y-m-d H:i:s') . PHP_EOL; - try { - if ($this->isReloading) { - return; - } - foreach ($this->dirs as $value) { - if ($this->isReloading) { - break; - } - $value = new DirectoryIterator($value); - if ($value->isDir()) { - $this->loadByDir($value, $isReload); - } - } - } catch (\Throwable $throwable) { - $this->logger->error($throwable->getMessage(), [$throwable]); - } - } - - - /** - * @param DirectoryIterator $iterator - * @param bool $isReload - * @return void - * @throws Exception - */ - private function loadByDir(DirectoryIterator $iterator, bool $isReload = FALSE): void - { - foreach ($iterator as $path) { - if ($this->isReloading) { - return; - } - if (!$this->isNeedCheck($path)) { - continue; - } - if ($path->isDir()) { - $this->loadByDir(new DirectoryIterator($path->getRealPath()), $isReload); - } - if ($this->checkFile($path, $isReload)) { - $this->isReloading = TRUE; - $this->timerReload(); - break; - } - } - } - - - private function isNeedCheck(DirectoryIterator $path): bool - { - if ($path->isDot() || str_starts_with($path->getFilename(), '.')) { - return false; - } - - if ($path->getExtension() !== 'php') { - return false; - } - return true; - } - - - /** - * @param DirectoryIterator $value - * @param $isReload - * @return bool - */ - private function checkFile(DirectoryIterator $value, $isReload): bool - { - $md5 = md5($value->getRealPath()); - $mTime = filectime($value->getRealPath()); - if (!isset($this->md5Map[$md5])) { - if ($isReload) { - return TRUE; - } - $this->md5Map[$md5] = $mTime; - } else { - if ($this->md5Map[$md5] != $mTime) { - if ($isReload) { - return TRUE; - } - $this->md5Map[$md5] = $mTime; - } - } - return FALSE; - } - - - /** - * @return $this - */ - public function onSigterm(): static - { - pcntl_signal(SIGTERM, function () { - Timer::clearAll(); - $this->onProcessStop(); - }); - return $this; - } - - - /** - * @throws Exception - */ - public function timerReload() - { - $this->logger->warning('file change'); - $swow = \Kiri::getDi()->get(ServerInterface::class); - $swow->reload(); - - $this->loadDirs(); - $this->isReloading = FALSE; - } - -} diff --git a/kiri-task/Annotation/AsynchronousTask.php b/kiri-task/Annotation/AsynchronousTask.php deleted file mode 100644 index c5903c9d..00000000 --- a/kiri-task/Annotation/AsynchronousTask.php +++ /dev/null @@ -1,33 +0,0 @@ -add($this->name, $class::class); - return parent::execute($class, $method); - } - -} diff --git a/kiri-task/OnServerTask.php b/kiri-task/OnServerTask.php deleted file mode 100644 index 7c8741b8..00000000 --- a/kiri-task/OnServerTask.php +++ /dev/null @@ -1,94 +0,0 @@ -resolve($data); - } catch (\Throwable $exception) { - $data = jTraceEx($exception); - - $this->logger->error('task', [throwable($exception)]); - } finally { - $server->finish($data); - } - } - - - /** - * @param Server|null $server - * @param Server\Task $task - * @throws ConfigException - */ - public function onCoroutineTask(?Server $server, Server\Task $task): void - { - try { - $data = $this->resolve($task->data); - } catch (\Throwable $exception) { - $data = jTraceEx($exception); - - $this->logger->error('task', [throwable($exception)]); - } finally { - $task->finish($data); - } - } - - - /** - * @param $data - * @return null - */ - private function resolve($data) - { - $execute = unserialize($data); - if ($execute instanceof OnTaskInterface) { - return $execute->execute(); - } - return null; - } - - - /** - * @param Server $server - * @param int $task_id - * @param mixed $data - */ - public function onFinish(Server $server, int $task_id, mixed $data): void - { - if (!($data instanceof OnTaskInterface)) { - return; - } - $data->finish($server, $task_id); - } - - -} diff --git a/kiri-task/OnTaskInterface.php b/kiri-task/OnTaskInterface.php deleted file mode 100644 index 16cb0f7c..00000000 --- a/kiri-task/OnTaskInterface.php +++ /dev/null @@ -1,17 +0,0 @@ -hashMap = new HashMap(); - } - - - /** - * @param string $key - * @param $handler - */ - public function add(string $key, $handler) - { - $this->hashMap->put($key, $handler); - } - - - /** - * @param string $key - * @return bool - */ - #[Pure] public function has(string $key): bool - { - return $this->hashMap->has($key); - } - - - /** - * @param string $key - * @return OnTaskInterface - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - public function get(string $key): OnTaskInterface - { - $task = $this->hashMap->get($key); - if (is_string($task)) { - $task = $this->container->get($task); - if (!empty($task)) { - $this->add($key, $task); - } - } - return $task; - } - - -} diff --git a/kiri-task/TaskExecute.php b/kiri-task/TaskExecute.php deleted file mode 100644 index 106110b0..00000000 --- a/kiri-task/TaskExecute.php +++ /dev/null @@ -1,108 +0,0 @@ -handle($handler, $params); - } - if ($this->container->has(ServerInterface::class)) { - $this->onAsyncExec($handler, $workerId); - } else { - Coroutine::create(fn() => $this->onCoronExec($handler)); - } - } - - - /** - * @param OnTaskInterface|string $handler - * @param int $workerId - * @return bool - * @throws Exception - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - protected function onAsyncExec(OnTaskInterface|string $handler, int $workerId = -1): bool - { - /** @var Server $server */ - $server = $this->container->get(ServerInterface::class); - if ($workerId < 0 || $workerId > $server->setting['task_worker_num']) { - $workerId = random_int(0, $server->setting['task_worker_num'] - 1); - } - return (bool)$server->task(serialize($handler), $workerId); - } - - - /** - * @param OnTaskInterface|string $handler - * @return bool - */ - protected function onCoronExec(OnTaskInterface|string $handler): bool - { - $handler->execute(); - $handler->finish(null, Coroutine::getCid()); - return true; - } - - - /** - * @param $handler - * @param $params - * @return object - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - * @throws \ReflectionException - * @throws Exception - */ - private function handle($handler, $params): object - { - if (!class_exists($handler) && $this->hashMap->has($handler)) { - $handler = $this->hashMap->get($handler); - } - $implements = $this->container->getReflect($handler); - if (!in_array(OnTaskInterface::class, $implements->getInterfaceNames())) { - throw new Exception('Task must instance ' . OnTaskInterface::class); - } - return $implements->newInstanceArgs($params); - } - -} diff --git a/kiri-websocket-server/Contract/OnCloseInterface.php b/kiri-websocket-server/Contract/OnCloseInterface.php deleted file mode 100644 index ee001924..00000000 --- a/kiri-websocket-server/Contract/OnCloseInterface.php +++ /dev/null @@ -1,17 +0,0 @@ -router = $this->collector->get('wss'); - } - - - /** - * @return void - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - * @throws ConfigException - */ - public function init(): void - { - $exception = Config::get('exception.websocket', ExceptionHandlerDispatcher::class); - if (!in_array(ExceptionHandlerInterface::class, class_implements($exception))) { - $exception = ExceptionHandlerDispatcher::class; - } - $this->exception = $this->container->get($exception); - } - - /** - * @param Request $request - * @param Response $response - * @return void - * @throws Exception - */ - public function OnHandshake(Request $request, Response $response): void - { - try { - /** @var \Kiri\Message\Response $psrResponse */ - $psrResponse = Context::set(ResponseInterface::class, new \Kiri\Message\Response()); - - $handler = $this->router->find('/', 'GET'); - if (is_integer($handler)) { - $psrResponse->withContent('Allow Method[' . $request->getMethod() . '].')->withStatus(405); - } else if (is_null($handler)) { - $psrResponse->withContent('Page not found.')->withStatus(404); - } else { - $executor = $handler->dispatch->handler; - - if (Context::inCoroutine()) { - $response->upgrade(); - if ($handler instanceof OnHandshakeInterface) { - $handler->OnHandshake($request, $response); - } - if ($executor instanceof OnOpenInterface) { - $executor->OnOpen($request); - } - while (true) { - $frame = $response->recv(); - if ($frame === false || $frame instanceof CloseFrame || $frame === '') { - $handler->OnClose($response->fd); - break; - } - $handler->OnMessage($frame); - } - } else { - $this->OnOpen($request); - } - } - } catch (\Throwable $throwable) { - $psrResponse = $this->exception->emit($throwable, di(CResponse::class)); - } finally { - $this->emitter->sender($response, $psrResponse); - } - } - - - /** - * @param Frame $frame - * @return void - */ - public function OnMessage(Frame $frame): void - { - } - - - /** - * @param int $fd - * @return void - */ - public function OnClose(int $fd): void - { - } - - - /** - * @param int $fd - * @return void - */ - public function OnDisconnect(int $fd): void - { - // TODO: Implement OnDisconnect() method. - } - - - /** - * @param Request $request - * @return void - */ - public function OnOpen(Request $request): void - { - } - - -} diff --git a/kiri-websocket-server/TestSocketServer.php b/kiri-websocket-server/TestSocketServer.php deleted file mode 100644 index e8f2d306..00000000 --- a/kiri-websocket-server/TestSocketServer.php +++ /dev/null @@ -1,38 +0,0 @@ -