ProtobufController.php 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. <?php
  2. namespace App\Module\AppGame\HttpControllers;
  3. use App\Http\Controllers\Controller;
  4. use App\Module\AppGame\Tools\Protobuf;
  5. use Illuminate\Http\Request as HttpRequest;
  6. use Illuminate\Support\Facades\Log;
  7. use Illuminate\Support\Str;
  8. use UCore\App;
  9. use UCore\Exception\HandleNotException;
  10. use UCore\Exception\ValidateException;
  11. use UCore\Helper\Logger;
  12. use Uraus\Kku\Common\RESPONSE_CODE;
  13. use Uraus\Kku\Request;
  14. use Uraus\Kku\Response;
  15. /**
  16. * Protobuf 控制器
  17. *
  18. * 负责处理来自客户端的 Protobuf 请求,并将其路由到相应的处理器
  19. */
  20. class ProtobufController extends Controller
  21. {
  22. /**
  23. * 处理 Protobuf 请求
  24. * @param HttpRequest $httpRequest HTTP请求对象
  25. * @return \Illuminate\Http\Response
  26. */
  27. public function gameapi(HttpRequest $httpRequest)
  28. {
  29. // 获取请求参数
  30. Log::info('请求信息', [
  31. 'method' => $httpRequest->method(),
  32. 'path' => $httpRequest->path(),
  33. 'content_type' => $httpRequest->header('Content-Type'),
  34. 'request_unid' => RUN_UNIQID,
  35. 'header'=>[
  36. 'token'=>$httpRequest->header('token')
  37. ]
  38. ]);
  39. // 初始化请求日志记录器
  40. $requestLogger = new \App\Module\System\Services\RequestLogger($httpRequest);
  41. Log::info('开始处理 Protobuf 请求', [
  42. 'method' => $httpRequest->method(),
  43. 'path' => $httpRequest->path(),
  44. 'content_type' => $httpRequest->header('Content-Type'),
  45. 'request_unid' => RUN_UNIQID
  46. ]);
  47. // 创建响应对象
  48. $response = new Response();
  49. $response->setRunUnid(RUN_UNIQID);
  50. $startTime = microtime(true);
  51. $contentType = $httpRequest->header('Content-Type');
  52. $callpath = '';
  53. try {
  54. // 获取原始请求数据
  55. $rawData = $httpRequest->getContent();
  56. if (empty($rawData)) {
  57. throw new \Exception('Empty request data');
  58. }
  59. // 解析请求数据
  60. $request = new Request();
  61. if (stripos($contentType, 'json') !== false) {
  62. // JSON 格式请求
  63. $jsonData = json_decode($rawData, true);
  64. if (json_last_error() !== JSON_ERROR_NONE) {
  65. throw new \Exception('Invalid JSON data: ' . json_last_error_msg());
  66. }
  67. $request->mergeFromJsonString(json_encode($jsonData));
  68. } else {
  69. // Protobuf 格式请求
  70. Logger::debug('base64: '.base64_encode($rawData));
  71. $request->mergeFromString($rawData);
  72. }
  73. \Illuminate\Support\Facades\Log::debug('Proto请求信息-json', json_decode($request->serializeToJsonString(),true));
  74. $requestLogger->setProtobuf($request);
  75. // 获取路由配置
  76. $config = config('proto_route');
  77. if (empty($config['routes'])) {
  78. throw new \Exception('Proto route configuration not found');
  79. }
  80. Logger::debug('router-proto',$config['routes']);
  81. // 查找匹配的请求
  82. $result = $this->findValidRequest($request, $config['routes']);
  83. if (!$result) {
  84. throw new \Exception('No valid request found');
  85. }
  86. // 处理请求
  87. ['field' => $field, 'method' => $method, 'data' => $data] = $result;
  88. $moduleName = ucfirst($field);
  89. $methodName = Str::studly($method);
  90. // 构造处理器类名和响应类名
  91. $handlerClass = "App\\Module\\AppGame\\Handler\\{$moduleName}\\{$methodName}Handler";
  92. $responseMethodClass = "Uraus\\Kku\\Response\\Response{$moduleName}{$methodName}";
  93. $callpath = $moduleName.'-'.$methodName;
  94. // 检查类是否存在
  95. if (!class_exists($handlerClass)) {
  96. throw new HandleNotException("Handler not found: {$handlerClass}");
  97. }
  98. if (!class_exists($responseMethodClass)) {
  99. throw new HandleNotException("Response class not found: {$responseMethodClass}");
  100. }
  101. Log::info('处理请求', [
  102. 'module' => $moduleName,
  103. 'method' => $methodName,
  104. 'handler' => $handlerClass
  105. ]);
  106. // 执行处理器
  107. $handler = new $handlerClass($response);
  108. // 将handler存入request以供中间件使用
  109. $httpRequest->attributes->set('_handler', $handler);
  110. // 执行登录检查中间件
  111. $middleware = new \App\Module\AppGame\Middleware\LoginCheck();
  112. $middlewareResponse = $middleware->handle($httpRequest, function ($request) use ($handler, $data,$requestLogger) {
  113. $requestLogger->setUserId($handler->user_id);
  114. return $handler->handle($data);
  115. });
  116. // 如果中间件返回了响应,说明验证未通过
  117. if ($middlewareResponse instanceof \Illuminate\Http\Response ||
  118. $middlewareResponse instanceof \Illuminate\Http\JsonResponse) {
  119. return $middlewareResponse;
  120. }
  121. $methodResponse = $middlewareResponse;
  122. // 验证返回值类型
  123. if (!($methodResponse instanceof $responseMethodClass)) {
  124. throw new \Exception(sprintf(
  125. 'Handler must return instance of %s, %s given',
  126. $responseMethodClass,
  127. is_object($methodResponse) ? get_class($methodResponse) : gettype($methodResponse)
  128. ));
  129. }
  130. // 设置主响应
  131. $setter = 'set' . ucfirst($field).ucfirst($method);
  132. $response->$setter($methodResponse);
  133. // 如果响应码未设置,则设置为 OK
  134. if ($response->getCode() === 0) {
  135. $response->setCode(RESPONSE_CODE::OK);
  136. }
  137. } catch (HandleNotException $e) {
  138. $errorMsg = $e->getMessage();
  139. Log::error('请求处理发生异常-未找到', [
  140. 'error' => $errorMsg,
  141. 'trace' => $e->getTraceAsString(),
  142. 'request_unid' => RUN_UNIQID
  143. ]);
  144. // 记录错误信息
  145. $requestLogger->setError($errorMsg);
  146. $response->setCode(RESPONSE_CODE::HANDLE_NOT);
  147. } catch (ValidateException $e) {
  148. $errorMsg = $e->validation->firstError() ?? $e->getMessage();
  149. \UCore\Helper\Logger::exception('请求处理发生验证错误', $e, [
  150. 'request_unid' => RUN_UNIQID
  151. ]);
  152. // 记录错误信息
  153. $requestLogger->setError($errorMsg);
  154. $response->setCode(RESPONSE_CODE::VALIDATE_ERROR);
  155. $response->setMsg($errorMsg);
  156. } catch (\Exception $e) {
  157. if(App::is_local()){
  158. dump("本地环境,直接输出异常信息");
  159. throw $e;
  160. }
  161. $errorMsg = $e->getMessage();
  162. \UCore\Helper\Logger::exception('请求处理发生异常', $e, [
  163. 'request_unid' => RUN_UNIQID
  164. ]);
  165. // 记录错误信息
  166. $requestLogger->setError($errorMsg);
  167. $response->setCode(RESPONSE_CODE::SERVER_ERROR);
  168. }
  169. // 设置运行时间
  170. $endTime = microtime(true);
  171. $runMs = intval(($endTime - $startTime) * 1000);
  172. $response->setRunMs($runMs);
  173. if($callpath){
  174. $response->setCallpath($callpath);
  175. }
  176. // 更新请求日志记录响应信息
  177. $requestLogger->setResponse($response);
  178. $requestLogger->setRunTime($startTime);
  179. return Protobuf::response($response);
  180. }
  181. /**
  182. * 查找有效的请求
  183. * @param Request $request Protobuf 请求对象
  184. * @param array $routes 路由配置
  185. * @return array|null 返回模块名、方法名和数据,如果没有找到则返回 null
  186. */
  187. protected function findValidRequest(Request $request, array $routes): ?array
  188. {
  189. foreach ($routes as $field => $methods) {
  190. $hasMethod = 'has' . ucfirst($field);
  191. $getMethod = 'get' . ucfirst($field);
  192. foreach ($methods as $action) {
  193. $actionName = Str::studly($action);
  194. $hasActionFunc = 'has' .ucfirst($field). $actionName;
  195. $getActionFunc = 'get' . ucfirst($field).$actionName;
  196. $request->hasHouseUp();
  197. // Logger::debug('<UNK>', [$hasMethod, $getMethod, $hasActionFunc]);
  198. if ( $request->$hasActionFunc()) {
  199. return [
  200. 'field' => $field,
  201. 'method' => $actionName,
  202. 'data' => $request->$getActionFunc()
  203. ];
  204. }
  205. }
  206. }
  207. return null;
  208. }
  209. }