This commit is contained in:
as2252258@163.com
2021-04-04 03:01:12 +08:00
parent 59a8974672
commit c7e059f104
14 changed files with 1230 additions and 1230 deletions
+2 -2
View File
@@ -71,7 +71,7 @@ class DatabasesProviders extends Providers
*/ */
public function createPool() public function createPool()
{ {
$databases = Config::get('databases', false, []); $databases = Config::get('databases', []);
if (empty($databases)) { if (empty($databases)) {
return; return;
} }
@@ -101,7 +101,7 @@ class DatabasesProviders extends Providers
*/ */
public function getConfig($name): mixed public function getConfig($name): mixed
{ {
return Config::get('databases.' . $name, true); return Config::get('databases.' . $name,null, true);
} }
+122 -122
View File
@@ -27,141 +27,141 @@ abstract class Callback extends HttpService
{ {
/** /**
* @param $server * @param $server
* @param $worker_id * @param $worker_id
* @param $message * @param $message
* @throws Exception * @throws Exception
*/ */
protected function clear(Server $server, $worker_id, $message) protected function clear(Server $server, $worker_id, $message)
{ {
try { try {
/** @var Process $logger */ /** @var Process $logger */
$logger = Snowflake::app()->get(LoggerProcess::class); $logger = Snowflake::app()->get(LoggerProcess::class);
$logger->write(Json::encode([$this->_MESSAGE[$message] . $worker_id, 'log/app'])); $logger->write(Json::encode([$this->_MESSAGE[$message] . $worker_id, 'log/app']));
$this->eventNotify($message); $this->eventNotify($message);
} catch (\Throwable $exception) { } catch (\Throwable $exception) {
$this->addError($exception,'throwable'); $this->addError($exception, 'throwable');
} }
} }
const EVENT_ERROR = 'WORKER:ERROR'; const EVENT_ERROR = 'WORKER:ERROR';
const EVENT_STOP = 'WORKER:STOP'; const EVENT_STOP = 'WORKER:STOP';
const EVENT_EXIT = 'WORKER:EXIT'; const EVENT_EXIT = 'WORKER:EXIT';
private array $_MESSAGE = [ private array $_MESSAGE = [
self::EVENT_ERROR => 'The server error. at No.', self::EVENT_ERROR => 'The server error. at No.',
self::EVENT_STOP => 'The server stop. at No.', self::EVENT_STOP => 'The server stop. at No.',
self::EVENT_EXIT => 'The server exit. at No.', self::EVENT_EXIT => 'The server exit. at No.',
]; ];
/** /**
* @param $message * @param $message
* @throws Exception * @throws Exception
*/ */
private function eventNotify($message) private function eventNotify($message)
{ {
switch ($message) { switch ($message) {
case self::EVENT_ERROR: case self::EVENT_ERROR:
fire(Event::SERVER_WORKER_ERROR); fire(Event::SERVER_WORKER_ERROR);
break; break;
case self::EVENT_EXIT: case self::EVENT_EXIT:
fire(Event::SERVER_WORKER_EXIT); fire(Event::SERVER_WORKER_EXIT);
break; break;
case self::EVENT_STOP: case self::EVENT_STOP:
fire(Event::SERVER_WORKER_STOP); fire(Event::SERVER_WORKER_STOP);
break; break;
} }
} }
/** /**
* @return PHPMailer * @return PHPMailer
* @throws \PHPMailer\PHPMailer\Exception * @throws \PHPMailer\PHPMailer\Exception
* @throws ConfigException * @throws ConfigException
*/ */
private function createEmail(): PHPMailer private function createEmail(): PHPMailer
{ {
$mail = new PHPMailer(true); $mail = new PHPMailer(true);
$mail->SMTPDebug = SMTP::DEBUG_SERVER; // Enable verbose debug output $mail->SMTPDebug = SMTP::DEBUG_SERVER; // Enable verbose debug output
$mail->isSMTP(); // Send using SMTP $mail->isSMTP(); // Send using SMTP
$mail->Host = Config::get('email.host'); // Set the SMTP server to send through $mail->Host = Config::get('email.host'); // Set the SMTP server to send through
$mail->SMTPAuth = true; // Enable SMTP authentication $mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Debugoutput = false; // Enable SMTP authentication $mail->Debugoutput = false; // Enable SMTP authentication
$mail->CharSet = "UTF8"; // Enable SMTP authentication $mail->CharSet = "UTF8"; // Enable SMTP authentication
$mail->Username = Config::get('email.username'); // SMTP username $mail->Username = Config::get('email.username'); // SMTP username
$mail->Password = Config::get('email.password'); // SMTP password $mail->Password = Config::get('email.password'); // SMTP password
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
$mail->Port = Config::get('email.port'); // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above $mail->Port = Config::get('email.port'); // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above
$mail->setFrom(Config::get('email.send.address'), Config::get('email.send.nickname')); $mail->setFrom(Config::get('email.send.address'), Config::get('email.send.nickname'));
return $mail; return $mail;
} }
/** /**
* @param $message * @param $message
* @throws * @throws
*/ */
protected function system_mail($message) protected function system_mail($message)
{ {
try { try {
if (!Config::get('email.enable', false, false)) { if (!Config::get('email.enable', false)) {
return; return;
} }
$mail = $this->createEmail(); $mail = $this->createEmail();
$receives = Config::get('email.receive'); $receives = Config::get('email.receive');
if (empty($receives) || !is_array($receives)) { if (empty($receives) || !is_array($receives)) {
throw new Exception('接收人信息错误'); throw new Exception('接收人信息错误');
} }
foreach ($receives as $receive) { foreach ($receives as $receive) {
$mail->addAddress($receive['address'], $receive['nickname']); // Add a recipient $mail->addAddress($receive['address'], $receive['nickname']); // Add a recipient
} }
$mail->isHTML(true); // Set email format to HTML $mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'service error'; $mail->Subject = 'service error';
$mail->Body = $message; $mail->Body = $message;
$mail->AltBody = $message; $mail->AltBody = $message;
$mail->send(); $mail->send();
} catch (\Throwable $e) { } catch (\Throwable $e) {
$this->addError($e, 'email'); $this->addError($e, 'email');
} }
} }
/** /**
* @throws ConfigException * @throws ConfigException
* @throws ComponentException * @throws ComponentException
* @throws Exception * @throws Exception
*/ */
protected function clearMysqlClient() protected function clearMysqlClient()
{ {
$databases = Config::get('databases', false, []); $databases = Config::get('databases', []);
if (empty($databases)) { if (empty($databases)) {
return; return;
} }
$application = Snowflake::app(); $application = Snowflake::app();
foreach ($databases as $name => $database) { foreach ($databases as $name => $database) {
/** @var Connection $connection */ /** @var Connection $connection */
$connection = $application->get('databases.' . $name, false); $connection = $application->get('databases.' . $name, false);
if (empty($connection)) { if (empty($connection)) {
continue; continue;
} }
$connection->disconnect(); $connection->disconnect();
} }
} }
/** /**
* @throws ConfigException * @throws ConfigException
* @throws ComponentException * @throws ComponentException
* @throws Exception * @throws Exception
*/ */
protected function clearRedisClient() protected function clearRedisClient()
{ {
$redis = Snowflake::app()->getRedis(); $redis = Snowflake::app()->getRedis();
$redis->destroy(); $redis->destroy();
} }
} }
+1 -1
View File
@@ -535,7 +535,7 @@ class Request extends HttpService
$port = $sRequest->clientInfo['server_port']; $port = $sRequest->clientInfo['server_port'];
$rpc = Config::get('rpc.port', false, []); $rpc = Config::get('rpc.port', []);
if ($rpc !== $port) { if ($rpc !== $port) {
$sRequest->headers->replace('request_uri', 'add-port-listen/port_' . $port); $sRequest->headers->replace('request_uri', 'add-port-listen/port_' . $port);
$sRequest->headers->replace('request_method', 'listen'); $sRequest->headers->replace('request_method', 'listen');
+1 -1
View File
@@ -61,7 +61,7 @@ class Router extends HttpService implements RouterInterface
*/ */
public function init() public function init()
{ {
$this->dir = Config::get('http.namespace', false, $this->dir); $this->dir = Config::get('http.namespace', $this->dir);
} }
+472 -472
View File
@@ -48,478 +48,478 @@ defined('PID_PATH') or define('PID_PATH', APP_PATH . 'storage/server.pid');
class Server extends HttpService class Server extends HttpService
{ {
const HTTP = 'HTTP'; const HTTP = 'HTTP';
const TCP = 'TCP'; const TCP = 'TCP';
const PACKAGE = 'PACKAGE'; const PACKAGE = 'PACKAGE';
const WEBSOCKET = 'WEBSOCKET'; const WEBSOCKET = 'WEBSOCKET';
private array $listening = []; private array $listening = [];
private array $server = [ private array $server = [
'HTTP' => [SWOOLE_TCP, Http::class], 'HTTP' => [SWOOLE_TCP, Http::class],
'TCP' => [SWOOLE_TCP, Receive::class], 'TCP' => [SWOOLE_TCP, Receive::class],
'PACKAGE' => [SWOOLE_UDP, Packet::class], 'PACKAGE' => [SWOOLE_UDP, Packet::class],
'WEBSOCKET' => [SWOOLE_SOCK_TCP, Websocket::class], 'WEBSOCKET' => [SWOOLE_SOCK_TCP, Websocket::class],
]; ];
private Packet|Websocket|Receive|null|Http $swoole = null; private Packet|Websocket|Receive|null|Http $swoole = null;
public int $daemon = 0; public int $daemon = 0;
private array $listenTypes = []; private array $listenTypes = [];
private array $process = [ private array $process = [
'biomonitoring' => Biomonitoring::class, 'biomonitoring' => Biomonitoring::class,
'logger_process' => LoggerProcess::class 'logger_process' => LoggerProcess::class
]; ];
private array $params = []; private array $params = [];
/** /**
* @param $name * @param $name
* @param $process * @param $process
* @param array $params * @param array $params
*/ */
public function addProcess($name, $process, $params = []) public function addProcess($name, $process, $params = [])
{ {
$this->process[$name] = $process; $this->process[$name] = $process;
$this->params[$name] = $params; $this->params[$name] = $params;
} }
/** /**
* @return array * @return array
*/ */
public function getProcesses(): array public function getProcesses(): array
{ {
return $this->process ?? []; return $this->process ?? [];
} }
/** /**
* @param $configs * @param $configs
* @return Packet|Websocket|Receive|Http|null * @return Packet|Websocket|Receive|Http|null
* @throws Exception * @throws Exception
*/ */
private function initCore($configs): Packet|Websocket|Receive|Http|null private function initCore($configs): Packet|Websocket|Receive|Http|null
{ {
$servers = $this->sortServers($configs); $servers = $this->sortServers($configs);
foreach ($servers as $server) { foreach ($servers as $server) {
$this->create($server); $this->create($server);
if (!$this->swoole) { if (!$this->swoole) {
throw new Exception('Base service create fail.'); throw new Exception('Base service create fail.');
} }
} }
return $this->startRpcService(); return $this->startRpcService();
} }
/** /**
* @return string start server * @return string start server
* *
* start server * start server
* @throws ConfigException * @throws ConfigException
* @throws Exception * @throws Exception
*/ */
public function start(): string public function start(): string
{ {
$configs = Config::get('servers', true); $configs = Config::get('servers', [], true);
$baseServer = $this->initCore($configs); $baseServer = $this->initCore($configs);
if (!$baseServer) { if (!$baseServer) {
return 'ok'; return 'ok';
} }
Runtime::enableCoroutine(true, SWOOLE_HOOK_ALL ^ SWOOLE_HOOK_BLOCKING_FUNCTION); Runtime::enableCoroutine(true, SWOOLE_HOOK_ALL ^ SWOOLE_HOOK_BLOCKING_FUNCTION);
Coroutine::set(['enable_deadlock_check' => false]); Coroutine::set(['enable_deadlock_check' => false]);
return $this->execute($baseServer); return $this->execute($baseServer);
} }
/** /**
* @param $baseServer * @param $baseServer
* @return mixed * @return mixed
* @throws Exception * @throws Exception
*/ */
private function execute($baseServer): mixed private function execute($baseServer): mixed
{ {
$app = Snowflake::app(); $app = Snowflake::app();
$app->set('base-server', $baseServer); $app->set('base-server', $baseServer);
return $baseServer->start(); return $baseServer->start();
} }
/** /**
* @param $host * @param $host
* @param $Port * @param $Port
* @return Packet|Websocket|Receive|Http|null * @return Packet|Websocket|Receive|Http|null
* @throws Exception * @throws Exception
*/ */
public function error_stop($host, $Port): Packet|Websocket|Receive|Http|null public function error_stop($host, $Port): Packet|Websocket|Receive|Http|null
{ {
$this->error(sprintf('Port %s::%d is already.', $host, $Port)); $this->error(sprintf('Port %s::%d is already.', $host, $Port));
if ($this->swoole) { if ($this->swoole) {
$this->swoole->shutdown(); $this->swoole->shutdown();
} else { } else {
$this->shutdown(); $this->shutdown();
} }
return $this->swoole; return $this->swoole;
} }
/** /**
* @return bool * @return bool
* @throws ConfigException * @throws ConfigException
* @throws Exception * @throws Exception
*/ */
public function isRunner(): bool public function isRunner(): bool
{ {
$port = $this->sortServers(Config::get('servers')); $port = $this->sortServers(Config::get('servers'));
if (empty($port)) { if (empty($port)) {
return false; return false;
} }
foreach ($port as $value) { foreach ($port as $value) {
if ($this->checkPort($value['port'])) { if ($this->checkPort($value['port'])) {
return true; return true;
} }
} }
return false; return false;
} }
/** /**
* @param $port * @param $port
* @return bool * @return bool
* @throws Exception * @throws Exception
*/ */
private function checkPort($port): bool private function checkPort($port): bool
{ {
if (Snowflake::getPlatform()->isLinux()) { if (Snowflake::getPlatform()->isLinux()) {
exec('netstat -tunlp | grep ' . $port, $output); exec('netstat -tunlp | grep ' . $port, $output);
} else { } else {
exec('lsof -i :' . $port . ' | grep -i "LISTEN"', $output); exec('lsof -i :' . $port . ' | grep -i "LISTEN"', $output);
} }
return !empty($output); return !empty($output);
} }
/** /**
* @return void * @return void
* *
* start server * start server
* @throws Exception * @throws Exception
*/ */
public function shutdown() public function shutdown()
{ {
/** @var Shutdown $shutdown */ /** @var Shutdown $shutdown */
$shutdown = Snowflake::app()->get('shutdown'); $shutdown = Snowflake::app()->get('shutdown');
$shutdown->shutdown(); $shutdown->shutdown();
} }
/** /**
* @throws ConfigException * @throws ConfigException
* @throws Exception * @throws Exception
*/ */
public function onProcessListener(): void public function onProcessListener(): void
{ {
if (!($this->swoole instanceof \Swoole\Server)) { if (!($this->swoole instanceof \Swoole\Server)) {
return; return;
} }
$processes = Config::get('processes'); $processes = Config::get('processes');
if (!empty($processes) && is_array($processes)) { if (!empty($processes) && is_array($processes)) {
$this->deliveryProcess(merge($processes, $this->process)); $this->deliveryProcess(merge($processes, $this->process));
} else { } else {
$this->deliveryProcess($this->process); $this->deliveryProcess($this->process);
} }
} }
/** /**
* @param $processes * @param $processes
* @throws Exception * @throws Exception
*/ */
private function deliveryProcess($processes) private function deliveryProcess($processes)
{ {
$application = Snowflake::app(); $application = Snowflake::app();
if (empty($processes) || !is_array($processes)) { if (empty($processes) || !is_array($processes)) {
return; return;
} }
foreach ($processes as $name => $process) { foreach ($processes as $name => $process) {
$this->debug(sprintf('Process %s', $process)); $this->debug(sprintf('Process %s', $process));
if (!is_string($process)) { if (!is_string($process)) {
continue; continue;
} }
$system = Snowflake::createObject($process, [Snowflake::app(), $name, true]); $system = Snowflake::createObject($process, [Snowflake::app(), $name, true]);
if (isset($this->params[$name]) && !empty($this->params[$name])) { if (isset($this->params[$name]) && !empty($this->params[$name])) {
$system->write(swoole_serialize($this->params[$name])); $system->write(swoole_serialize($this->params[$name]));
} }
$this->swoole->addProcess($system); $this->swoole->addProcess($system);
$application->set($process, $system); $application->set($process, $system);
} }
} }
/** /**
* @param $daemon * @param $daemon
* @return Server * @return Server
*/ */
public function setDaemon($daemon): static public function setDaemon($daemon): static
{ {
if (!in_array($daemon, [0, 1])) { if (!in_array($daemon, [0, 1])) {
return $this; return $this;
} }
$this->daemon = $daemon; $this->daemon = $daemon;
return $this; return $this;
} }
/** /**
* @return Packet|Websocket|Receive|Http|null * @return Packet|Websocket|Receive|Http|null
*/ */
public function getServer(): Packet|Websocket|Receive|Http|null public function getServer(): Packet|Websocket|Receive|Http|null
{ {
return $this->swoole; return $this->swoole;
} }
/** /**
* @param $config * @param $config
* @return mixed * @return mixed
* @throws Exception * @throws Exception
*/ */
private function create($config): mixed private function create($config): mixed
{ {
$settings = Config::get('settings', false, []); $settings = Config::get('settings', []);
if (!isset($this->server[$config['type']])) { if (!isset($this->server[$config['type']])) {
throw new Exception('Unknown server type(' . $config['type'] . ').'); throw new Exception('Unknown server type(' . $config['type'] . ').');
} }
$server = $this->dispatchCreate($config, $settings); $server = $this->dispatchCreate($config, $settings);
if (isset($config['events'])) { if (isset($config['events'])) {
$this->createEventListen($config); $this->createEventListen($config);
} }
return $server; return $server;
} }
/** /**
* @param $config * @param $config
* @throws Exception * @throws Exception
*/ */
protected function createEventListen($config) protected function createEventListen($config)
{ {
if (!is_array($config['events'])) { if (!is_array($config['events'])) {
return; return;
} }
$event = Snowflake::app()->getEvent(); $event = Snowflake::app()->getEvent();
foreach ($config['events'] as $name => $_event) { foreach ($config['events'] as $name => $_event) {
$event->on('listen ' . $config['port'] . ' ' . $name, $_event); $event->on('listen ' . $config['port'] . ' ' . $name, $_event);
} }
} }
/** /**
* @param $config * @param $config
* @param $settings * @param $settings
* @return \Swoole\Server|Packet|Receive|Http|Websocket|null * @return \Swoole\Server|Packet|Receive|Http|Websocket|null
* @throws NotFindClassException * @throws NotFindClassException
* @throws ReflectionException * @throws ReflectionException
* @throws Exception * @throws Exception
*/ */
private function dispatchCreate($config, $settings): \Swoole\Server|Packet|Receive|Http|Websocket|null private function dispatchCreate($config, $settings): \Swoole\Server|Packet|Receive|Http|Websocket|null
{ {
if (Snowflake::port_already($config['port'])) { if (Snowflake::port_already($config['port'])) {
return $this->error_stop($config['host'], $config['port']); return $this->error_stop($config['host'], $config['port']);
} }
if (!($this->swoole instanceof \Swoole\Server)) { if (!($this->swoole instanceof \Swoole\Server)) {
return $this->parseServer($config, $settings); return $this->parseServer($config, $settings);
} }
return $this->addListener($config); return $this->addListener($config);
} }
/** /**
* @param $config * @param $config
* @return Http|Packet|Receive|Websocket|null * @return Http|Packet|Receive|Websocket|null
* @throws NotFindClassException * @throws NotFindClassException
* @throws ReflectionException * @throws ReflectionException
* @throws Exception * @throws Exception
*/ */
private function addListener($config): Packet|Websocket|Receive|Http|null private function addListener($config): Packet|Websocket|Receive|Http|null
{ {
$newListener = $this->swoole->addlistener($config['host'], $config['port'], $config['mode']); $newListener = $this->swoole->addlistener($config['host'], $config['port'], $config['mode']);
if (!$newListener) { if (!$newListener) {
exit($this->addError(sprintf('Listen %s::%d fail.', $config['host'], $config['port']))); exit($this->addError(sprintf('Listen %s::%d fail.', $config['host'], $config['port'])));
} }
if (isset($config['settings']) && is_array($config['settings'])) { if (isset($config['settings']) && is_array($config['settings'])) {
$newListener->set($config['settings']); $newListener->set($config['settings']);
} }
$this->onListenerBind($config, $this->swoole); $this->onListenerBind($config, $this->swoole);
return $this->swoole; return $this->swoole;
} }
/** /**
* @return Packet|Websocket|Receive|Http|null * @return Packet|Websocket|Receive|Http|null
* @throws ConfigException * @throws ConfigException
* @throws Exception * @throws Exception
*/ */
private function startRpcService(): Packet|Websocket|Receive|Http|null private function startRpcService(): Packet|Websocket|Receive|Http|null
{ {
$rpcService = Config::get('rpc.enable', false, []); $rpcService = Config::get('rpc.enable', []);
if ($rpcService === true) { if ($rpcService === true) {
/** @var Service $service */ /** @var Service $service */
$service = Snowflake::app()->get('rpc-service'); $service = Snowflake::app()->get('rpc-service');
$service->instance($this->swoole); $service->instance($this->swoole);
} }
return $this->swoole; return $this->swoole;
} }
/** /**
* @param $config * @param $config
* @param $settings * @param $settings
* @return Packet|Websocket|Receive|Http|null * @return Packet|Websocket|Receive|Http|null
* @throws Exception * @throws Exception
*/ */
private function parseServer($config, $settings): Packet|Websocket|Receive|Http|null private function parseServer($config, $settings): Packet|Websocket|Receive|Http|null
{ {
$class = $this->dispatch($config['type']); $class = $this->dispatch($config['type']);
if (is_array($config['settings'] ?? null)) { if (is_array($config['settings'] ?? null)) {
$settings = array_merge($settings, $config['settings']); $settings = array_merge($settings, $config['settings']);
} }
$this->swoole = $this->createServer($class, $config); $this->swoole = $this->createServer($class, $config);
$settings['daemonize'] = $this->daemon; $settings['daemonize'] = $this->daemon;
if (!isset($settings['pid_file'])) { if (!isset($settings['pid_file'])) {
$settings['pid_file'] = PID_PATH; $settings['pid_file'] = PID_PATH;
} }
$this->debug(Snowflake::listen($config)); $this->debug(Snowflake::listen($config));
$this->swoole->set($settings); $this->swoole->set($settings);
$this->onProcessListener(); $this->onProcessListener();
return $this->swoole; return $this->swoole;
} }
/** /**
* @param $class * @param $class
* @param $config * @param $config
* @return mixed * @return mixed
*/ */
private function createServer($class, $config): mixed private function createServer($class, $config): mixed
{ {
return new $class($config['host'], $config['port'], SWOOLE_PROCESS, $config['mode']); return new $class($config['host'], $config['port'], SWOOLE_PROCESS, $config['mode']);
} }
/** /**
* @param $listen * @param $listen
* @return bool * @return bool
*/ */
#[Pure] public function isListen($listen): bool #[Pure] public function isListen($listen): bool
{ {
return in_array($listen, $this->listenTypes); return in_array($listen, $this->listenTypes);
} }
/** /**
* @param $config * @param $config
* @param $newListener * @param $newListener
* @return Packet|Websocket|Receive|Http|null * @return Packet|Websocket|Receive|Http|null
* @throws NotFindClassException * @throws NotFindClassException
* @throws ReflectionException * @throws ReflectionException
* @throws Exception * @throws Exception
*/ */
private function onListenerBind($config, $newListener): Packet|Websocket|Receive|Http|null private function onListenerBind($config, $newListener): Packet|Websocket|Receive|Http|null
{ {
if (!in_array($config['type'], [self::HTTP, self::TCP, self::PACKAGE])) { if (!in_array($config['type'], [self::HTTP, self::TCP, self::PACKAGE])) {
throw new Exception('Unknown server type(' . $config['type'] . ').'); throw new Exception('Unknown server type(' . $config['type'] . ').');
} }
if ($config['type'] == self::HTTP && !$this->swoole->getCallback('request')) { if ($config['type'] == self::HTTP && !$this->swoole->getCallback('request')) {
$this->onBindCallback('request', [make(OnRequest::class), 'onHandler']); $this->onBindCallback('request', [make(OnRequest::class), 'onHandler']);
} else { } else {
$this->noHttp($newListener, $config); $this->noHttp($newListener, $config);
} }
$this->debug(sprintf('Check listen %s::%d -> ok', $config['host'], $config['port'])); $this->debug(sprintf('Check listen %s::%d -> ok', $config['host'], $config['port']));
$this->listenTypes[] = $config['type']; $this->listenTypes[] = $config['type'];
return $this->swoole; return $this->swoole;
} }
/** /**
* @param $newListener * @param $newListener
* @param $config * @param $config
* @throws Exception * @throws Exception
*/ */
private function noHttp($newListener, $config) private function noHttp($newListener, $config)
{ {
$this->onBindCallback('connect', [make(OnConnect::class), 'onHandler']); $this->onBindCallback('connect', [make(OnConnect::class), 'onHandler']);
$this->onBindCallback('close', [make(OnClose::class), 'onHandler']); $this->onBindCallback('close', [make(OnClose::class), 'onHandler']);
if ($config['type'] == self::TCP) { if ($config['type'] == self::TCP) {
$this->onBindCallback('receive', [make(OnReceive::class), 'onHandler']); $this->onBindCallback('receive', [make(OnReceive::class), 'onHandler']);
} else { } else {
$this->onBindCallback('packet', [make(OnPacket::class), 'onHandler']); $this->onBindCallback('packet', [make(OnPacket::class), 'onHandler']);
} }
} }
/** /**
* @param $name * @param $name
* @param $callback * @param $callback
* @throws Exception * @throws Exception
*/ */
public function onBindCallback($name, $callback) public function onBindCallback($name, $callback)
{ {
if ($this->swoole->getCallback($name) !== null) { if ($this->swoole->getCallback($name) !== null) {
return; return;
} }
$this->swoole->on($name, $callback); $this->swoole->on($name, $callback);
} }
/** /**
* @param $type * @param $type
* @return string * @return string
*/ */
private function dispatch($type): string private function dispatch($type): string
{ {
return match ($type) { return match ($type) {
self::HTTP => Http::class, self::HTTP => Http::class,
self::WEBSOCKET => Websocket::class, self::WEBSOCKET => Websocket::class,
self::PACKAGE => Packet::class, self::PACKAGE => Packet::class,
default => Receive::class default => Receive::class
}; };
} }
/** /**
* @param $servers * @param $servers
* @return array * @return array
*/ */
private function sortServers($servers): array private function sortServers($servers): array
{ {
$array = []; $array = [];
foreach ($servers as $server) { foreach ($servers as $server) {
switch ($server['type']) { switch ($server['type']) {
case self::WEBSOCKET: case self::WEBSOCKET:
array_unshift($array, $server); array_unshift($array, $server);
break; break;
case self::HTTP: case self::HTTP:
case self::PACKAGE | self::TCP: case self::PACKAGE | self::TCP:
$array[] = $server; $array[] = $server;
break; break;
default: default:
$array[] = $server; $array[] = $server;
} }
} }
return $array; return $array;
} }
} }
+1 -1
View File
@@ -36,7 +36,7 @@ class KafkaProviders extends Providers
return; return;
} }
$kafkaServers = Config::get('kafka.servers', false, []); $kafkaServers = Config::get('kafka.servers', []);
if (empty($kafkaServers)) { if (empty($kafkaServers)) {
return; return;
} }
+1 -1
View File
@@ -156,7 +156,7 @@ abstract class BaseApplication extends Service
foreach ($config as $key => $value) { foreach ($config as $key => $value) {
Config::set($key, $value); Config::set($key, $value);
} }
if ($storage = Config::get('storage', false, 'storage')) { if ($storage = Config::get('storage', 'storage')) {
if (!str_contains($storage, APP_PATH)) { if (!str_contains($storage, APP_PATH)) {
$storage = APP_PATH . $storage . '/'; $storage = APP_PATH . $storage . '/';
} }
+1 -1
View File
@@ -53,7 +53,7 @@ class Config extends Component
* @return mixed * @return mixed
* @throws * @throws
*/ */
public static function get($key, $try = FALSE, $default = null): mixed public static function get($key, $default = null, $try = FALSE): mixed
{ {
$instance = Snowflake::app()->getConfig()->getData(); $instance = Snowflake::app()->getConfig()->getData();
if (!str_contains($key, '.')) { if (!str_contains($key, '.')) {
+2 -2
View File
@@ -40,8 +40,8 @@ abstract class Pool extends Component
*/ */
private function getClearTime(): array private function getClearTime(): array
{ {
$firstClear = Config::get('pool.clear.start', false, 600); $firstClear = Config::get('pool.clear.start', 600);
$lastClear = Config::get('pool.clear.end', false, 300); $lastClear = Config::get('pool.clear.end', 300);
return [$firstClear, $lastClear]; return [$firstClear, $lastClear];
} }
+1 -1
View File
@@ -112,7 +112,7 @@ class Logger extends Component
*/ */
public function print_r($message, $method = '') public function print_r($message, $method = '')
{ {
$debug = Config::get('debug', false, ['enable' => false]); $debug = Config::get('debug', ['enable' => false]);
if ((bool)$debug['enable'] === true) { if ((bool)$debug['enable'] === true) {
if (!is_callable($debug['callback'] ?? null, true)) { if (!is_callable($debug['callback'] ?? null, true)) {
return; return;
+380 -380
View File
@@ -26,20 +26,20 @@ use Snowflake\Snowflake;
class Jwt extends Component class Jwt extends Component
{ {
/** @var int $user */ /** @var int $user */
private int $user; private int $user;
private array $data; private array $data;
private array $source = ['browser', 'android', 'iphone', 'pc', 'mingame']; private array $source = ['browser', 'android', 'iphone', 'pc', 'mingame'];
private array $config = ['token' => '']; private array $config = ['token' => ''];
private ?int $timeout = 7200; private ?int $timeout = 7200;
private string $key = 'www.xshucai.com'; private string $key = 'www.xshucai.com';
private ?string $public = '-----BEGIN PUBLIC KEY----- private ?string $public = '-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA6BuML3gtLGde7QKNuNST MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA6BuML3gtLGde7QKNuNST
UCB9gdHC7XIpOc7Wx2I64Esj3UxWHTgp3URj0ge8zpy7A3FfBdppR7d1nwoD6Xad UCB9gdHC7XIpOc7Wx2I64Esj3UxWHTgp3URj0ge8zpy7A3FfBdppR7d1nwoD6Xad
jqfjEWpTy4WwGYsOfH0tFl3wAmse0lebF4NFsS9pzrikQT6c9qsVm88pCjvg4i5t jqfjEWpTy4WwGYsOfH0tFl3wAmse0lebF4NFsS9pzrikQT6c9qsVm88pCjvg4i5t
@@ -49,7 +49,7 @@ WlQhpQrA5/wKd76dCzjvqw9M32OiZl2lCKT73cV8GUvt7BNsM1SiPhqfY7nhO6y3
cwIDAQAB cwIDAQAB
-----END PUBLIC KEY-----'; -----END PUBLIC KEY-----';
private ?string $private = '-----BEGIN RSA PRIVATE KEY----- private ?string $private = '-----BEGIN RSA PRIVATE KEY-----
MIIEpQIBAAKCAQEA6BuML3gtLGde7QKNuNSTUCB9gdHC7XIpOc7Wx2I64Esj3UxW MIIEpQIBAAKCAQEA6BuML3gtLGde7QKNuNSTUCB9gdHC7XIpOc7Wx2I64Esj3UxW
HTgp3URj0ge8zpy7A3FfBdppR7d1nwoD6XadjqfjEWpTy4WwGYsOfH0tFl3wAmse HTgp3URj0ge8zpy7A3FfBdppR7d1nwoD6XadjqfjEWpTy4WwGYsOfH0tFl3wAmse
0lebF4NFsS9pzrikQT6c9qsVm88pCjvg4i5tWhTMEnpTFDYoDR0KXlLXltQMudBB 0lebF4NFsS9pzrikQT6c9qsVm88pCjvg4i5tWhTMEnpTFDYoDR0KXlLXltQMudBB
@@ -78,425 +78,425 @@ mlAZUEjsoaT9vjvjGTxl3uCm0TX5KTgtSJIt2kA1tYVjQef+/iZTHxY=
-----END RSA PRIVATE KEY-----'; -----END RSA PRIVATE KEY-----';
/** /**
* @throws ConfigException * @throws ConfigException
*/ */
public function init() public function init()
{ {
if (!Config::has('ssl.public') || !Config::has('ssl.private')) { if (!Config::has('ssl.public') || !Config::has('ssl.private')) {
return; return;
} }
$this->public = Config::get('ssl.public', false, $this->public); $this->public = Config::get('ssl.public', $this->public);
$this->private = Config::get('ssl.private', false, $this->private); $this->private = Config::get('ssl.private', $this->private);
$this->timeout = Config::get('ssl.timeout', false, 7200); $this->timeout = Config::get('ssl.timeout', 7200);
} }
/** /**
* @param string $publicKey * @param string $publicKey
*/ */
public function setPublic(string $publicKey) public function setPublic(string $publicKey)
{ {
$this->public = $publicKey; $this->public = $publicKey;
} }
/** /**
* @param $timeout * @param $timeout
*/ */
public function setTimeout(int $timeout) public function setTimeout(int $timeout)
{ {
$this->timeout = $timeout; $this->timeout = $timeout;
} }
/** /**
* @param $timeout * @param $timeout
*/ */
public function setKey(string $timeout) public function setKey(string $timeout)
{ {
$this->key = $timeout; $this->key = $timeout;
} }
/** /**
* @param string $privateKey * @param string $privateKey
*/ */
public function setPrivate(string $privateKey) public function setPrivate(string $privateKey)
{ {
$this->private = $privateKey; $this->private = $privateKey;
} }
/** /**
* @param int $unionId * @param int $unionId
* @param array $headers * @param array $headers
* *
* @return array * @return array
* @throws Exception * @throws Exception
*/ */
public function create(int $unionId, $headers = []): array public function create(int $unionId, $headers = []): array
{ {
$this->user = $unionId; $this->user = $unionId;
$this->config['time'] = time(); $this->config['time'] = time();
if (empty($headers)) { if (empty($headers)) {
$headers = request()->headers->getHeaders(); $headers = request()->headers->getHeaders();
} else if ($headers instanceof HttpHeaders) { } else if ($headers instanceof HttpHeaders) {
$headers = $headers->getHeaders(); $headers = $headers->getHeaders();
} }
$this->data = $headers; $this->data = $headers;
if (empty($unionId)) { if (empty($unionId)) {
throw new AuthException('您还未登录或已登录超时'); throw new AuthException('您还未登录或已登录超时');
} }
$source = $header['source'] ?? 'browser'; $source = $header['source'] ?? 'browser';
if (empty($source) || !in_array($source, $this->source)) { if (empty($source) || !in_array($source, $this->source)) {
throw new Exception('未知的登录设备'); throw new Exception('未知的登录设备');
} }
return $this->createEncrypt($unionId); return $this->createEncrypt($unionId);
} }
/** /**
* @param $unionId * @param $unionId
* @return array * @return array
* @throws Exception * @throws Exception
* 对相关信息进行加密 * 对相关信息进行加密
*/ */
private function createEncrypt($unionId): array private function createEncrypt($unionId): array
{ {
$caches = $this->clear($unionId); $caches = $this->clear($unionId);
$param = $this->assembly(array_merge($this->config, [ $param = $this->assembly(array_merge($this->config, [
'user' => $unionId, 'user' => $unionId,
'token' => $this->token($unionId, [ 'token' => $this->token($unionId, [
'device' => Str::rand(128), 'device' => Str::rand(128),
], $this->config['time']), ], $this->config['time']),
]), TRUE); ]), TRUE);
$refresh = array_intersect_key($param, $this->config); $refresh = array_intersect_key($param, $this->config);
$params['user'] = $this->user; $params['user'] = $this->user;
$params['token'] = $refresh['token']; $params['token'] = $refresh['token'];
$json = json_encode($params, JSON_NUMERIC_CHECK | JSON_UNESCAPED_UNICODE); $json = json_encode($params, JSON_NUMERIC_CHECK | JSON_UNESCAPED_UNICODE);
openssl_private_encrypt($json, $encode, $this->private); openssl_private_encrypt($json, $encode, $this->private);
$refresh['refresh'] = base64_encode($encode); $refresh['refresh'] = base64_encode($encode);
$this->setRefresh($refresh['refresh']); $this->setRefresh($refresh['refresh']);
$redis = $this->getRedis(); $redis = $this->getRedis();
foreach ($caches as $cache) { foreach ($caches as $cache) {
$redis->del($cache); $redis->del($cache);
} }
return $refresh; return $refresh;
} }
/** /**
* @param bool $update * @param bool $update
* @param array $param * @param array $param
* @return array * @return array
* @throws * @throws
*/ */
private function assembly(array $param, $update = FALSE): array private function assembly(array $param, $update = FALSE): array
{ {
if (isset($param['sign'])) { if (isset($param['sign'])) {
unset($param['sign']); unset($param['sign']);
} }
$param = $this->initialize($param); $param = $this->initialize($param);
asort($param, SORT_STRING); asort($param, SORT_STRING);
$_tmp = []; $_tmp = [];
foreach ($param as $key => $val) { foreach ($param as $key => $val) {
$_tmp[] = trim($key) . '=>' . trim((string)$val); $_tmp[] = trim($key) . '=>' . trim((string)$val);
} }
$param['sign'] = md5(implode(':', $_tmp)); $param['sign'] = md5(implode(':', $_tmp));
if ($update) { if ($update) {
$this->setCache($param); $this->setCache($param);
} }
return $param; return $param;
} }
/** /**
* @param array $headers * @param array $headers
* @return array * @return array
* @throws Exception * @throws Exception
*/ */
public function refresh($headers = []): array public function refresh($headers = []): array
{ {
$this->data = $headers; $this->data = $headers;
if (!openssl_public_decrypt(base64_decode($headers['refresh']), $data, $this->public)) { if (!openssl_public_decrypt(base64_decode($headers['refresh']), $data, $this->public)) {
throw new AuthException('信息解码失败.'); throw new AuthException('信息解码失败.');
} }
$this->user = $data['user']; $this->user = $data['user'];
if (!$this->getRedis()->exists('refresh:' . $this->user)) { if (!$this->getRedis()->exists('refresh:' . $this->user)) {
throw new AuthException('refresh data error.'); throw new AuthException('refresh data error.');
} }
$this->getRedis()->del('refresh:' . $this->user); $this->getRedis()->del('refresh:' . $this->user);
return $this->create($this->user, $headers); return $this->create($this->user, $headers);
} }
/** /**
* @param $param * @param $param
* *
* @return array * @return array
*/ */
private function initialize(array $param): array private function initialize(array $param): array
{ {
$_param = [ $_param = [
'version' => '1', 'version' => '1',
'source' => $this->getSource(), 'source' => $this->getSource(),
]; ];
if (!isset($param['device'])) { if (!isset($param['device'])) {
$param['device'] = Str::rand(128); $param['device'] = Str::rand(128);
} }
return array_merge($_param, $param); return array_merge($_param, $param);
} }
/** /**
* @param array $data * @param array $data
* @throws Exception * @throws Exception
*/ */
private function setCache(array $data) private function setCache(array $data)
{ {
$redis = $this->getRedis(); $redis = $this->getRedis();
$redis->hMset($this->authKey($this->getSource(), $data['token']), $data); $redis->hMset($this->authKey($this->getSource(), $data['token']), $data);
$redis->expire($this->authKey($this->getSource(), $data['token']), $this->timeout); $redis->expire($this->authKey($this->getSource(), $data['token']), $this->timeout);
} }
/** /**
* @param string $refresh * @param string $refresh
* @throws Exception * @throws Exception
*/ */
private function setRefresh(string $refresh) private function setRefresh(string $refresh)
{ {
$redis = $this->getRedis(); $redis = $this->getRedis();
$redis->set('refresh:' . $this->user, $refresh); $redis->set('refresh:' . $this->user, $refresh);
$redis->expire('refresh:' . $this->user, $this->timeout); $redis->expire('refresh:' . $this->user, $this->timeout);
} }
/** /**
* @param string $_source * @param string $_source
* @param string $token * @param string $token
* *
* @return string * @return string
* @throws Exception * @throws Exception
*/ */
private function authKey(string $_source, string $token): string private function authKey(string $_source, string $token): string
{ {
$source = $this->getSource(); $source = $this->getSource();
if (!empty($_source)) $source = $_source; if (!empty($_source)) $source = $_source;
if (empty($source)) { if (empty($source)) {
throw new AuthException("未知的登陆设备"); throw new AuthException("未知的登陆设备");
} }
return 'Tmp_Token:' . strtoupper($source) . ':' . $token; return 'Tmp_Token:' . strtoupper($source) . ':' . $token;
} }
/** /**
* @return string * @return string
*/ */
public function getSource(): string public function getSource(): string
{ {
return $this->data['source'] ?? 'browser'; return $this->data['source'] ?? 'browser';
} }
/** /**
* @param int $user * @param int $user
* @param array $param * @param array $param
* @param null $requestTime * @param null $requestTime
* *
* @return string * @return string
*/ */
private function token(int $user, $param = [], $requestTime = NULL): string private function token(int $user, $param = [], $requestTime = NULL): string
{ {
$str = ''; $str = '';
$user = (string)$user; $user = (string)$user;
$_user = str_split(md5($user . md5($user))); $_user = str_split(md5($user . md5($user)));
ksort($_user); ksort($_user);
foreach ($_user as $key => $val) { foreach ($_user as $key => $val) {
$str .= md5(sha1($key . $val . $this->key)); $str .= md5(sha1($key . $val . $this->key));
} }
foreach ($param as $key => $val) { foreach ($param as $key => $val) {
$str .= md5($str . sha1($key . md5($val))); $str .= md5($str . sha1($key . md5($val)));
} }
$str .= sha1(base64_encode((string)$requestTime)); $str .= sha1(base64_encode((string)$requestTime));
return $this->preg(md5($str . $user)); return $this->preg(md5($str . $user));
} }
/** /**
* @param string $str * @param string $str
* *
* @return array|string|null 将字符串替换成指定格式 * @return array|string|null 将字符串替换成指定格式
*/ */
private function preg(string $str): null|array|string private function preg(string $str): null|array|string
{ {
return preg_replace('/(\w{10})(\w{3})(\w{4})(\w{9})(\w{6})/', '$1-$2-$3-$4-$5', $str); return preg_replace('/(\w{10})(\w{3})(\w{4})(\w{9})(\w{6})/', '$1-$2-$3-$4-$5', $str);
} }
/** /**
* @param int $user * @param int $user
* @return string[] * @return string[]
* @throws Exception * @throws Exception
*/ */
public function clear(int $user): array public function clear(int $user): array
{ {
$this->user = $user; $this->user = $user;
$redis = $this->getRedis(); $redis = $this->getRedis();
if (is_bool($refresh = $redis->get('refresh:' . $this->user))) { if (is_bool($refresh = $redis->get('refresh:' . $this->user))) {
return []; return [];
}; };
openssl_public_decrypt(base64_decode($refresh), $info, $this->public); openssl_public_decrypt(base64_decode($refresh), $info, $this->public);
$_tmp = []; $_tmp = [];
if (!empty($info) && $json = json_decode($info, true)) { if (!empty($info) && $json = json_decode($info, true)) {
if (!isset($json['token'])) { if (!isset($json['token'])) {
return []; return [];
} }
foreach ($this->source as $value) { foreach ($this->source as $value) {
$_tmp[] = $this->authKey($value, $json['token']); $_tmp[] = $this->authKey($value, $json['token']);
} }
} }
return $_tmp; return $_tmp;
} }
/** /**
* @param array $data * @param array $data
* @param int $user * @param int $user
* @return bool * @return bool
* @throws AuthException * @throws AuthException
*/ */
public function check(array $data, int $user): bool public function check(array $data, int $user): bool
{ {
$this->data = $data; $this->data = $data;
$this->user = $user; $this->user = $user;
if (empty($this->user)) return FALSE; if (empty($this->user)) return FALSE;
$cache = $this->getUserModel(); $cache = $this->getUserModel();
if (empty($cache)) { if (empty($cache)) {
return FALSE; return FALSE;
} }
$merge = $this->assembly(array_merge($cache, [ $merge = $this->assembly(array_merge($cache, [
'token' => $data['token'], 'token' => $data['token'],
])); ]));
$check = array_diff_assoc($this->initialize($cache), $merge); $check = array_diff_assoc($this->initialize($cache), $merge);
return !((bool)count($check)); return !((bool)count($check));
} }
/** /**
* @return mixed * @return mixed
* @throws * @throws
*/ */
public function getCurrentOnlineUser(): int public function getCurrentOnlineUser(): int
{ {
$this->data = request()->headers->getHeaders(); $this->data = request()->headers->getHeaders();
return $this->loadByCache(); return $this->loadByCache();
} }
/** /**
* @param string $token * @param string $token
* @param string $source * @param string $source
* @return mixed * @return mixed
* @throws AuthException * @throws AuthException
*/ */
public function getOnlineUserByToken(string $token, string $source = 'BROWSER'): int public function getOnlineUserByToken(string $token, string $source = 'BROWSER'): int
{ {
$this->data['token'] = $token; $this->data['token'] = $token;
$this->data['source'] = $source; $this->data['source'] = $source;
return $this->loadByCache(); return $this->loadByCache();
} }
/** /**
* @return int * @return int
* @throws AuthException * @throws AuthException
* @throws Exception * @throws Exception
*/ */
private function loadByCache(): int private function loadByCache(): int
{ {
$model = $this->getUserModel(); $model = $this->getUserModel();
if (empty($model)) { if (empty($model)) {
throw new AuthException('授权信息已过期!'); throw new AuthException('授权信息已过期!');
} }
if (!isset($model['user'])) { if (!isset($model['user'])) {
throw new AuthException('授权信息错误!'); throw new AuthException('授权信息错误!');
} }
if (!$this->check($this->data, (int)$model['user'])) { if (!$this->check($this->data, (int)$model['user'])) {
throw new AuthException('授权信息不合法!'); throw new AuthException('授权信息不合法!');
} }
$this->expireRefresh(); $this->expireRefresh();
return (int)$model['user']; return (int)$model['user'];
} }
/** /**
* @param array $header * @param array $header
* @return mixed * @return mixed
* @throws AuthException * @throws AuthException
* @throws Exception * @throws Exception
*/ */
public static function checkAuth(array $header = []): mixed public static function checkAuth(array $header = []): mixed
{ {
$instance = Snowflake::app()->getJwt(); $instance = Snowflake::app()->getJwt();
if (empty($header)) { if (empty($header)) {
$header = request()->headers->getHeaders(); $header = request()->headers->getHeaders();
} }
$instance->data = $header; $instance->data = $header;
$model = $instance->getUserModel(); $model = $instance->getUserModel();
if (empty($model) || !isset($model['user'])) { if (empty($model) || !isset($model['user'])) {
return false; return false;
} }
if (!$instance->check($header, (int)$model['user'])) { if (!$instance->check($header, (int)$model['user'])) {
return false; return false;
} }
$instance->expireRefresh(); $instance->expireRefresh();
return $model['user']; return $model['user'];
} }
/** /**
* @param null $token * @param null $token
* @param null $source * @param null $source
* @throws Exception * @throws Exception
*/ */
public function expireRefresh($token = null, $source = null) public function expireRefresh($token = null, $source = null)
{ {
if (!empty($token)) { if (!empty($token)) {
$this->data['token'] = $token; $this->data['token'] = $token;
} }
if (!empty($source)) { if (!empty($source)) {
$this->data['source'] = $source; $this->data['source'] = $source;
} }
$key = $this->authKey($this->getSource(), $this->data['token']); $key = $this->authKey($this->getSource(), $this->data['token']);
$this->getRedis()->expire($key, $this->timeout); $this->getRedis()->expire($key, $this->timeout);
} }
/** /**
* @return bool|array * @return bool|array
* @throws AuthException * @throws AuthException
* @throws Exception * @throws Exception
*/ */
private function getUserModel(): bool|array private function getUserModel(): bool|array
{ {
if (!isset($this->data['token'])) { if (!isset($this->data['token'])) {
throw new AuthException('暂无访问权限!'); throw new AuthException('暂无访问权限!');
} }
$key = $this->authKey($this->getSource(), $this->data['token']); $key = $this->authKey($this->getSource(), $this->data['token']);
return $this->getRedis()->hGetAll($key); return $this->getRedis()->hGetAll($key);
} }
/** /**
* @return Redis|\Redis * @return Redis|\Redis
* @throws * @throws
*/ */
private function getRedis(): Redis|\Redis private function getRedis(): Redis|\Redis
{ {
return Snowflake::app()->getRedis(); return Snowflake::app()->getRedis();
} }
} }
+244 -244
View File
@@ -25,285 +25,285 @@ use Swoole\Timer;
*/ */
class ServerInotify extends Process class ServerInotify extends Process
{ {
private mixed $inotify; private mixed $inotify;
private bool $isReloading = false; private bool $isReloading = false;
private bool $isReloadingOut = false; private bool $isReloadingOut = false;
private array $watchFiles = []; private array $watchFiles = [];
private ?array $dirs = []; private ?array $dirs = [];
private int $events; private int $events;
private int $int = -1; private int $int = -1;
/** /**
* @param \Swoole\Process $process * @param \Swoole\Process $process
* @throws Exception * @throws Exception
*/ */
public function onHandler(\Swoole\Process $process): void public function onHandler(\Swoole\Process $process): void
{ {
set_error_handler([$this, 'onErrorHandler']); set_error_handler([$this, 'onErrorHandler']);
$this->dirs = Config::get('inotify', false, [APP_PATH]); $this->dirs = Config::get('inotify', [APP_PATH]);
if (extension_loaded('inotify')) { if (extension_loaded('inotify')) {
$this->inotify = inotify_init(); $this->inotify = inotify_init();
$this->events = IN_MODIFY | IN_DELETE | IN_CREATE | IN_MOVE; $this->events = IN_MODIFY | IN_DELETE | IN_CREATE | IN_MOVE;
foreach ($this->dirs as $dir) { foreach ($this->dirs as $dir) {
if (!is_dir($dir)) continue; if (!is_dir($dir)) continue;
$this->watch($dir); $this->watch($dir);
} }
Event::add($this->inotify, [$this, 'check']); Event::add($this->inotify, [$this, 'check']);
Event::wait(); Event::wait();
} else { } else {
$this->loadDirs(); $this->loadDirs();
$this->tick(); $this->tick();
} }
} }
/** /**
* @param bool $isReload * @param bool $isReload
* @throws Exception * @throws Exception
*/ */
private function loadDirs($isReload = false) private function loadDirs($isReload = false)
{ {
foreach ($this->dirs as $value) { foreach ($this->dirs as $value) {
if (is_bool($path = realpath($value))) { if (is_bool($path = realpath($value))) {
continue; continue;
} }
if (!is_dir($path)) continue; if (!is_dir($path)) continue;
$this->loadByDir($path, $isReload); $this->loadByDir($path, $isReload);
} }
} }
private array $md5Map = []; private array $md5Map = [];
/** /**
* @throws Exception * @throws Exception
*/ */
public function tick() public function tick()
{ {
if ($this->isReloading) { if ($this->isReloading) {
return; return;
} }
$this->loadDirs(true); $this->loadDirs(true);
Timer::after(2000, [$this, 'tick']); Timer::after(2000, [$this, 'tick']);
} }
/** /**
* @param $path * @param $path
* @param bool $isReload * @param bool $isReload
* @return void * @return void
* @throws Exception * @throws Exception
*/ */
private function loadByDir($path, $isReload = false): void private function loadByDir($path, $isReload = false): void
{ {
if (!is_string($path)) { if (!is_string($path)) {
return; return;
} }
$path = rtrim($path, '/'); $path = rtrim($path, '/');
foreach (glob(realpath($path) . '/*') as $value) { foreach (glob(realpath($path) . '/*') as $value) {
if (is_dir($value)) { if (is_dir($value)) {
$this->loadByDir($value, $isReload); $this->loadByDir($value, $isReload);
} }
if (is_file($value)) { if (is_file($value)) {
if ($this->checkFile($value, $isReload)) { if ($this->checkFile($value, $isReload)) {
$this->timerReload(); $this->timerReload();
break; break;
} }
} }
} }
} }
/** /**
* @param $value * @param $value
* @param $isReload * @param $isReload
* @return bool * @return bool
*/ */
private function checkFile($value, $isReload): bool private function checkFile($value, $isReload): bool
{ {
$md5 = md5($value); $md5 = md5($value);
$mTime = filectime($value); $mTime = filectime($value);
if (!isset($this->md5Map[$md5])) { if (!isset($this->md5Map[$md5])) {
if ($isReload) { if ($isReload) {
return true; return true;
} }
$this->md5Map[$md5] = $mTime; $this->md5Map[$md5] = $mTime;
} else { } else {
if ($this->md5Map[$md5] != $mTime) { if ($this->md5Map[$md5] != $mTime) {
if ($isReload) { if ($isReload) {
return true; return true;
} }
$this->md5Map[$md5] = $mTime; $this->md5Map[$md5] = $mTime;
} }
} }
return false; return false;
} }
/** /**
* 开始监听 * 开始监听
*/ */
public function check() public function check()
{ {
if (!($events = inotify_read($this->inotify))) { if (!($events = inotify_read($this->inotify))) {
return; return;
} }
if ($this->isReloading) { if ($this->isReloading) {
if (!$this->isReloadingOut) { if (!$this->isReloadingOut) {
$this->isReloadingOut = true; $this->isReloadingOut = true;
} }
return; return;
} }
$eventList = [IN_CREATE, IN_DELETE, IN_MODIFY, IN_MOVED_TO, IN_MOVED_FROM]; $eventList = [IN_CREATE, IN_DELETE, IN_MODIFY, IN_MOVED_TO, IN_MOVED_FROM];
foreach ($events as $ev) { foreach ($events as $ev) {
if (empty($ev['name'])) { if (empty($ev['name'])) {
continue; continue;
} }
if ($ev['mask'] == IN_IGNORED) { if ($ev['mask'] == IN_IGNORED) {
continue; continue;
} }
if (!in_array($ev['mask'], $eventList)) { if (!in_array($ev['mask'], $eventList)) {
continue; continue;
} }
$fileType = strstr($ev['name'], '.'); $fileType = strstr($ev['name'], '.');
//非重启类型 //非重启类型
if ($fileType !== '.php') { if ($fileType !== '.php') {
continue; continue;
} }
if ($this->int !== -1) { if ($this->int !== -1) {
return; return;
} }
$this->int = @swoole_timer_after(2000, [$this, 'reload']); $this->int = @swoole_timer_after(2000, [$this, 'reload']);
$this->isReloading = true; $this->isReloading = true;
} }
} }
/** /**
* @throws Exception * @throws Exception
*/ */
public function reload() public function reload()
{ {
$this->isReloading = true; $this->isReloading = true;
$this->trigger_reload(); $this->trigger_reload();
$this->clearWatch(); $this->clearWatch();
foreach ($this->dirs as $root) { foreach ($this->dirs as $root) {
$this->watch($root); $this->watch($root);
} }
$this->int = -1; $this->int = -1;
$this->isReloading = FALSE; $this->isReloading = FALSE;
$this->isReloadingOut = FALSE; $this->isReloadingOut = FALSE;
$this->md5Map = []; $this->md5Map = [];
} }
/** /**
* @throws Exception * @throws Exception
*/ */
public function timerReload() public function timerReload()
{ {
$this->isReloading = true; $this->isReloading = true;
$this->trigger_reload(); $this->trigger_reload();
$this->int = -1; $this->int = -1;
$this->loadDirs(); $this->loadDirs();
$this->isReloading = FALSE; $this->isReloading = FALSE;
$this->isReloadingOut = FALSE; $this->isReloadingOut = FALSE;
$this->tick(); $this->tick();
} }
/** /**
* 重启 * 重启
* @throws Exception * @throws Exception
*/ */
public function trigger_reload() public function trigger_reload()
{ {
Snowflake::reload(); Snowflake::reload();
} }
/** /**
* @throws Exception * @throws Exception
*/ */
public function clearWatch() public function clearWatch()
{ {
foreach ($this->watchFiles as $wd) { foreach ($this->watchFiles as $wd) {
try { try {
inotify_rm_watch($this->inotify, $wd); inotify_rm_watch($this->inotify, $wd);
} catch (\Throwable $exception) { } catch (\Throwable $exception) {
logger()->addError($exception, 'throwable'); logger()->addError($exception, 'throwable');
} }
} }
$this->watchFiles = []; $this->watchFiles = [];
} }
/** /**
* @param $code * @param $code
* @param $message * @param $message
* @param $file * @param $file
* @param $line * @param $line
* @throws Exception * @throws Exception
*/ */
protected function onErrorHandler($code, $message, $file, $line) protected function onErrorHandler($code, $message, $file, $line)
{ {
if (str_contains($message, 'The file descriptor is not an inotify instance')) { if (str_contains($message, 'The file descriptor is not an inotify instance')) {
return; return;
} }
$this->application->debug('Error:' . $message); $this->application->debug('Error:' . $message);
$this->application->debug($file . ':' . $line); $this->application->debug($file . ':' . $line);
} }
/** /**
* @param $dir * @param $dir
* @return bool * @return bool
* @throws Exception * @throws Exception
*/ */
public function watch($dir): bool public function watch($dir): bool
{ {
//目录不存在 //目录不存在
if (!is_dir($dir)) { if (!is_dir($dir)) {
return $this->application->addError("[$dir] is not a directory."); return $this->application->addError("[$dir] is not a directory.");
} }
//避免重复监听 //避免重复监听
if (isset($this->watchFiles[$dir])) { if (isset($this->watchFiles[$dir])) {
return FALSE; return FALSE;
} }
if (in_array($dir, [APP_PATH . 'config', APP_PATH . 'commands', APP_PATH . '.git', APP_PATH . '.gitee'])) { if (in_array($dir, [APP_PATH . 'config', APP_PATH . 'commands', APP_PATH . '.git', APP_PATH . '.gitee'])) {
return FALSE; return FALSE;
} }
$wd = @inotify_add_watch($this->inotify, $dir, $this->events); $wd = @inotify_add_watch($this->inotify, $dir, $this->events);
$this->watchFiles[$dir] = $wd; $this->watchFiles[$dir] = $wd;
$files = scandir($dir); $files = scandir($dir);
foreach ($files as $f) { foreach ($files as $f) {
if ($f == '.' or $f == '..' or $f == 'runtime' or preg_match('/\.txt/', $f) or preg_match('/\.sql/', $f) or preg_match('/\.log/', $f)) { if ($f == '.' or $f == '..' or $f == 'runtime' or preg_match('/\.txt/', $f) or preg_match('/\.sql/', $f) or preg_match('/\.log/', $f)) {
continue; continue;
} }
$path = $dir . '/' . $f; $path = $dir . '/' . $f;
//递归目录 //递归目录
if (is_dir($path)) { if (is_dir($path)) {
$this->watch($path); $this->watch($path);
} }
//检测文件类型 //检测文件类型
if (strstr($f, '.') == '.php') { if (strstr($f, '.') == '.php') {
$wd = @inotify_add_watch($this->inotify, $path, $this->events); $wd = @inotify_add_watch($this->inotify, $path, $this->events);
$this->watchFiles[$path] = $wd; $this->watchFiles[$path] = $wd;
} }
} }
return TRUE; return TRUE;
} }
} }
+1 -1
View File
@@ -172,7 +172,7 @@ class Snowflake
public static function getStoragePath(): string public static function getStoragePath(): string
{ {
$default = APP_PATH . 'storage' . DIRECTORY_SEPARATOR; $default = APP_PATH . 'storage' . DIRECTORY_SEPARATOR;
$path = Config::get('storage', false, $default); $path = Config::get('storage', $default);
if (!is_dir($path)) { if (!is_dir($path)) {
mkdir($path, 0777, true); mkdir($path, 0777, true);
} }
+1 -1
View File
@@ -616,7 +616,7 @@ if (!function_exists('name')) {
return; return;
} }
$name = Config::get('id', false, 'system') . '[' . $pid . ']'; $name = Config::get('id', 'system') . '[' . $pid . ']';
if (!empty($prefix)) { if (!empty($prefix)) {
$name .= '.' . $prefix; $name .= '.' . $prefix;
} }