ProtobufController.php 10 KB

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