ProtobufController.php 9.1 KB

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