Compare commits

...

54 Commits

Author SHA1 Message Date
as2252258 044d213a69 改名 2021-12-07 16:44:12 +08:00
as2252258 e5fe525f82 改名 2021-12-07 16:02:07 +08:00
as2252258 39e4e52908 改名 2021-12-07 16:00:52 +08:00
as2252258 f62014ff34 改名 2021-12-07 15:59:13 +08:00
as2252258 7935e6a6a3 改名 2021-12-07 15:53:56 +08:00
as2252258 d2acd50352 改名 2021-12-06 18:07:33 +08:00
as2252258 d02337ec22 改名 2021-12-06 17:58:11 +08:00
as2252258 57f12b6701 改名 2021-12-06 17:22:26 +08:00
as2252258 d500fd21ce 改名 2021-12-06 16:14:48 +08:00
as2252258 30d7b8684e 改名 2021-12-06 16:13:52 +08:00
as2252258 d8eb4d4e45 改名 2021-12-06 16:03:39 +08:00
as2252258 7004c5c0f8 改名 2021-12-06 15:54:31 +08:00
as2252258 81e55ecdf1 改名 2021-12-06 15:52:05 +08:00
as2252258 20adc186d4 改名 2021-12-06 15:51:29 +08:00
as2252258 8c16d9f4b3 改名 2021-12-06 15:48:57 +08:00
as2252258 b3e06a680a 改名 2021-12-06 15:47:12 +08:00
as2252258 3176443e5c 改名 2021-12-06 15:39:35 +08:00
as2252258 83962fa3ba 改名 2021-12-06 14:49:47 +08:00
as2252258 5475f2cd51 改名 2021-12-06 14:45:12 +08:00
as2252258 30212c0b86 改名 2021-12-06 14:44:18 +08:00
as2252258 4731463897 改名 2021-12-06 14:43:46 +08:00
as2252258 87e901f5b1 改名 2021-12-06 14:42:54 +08:00
as2252258 66f87b6da4 改名 2021-12-06 14:41:05 +08:00
as2252258 0007242b70 改名 2021-12-06 14:40:18 +08:00
as2252258 8653e6914b 改名 2021-12-06 14:39:03 +08:00
as2252258 816fec8ef4 改名 2021-12-06 14:38:17 +08:00
as2252258 b0ef09fd35 改名 2021-12-06 14:38:06 +08:00
as2252258 f7a2d6f30e 改名 2021-12-06 14:32:04 +08:00
as2252258 2950ba8fd5 改名 2021-12-06 14:24:41 +08:00
as2252258 2de5c82a73 改名 2021-12-06 14:22:08 +08:00
as2252258 758c4e7d5b 改名 2021-12-06 14:12:03 +08:00
as2252258 33f045aec7 改名 2021-12-06 13:49:01 +08:00
as2252258 35189de442 改名 2021-12-06 11:44:01 +08:00
as2252258 34e7fc0392 改名 2021-12-03 18:40:27 +08:00
as2252258 a3ce9f52ba 改名 2021-12-03 18:22:26 +08:00
as2252258 6e7da1b0ed 改名 2021-12-03 17:40:21 +08:00
as2252258 a6e0b5c1a2 改名 2021-12-03 16:24:44 +08:00
as2252258 13ab14f965 改名 2021-12-03 15:42:05 +08:00
as2252258 6729094f63 改名 2021-12-03 15:35:16 +08:00
as2252258 e1aeb17a5a 改名 2021-12-03 14:46:38 +08:00
as2252258 b9e20051ef 改名 2021-12-02 14:06:57 +08:00
as2252258 4ab6332176 改名 2021-12-01 19:05:10 +08:00
as2252258 abe2dad521 改名 2021-12-01 19:05:00 +08:00
as2252258 b0f70a13da 改名 2021-12-01 15:16:08 +08:00
as2252258 1e8aca91dd 改名 2021-12-01 14:08:09 +08:00
as2252258 b4ac5c4758 改名 2021-11-30 19:04:29 +08:00
as2252258 d161477957 改名 2021-11-30 19:04:16 +08:00
as2252258 a26b99dd1e 改名 2021-11-30 18:33:22 +08:00
as2252258 86e4a92ab0 改名 2021-11-30 18:31:41 +08:00
as2252258 ea425bb82d 改名 2021-11-30 18:30:15 +08:00
as2252258 ad0154d319 改名 2021-11-30 18:29:10 +08:00
as2252258 edb70d2b9b 改名 2021-11-30 18:26:23 +08:00
as2252258 9f3355cab4 改名 2021-11-30 18:23:56 +08:00
as2252258 4107b5bb07 改名 2021-11-30 15:48:18 +08:00
24 changed files with 524 additions and 376 deletions
+1 -1
View File
@@ -30,7 +30,7 @@
"swiftmailer/swiftmailer": "v6.3.*",
"psr/container": "^2.0",
"psr/http-server-middleware": "1.0.1",
"game-worker/kiri-event": "v1.0",
"game-worker/kiri-event": "^v1.0",
"ext-inotify": "*"
},
"autoload": {
+44 -3
View File
@@ -3,8 +3,6 @@
defined('APP_PATH') or define('APP_PATH', realpath(__DIR__ . '/../../'));
use Note\Note;
use Note\Route\Route;
use Http\Handler\Router;
use JetBrains\PhpStorm\Pure;
use Kiri\Abstracts\Config;
@@ -16,6 +14,8 @@ use Kiri\Events\EventDispatch;
use Kiri\Events\EventProvider;
use Kiri\Exception\ConfigException;
use Kiri\Kiri;
use Note\Note;
use Note\Route\Route;
use Psr\Log\LoggerInterface;
use Swoole\Process;
use Swoole\WebSocket\Server;
@@ -52,6 +52,22 @@ if (!function_exists('make')) {
}
if (!function_exists('map')) {
/**
* @param array $params
* @param Closure $closure
* @return mixed
*/
function map(array $params, Closure $closure): mixed
{
return array_map($closure, $params);
}
}
if (!function_exists('checkPortIsAlready')) {
@@ -900,6 +916,27 @@ if (!function_exists('di')) {
}
if (!function_exists('interval')) {
/**
* @param callable $callback
* @param int $interval
* @param bool $is
*/
function interval(callable $callback, int $interval = 1000, bool $is = false)
{
usleep($interval * 1000);
$callback();
interval($callback, $interval, $is);
}
}
if (!function_exists('duplicate')) {
@@ -911,7 +948,11 @@ if (!function_exists('duplicate')) {
function duplicate(string $className): mixed
{
$class = di($className);
return clone $class;
$clone = clone $class;
if (method_exists($clone, 'clear')) {
$clone->clear();
}
return $clone;
}
}
+2 -1
View File
@@ -29,6 +29,7 @@ use Kiri\Kiri;
use ReflectionException;
use Server\ServerManager;
use Server\Contract\OnTaskInterface;
use Server\Tasker\AsyncTaskExecute;
use Swoole\Table;
/**
@@ -210,7 +211,7 @@ abstract class BaseApplication extends Component
*/
public function task(OnTaskInterface $execute): void
{
di(ServerManager::class)->task($execute);
di(AsyncTaskExecute::class)->execute($execute);
}
-243
View File
@@ -1,243 +0,0 @@
<?php
/**
* Created by PhpStorm.
* User: whwyy
* Date: 2018/3/30 0030
* Time: 14:10
*/
declare(strict_types=1);
namespace Kiri\Abstracts;
use Exception;
use JetBrains\PhpStorm\Pure;
use Kiri\Kiri;
use Swoole\Coroutine;
/**
* Class BaseObject
* @package Kiri\Kiri\Base
*/
class BaseObject implements Configure
{
/**
* BaseAbstract constructor.
*
* @param array $config
* @throws Exception
*/
public function __construct(array $config = [])
{
if (!empty($config) && is_array($config)) {
Kiri::configure($this, $config);
}
}
/**
* @throws Exception
*/
public function init()
{
}
/**
* @param array|callable $callback
* @param object $scope
*/
public function async_create(array|callable $callback, object $scope)
{
Coroutine::create($callback, $scope);
}
/**
* @return string
*/
#[Pure] public static function className(): string
{
return static::class;
}
/**
* @param $name
* @param $value
*
* @throws Exception
*/
public function __set($name, $value)
{
$method = 'set' . ucfirst($name);
if (method_exists($this, $method)) {
$this->{$method}($value);
} else {
throw new Exception('The set name ' . $name . ' not find in class ' . static::class);
}
}
/**
* @param $name
*
* @return mixed
* @throws Exception
*/
public function __get($name): mixed
{
$method = 'get' . ucfirst($name);
if (method_exists($this, $method)) {
return $this->$method();
} else {
throw new Exception('The get name ' . $name . ' not find in class ' . static::class);
}
}
/**
* @param $message
* @param string $model
* @return bool
* @throws Exception
*/
public function addError($message, string $model = 'app'): bool
{
if ($message instanceof \Throwable) {
$this->error(jTraceEx($message));
} else {
if (!is_string($message)) {
$message = json_encode($message, JSON_UNESCAPED_UNICODE);
}
$this->error($message);
}
return FALSE;
}
/**
* @return Logger
* @throws Exception
*/
private function logger(): Logger
{
return Kiri::getDi()->get(Logger::class);
}
/**
* @param mixed $message
* @param string $method
* @param string $file
* @throws Exception
*/
public function debug(mixed $message, string $method = '', string $file = '')
{
if (!is_string($message)) {
$message = print_r($message, true);
}
$message = "\033[35m" . $message . "\033[0m";
$context = [];
if (!empty($method)) $context['method'] = $method;
if (!empty($file)) $context['file'] = $file;
$this->logger()->debug($message, $context);
}
/**
* @param mixed $message
* @param string $method
* @param string $file
* @throws Exception
*/
public function info(mixed $message, string $method = '', string $file = '')
{
if (!is_string($message)) {
$message = print_r($message, true);
}
$message = "\033[34m" . $message . "\033[0m";
$context = [];
if (!empty($method)) $context['method'] = $method;
if (!empty($file)) $context['file'] = $file;
$this->logger()->info($message, $context);
}
/**
* @param mixed $message
* @param string $method
* @param string $file
* @throws Exception
*/
public function success(mixed $message, string $method = '', string $file = '')
{
if (!is_string($message)) {
$message = print_r($message, true);
}
$message = "\033[36m" . $message . "\033[0m";
$context = [];
if (!empty($method)) $context['method'] = $method;
if (!empty($file)) $context['file'] = $file;
$this->logger()->notice($message, $context);
}
/**
* @param mixed $message
* @param string $method
* @param string $file
* @throws Exception
*/
public function warning(mixed $message, string $method = '', string $file = '')
{
if (!is_string($message)) {
$message = print_r($message, true);
}
$message = "\033[33m" . $message . "\033[0m";
$context = [];
if (!empty($method)) $context['method'] = $method;
if (!empty($file)) $context['file'] = $file;
$this->logger()->critical($message, $context);
}
/**
* @param mixed $message
* @param null $method
* @param null $file
* @throws Exception
*/
public function error(mixed $message, $method = null, $file = null)
{
if ($message instanceof \Throwable) {
$message = $message->getMessage() . " on line " . $message->getLine() . " at file " . $message->getFile();
}
$content = (empty($method) ? '' : $method . ': ') . $message;
$message = "\033[41;37m" . $content . "\033[0m";
if (!empty($file)) {
$message .= PHP_EOL . "\03341;37m[" . $file . "\033[0m";
}
$context = [];
if (!empty($method)) $context['method'] = $method;
if (!empty($file)) $context['file'] = $file;
$this->logger()->error($message, $context);
}
}
+203 -14
View File
@@ -11,45 +11,234 @@ namespace Kiri\Abstracts;
use Exception;
use JetBrains\PhpStorm\Pure;
use Kiri\Exception\ComponentException;
use Kiri\Di\Container;
use Kiri\Kiri;
use Psr\Container\ContainerInterface;
/**
* Class Component
* @package Kiri\Kiri\Base
* @property ContainerInterface|Container $container
*/
class Component extends BaseObject
class Component implements Configure
{
/**
* @param $name
* @param $value
* BaseAbstract constructor.
*
* @param array $config
* @throws Exception
*/
public function __set($name, $value)
public function __construct(array $config = [])
{
if (property_exists($this, $name)) {
$this->$name = $value;
} else {
parent::__set($name, $value);
if (!empty($config) && is_array($config)) {
Kiri::configure($this, $config);
}
}
/**
* @throws Exception
*/
public function init()
{
}
/**
* @return Container
*/
#[Pure] public function getContainer(): ContainerInterface
{
return Kiri::getDi();
}
/**
* @return string
*/
#[Pure] public static function className(): string
{
return static::class;
}
/**
* @param $name
* @param $value
*
* @throws Exception
*/
public function __set($name, $value)
{
$method = 'set' . ucfirst($name);
if (method_exists($this, $method)) {
$this->{$method}($value);
} else {
throw new Exception('The set name ' . $name . ' not find in class ' . static::class);
}
}
/**
* @param $name
*
* @return mixed
* @throws Exception
*/
public function __get($name): mixed
{
if (property_exists($this, $name)) {
return $this->$name ?? null;
$method = 'get' . ucfirst($name);
if (method_exists($this, $method)) {
return $this->$method();
} else {
return parent::__get($name);
throw new Exception('The get name ' . $name . ' not find in class ' . static::class);
}
}
/**
* @param $message
* @param string $model
* @return bool
* @throws Exception
*/
public function addError($message, string $model = 'app'): bool
{
if ($message instanceof \Throwable) {
$this->error(jTraceEx($message));
} else {
if (!is_string($message)) {
$message = json_encode($message, JSON_UNESCAPED_UNICODE);
}
$this->error($message);
}
return FALSE;
}
/**
* @return Logger
* @throws Exception
*/
private function logger(): Logger
{
return Kiri::getDi()->get(Logger::class);
}
/**
* @param mixed $message
* @param string $method
* @param string $file
* @throws Exception
*/
public function debug(mixed $message, string $method = '', string $file = '')
{
if (!is_string($message)) {
$message = print_r($message, true);
}
// $message = "\033[35m" . $message . "\033[0m";
$context = [];
if (!empty($method)) $context['method'] = $method;
if (!empty($file)) $context['file'] = $file;
$this->logger()->debug($message, $context);
}
/**
* @param mixed $message
* @param string $method
* @param string $file
* @throws Exception
*/
public function info(mixed $message, string $method = '', string $file = '')
{
if (!is_string($message)) {
$message = print_r($message, true);
}
// $message = "\033[34m" . $message . "\033[0m";
$context = [];
if (!empty($method)) $context['method'] = $method;
if (!empty($file)) $context['file'] = $file;
$this->logger()->info($message, $context);
}
/**
* @param mixed $message
* @param string $method
* @param string $file
* @throws Exception
*/
public function success(mixed $message, string $method = '', string $file = '')
{
if (!is_string($message)) {
$message = print_r($message, true);
}
// $message = "\033[36m" . $message . "\033[0m";
$context = [];
if (!empty($method)) $context['method'] = $method;
if (!empty($file)) $context['file'] = $file;
$this->logger()->notice($message, $context);
}
/**
* @param mixed $message
* @param string $method
* @param string $file
* @throws Exception
*/
public function warning(mixed $message, string $method = '', string $file = '')
{
if (!is_string($message)) {
$message = print_r($message, true);
}
// $message = "\033[33m" . $message . "\033[0m";
$context = [];
if (!empty($method)) $context['method'] = $method;
if (!empty($file)) $context['file'] = $file;
$this->logger()->critical($message, $context);
}
/**
* @param mixed $message
* @param null $method
* @param null $file
* @throws Exception
*/
public function error(mixed $message, $method = null, $file = null)
{
if ($message instanceof \Throwable) {
$message = $message->getMessage() . " on line " . $message->getLine() . " at file " . $message->getFile();
}
$context = [];
if (is_string($method)) {
$message = (empty($method) ? '' : $method . ': ') . $message;
} else {
if (is_null($method)) {
$method = [];
}
$context = $method;
}
// $message = "\033[41;37m" . $message . "\033[0m";
if (!empty($method)) $context['method'] = $method;
if (!empty($file)) $context['file'] = $file;
$this->logger()->error($message, $context);
}
}
+1 -1
View File
@@ -194,7 +194,7 @@ class Logger implements LoggerInterface
private function _string($message, $context): string
{
if (!empty($context)) {
return $message . ' ' . print_r($context, true) . PHP_EOL;
return $message . ' ' . PHP_EOL . print_r($context, true) . PHP_EOL;
}
return $message . PHP_EOL;
}
+3 -2
View File
@@ -7,6 +7,7 @@ namespace Kiri;
use Exception;
use Kiri\Abstracts\Component;
use Server\ServerManager;
use Server\Tasker\AsyncTaskExecute;
/**
* Class Async
@@ -36,8 +37,8 @@ class Async extends Component
*/
public function dispatch(string $name, array $params = [])
{
$context = di(ServerManager::class);
$context->task(static::$_absences[$name], $params);
$context = di(AsyncTaskExecute::class);
$context->execute(static::$_absences[$name], $params);
}
}
+46 -27
View File
@@ -2,12 +2,12 @@
namespace Kiri\Cache\Base;
use Exception;
use Kiri\Abstracts\Logger;
use Kiri\Exception\RedisConnectException;
use Kiri\Kiri;
use Kiri\Pool\StopHeartbeatCheck;
use RedisException;
use Kiri\Context;
use Swoole\Timer;
@@ -22,9 +22,21 @@ class Redis implements StopHeartbeatCheck
private ?\Redis $pdo = null;
public string $host;
private int $_transaction = 0;
public int $port;
public int $database = 0;
public string $auth = '';
public string $prefix = '';
public int $timeout = 30;
public int $read_timeout = 30;
public array $pool = [];
private int $_timer = -1;
@@ -32,18 +44,18 @@ class Redis implements StopHeartbeatCheck
/**
* @param string $host
* @param int $port
* @param int $database
* @param string $auth
* @param string $prefix
* @param int $timeout
* @param int $read_timeout
* @param array $config
*/
public function __construct(public string $host, public int $port, public int $database = 0,
public string $auth = '', public string $prefix = '', public int $timeout = 30,
public int $read_timeout = 30)
public function __construct(array $config)
{
$this->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'];
}
@@ -61,21 +73,28 @@ class Redis implements StopHeartbeatCheck
if (env('state', 'start') == 'exit') {
return;
}
if ($this->_timer === -1 && Context::inCoroutine()) {
$this->_timer = Timer::tick(1000, function () {
try {
if (env('state', 'start') == 'exit') {
Kiri::getDi()->get(Logger::class)->critical('timer end');
$this->stopHeartbeatCheck();
}
if (time() - $this->_last > 10 * 60) {
$this->stopHeartbeatCheck();
$this->pdo = null;
}
} catch (\Throwable $throwable) {
error($throwable);
}
});
if ($this->_timer === -1) {
$this->_timer = Timer::tick(1000, fn() => $this->waite());
}
}
/**
* @throws Exception
*/
private function waite(): void
{
try {
if (env('state', 'start') == 'exit') {
Kiri::getDi()->get(Logger::class)->critical('timer end');
$this->stopHeartbeatCheck();
}
if (time() - $this->_last > intval($this->pool['tick'] ?? 60)) {
$this->stopHeartbeatCheck();
$this->pdo = null;
}
} catch (\Throwable $throwable) {
error($throwable);
}
}
+18 -6
View File
@@ -9,9 +9,7 @@ declare(strict_types=1);
namespace Kiri\Cache;
use Note\Inject;
use Exception;
use Server\Events\OnWorkerExit;
use Kiri\Abstracts\Component;
use Kiri\Abstracts\Config;
use Kiri\Core\Json;
@@ -19,6 +17,8 @@ use Kiri\Events\EventProvider;
use Kiri\Exception\ConfigException;
use Kiri\Kiri;
use Kiri\Pool\Redis as PoolRedis;
use Note\Inject;
use Server\Events\OnWorkerExit;
/**
* Class Redis
@@ -35,17 +35,29 @@ class Redis extends Component
public EventProvider $eventProvider;
const REDIS_OPTION_HOST = 'host';
const REDIS_OPTION_PORT = 'port';
const REDIS_OPTION_PREFIX = 'prefix';
const REDIS_OPTION_AUTH = 'auth';
const REDIS_OPTION_DATABASES = 'databases';
const REDIS_OPTION_TIMEOUT = 'timeout';
const REDIS_OPTION_POOL = 'pool';
const REDIS_OPTION_POOL_TICK = 'tick';
const REDIS_OPTION_POOL_MIN = 'min';
const REDIS_OPTION_POOL_MAX = 'max';
/**
* @throws ConfigException
* @throws Exception
*/
public function init()
{
$connections = Kiri::getDi()->get(PoolRedis::class);
$connections = Kiri::getDi()->get(PoolRedis::class);
$config = $this->get_config();
$length = Config::get('connections.pool.max', 10);
$length = Config::get('cache.redis.pool.max', 10);
$this->eventProvider->on(OnWorkerExit::class, [$this, 'destroy'], 0);
@@ -111,7 +123,7 @@ SCRIPT;
*/
public function release()
{
$connections = Kiri::getDi()->get(PoolRedis::class);
$connections = Kiri::getDi()->get(PoolRedis::class);
$connections->release($this->get_config(), true);
}
@@ -135,7 +147,7 @@ SCRIPT;
*/
public function proxy($name, $arguments): mixed
{
$connections = Kiri::getDi()->get(PoolRedis::class);
$connections = Kiri::getDi()->get(PoolRedis::class);
$config = $this->get_config();
+18
View File
@@ -0,0 +1,18 @@
<?php
namespace Kiri\Core;
class Network
{
/**
* @return string
*/
public static function local(): string
{
return current(swoole_get_local_ip());
}
}
+2 -3
View File
@@ -9,10 +9,10 @@ declare(strict_types=1);
namespace Kiri\Di;
use Kiri\Abstracts\Component;
use Note\Inject;
use Closure;
use Exception;
use Kiri\Abstracts\BaseObject;
use Kiri\Abstracts\Logger;
use Kiri\Kiri;
use Psr\Log\LoggerInterface;
@@ -27,7 +27,7 @@ use Psr\Container\ContainerInterface;
* Class Container
* @package Kiri\Di
*/
class Container extends BaseObject implements ContainerInterface
class Container extends Component implements ContainerInterface
{
/**
@@ -261,7 +261,6 @@ class Container extends BaseObject implements ContainerInterface
/**
* @param $class
* @return ReflectionClass
* @throws ReflectionException
*/
private function resolveDependencies($class): ReflectionClass
{
+4 -3
View File
@@ -9,6 +9,7 @@ use Http\Aspect\OnAspectInterface;
use Http\Aspect\OnJoinPointInterface;
use Http\Constrict\RequestInterface;
use Kiri\Kiri;
use Psr\Log\LoggerInterface;
/**
@@ -43,10 +44,10 @@ class LoggerAspect implements OnAspectInterface
private function print_runtime($startTime)
{
$request = Kiri::getDi()->get(RequestInterface::class);
$runTime = round(microtime(true) - $startTime, 6);
echo sprintf('run %s use time %6f', $request->getUri()->__toString(), $runTime);
echo PHP_EOL;
$logger = Kiri::getDi()->get(LoggerInterface::class);
$logger->debug(sprintf('run %s use time %6f', $request->getUri()->__toString(), $runTime));
}
}
+4 -3
View File
@@ -5,13 +5,12 @@ namespace Kiri\Error;
use Exception;
use JetBrains\PhpStorm\Pure;
use Kiri\Core\Json;
use Kiri\Exception\ComponentException;
use Kiri\Kiri;
use Server\Abstracts\BaseProcess;
use Swoole\Coroutine;
use Swoole\Process;
use Server\Abstracts\BaseProcess;
/**
* Class LoggerProcess
@@ -24,7 +23,6 @@ class LoggerProcess extends BaseProcess
public string $name = 'logger process';
/**
* @param Process $process
* @throws ComponentException
@@ -43,6 +41,9 @@ class LoggerProcess extends BaseProcess
*/
public function message(Process $process)
{
if ($this->isStop()) {
return;
}
$message = Json::decode($process->read());
if (!empty($message)) {
Kiri::writeFile($this->getDirName($message), $message[0], FILE_APPEND);
+2 -3
View File
@@ -6,14 +6,13 @@ namespace Kiri;
use Exception;
use Kiri\Abstracts\BaseObject;
use Swoole\Coroutine;
use Kiri\Abstracts\Component;
/**
* Class Event
* @package Kiri
*/
class Event extends BaseObject
class Event extends Component
{
public bool $isVide = true;
+118 -40
View File
@@ -2,14 +2,16 @@
namespace Kiri\FileListen;
use Note\Inject;
use Exception;
use Kiri\Abstracts\Config;
use Kiri\Core\Json;
use Kiri\Error\Logger;
use Kiri\Exception\ConfigException;
use Kiri\Kiri;
use Note\Inject;
use Swoole\Coroutine;
use Swoole\Process;
use Swoole\Timer;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
@@ -49,12 +51,74 @@ class HotReload extends Command
/**
*
*/
protected function configure()
{
$this->setName('sw:wather')
->setDescription('server start');
$this->setName('sw:wather')->setDescription('server start');
}
/**
* @throws ConfigException
* @throws \ReflectionException
* @throws Exception
*/
protected function initCore()
{
$this->dirs = Config::get('inotify', [APP_PATH . 'app']);
if (!extension_loaded('inotify')) {
$this->driver = Kiri::getDi()->make(Scaner::class, [$this->dirs, $this]);
} else {
$this->driver = Kiri::getDi()->make(Inotify::class, [$this->dirs, $this]);
}
$this->clearOtherService();
$this->setProcessName();
}
/**
* @throws ConfigException
*/
public function setProcessName()
{
swoole_async_set(['enable_coroutine' => false]);
set_error_handler([$this, 'errorHandler']);
if (Kiri::getPlatform()->isLinux()) {
swoole_set_process_name('[' . Config::get('id', 'sw service.') . '].sw:wather');
}
}
/**
* @throws Exception
*/
public function clearOtherService()
{
if (file_exists(storage('.manager.pid'))) {
$pid = (int)file_get_contents(storage('.manager.pid'));
if ($pid > 0 && Process::kill($pid, 0)) {
Process::kill($pid, 15) && Process::wait(true);
}
}
file_put_contents(storage('.manager.pid'), getmypid());
}
/**
* @throws Exception
*/
public function errorHandler()
{
$error = func_get_args();
$path = ['file' => $error[2], 'line' => $error[3]];
if ($error[0] === 0) {
$error[0] = 500;
}
$data = Json::to(500, $error[1], $path);
$this->logger->error($data, 'error');
}
@@ -67,21 +131,12 @@ class HotReload extends Command
*/
public function execute(InputInterface $input, OutputInterface $output): int
{
// TODO: Implement onHandler() method.
set_error_handler([$this, 'onErrorHandler']);
$this->dirs = Config::get('inotify', [APP_PATH . 'app']);
swoole_async_set(['enable_coroutine' => false]);
if (!extension_loaded('inotify')) {
$this->driver = Kiri::getDi()->make(Scaner::class, [$this->dirs, $this]);
} else {
$this->driver = Kiri::getDi()->make(Inotify::class, [$this->dirs, $this]);
}
if (Kiri::getPlatform()->isLinux()) {
swoole_set_process_name('[' . Config::get('id', 'sw service.') . '].sw:wather');
}
$this->initCore();
$this->trigger_reload();
var_dump(getmypid());
Timer::tick(1000, fn() => $this->healthCheck());
Process::signal(SIGTERM, [$this, 'onSignal']);
Process::signal(SIGKILL, [$this, 'onSignal']);
@@ -90,6 +145,22 @@ class HotReload extends Command
}
/**
* @throws Exception
*/
public function healthCheck()
{
$pid = (int)file_get_contents(storage('.swoole.pid'));
if (empty($pid)) {
$this->logger->warning('service is shutdown you need reload.');
$this->trigger_reload();
} else if (!Process::kill($pid, 0)) {
$this->logger->warning('service is shutdown you need reload.');
$this->trigger_reload();
}
}
/**
* @param $data
* @throws Exception
@@ -99,14 +170,10 @@ class HotReload extends Command
if (!$data) {
return;
}
Timer::clearAll();
$this->driver->clear();
$pid = file_get_contents(storage('.swoole.pid'));
if (!empty($pid) && Process::kill($pid, 0)) {
Process::kill($pid, SIGTERM);
}
if ($this->process && Process::kill($this->process->pid, 0)) {
Process::kill($this->process->pid) && Process::wait(true);
}
$this->stopServer();
$this->stopManager();
while ($ret = Process::wait(true)) {
echo "PID={$ret['pid']}\n";
sleep(1);
@@ -115,18 +182,25 @@ class HotReload extends Command
/**
* @param $code
* @param $message
* @param $file
* @param $line
* @throws Exception
*/
public function onErrorHandler($code, $message, $file, $line)
protected function stopServer()
{
if (str_contains($message, 'The file descriptor is not an inotify instance')) {
return;
$pid = file_get_contents(storage('.swoole.pid'));
if (!empty($pid) && Process::kill($pid, 0)) {
Process::kill($pid, SIGTERM);
}
}
/**
*
*/
protected function stopManager()
{
if ($this->process && Process::kill($this->process->pid, 0)) {
Process::kill($this->process->pid) && Process::wait(true);
}
debug('Error:' . $message . ' at ' . $file . ':' . $line);
}
@@ -137,17 +211,21 @@ class HotReload extends Command
*/
public function trigger_reload()
{
if ($this->int == 1) {
return;
}
$this->int = 1;
$this->logger->warning('change reload');
$pid = $this->process?->pid;
$process = new Process(function (Process $process) {
$this->stopServer();
$this->stopManager();
$this->process = new Process(function (Process $process) {
$process->exec(PHP_BINARY, [APP_PATH . "kiri.php", "sw:server", "restart"]);
});
$process->start();
if ($pid && Process::kill($pid, 0)) {
Process::kill($pid) && Process::wait(true);
}
$this->process = null;
$this->process = $process;
$this->process->start();
$this->int = -1;
}
+1 -1
View File
@@ -105,7 +105,7 @@ class Inotify
try {
inotify_rm_watch($this->inotify, $wd);
} catch (\Throwable $exception) {
logger()->addError($exception, 'throwable');
logger()->addError($exception->getMessage(), 'throwable');
}
}
$this->watchFiles = [];
+3 -2
View File
@@ -16,6 +16,7 @@ use Kiri\Di\Container;
use Psr\Container\ContainerInterface;
use ReflectionException;
use Server\ServerManager;
use Server\Tasker\AsyncTaskExecute;
use Swoole\Coroutine;
use Swoole\Process;
use Swoole\WebSocket\Server;
@@ -457,8 +458,8 @@ class Kiri
*/
public static function async(string $class, array $params = [])
{
$manager = di(ServerManager::class);
$manager->task(new $class(...$params));
$manager = di(AsyncTaskExecute::class);
$manager->execute(new $class(...$params));
}
+1 -3
View File
@@ -113,9 +113,7 @@ class Connection extends Component
public function create($coroutineName, $config): Closure
{
return static function () use ($coroutineName, $config) {
return Kiri::getDi()->create(PDO::class, [
$config['database'], $config['cds'], $config['username'], $config['password'], $config['charset'] ?? 'utf8mb4'
]);
return Kiri::getDi()->create(PDO::class, [$config]);
};
}
+1 -5
View File
@@ -50,11 +50,7 @@ class Redis extends Component
public function create(string $name, mixed $config): Closure
{
return static function () use ($name, $config) {
return Kiri::getDi()->create(\Kiri\Cache\Base\Redis::class, [
$config['host'], (int)$config['port'], $config['databases'] ?? 0,
$config['auth'], $config['prefix'] ?? '', $config['timeout'] ?? 30,
$config['read_timeout'] ?? 30
]);
return Kiri::getDi()->create(\Kiri\Cache\Base\Redis::class, [$config]);
};
}
+1
View File
@@ -334,6 +334,7 @@ class Gii
private function getClassName($tableName): string
{
$res = [];
$tableName = str_replace($this->db->tablePrefix,'', $tableName);
foreach (explode('_', $tableName) as $n => $val) {
$res[] = ucfirst($val);
}
-3
View File
@@ -47,9 +47,6 @@ class GiiController extends GiiBase
$namespace = rtrim($path['namespace'], '\\');
$model_namespace = rtrim($modelPath['namespace'], '\\');
$prefix = str_replace('_', '', $this->db->tablePrefix);
$managerName = str_replace(ucfirst($prefix), '', $managerName);
$class = '';
$controller = str_replace('\\\\', '\\', "$namespace\\{$managerName}Controller");
+10 -10
View File
@@ -51,9 +51,6 @@ class GiiModel extends GiiBase
$namespace = rtrim($modelPath['namespace'], '\\');
$prefix = str_replace('_', '', $this->db->tablePrefix);
$managerName = str_replace(ucfirst($prefix), '', $managerName);
if (file_exists($modelPath['path'] . '/' . $managerName . '.php')) {
try {
$className = str_replace('\\\\', '\\', "{$modelPath['namespace']}\\{$managerName}");
@@ -263,7 +260,7 @@ use Database\Model;
$field = '\'' . current($val)['Field'] . '\'';
}
$_field_one .= '
[' . $field . ', \'' . $key . '\'],';
[' . $field . ', \'' . $key . '\'],';
}
foreach ($data as $key => $val) {
$length = $this->getLength($val);
@@ -279,8 +276,11 @@ use Database\Model;
/**
* @return array
*/
protected array $rules = [' . $_field_one . '
];
public function rules(): array
{
return [' . $_field_one . '
];
}
';
}
@@ -311,10 +311,10 @@ use Database\Model;
}
if (count($_val) == 1) {
$_tmp = '
[\'' . $_val[0][3] . '\', ' . ($_val[0][1] == 'enum' ? '\'enum\' => [' . $key .']' : $key) . ']';
[\'' . $_val[0][3] . '\', ' . ($_val[0][1] == 'enum' ? '\'enum\' => [' . $key .']' : $key) . ']';
} else {
$_tmp = '
[[\'' . implode('\', \'', array_column($_val, 3)) . '\'], ' . $key . ']';
[[\'' . implode('\', \'', array_column($_val, 3)) . '\'], ' . $key . ']';
}
$string[] = $_tmp;
}
@@ -338,7 +338,7 @@ use Database\Model;
return '';
}
return '
[[\'' . implode('\', \'', $data) . '\'], \'unique\'],';
[[\'' . implode('\', \'', $data) . '\'], \'unique\'],';
}
/**
@@ -358,7 +358,7 @@ use Database\Model;
return '';
}
return '
[[\'' . implode('\', \'', $data) . '\'], \'required\'],';
[[\'' . implode('\', \'', $data) . '\'], \'required\'],';
}
/**
+2 -2
View File
@@ -6,7 +6,7 @@ namespace Note;
use DirectoryIterator;
use Exception;
use Kiri\Abstracts\BaseObject;
use Kiri\Abstracts\Component;
use Kiri\Kiri;
use ReflectionClass;
use ReflectionException;
@@ -17,7 +17,7 @@ use Throwable;
* Class Loader
* @package Note
*/
class Loader extends BaseObject
class Loader extends Component
{
+39
View File
@@ -49,3 +49,42 @@
// after($process);
//});
var_dump(json_encode([
"Datacenter" => "dc1",
"Node" => "iz8vbi3edjyskl7kpuwudqz",
"SkipNodeUpdate" => false,
"Service" => [
"ID" => "redis1",
"Service" => "FriendRpcService",
"Address" => "172.26.221.211",
"TaggedAddresses" => [
"lan" => [
"address" => "127.0.0.1",
"port" => 9627
],
"wan" => [
"address" => "172.26.221.211",
"port" => 9627
]
],
"Meta" => [
"redis_version" => "4.0"
],
"Port" => 9627
],
"Check" => [
"Node" => "iz8vbi3edjyskl7kpuwudqz",
"CheckId" => "service:redis1",
"Name" => "Redis health check",
"Notes" => "Script based health check",
"Status" => "passing",
"ServiceID" => "redis1",
"Definition" => [
"Http" => "http://172.26.221.211:9627",
"Interval" => "5s",
"Timeout" => "1s",
"DeregisterCriticalServiceAfter" => "30s"
],
],
]));