| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247 |
- <?php
- namespace App\Module\AppGame\HttpControllers;
- use App\Http\Controllers\Controller;
- use App\Module\AppGame\Tools\Protobuf;
- use Illuminate\Http\Request as HttpRequest;
- use Illuminate\Support\Facades\Log;
- use Illuminate\Support\Str;
- use UCore\App;
- use UCore\Exception\HandleNotException;
- use UCore\Exception\ValidateException;
- use UCore\Helper\Logger;
- use Uraus\Kku\Common\RESPONSE_CODE;
- use Uraus\Kku\Request;
- use Uraus\Kku\Response;
- /**
- * Protobuf 控制器
- *
- * 负责处理来自客户端的 Protobuf 请求,并将其路由到相应的处理器
- */
- class ProtobufController extends Controller
- {
- /**
- * 处理 Protobuf 请求
- * @param HttpRequest $httpRequest HTTP请求对象
- * @return \Illuminate\Http\Response
- */
- public function gameapi(HttpRequest $httpRequest)
- {
- // 获取请求参数
- Log::info('请求信息', [
- 'method' => $httpRequest->method(),
- 'path' => $httpRequest->path(),
- 'content_type' => $httpRequest->header('Content-Type'),
- 'request_unid' => RUN_UNIQID,
- 'header'=>[
- 'token'=>$httpRequest->header('token')
- ]
- ]);
- // 初始化请求日志记录器
- $requestLogger = new \App\Module\System\Services\RequestLogger($httpRequest);
- Log::info('开始处理 Protobuf 请求', [
- 'method' => $httpRequest->method(),
- 'path' => $httpRequest->path(),
- 'content_type' => $httpRequest->header('Content-Type'),
- 'request_unid' => RUN_UNIQID
- ]);
- // 创建响应对象
- $response = new Response();
- $response->setRunUnid(RUN_UNIQID);
- $startTime = microtime(true);
- $contentType = $httpRequest->header('Content-Type');
- $callpath = '';
- try {
- // 获取原始请求数据
- $rawData = $httpRequest->getContent();
- if (empty($rawData)) {
- throw new \Exception('Empty request data');
- }
- // 解析请求数据
- $request = new Request();
- if (stripos($contentType, 'json') !== false) {
- // JSON 格式请求
- $jsonData = json_decode($rawData, true);
- if (json_last_error() !== JSON_ERROR_NONE) {
- throw new \Exception('Invalid JSON data: ' . json_last_error_msg());
- }
- $request->mergeFromJsonString(json_encode($jsonData));
- } else {
- // Protobuf 格式请求
- Logger::debug('base64: '.base64_encode($rawData));
- $request->mergeFromString($rawData);
- }
- \Illuminate\Support\Facades\Log::debug('Proto请求信息-json', json_decode($request->serializeToJsonString(),true));
- $requestLogger->setProtobuf($request);
- // 获取路由配置
- $config = config('proto_route');
- if (empty($config['routes'])) {
- throw new \Exception('Proto route configuration not found');
- }
- Logger::debug('router-proto',$config['routes']);
- // 查找匹配的请求
- $result = $this->findValidRequest($request, $config['routes']);
- if (!$result) {
- throw new \Exception('No valid request found');
- }
- // 处理请求
- ['field' => $field, 'method' => $method, 'data' => $data] = $result;
- $moduleName = ucfirst($field);
- $methodName = Str::studly($method);
- // 构造处理器类名和响应类名
- $handlerClass = "App\\Module\\AppGame\\Handler\\{$moduleName}\\{$methodName}Handler";
- $responseMethodClass = "Uraus\\Kku\\Response\\Response{$moduleName}{$methodName}";
- $callpath = $moduleName.'-'.$methodName;
- // 检查类是否存在
- if (!class_exists($handlerClass)) {
- throw new HandleNotException("Handler not found: {$handlerClass}");
- }
- if (!class_exists($responseMethodClass)) {
- throw new HandleNotException("Response class not found: {$responseMethodClass}");
- }
- Log::info('处理请求', [
- 'module' => $moduleName,
- 'method' => $methodName,
- 'handler' => $handlerClass
- ]);
- // 执行处理器
- $handler = new $handlerClass($response);
- // 将handler存入request以供中间件使用
- $httpRequest->attributes->set('_handler', $handler);
- // 执行登录检查中间件
- $middleware = new \App\Module\AppGame\Middleware\LoginCheck();
- $middlewareResponse = $middleware->handle($httpRequest, function ($request) use ($handler, $data,$requestLogger) {
- $requestLogger->setUserId($handler->user_id);
- return $handler->handle($data);
- });
- // 如果中间件返回了响应,说明验证未通过
- if ($middlewareResponse instanceof \Illuminate\Http\Response ||
- $middlewareResponse instanceof \Illuminate\Http\JsonResponse) {
- return $middlewareResponse;
- }
- $methodResponse = $middlewareResponse;
- // 验证返回值类型
- if (!($methodResponse instanceof $responseMethodClass)) {
- throw new \Exception(sprintf(
- 'Handler must return instance of %s, %s given',
- $responseMethodClass,
- is_object($methodResponse) ? get_class($methodResponse) : gettype($methodResponse)
- ));
- }
- // 设置主响应
- $setter = 'set' . ucfirst($field).ucfirst($method);
- $response->$setter($methodResponse);
- // 如果响应码未设置,则设置为 OK
- if ($response->getCode() === 0) {
- $response->setCode(RESPONSE_CODE::OK);
- }
- } catch (HandleNotException $e) {
- $errorMsg = $e->getMessage();
- Log::error('请求处理发生异常-未找到', [
- 'error' => $errorMsg,
- 'trace' => $e->getTraceAsString(),
- 'request_unid' => RUN_UNIQID
- ]);
- // 记录错误信息
- $requestLogger->setError($errorMsg);
- $response->setCode(RESPONSE_CODE::HANDLE_NOT);
- } catch (ValidateException $e) {
- $errorMsg = $e->validation->firstError() ?? $e->getMessage();
- \UCore\Helper\Logger::exception('请求处理发生验证错误', $e, [
- 'request_unid' => RUN_UNIQID
- ]);
- // 记录错误信息
- $requestLogger->setError($errorMsg);
- $response->setCode(RESPONSE_CODE::VALIDATE_ERROR);
- $response->setMsg($errorMsg);
- } catch (\Exception $e) {
- if(App::is_local()){
- dump("本地环境,直接输出异常信息");
- throw $e;
- }
- $errorMsg = $e->getMessage();
- \UCore\Helper\Logger::exception('请求处理发生异常', $e, [
- 'request_unid' => RUN_UNIQID
- ]);
- // 记录错误信息
- $requestLogger->setError($errorMsg);
- $response->setCode(RESPONSE_CODE::SERVER_ERROR);
- }
- // 设置运行时间
- $endTime = microtime(true);
- $runMs = intval(($endTime - $startTime) * 1000);
- $response->setRunMs($runMs);
- if($callpath){
- $response->setCallpath($callpath);
- }
- // 更新请求日志记录响应信息
- $requestLogger->setResponse($response);
- $requestLogger->setRunTime($startTime);
- return Protobuf::response($response);
- }
- /**
- * 查找有效的请求
- * @param Request $request Protobuf 请求对象
- * @param array $routes 路由配置
- * @return array|null 返回模块名、方法名和数据,如果没有找到则返回 null
- */
- protected function findValidRequest(Request $request, array $routes): ?array
- {
- foreach ($routes as $field => $methods) {
- $hasMethod = 'has' . ucfirst($field);
- $getMethod = 'get' . ucfirst($field);
- foreach ($methods as $action) {
- $actionName = Str::studly($action);
- $hasActionFunc = 'has' .ucfirst($field). $actionName;
- $getActionFunc = 'get' . ucfirst($field).$actionName;
- $request->hasHouseUp();
- // Logger::debug('<UNK>', [$hasMethod, $getMethod, $hasActionFunc]);
- if ( $request->$hasActionFunc()) {
- return [
- 'field' => $field,
- 'method' => $actionName,
- 'data' => $request->$getActionFunc()
- ];
- }
- }
- }
- return null;
- }
- }
|