mirror of
https://github.com/zhamao-robot/zhamao-framework.git
synced 2026-07-22 08:05:34 +08:00
initial 2.0 commit
This commit is contained in:
@@ -6,25 +6,23 @@ namespace ZM\Event\CQ;
|
||||
|
||||
use Co;
|
||||
use Doctrine\Common\Annotations\AnnotationException;
|
||||
use Framework\Console;
|
||||
use Framework\ZMBuf;
|
||||
use ZM\ConnectionManager\ConnectionObject;
|
||||
use ZM\Console\Console;
|
||||
use ZM\Store\ZMBuf;
|
||||
use ZM\Annotation\CQ\CQAfter;
|
||||
use ZM\Annotation\CQ\CQBefore;
|
||||
use ZM\Annotation\CQ\CQCommand;
|
||||
use ZM\Annotation\CQ\CQMessage;
|
||||
use ZM\Connection\WSConnection;
|
||||
use ZM\Event\EventHandler;
|
||||
use ZM\Exception\WaitTimeoutException;
|
||||
use ZM\Http\Response;
|
||||
use ZM\ModBase;
|
||||
use ZM\ModHandleType;
|
||||
|
||||
class MessageEvent
|
||||
{
|
||||
private $function_call = false;
|
||||
private $data;
|
||||
private $circle;
|
||||
/** @var WSConnection|Response */
|
||||
/** @var ConnectionObject|Response */
|
||||
private $connection;
|
||||
|
||||
public function __construct($data, $conn_or_response, $circle = 0) {
|
||||
@@ -84,6 +82,7 @@ class MessageEvent
|
||||
|
||||
/**
|
||||
* @throws AnnotationException
|
||||
* @noinspection PhpRedundantCatchClauseInspection
|
||||
*/
|
||||
public function onActivate() {
|
||||
try {
|
||||
@@ -96,7 +95,6 @@ class MessageEvent
|
||||
$word[$k] = trim($word[$k]);
|
||||
}
|
||||
}
|
||||
/** @var ModBase[] $obj */
|
||||
$obj = [];
|
||||
foreach (ZMBuf::$events[CQCommand::class] ?? [] as $v) {
|
||||
/** @var CQCommand $v */
|
||||
@@ -107,30 +105,26 @@ class MessageEvent
|
||||
($v->message_type == '' || ($v->message_type != '' && $v->message_type == context()->getData()["message_type"]))
|
||||
) {
|
||||
$c = $v->class;
|
||||
$class_construct = [
|
||||
"data" => context()->getData(),
|
||||
"connection" => context()->getConnection()
|
||||
];
|
||||
if (!isset($obj[$c])) {
|
||||
$obj[$c] = new $c($class_construct);
|
||||
$obj[$c] = new $c();
|
||||
}
|
||||
if ($word[0] != "" && $v->match == $word[0]) {
|
||||
Console::debug("Calling $c -> {$v->method}");
|
||||
$this->function_call = EventHandler::callWithMiddleware($obj[$c], $v->method, $class_construct, [$word], function ($r) {
|
||||
$this->function_call = EventHandler::callWithMiddleware($obj[$c], $v->method, [], [$word], function ($r) {
|
||||
if (is_string($r)) context()->reply($r);
|
||||
return true;
|
||||
});
|
||||
return;
|
||||
} elseif (in_array($word[0], $v->alias)) {
|
||||
Console::debug("Calling $c -> {$v->method}");
|
||||
$this->function_call = EventHandler::callWithMiddleware($obj[$c], $v->method, $class_construct, [$word], function ($r) {
|
||||
$this->function_call = EventHandler::callWithMiddleware($obj[$c], $v->method, [], [$word], function ($r) {
|
||||
if (is_string($r)) context()->reply($r);
|
||||
return true;
|
||||
});
|
||||
return;
|
||||
} elseif ($v->regexMatch != "" && ($args = matchArgs($v->regexMatch, context()->getMessage())) !== false) {
|
||||
Console::debug("Calling $c -> {$v->method}");
|
||||
$this->function_call = EventHandler::callWithMiddleware($obj[$c], $v->method, $class_construct, [$args], function ($r) {
|
||||
$this->function_call = EventHandler::callWithMiddleware($obj[$c], $v->method, [], [$args], function ($r) {
|
||||
if (is_string($r)) context()->reply($r);
|
||||
return true;
|
||||
});
|
||||
@@ -138,7 +132,7 @@ class MessageEvent
|
||||
} elseif ($v->fullMatch != "" && (preg_match("/".$v->fullMatch."/u", ctx()->getMessage(), $args)) != 0) {
|
||||
Console::debug("Calling $c -> {$v->method}");
|
||||
array_shift($args);
|
||||
$this->function_call = EventHandler::callWithMiddleware($obj[$c], $v->method, $class_construct, [$args], function ($r) {
|
||||
$this->function_call = EventHandler::callWithMiddleware($obj[$c], $v->method, [], [$args], function ($r) {
|
||||
if (is_string($r)) context()->reply($r);
|
||||
return true;
|
||||
});
|
||||
@@ -158,10 +152,7 @@ class MessageEvent
|
||||
$c = $v->class;
|
||||
Console::debug("Calling CQMessage: $c -> {$v->method}");
|
||||
if (!isset($obj[$c]))
|
||||
$obj[$c] = new $c([
|
||||
"data" => context()->getData(),
|
||||
"connection" => $this->connection
|
||||
], ModHandleType::CQ_MESSAGE);
|
||||
$obj[$c] = new $c();
|
||||
EventHandler::callWithMiddleware($obj[$c], $v->method, [], [context()->getData()["message"]], function ($r) {
|
||||
if (is_string($r)) context()->reply($r);
|
||||
});
|
||||
|
||||
@@ -5,19 +5,15 @@ namespace ZM\Event\CQ;
|
||||
|
||||
|
||||
use Doctrine\Common\Annotations\AnnotationException;
|
||||
use Framework\ZMBuf;
|
||||
use ZM\Annotation\CQ\CQBefore;
|
||||
use ZM\Annotation\CQ\CQMetaEvent;
|
||||
use ZM\Connection\CQConnection;
|
||||
use ZM\Event\EventHandler;
|
||||
use ZM\Exception\WaitTimeoutException;
|
||||
use ZM\ModBase;
|
||||
use ZM\ModHandleType;
|
||||
use ZM\Store\ZMBuf;
|
||||
|
||||
class MetaEvent
|
||||
{
|
||||
private $data;
|
||||
/** @var CQConnection */
|
||||
private $connection;
|
||||
private $circle;
|
||||
|
||||
@@ -53,7 +49,6 @@ class MetaEvent
|
||||
*/
|
||||
public function onActivate() {
|
||||
try {
|
||||
/** @var ModBase[] $obj */
|
||||
$obj = [];
|
||||
foreach (ZMBuf::$events[CQMetaEvent::class] ?? [] as $v) {
|
||||
/** @var CQMetaEvent $v */
|
||||
@@ -62,10 +57,7 @@ class MetaEvent
|
||||
($v->sub_type == 0 || ($v->sub_type != 0 && $v->sub_type == $this->data["sub_type"]))) {
|
||||
$c = $v->class;
|
||||
if (!isset($obj[$c]))
|
||||
$obj[$c] = new $c([
|
||||
"data" => $this->data,
|
||||
"connection" => $this->connection
|
||||
], ModHandleType::CQ_META_EVENT);
|
||||
$obj[$c] = new $c();
|
||||
EventHandler::callWithMiddleware($obj[$c],$v->method, [], [], function($r) {
|
||||
if (is_string($r)) context()->reply($r);
|
||||
});
|
||||
|
||||
@@ -5,20 +5,16 @@ namespace ZM\Event\CQ;
|
||||
|
||||
|
||||
use Doctrine\Common\Annotations\AnnotationException;
|
||||
use Framework\ZMBuf;
|
||||
use ZM\Annotation\CQ\CQAfter;
|
||||
use ZM\Annotation\CQ\CQBefore;
|
||||
use ZM\Annotation\CQ\CQNotice;
|
||||
use ZM\Connection\CQConnection;
|
||||
use ZM\Event\EventHandler;
|
||||
use ZM\Exception\WaitTimeoutException;
|
||||
use ZM\ModBase;
|
||||
use ZM\ModHandleType;
|
||||
use ZM\Store\ZMBuf;
|
||||
|
||||
class NoticeEvent
|
||||
{
|
||||
private $data;
|
||||
/** @var CQConnection */
|
||||
private $connection;
|
||||
private $circle;
|
||||
|
||||
@@ -54,7 +50,6 @@ class NoticeEvent
|
||||
*/
|
||||
public function onActivate() {
|
||||
try {
|
||||
/** @var ModBase[] $obj */
|
||||
$obj = [];
|
||||
foreach (ZMBuf::$events[CQNotice::class] ?? [] as $v) {
|
||||
/** @var CQNotice $v */
|
||||
@@ -65,10 +60,7 @@ class NoticeEvent
|
||||
($v->operator_id == 0 || ($v->operator_id != 0 && $v->operator_id == ($this->data["operator_id"] ?? 0)))) {
|
||||
$c = $v->class;
|
||||
if (!isset($obj[$c]))
|
||||
$obj[$c] = new $c([
|
||||
"data" => $this->data,
|
||||
"connection" => $this->connection
|
||||
], ModHandleType::CQ_NOTICE);
|
||||
$obj[$c] = new $c();
|
||||
EventHandler::callWithMiddleware($obj[$c],$v->method, [], [], function($r) {
|
||||
if (is_string($r)) context()->reply($r);
|
||||
});
|
||||
|
||||
@@ -5,20 +5,16 @@ namespace ZM\Event\CQ;
|
||||
|
||||
|
||||
use Doctrine\Common\Annotations\AnnotationException;
|
||||
use Framework\ZMBuf;
|
||||
use ZM\Annotation\CQ\CQAfter;
|
||||
use ZM\Annotation\CQ\CQBefore;
|
||||
use ZM\Annotation\CQ\CQRequest;
|
||||
use ZM\Connection\CQConnection;
|
||||
use ZM\Event\EventHandler;
|
||||
use ZM\Exception\WaitTimeoutException;
|
||||
use ZM\ModBase;
|
||||
use ZM\ModHandleType;
|
||||
use ZM\Store\ZMBuf;
|
||||
|
||||
class RequestEvent
|
||||
{
|
||||
private $data;
|
||||
/** @var CQConnection */
|
||||
private $connection;
|
||||
private $circle;
|
||||
|
||||
@@ -51,10 +47,10 @@ class RequestEvent
|
||||
|
||||
/**
|
||||
* @throws AnnotationException
|
||||
* @noinspection PhpRedundantCatchClauseInspection
|
||||
*/
|
||||
public function onActivate() {
|
||||
try {
|
||||
/** @var ModBase[] $obj */
|
||||
$obj = [];
|
||||
foreach (ZMBuf::$events[CQRequest::class] ?? [] as $v) {
|
||||
/** @var CQRequest $v */
|
||||
@@ -65,10 +61,7 @@ class RequestEvent
|
||||
($v->comment == 0 || ($v->comment != 0 && $v->comment == ($this->data["comment"] ?? 0)))) {
|
||||
$c = $v->class;
|
||||
if (!isset($obj[$c]))
|
||||
$obj[$c] = new $c([
|
||||
"data" => $this->data,
|
||||
"connection" => $this->connection
|
||||
], ModHandleType::CQ_REQUEST);
|
||||
$obj[$c] = new $c();
|
||||
EventHandler::callWithMiddleware($obj[$c],$v->method, [], [], function($r) {
|
||||
if (is_string($r)) context()->reply($r);
|
||||
});
|
||||
|
||||
@@ -8,8 +8,9 @@ use Co;
|
||||
use Doctrine\Common\Annotations\AnnotationException;
|
||||
use Error;
|
||||
use Exception;
|
||||
use Framework\Console;
|
||||
use Framework\ZMBuf;
|
||||
use ZM\ConnectionManager\ConnectionObject;
|
||||
use ZM\ConnectionManager\ManagerGM;
|
||||
use ZM\Console\Console;
|
||||
use ZM\Event\Swoole\{MessageEvent, RequestEvent, WorkerStartEvent, WSCloseEvent, WSOpenEvent};
|
||||
use Swoole\Http\Request;
|
||||
use Swoole\Server;
|
||||
@@ -17,11 +18,10 @@ use Swoole\WebSocket\Frame;
|
||||
use ZM\Annotation\CQ\CQAPIResponse;
|
||||
use ZM\Annotation\CQ\CQAPISend;
|
||||
use ZM\Annotation\Http\MiddlewareClass;
|
||||
use ZM\Connection\ConnectionManager;
|
||||
use ZM\Connection\CQConnection;
|
||||
use ZM\Http\MiddlewareInterface;
|
||||
use ZM\Http\Response;
|
||||
use Framework\DataProvider;
|
||||
use ZM\Store\ZMBuf;
|
||||
use ZM\Utils\DataProvider;
|
||||
use ZM\Utils\ZMUtil;
|
||||
|
||||
class EventHandler
|
||||
@@ -51,7 +51,7 @@ class EventHandler
|
||||
});
|
||||
ZMBuf::$server = $param0;
|
||||
$r = (new WorkerStartEvent($param0, $param1))->onActivate();
|
||||
Console::log("\n=== Worker #" . $param0->worker_id . " 已启动 ===\n", "gold");
|
||||
Console::success("Worker #" . $param0->worker_id . " 已启动");
|
||||
$r->onAfter();
|
||||
self::startTick();
|
||||
} catch (Exception $e) {
|
||||
@@ -69,14 +69,14 @@ class EventHandler
|
||||
case "message":
|
||||
/** @var Frame $param1 */
|
||||
/** @var Server $param0 */
|
||||
$conn = ConnectionManager::get($param1->fd);
|
||||
$conn = ManagerGM::get($param1->fd);
|
||||
set_coroutine_params(["server" => $param0, "frame" => $param1, "connection" => $conn]);
|
||||
try {
|
||||
(new MessageEvent($param0, $param1))->onActivate()->onAfter();
|
||||
} catch (Error $e) {
|
||||
$error_msg = $e->getMessage() . " at " . $e->getFile() . "(" . $e->getLine() . ")";
|
||||
Console::error("Fatal error when calling $event_name: " . $error_msg);
|
||||
Console::stackTrace();
|
||||
Console::trace();
|
||||
}
|
||||
break;
|
||||
case "request":
|
||||
@@ -89,7 +89,12 @@ class EventHandler
|
||||
Console::info($param0->server["remote_addr"] . ":" . $param0->server["remote_port"] .
|
||||
" [" . $param1->getStatusCode() . "] " . $param0->server["request_uri"]
|
||||
);
|
||||
if (!$param1->isEnd()) $param1->end("Internal server error: " . $e->getMessage());
|
||||
if (!$param1->isEnd()) {
|
||||
if (\ZM\Config\ZMConfig::get("global", "debug_mode"))
|
||||
$param1->end("Internal server error: " . $e->getMessage());
|
||||
else
|
||||
$param1->end("Internal server error.");
|
||||
}
|
||||
Console::error("Internal server exception (500), caused by " . get_class($e));
|
||||
Console::log($e->getTraceAsString(), "gray");
|
||||
} catch (Error $e) {
|
||||
@@ -100,7 +105,7 @@ class EventHandler
|
||||
);
|
||||
$doc = "Internal server error<br>";
|
||||
$error_msg = $e->getMessage() . " at " . $e->getFile() . "(" . $e->getLine() . ")";
|
||||
if (ZMBuf::$atomics["info_level"]->get() >= 4) $doc .= $error_msg;
|
||||
if (Console::getLevel() >= 4) $doc .= $error_msg;
|
||||
if (!$param1->isEnd()) $param1->end($doc);
|
||||
Console::error("Internal server error (500): " . $error_msg);
|
||||
Console::log($e->getTraceAsString(), "gray");
|
||||
@@ -114,7 +119,7 @@ class EventHandler
|
||||
} catch (Error $e) {
|
||||
$error_msg = $e->getMessage() . " at " . $e->getFile() . "(" . $e->getLine() . ")";
|
||||
Console::error("Fatal error when calling $event_name: " . $error_msg);
|
||||
Console::stackTrace();
|
||||
Console::trace();
|
||||
}
|
||||
break;
|
||||
case "close":
|
||||
@@ -124,7 +129,7 @@ class EventHandler
|
||||
} catch (Error $e) {
|
||||
$error_msg = $e->getMessage() . " at " . $e->getFile() . "(" . $e->getLine() . ")";
|
||||
Console::error("Fatal error when calling $event_name: " . $error_msg);
|
||||
Console::stackTrace();
|
||||
Console::trace();
|
||||
}
|
||||
break;
|
||||
}
|
||||
@@ -142,7 +147,7 @@ class EventHandler
|
||||
ctx()->setCache("level", $level);
|
||||
if ($level >= 5) {
|
||||
Console::warning("Recursive call reached " . $level . " times");
|
||||
Console::stackTrace();
|
||||
Console::trace();
|
||||
return false;
|
||||
}
|
||||
$starttime = microtime(true);
|
||||
@@ -220,7 +225,7 @@ class EventHandler
|
||||
}
|
||||
}
|
||||
|
||||
public static function callCQAPISend($reply, ?CQConnection $connection) {
|
||||
public static function callCQAPISend($reply, ?ConnectionObject $connection) {
|
||||
$action = $reply["action"] ?? null;
|
||||
if ($action === null) {
|
||||
Console::warning("API 激活事件异常!");
|
||||
@@ -235,7 +240,7 @@ class EventHandler
|
||||
foreach (ZMBuf::$events[CQAPISend::class] ?? [] as $k => $v) {
|
||||
if (($v->action == "" || $v->action == $action) && !$v->with_result) {
|
||||
$c = $v->class;
|
||||
self::callWithMiddleware($c, $v->method, context()->copy(), [$reply["action"], $reply["params"] ?? [], $connection->getQQ()]);
|
||||
self::callWithMiddleware($c, $v->method, context()->copy(), [$reply["action"], $reply["params"] ?? [], $connection->getOption('connect_id')]);
|
||||
if (context()->getCache("block_continue") === true) break;
|
||||
}
|
||||
}
|
||||
|
||||
80
src/ZM/Event/ServerEventHandler.php
Normal file
80
src/ZM/Event/ServerEventHandler.php
Normal file
@@ -0,0 +1,80 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace ZM\Event;
|
||||
|
||||
|
||||
use Co;
|
||||
use Doctrine\Common\Annotations\AnnotationException;
|
||||
use ZM\Console\Console;
|
||||
use Swoole\Http\Request;
|
||||
use Swoole\Server;
|
||||
use Swoole\WebSocket\Frame;
|
||||
use ZM\Annotation\Swoole\OnEvent;
|
||||
use ZM\Http\Response;
|
||||
use ZM\Store\ZMBuf;
|
||||
|
||||
class ServerEventHandler
|
||||
{
|
||||
/**
|
||||
* @OnEvent("WorkerStart")
|
||||
* @param Server $server
|
||||
* @param $worker_id
|
||||
* @throws AnnotationException
|
||||
*/
|
||||
public function onWorkerStart(Server $server, $worker_id) {
|
||||
if ($server->taskworker === false) {
|
||||
EventHandler::callSwooleEvent("WorkerStart", $server, $worker_id);
|
||||
} else {
|
||||
ob_start();
|
||||
//AnnotationParser::registerMods();
|
||||
ob_get_clean();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @OnEvent("message")
|
||||
* @param $server
|
||||
* @param Frame $frame
|
||||
* @throws AnnotationException
|
||||
*/
|
||||
public function onMessage($server, Frame $frame) {
|
||||
if ($frame->fd !== ZMBuf::get("terminal_fd"))
|
||||
Console::debug("Calling Swoole \"message\" from fd=" . $frame->fd);
|
||||
EventHandler::callSwooleEvent("message", $server, $frame);
|
||||
}
|
||||
|
||||
/**
|
||||
* @OnEvent("request")
|
||||
* @param $request
|
||||
* @param $response
|
||||
* @throws AnnotationException
|
||||
*/
|
||||
public function onRequest($request, $response) {
|
||||
$response = new Response($response);
|
||||
Console::debug("Receiving Http request event, cid=" . Co::getCid());
|
||||
EventHandler::callSwooleEvent("request", $request, $response);
|
||||
}
|
||||
|
||||
/**
|
||||
* @OnEvent("open")
|
||||
* @param $server
|
||||
* @param Request $request
|
||||
* @throws AnnotationException
|
||||
*/
|
||||
public function onOpen($server, Request $request) {
|
||||
Console::debug("Calling Swoole \"open\" event from fd=" . $request->fd);
|
||||
EventHandler::callSwooleEvent("open", $server, $request);
|
||||
}
|
||||
|
||||
/**
|
||||
* @OnEvent("close")
|
||||
* @param $server
|
||||
* @param $fd
|
||||
* @throws AnnotationException
|
||||
*/
|
||||
public function onClose($server, $fd) {
|
||||
Console::debug("Calling Swoole \"close\" event from fd=" . $fd);
|
||||
EventHandler::callSwooleEvent("close", $server, $fd);
|
||||
}
|
||||
}
|
||||
@@ -5,17 +5,15 @@ namespace ZM\Event\Swoole;
|
||||
|
||||
|
||||
use Closure;
|
||||
use Framework\Console;
|
||||
use Framework\ZMBuf;
|
||||
use ZM\ConnectionManager\ManagerGM;
|
||||
use ZM\Console\Console;
|
||||
use Swoole\WebSocket\Frame;
|
||||
use Swoole\WebSocket\Server;
|
||||
use ZM\Annotation\Swoole\SwooleEventAfter;
|
||||
use ZM\Annotation\Swoole\SwooleEventAt;
|
||||
use ZM\Connection\ConnectionManager;
|
||||
use Exception;
|
||||
use ZM\Event\EventHandler;
|
||||
use ZM\ModBase;
|
||||
use ZM\ModHandleType;
|
||||
use ZM\Store\ZMBuf;
|
||||
use ZM\Utils\ZMUtil;
|
||||
|
||||
class MessageEvent implements SwooleEvent
|
||||
@@ -39,15 +37,15 @@ class MessageEvent implements SwooleEvent
|
||||
*/
|
||||
public function onActivate() {
|
||||
ZMUtil::checkWait();
|
||||
$conn = ConnectionManager::get(context()->getFrame()->fd);
|
||||
$conn = ManagerGM::get(context()->getFrame()->fd);
|
||||
try {
|
||||
if ($conn->getType() == "qq") {
|
||||
if ($conn->getName() == "qq") {
|
||||
$data = json_decode(context()->getFrame()->data, true);
|
||||
if (isset($data["post_type"])) {
|
||||
set_coroutine_params(["data" => $data, "connection" => $conn]);
|
||||
ctx()->setCache("level", 0);
|
||||
Console::debug("Calling CQ Event from fd=" . $conn->fd);
|
||||
EventHandler::callCQEvent($data, ConnectionManager::get(context()->getFrame()->fd), 0);
|
||||
Console::debug("Calling CQ Event from fd=" . $conn->getFd());
|
||||
EventHandler::callCQEvent($data, ManagerGM::get(context()->getFrame()->fd), 0);
|
||||
} else{
|
||||
set_coroutine_params(["connection" => $conn]);
|
||||
EventHandler::callCQResponse($data);
|
||||
@@ -78,10 +76,8 @@ class MessageEvent implements SwooleEvent
|
||||
public function onAfter() {
|
||||
foreach (ZMBuf::$events[SwooleEventAfter::class] ?? [] as $v) {
|
||||
if (strtolower($v->type) == "message" && $this->parseSwooleRule($v) === true) {
|
||||
$conn = ConnectionManager::get($this->frame->fd);
|
||||
$c = $v->class;
|
||||
/** @var ModBase $class */
|
||||
$class = new $c(["server" => $this->server, "frame" => $this->frame, "connection" => $conn], ModHandleType::SWOOLE_MESSAGE);
|
||||
$class = new $c();
|
||||
call_user_func_array([$class, $v->method], []);
|
||||
if (context()->getCache("block_continue") === true) break;
|
||||
}
|
||||
@@ -92,7 +88,7 @@ class MessageEvent implements SwooleEvent
|
||||
private function parseSwooleRule($v) {
|
||||
switch (explode(":", $v->rule)[0]) {
|
||||
case "connectType": //websocket连接类型
|
||||
if ($v->callback instanceof Closure) return call_user_func($v->callback, ConnectionManager::get($this->frame->fd));
|
||||
if ($v->callback instanceof Closure) return call_user_func($v->callback, ManagerGM::get($this->frame->fd));
|
||||
break;
|
||||
case "dataEqual": //handle websocket message事件时才能用
|
||||
if ($v->callback instanceof Closure) return call_user_func($v->callback, $this->frame->data);
|
||||
|
||||
@@ -6,14 +6,14 @@ namespace ZM\Event\Swoole;
|
||||
|
||||
use Closure;
|
||||
use Exception;
|
||||
use Framework\Console;
|
||||
use ZM\Console\Console;
|
||||
use Framework\ZMBuf;
|
||||
use Swoole\Http\Request;
|
||||
use ZM\Annotation\Swoole\SwooleEventAfter;
|
||||
use ZM\Annotation\Swoole\SwooleEventAt;
|
||||
use ZM\Event\EventHandler;
|
||||
use ZM\Http\Response;
|
||||
use Framework\DataProvider;
|
||||
use ZM\Utils\DataProvider;
|
||||
use ZM\Utils\ZMUtil;
|
||||
|
||||
class RequestEvent implements SwooleEvent
|
||||
@@ -38,7 +38,7 @@ class RequestEvent implements SwooleEvent
|
||||
*/
|
||||
public function onActivate() {
|
||||
ZMUtil::checkWait();
|
||||
foreach (ZMBuf::globals("http_header") as $k => $v) {
|
||||
foreach (\ZM\Config\ZMConfig::get("global", "http_header") as $k => $v) {
|
||||
$this->response->setHeader($k, $v);
|
||||
}
|
||||
$uri = $this->request->server["request_uri"];
|
||||
@@ -81,9 +81,9 @@ class RequestEvent implements SwooleEvent
|
||||
}
|
||||
}
|
||||
|
||||
if (ZMBuf::globals("static_file_server")["status"]) {
|
||||
$base_dir = ZMBuf::globals("static_file_server")["document_root"];
|
||||
$base_index = ZMBuf::globals("static_file_server")["document_index"];
|
||||
if (\ZM\Config\ZMConfig::get("global", "static_file_server")["status"]) {
|
||||
$base_dir = \ZM\Config\ZMConfig::get("global", "static_file_server")["document_root"];
|
||||
$base_index = \ZM\Config\ZMConfig::get("global", "static_file_server")["document_index"];
|
||||
$uri = $this->request->server["request_uri"];
|
||||
$path = realpath($base_dir . urldecode($uri));
|
||||
if ($path !== false) {
|
||||
@@ -116,7 +116,6 @@ class RequestEvent implements SwooleEvent
|
||||
$this->response->end(ZMUtil::getHttpCodePage(404));
|
||||
return $this;
|
||||
}
|
||||
|
||||
context()->setCache("params", $params);
|
||||
|
||||
if (in_array(strtoupper($this->request->server["request_method"]), $node["request_method"] ?? [])) { //判断目标方法在不在里面
|
||||
|
||||
@@ -6,12 +6,13 @@ namespace ZM\Event\Swoole;
|
||||
|
||||
use Closure;
|
||||
use Doctrine\Common\Annotations\AnnotationException;
|
||||
use Framework\ZMBuf;
|
||||
use ZM\ConnectionManager\ManagerGM;
|
||||
use ZM\Console\Console;
|
||||
use Swoole\Server;
|
||||
use ZM\Annotation\Swoole\SwooleEventAfter;
|
||||
use ZM\Annotation\Swoole\SwooleEventAt;
|
||||
use ZM\Connection\ConnectionManager;
|
||||
use ZM\Event\EventHandler;
|
||||
use ZM\Store\ZMBuf;
|
||||
use ZM\Utils\ZMUtil;
|
||||
|
||||
class WSCloseEvent implements SwooleEvent
|
||||
@@ -30,8 +31,9 @@ class WSCloseEvent implements SwooleEvent
|
||||
* @throws AnnotationException
|
||||
*/
|
||||
public function onActivate() {
|
||||
Console::info("Closed #{$this->fd}");
|
||||
ZMUtil::checkWait();
|
||||
set_coroutine_params(["server" => $this->server, "fd" => $this->fd, "connection" => ConnectionManager::get($this->fd)]);
|
||||
set_coroutine_params(["server" => $this->server, "fd" => $this->fd, "connection" => ManagerGM::get($this->fd)]);
|
||||
foreach(ZMBuf::$events[SwooleEventAt::class] ?? [] as $v) {
|
||||
if(strtolower($v->type) == "close" && $this->parseSwooleRule($v)) {
|
||||
$c = $v->class;
|
||||
@@ -39,7 +41,7 @@ class WSCloseEvent implements SwooleEvent
|
||||
if(context()->getCache("block_continue") === true) break;
|
||||
}
|
||||
}
|
||||
ConnectionManager::close($this->fd);
|
||||
ManagerGM::popConnect($this->fd);
|
||||
return $this;
|
||||
}
|
||||
|
||||
@@ -61,7 +63,7 @@ class WSCloseEvent implements SwooleEvent
|
||||
private function parseSwooleRule($v) {
|
||||
switch (explode(":", $v->rule)[0]) {
|
||||
case "connectType": //websocket连接类型
|
||||
if ($v->callback instanceof Closure) return call_user_func($v->callback, ConnectionManager::get($this->fd));
|
||||
if ($v->callback instanceof Closure) return call_user_func($v->callback, ManagerGM::get($this->fd));
|
||||
break;
|
||||
}
|
||||
return true;
|
||||
|
||||
@@ -6,19 +6,16 @@ namespace ZM\Event\Swoole;
|
||||
|
||||
use Closure;
|
||||
use Doctrine\Common\Annotations\AnnotationException;
|
||||
use Framework\Console;
|
||||
use Framework\ZMBuf;
|
||||
use ZM\Config\ZMConfig;
|
||||
use ZM\ConnectionManager\ConnectionObject;
|
||||
use ZM\ConnectionManager\ManagerGM;
|
||||
use ZM\Console\Console;
|
||||
use Swoole\Http\Request;
|
||||
use Swoole\WebSocket\Server;
|
||||
use ZM\Annotation\Swoole\SwooleEventAfter;
|
||||
use ZM\Annotation\Swoole\SwooleEventAt;
|
||||
use ZM\Connection\ConnectionManager;
|
||||
use ZM\Connection\CQConnection;
|
||||
use ZM\Connection\UnknownConnection;
|
||||
use ZM\Connection\WSConnection;
|
||||
use ZM\Event\EventHandler;
|
||||
use ZM\ModBase;
|
||||
use ZM\ModHandleType;
|
||||
use ZM\Store\ZMBuf;
|
||||
use ZM\Utils\ZMUtil;
|
||||
|
||||
class WSOpenEvent implements SwooleEvent
|
||||
@@ -31,9 +28,7 @@ class WSOpenEvent implements SwooleEvent
|
||||
* @var Request
|
||||
*/
|
||||
private $request;
|
||||
/**
|
||||
* @var WSConnection
|
||||
*/
|
||||
/** @var ConnectionObject */
|
||||
private $conn;
|
||||
|
||||
public function __construct(Server $server, Request $request) {
|
||||
@@ -47,25 +42,28 @@ class WSOpenEvent implements SwooleEvent
|
||||
*/
|
||||
public function onActivate() {
|
||||
ZMUtil::checkWait();
|
||||
ManagerGM::pushConnect($this->request->fd);
|
||||
$type = strtolower($this->request->get["type"] ?? $this->request->header["x-client-role"] ?? "");
|
||||
$type_conn = ConnectionManager::getTypeClassName($type);
|
||||
if ($type_conn == CQConnection::class) {
|
||||
$type_conn = $this->getTypeClassName($type);
|
||||
if ($type_conn == "qq") {
|
||||
ManagerGM::setName($this->request->fd, "qq");
|
||||
$qq = $this->request->get["qq"] ?? $this->request->header["x-self-id"] ?? "";
|
||||
$self_token = ZMBuf::globals("access_token") ?? "";
|
||||
if(isset($this->request->header["authorization"])) {
|
||||
$self_token = ZMConfig::get("global", "access_token") ?? "";
|
||||
if (isset($this->request->header["authorization"])) {
|
||||
Console::debug($this->request->header["authorization"]);
|
||||
}
|
||||
$remote_token = $this->request->get["token"] ?? (isset($this->request->header["authorization"]) ? explode(" ", $this->request->header["authorization"])[1] : "");
|
||||
if ($qq != "" && ($self_token == $remote_token)) $this->conn = new CQConnection($this->server, $this->request->fd, $qq);
|
||||
else {
|
||||
$this->conn = new UnknownConnection($this->server, $this->request->fd);
|
||||
if ($qq != "" && ($self_token == $remote_token)) {
|
||||
ManagerGM::setOption($this->request->fd, "connect_id", $qq);
|
||||
$this->conn = ManagerGM::get($this->request->fd);
|
||||
} else {
|
||||
$this->conn = ManagerGM::get($this->request->fd);
|
||||
Console::warning("connection of CQ has invalid QQ or token!");
|
||||
Console::debug("Remote token: ".$remote_token);
|
||||
Console::debug("Remote token: " . $remote_token);
|
||||
}
|
||||
} else {
|
||||
$this->conn = new $type_conn($this->server, $this->request->fd);
|
||||
$this->conn = ManagerGM::get($this->request->fd);
|
||||
}
|
||||
ZMBuf::$connect[$this->request->fd] = $this->conn;
|
||||
set_coroutine_params(["server" => $this->server, "request" => $this->request, "connection" => $this->conn]);
|
||||
foreach (ZMBuf::$events[SwooleEventAt::class] ?? [] as $v) {
|
||||
if (strtolower($v->type) == "open" && $this->parseSwooleRule($v) === true) {
|
||||
@@ -86,11 +84,10 @@ class WSOpenEvent implements SwooleEvent
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function onAfter() {
|
||||
if (!$this->conn->exists()) return $this;
|
||||
if (!$this->server->exists($this->conn->getFd())) return $this;
|
||||
foreach (ZMBuf::$events[SwooleEventAfter::class] ?? [] as $v) {
|
||||
if (strtolower($v->type) == "open" && $this->parseSwooleRule($v) === true) {
|
||||
/** @var ModBase $class */
|
||||
$class = new $v["class"](["server" => $this->server, "request" => $this->request, "connection" => $this->conn], ModHandleType::SWOOLE_OPEN);
|
||||
$class = new $v["class"]();
|
||||
call_user_func_array([$class, $v["method"]], [$this->conn]);
|
||||
if (context()->getCache("block_continue") === true) break;
|
||||
}
|
||||
@@ -106,4 +103,15 @@ class WSOpenEvent implements SwooleEvent
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private function getTypeClassName(string $type) {
|
||||
$map = [
|
||||
"qq" => "qq",
|
||||
"universal" => "qq",
|
||||
"webconsole" => "webconsole",
|
||||
"proxy" => "proxy",
|
||||
"terminal" => "terminal"
|
||||
];
|
||||
return $map[$type] ?? "default";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,7 +4,6 @@
|
||||
namespace ZM\Event\Swoole;
|
||||
|
||||
|
||||
use Co;
|
||||
use Doctrine\Common\Annotations\AnnotationException;
|
||||
use Exception;
|
||||
use PDO;
|
||||
@@ -14,20 +13,18 @@ use Swoole\Database\PDOConfig;
|
||||
use Swoole\Database\PDOPool;
|
||||
use Swoole\Process;
|
||||
use Swoole\Timer;
|
||||
use ZM\Annotation\AnnotationBase;
|
||||
use ZM\Annotation\AnnotationParser;
|
||||
use ZM\Annotation\Swoole\OnStart;
|
||||
use ZM\Annotation\Swoole\SwooleEventAfter;
|
||||
use ZM\Connection\ConnectionManager;
|
||||
use ZM\Config\ZMConfig;
|
||||
use ZM\Context\ContextInterface;
|
||||
use ZM\DB\DB;
|
||||
use Framework\Console;
|
||||
use Framework\GlobalConfig;
|
||||
use Framework\ZMBuf;
|
||||
use ZM\Console\Console;
|
||||
use Swoole\Server;
|
||||
use ZM\Event\EventHandler;
|
||||
use ZM\Exception\DbException;
|
||||
use Framework\DataProvider;
|
||||
use ZM\Store\ZMBuf;
|
||||
use ZM\Utils\DataProvider;
|
||||
use ZM\Utils\Terminal;
|
||||
use ZM\Utils\ZMUtil;
|
||||
|
||||
class WorkerStartEvent implements SwooleEvent
|
||||
@@ -50,50 +47,46 @@ class WorkerStartEvent implements SwooleEvent
|
||||
* @throws DbException
|
||||
*/
|
||||
public function onActivate(): WorkerStartEvent {
|
||||
Console::info("Worker启动中");
|
||||
ZMBuf::$server = $this->server;
|
||||
Console::listenConsole(); //这个方法只能在这里调用,且如果worker_num不为1的话,此功能不可用
|
||||
|
||||
Process::signal(SIGINT, function () {
|
||||
Console::warning("Server interrupted by keyboard.");
|
||||
ZMUtil::stop(true);
|
||||
});
|
||||
Console::info("Worker #{$this->server->worker_id} 启动中");
|
||||
ZMBuf::$server = $this->server;
|
||||
ZMBuf::resetCache(); //清空变量缓存
|
||||
ZMBuf::set("wait_start", []); //添加队列,在workerStart运行完成前先让其他协程等待执行
|
||||
$this->resetConnections();//释放所有与framework的连接
|
||||
|
||||
//设置炸毛buf中储存的对象
|
||||
ZMBuf::$globals = new GlobalConfig();
|
||||
ZMBuf::$config = [];
|
||||
$file = scandir(DataProvider::getWorkingDir() . '/config/');
|
||||
unset($file[0], $file[1]);
|
||||
foreach ($file as $k => $v) {
|
||||
if ($v == "global.php") continue;
|
||||
$name = explode(".", $v);
|
||||
if (($prefix = end($name)) == "json") {
|
||||
ZMBuf::$config[$name[0]] = json_decode(Co::readFile(DataProvider::getWorkingDir() . '/config/' . $v), true);
|
||||
Console::info("已读取配置文件:" . $v);
|
||||
} elseif ($prefix == "php") {
|
||||
ZMBuf::$config[$name[0]] = include_once DataProvider::getWorkingDir() . '/config/' . $v;
|
||||
if (is_array(ZMBuf::$config[$name[0]]))
|
||||
Console::info("已读取配置文件:" . $v);
|
||||
}
|
||||
global $terminal_id;
|
||||
|
||||
Terminal::listenConsole($terminal_id); //这个方法只能在这里调用,且如果worker_num不为1的话,此功能不可用
|
||||
// 这里执行的是只需要执行一遍的代码,比如终端监听器和键盘监听器
|
||||
if ($this->server->worker_id === 0) {
|
||||
if($terminal_id !== null) Console::info("监听console输入");
|
||||
Process::signal(SIGINT, function () {
|
||||
echo PHP_EOL;
|
||||
Console::warning("Server interrupted by keyboard.");
|
||||
ZMUtil::stop();
|
||||
});
|
||||
ZMBuf::$atomics['reload_time']->add(1);
|
||||
$this->setAutosaveTimer(ZMConfig::get("global", "auto_save_interval"));
|
||||
} else {
|
||||
Process::signal(SIGINT, function () {
|
||||
// Do Nothing
|
||||
});
|
||||
}
|
||||
if (ZMBuf::globals("sql_config")["sql_host"] != "") {
|
||||
if (ZMConfig::get("global", "sql_config")["sql_host"] != "") {
|
||||
Console::info("新建SQL连接池中");
|
||||
ob_start();
|
||||
phpinfo();
|
||||
$str = ob_get_clean();
|
||||
$str = explode("\n", $str);
|
||||
foreach($str as $k => $v) {
|
||||
foreach ($str as $k => $v) {
|
||||
$v = trim($v);
|
||||
if($v == "") continue;
|
||||
if(mb_strpos($v, "API Extensions") === false) continue;
|
||||
if(mb_strpos($v, "pdo_mysql") === false) {
|
||||
if ($v == "") continue;
|
||||
if (mb_strpos($v, "API Extensions") === false) continue;
|
||||
if (mb_strpos($v, "pdo_mysql") === false) {
|
||||
throw new DbException("未安装 mysqlnd php-mysql扩展。");
|
||||
}
|
||||
}
|
||||
$sql = ZMBuf::globals("sql_config");
|
||||
$sql = ZMConfig::get("global", "sql_config");
|
||||
ZMBuf::$sql_pool = new PDOPool((new PDOConfig())
|
||||
->withHost($sql["sql_host"])
|
||||
->withPort($sql["sql_port"])
|
||||
@@ -107,11 +100,6 @@ class WorkerStartEvent implements SwooleEvent
|
||||
DB::initTableList();
|
||||
}
|
||||
|
||||
ZMBuf::$atomics['reload_time']->add(1);
|
||||
|
||||
Console::info("监听console输入");
|
||||
|
||||
$this->setAutosaveTimer(ZMBuf::globals("auto_save_interval"));
|
||||
$this->loadAllClass(); //加载composer资源、phar外置包、注解解析注册等
|
||||
return $this;
|
||||
}
|
||||
@@ -126,22 +114,14 @@ class WorkerStartEvent implements SwooleEvent
|
||||
}
|
||||
ZMBuf::unsetCache("wait_start");
|
||||
set_coroutine_params(["server" => $this->server, "worker_id" => $this->worker_id]);
|
||||
|
||||
foreach (ZMBuf::$events[OnStart::class] ?? [] as $v) {
|
||||
$class_name = $v->class;
|
||||
Console::debug("正在调用启动时函数: " . $class_name . " -> " . $v->method);
|
||||
EventHandler::callWithMiddleware($class_name, $v->method, ["server" => $this->server, "worker_id" => $this->worker_id], []);
|
||||
}
|
||||
foreach (ZMBuf::$events[SwooleEventAfter::class] ?? [] as $v) {
|
||||
/** @var AnnotationBase $v */
|
||||
if (strtolower($v->type) == "workerstart") {
|
||||
if($this->server->worker_id === 0) {
|
||||
foreach (ZMBuf::$events[OnStart::class] ?? [] as $v) {
|
||||
$class_name = $v->class;
|
||||
Console::debug("正在调用启动时函数after: " . $class_name . " -> " . $v->method);
|
||||
Console::debug("正在调用启动时函数: " . $class_name . " -> " . $v->method);
|
||||
EventHandler::callWithMiddleware($class_name, $v->method, ["server" => $this->server, "worker_id" => $this->worker_id], []);
|
||||
if (context()->getCache("block_continue") === true) break;
|
||||
}
|
||||
Console::debug("@OnStart 执行完毕");
|
||||
}
|
||||
Console::debug("调用完毕!");
|
||||
return $this;
|
||||
}
|
||||
|
||||
@@ -156,7 +136,6 @@ class WorkerStartEvent implements SwooleEvent
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws AnnotationException
|
||||
* @throws ReflectionException
|
||||
* @throws Exception
|
||||
*/
|
||||
@@ -181,15 +160,13 @@ class WorkerStartEvent implements SwooleEvent
|
||||
|
||||
//加载各个模块的注解类,以及反射
|
||||
Console::info("检索Module中");
|
||||
AnnotationParser::registerMods();
|
||||
|
||||
//加载Custom目录下的自定义的内部类
|
||||
ConnectionManager::registerCustomClass();
|
||||
$parser = new AnnotationParser();
|
||||
$parser->addRegisterPath(DataProvider::getWorkingDir() . "/src/Module/", "Module");
|
||||
$parser->registerMods();
|
||||
$parser->sortLevels();
|
||||
|
||||
//加载自定义的全局函数
|
||||
Console::debug("加载自定义的全局函数中");
|
||||
if (file_exists(DataProvider::getWorkingDir() . "/src/Custom/global_function.php"))
|
||||
require_once DataProvider::getWorkingDir() . "/src/Custom/global_function.php";
|
||||
$this->afterCheck();
|
||||
}
|
||||
|
||||
@@ -204,7 +181,7 @@ class WorkerStartEvent implements SwooleEvent
|
||||
* @throws Exception
|
||||
*/
|
||||
private function afterCheck() {
|
||||
$context_class = ZMBuf::globals("context_class");
|
||||
$context_class = ZMConfig::get("global", "context_class");
|
||||
if (!is_a($context_class, ContextInterface::class, true)) {
|
||||
throw new Exception("Context class must implemented from ContextInterface!");
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user