| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705 |
- <?php
- namespace App\Console\Commands;
- use App\Module\AppGame\SessionApp;
- use App\Module\AppGame\SessionHelper;
- use GuzzleHttp\Client;
- use Illuminate\Console\Command;
- use UCore\Model\RequestLog;
- use Illuminate\Support\Facades\Log;
- use UCore\Helper\Logger;
- /**
- * 错误复现命令
- *
- * 通过 sys_request_logs 表的记录来复现请求,用于调试和错误排查
- * 默认使用 post 字段的原始请求数据,根据 headers 中的 Content-Type 自动检测数据类型
- * 根据响应的 Content-Type 头智能显示响应内容(JSON、HTML、Protobuf、文本等)
- *
- * 使用示例:
- * php artisan debug:reproduce-error 68981433 # 使用ID查找,自动选择数据源
- * php artisan debug:reproduce-error request_1749626545371 # 使用request_unid查找
- * php artisan debug:reproduce-error 68973982 --type=request_unid # 明确指定查找类型
- * php artisan debug:reproduce-error 68973982 --no-clear-logs # 不清空日志文件
- * php artisan debug:reproduce-error 68973982 --data-source=post # 强制使用post数据
- * php artisan debug:reproduce-error 68973982 --data-source=protobuf_json # 强制使用protobuf_json数据
- *
- */
- class ReproduceErrorCommand extends Command
- {
- /**
- * 命令签名
- *
- * @var string
- */
- protected $signature = 'debug:reproduce-error {identifier : 请求标识符(可以是id、request_unid或run_unid)} {--type=auto : 标识符类型(id|request_unid|run_unid|auto),auto为自动检测} {--timeout=30 : 请求超时时间(秒)} {--no-clear-logs : 运行时不前清空当前日志文件} {--data-source=auto : 数据源(post|protobuf_json|auto),auto为自动选择,优先使用post}';
- /**
- * 命令描述
- *
- * @var string
- */
- protected $description = '通过请求日志记录复现错误请求,用于调试和问题排查。支持运行前清空日志文件,默认使用post字段数据并根据headers自动检测数据类型,根据响应Content-Type智能显示内容';
- /**
- * HTTP 客户端
- *
- * @var Client
- */
- protected Client $client;
- /**
- * 基础URL
- *
- * @var string
- */
- protected string $baseUrl;
- /**
- * 执行命令
- */
- public function handle()
- {
- $identifier = $this->argument('identifier');
- $type = $this->option('type');
- $timeout = (int)$this->option('timeout');
- $noclearLogs = $this->option('no-clear-logs');
- $dataSource = $this->option('data-source');
- // 如果开启了清空日志选项,则清空日志文件
- if ($noclearLogs) {
- } else {
- $this->clearLogFiles();
- }
- Log::info("正在使用 debug:reproduce-error 命令重放请求,当前执行命令: 'php artisan debug:reproduce-error {$identifier}' ");
- $this->info("开始查找请求记录...");
- $this->info("标识符: {$identifier}");
- $this->info("类型: {$type}");
- $this->info("数据源: {$dataSource}");
- // 查找请求记录
- $requestLog = $this->findRequestLog($identifier, $type);
- if (!$requestLog) {
- $this->error("未找到匹配的请求记录");
- return 1;
- }
- $this->info("找到请求记录:");
- $this->line(" ID: {$requestLog->id}");
- $this->line(" Request UNID: {$requestLog->request_unid}");
- $this->line(" Run UNID: {$requestLog->run_unid}");
- $this->line(" UserId : {$requestLog->user_id}");
- $this->line(" 路径: {$requestLog->path}");
- $this->line(" 方法: {$requestLog->method}");
- $this->line(" 创建时间: {$requestLog->created_at}");
- // 解析 headers 获取 Content-Type 和 token
- $headers = $this->parseHeaders($requestLog->headers);
- $contentType = $this->extractContentType($headers);
- $token = $this->extractToken($requestLog->headers);
- $this->info("Content-Type: " . ($contentType ?: '未检测到'));
- if (!$token) {
- $this->warn("未找到 token,将不携带 token 发起请求");
- } else {
- $this->info("提取到 token: " . substr($token, 0, 10) . "...");
- }
- // 设置用户会话
- if ($requestLog->user_id) {
- SessionHelper::sessionLogin($token, $requestLog->user_id);
- $this->info("token 设置用户: {$requestLog->user_id} ");
- }
- // 准备请求数据
- $requestData = $this->prepareRequestData($requestLog, $dataSource, $contentType);
- if ($requestData === null) {
- return 1;
- }
- $this->info("使用数据源: {$requestData['source']}");
- $this->info("检测到数据类型: {$requestData['type']}");
- $this->info("请求数据预览:");
- if ($requestData['type'] === 'json') {
- dump(json_decode($requestData['data'], true));
- } else {
- $this->line(" 二进制数据长度: " . strlen($requestData['data']) . " 字节");
- $this->line(" Base64预览: " . substr(base64_encode($requestData['data']), 0, 100) . "...");
- }
- // 初始化 HTTP 客户端
- $this->initializeHttpClient($timeout);
- // 发起请求
- $this->info("开始发起请求...");
- $response = $this->makeRequest($requestData['data'], $token, $requestData['type']);
- if ($response === null) {
- return 1;
- }
- // 输出结果
- $this->line("响应内容:");
- $this->displayResponse($response);
- return 0;
- }
- /**
- * 查找请求记录
- *
- * @param string $identifier 标识符
- * @param string $type 类型
- * @return RequestLog|null
- */
- protected function findRequestLog(string $identifier, string $type): ?RequestLog
- {
- $query = RequestLog::query();
- if ($type === 'auto') {
- // 自动检测类型
- if (is_numeric($identifier)) {
- // 纯数字,优先按 ID 查找
- $requestLog = $query->where('id', $identifier)->first();
- if ($requestLog) {
- return $requestLog;
- }
- }
- // 按 request_unid 查找
- $requestLog = RequestLog::query()->where('request_unid', $identifier)->first();
- if ($requestLog) {
- return $requestLog;
- }
- // 按 run_unid 查找
- $requestLog = RequestLog::query()->where('run_unid', $identifier)->first();
- if ($requestLog) {
- return $requestLog;
- }
- return null;
- }
- // 指定类型查找
- switch ($type) {
- case 'id':
- return $query->where('id', $identifier)->first();
- case 'request_unid':
- return $query->where('request_unid', $identifier)->first();
- case 'run_unid':
- return $query->where('run_unid', $identifier)->first();
- default:
- $this->error("不支持的类型: {$type}");
- return null;
- }
- }
- /**
- * 解析 headers JSON 字符串
- *
- * @param string|null $headersJson
- * @return array
- */
- protected function parseHeaders(?string $headersJson): array
- {
- if (empty($headersJson)) {
- return [];
- }
- try {
- $headers = json_decode($headersJson, true);
- return is_array($headers) ? $headers : [];
- } catch (\Exception $e) {
- $this->warn("解析 headers 失败: " . $e->getMessage());
- return [];
- }
- }
- /**
- * 从 headers 中提取 Content-Type
- *
- * @param array $headers
- * @return string|null
- */
- protected function extractContentType(array $headers): ?string
- {
- $contentTypeKeys = ['content-type', 'Content-Type', 'CONTENT-TYPE'];
- foreach ($contentTypeKeys as $key) {
- if (isset($headers[$key])) {
- $contentType = $headers[$key];
- // headers 中的值可能是数组
- if (is_array($contentType)) {
- return $contentType[0] ?? null;
- }
- return $contentType;
- }
- }
- return null;
- }
- /**
- * 从 headers JSON 中提取 token
- *
- * @param string|null $headersJson
- * @return string|null
- */
- protected function extractToken(?string $headersJson): ?string
- {
- $headers = $this->parseHeaders($headersJson);
- // 查找 token 字段(可能在不同的键名下)
- $tokenKeys = [ 'token', 'Token', 'authorization', 'Authorization' ];
- foreach ($tokenKeys as $key) {
- if (isset($headers[$key])) {
- $tokenValue = $headers[$key];
- // headers 中的值可能是数组
- if (is_array($tokenValue)) {
- return $tokenValue[0] ?? null;
- }
- return $tokenValue;
- }
- }
- return null;
- }
- /**
- * 准备请求数据
- *
- * @param RequestLog $requestLog
- * @param string $dataSource
- * @param string|null $contentType
- * @return array|null
- */
- protected function prepareRequestData(RequestLog $requestLog, string $dataSource, ?string $contentType): ?array
- {
- // 根据数据源选择策略
- if ($dataSource === 'auto') {
- // 自动选择:优先使用 post 数据,如果没有则使用 protobuf_json
- if (!empty($requestLog->post)) {
- return $this->preparePostData($requestLog->post, $contentType);
- } elseif (!empty($requestLog->protobuf_json)) {
- return $this->prepareProtobufJsonData($requestLog->protobuf_json);
- } else {
- $this->error("请求记录中既没有 post 数据也没有 protobuf_json 数据");
- return null;
- }
- } elseif ($dataSource === 'post') {
- if (empty($requestLog->post)) {
- $this->error("请求记录中缺少 post 数据");
- return null;
- }
- return $this->preparePostData($requestLog->post, $contentType);
- } elseif ($dataSource === 'protobuf_json') {
- if (empty($requestLog->protobuf_json)) {
- $this->error("请求记录中缺少 protobuf_json 数据");
- return null;
- }
- return $this->prepareProtobufJsonData($requestLog->protobuf_json);
- } else {
- $this->error("不支持的数据源: {$dataSource}");
- return null;
- }
- }
- /**
- * 准备 post 数据
- *
- * @param string $postData base64 编码的原始请求数据
- * @param string|null $contentType
- * @return array
- */
- protected function preparePostData(string $postData, ?string $contentType): array
- {
- // 解码 base64 数据
- $rawData = base64_decode($postData);
- // 根据 Content-Type 判断数据类型
- if ($contentType && stripos($contentType, 'json') !== false) {
- // JSON 格式数据
- return [
- 'source' => 'post',
- 'type' => 'json',
- 'data' => $rawData
- ];
- } else {
- // 默认为 protobuf 二进制格式
- return [
- 'source' => 'post',
- 'type' => 'protobuf',
- 'data' => $rawData
- ];
- }
- }
- /**
- * 准备 protobuf_json 数据
- *
- * @param string $protobufJson
- * @return array
- */
- protected function prepareProtobufJsonData(string $protobufJson): array
- {
- return [
- 'source' => 'protobuf_json',
- 'type' => 'json',
- 'data' => $protobufJson
- ];
- }
- /**
- * 初始化 HTTP 客户端
- *
- * @param int $timeout
- */
- protected function initializeHttpClient(int $timeout): void
- {
- $this->baseUrl = env('UNITTEST_URL', 'http://localhost:8000');
- $this->info("目标地址: {$this->baseUrl}");
- $this->client = new Client([
- 'base_uri' => $this->baseUrl,
- 'timeout' => $timeout,
- 'http_errors' => false,
- 'verify' => false, // 禁用 SSL 验证
- ]);
- }
- /**
- * 发起请求
- *
- * @param string $requestData 请求数据
- * @param string|null $token 认证token
- * @param string $dataType 数据类型 (json|protobuf)
- * @return array|null
- */
- protected function makeRequest(string $requestData, ?string $token, string $dataType): ?array
- {
- try {
- // 根据数据类型设置不同的 headers
- if ($dataType === 'json') {
- $headers = [
- 'Content-Type' => 'application/json',
- 'Accept' => 'application/json'
- ];
- } else {
- // protobuf 二进制格式
- $headers = [
- 'Content-Type' => 'application/x-protobuf',
- 'Accept' => 'application/x-protobuf',
- 'Force-Json'=>'1'
- ];
- }
- if ($token) {
- $headers['token'] = $token;
- }
- Log::info('复现请求开始', [
- 'url' => $this->baseUrl . '/gameapi',
- 'headers' => $headers,
- 'body_length' => strlen($requestData),
- 'data_type' => $dataType
- ]);
- $response = $this->client->post('/gameapi', [
- 'body' => $requestData,
- 'headers' => $headers
- ]);
- $statusCode = $response->getStatusCode();
- $responseHeaders = $response->getHeaders();
- $responseBody = $response->getBody()->getContents();
- Log::info('复现请求完成', [
- 'status_code' => $statusCode,
- 'response_length' => strlen($responseBody),
- 'data_type' => $dataType
- ]);
- return [
- 'status_code' => $statusCode,
- 'headers' => $responseHeaders,
- 'body' => $responseBody
- ];
- } catch (\Exception $e) {
- $this->error("请求失败: " . $e->getMessage());
- Log::error('复现请求失败', [
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString(),
- 'data_type' => $dataType
- ]);
- return null;
- }
- }
- /**
- * 显示响应内容
- *
- * @param array $response 响应数据(包含status_code、headers、body)
- */
- protected function displayResponse(array $response): void
- {
- $this->line("状态码: " . $response['status_code']);
- // 显示响应头信息
- $this->line("响应头:");
- foreach ($response['headers'] as $name => $values) {
- $value = is_array($values) ? implode(', ', $values) : $values;
- $this->line(" {$name}: {$value}");
- }
- // 从响应头中提取Content-Type
- $responseContentType = $this->extractResponseContentType($response['headers']);
- $this->line("检测到响应Content-Type: " . ($responseContentType ?: '未知'));
- // 根据响应Content-Type决定显示方式
- $responseBody = $response['body'];
- $bodyLength = strlen($responseBody);
- $this->line("响应体长度: {$bodyLength} 字节");
- if ($this->isJsonContentType($responseContentType)) {
- // JSON 响应
- $this->line("按JSON格式解析响应:");
- $jsonData = json_decode($responseBody, true);
- if ($jsonData !== null) {
- dump($jsonData);
- } else {
- $this->warn("响应Content-Type为JSON但解析失败");
- $this->displayRawContent($responseBody);
- }
- } elseif ($this->isProtobufContentType($responseContentType)) {
- // Protobuf 二进制响应
- $this->line("按Protobuf格式处理响应:");
- $this->line("Base64 编码: " . substr(base64_encode($responseBody), 0, 200) . "...");
- // 尝试解析为 JSON(某些情况下服务器可能返回 JSON)
- $jsonData = json_decode($responseBody, true);
- if ($jsonData !== null) {
- $this->line("响应可解析为 JSON:");
- dump($jsonData);
- } else {
- $this->line("响应为二进制 Protobuf 数据,无法直接显示");
- }
- } elseif ($this->isHtmlContentType($responseContentType)) {
- // HTML 响应
- $this->line("按HTML格式处理响应:");
- $this->displayHtmlContent($responseBody);
- } elseif ($this->isTextContentType($responseContentType)) {
- // 纯文本响应
- $this->line("按文本格式显示响应:");
- $this->line($responseBody);
- } else {
- // 未知类型,尝试智能检测
- $this->line("未知Content-Type,尝试智能检测:");
- $this->smartDisplayContent($responseBody);
- }
- }
- /**
- * 从响应头中提取Content-Type
- *
- * @param array $headers 响应头数组
- * @return string|null
- */
- protected function extractResponseContentType(array $headers): ?string
- {
- // 尝试不同的Content-Type键名(大小写不敏感)
- $contentTypeKeys = ['Content-Type', 'content-type', 'Content-type', 'CONTENT-TYPE'];
- foreach ($contentTypeKeys as $key) {
- if (isset($headers[$key])) {
- $value = $headers[$key];
- // 如果是数组,取第一个值
- if (is_array($value)) {
- $value = $value[0] ?? '';
- }
- // 只取分号前的部分(去掉charset等参数)
- return trim(explode(';', $value)[0]);
- }
- }
- return null;
- }
- /**
- * 判断是否为JSON内容类型
- *
- * @param string|null $contentType
- * @return bool
- */
- protected function isJsonContentType(?string $contentType): bool
- {
- if (!$contentType) {
- return false;
- }
- $jsonTypes = [
- 'application/json',
- 'text/json',
- 'application/ld+json'
- ];
- return in_array(strtolower($contentType), $jsonTypes);
- }
- /**
- * 判断是否为Protobuf内容类型
- *
- * @param string|null $contentType
- * @return bool
- */
- protected function isProtobufContentType(?string $contentType): bool
- {
- if (!$contentType) {
- return false;
- }
- $protobufTypes = [
- 'application/x-protobuf',
- 'application/protobuf',
- 'application/octet-stream'
- ];
- return in_array(strtolower($contentType), $protobufTypes);
- }
- /**
- * 判断是否为HTML内容类型
- *
- * @param string|null $contentType
- * @return bool
- */
- protected function isHtmlContentType(?string $contentType): bool
- {
- if (!$contentType) {
- return false;
- }
- $htmlTypes = [
- 'text/html',
- 'application/xhtml+xml'
- ];
- return in_array(strtolower($contentType), $htmlTypes);
- }
- /**
- * 判断是否为文本内容类型
- *
- * @param string|null $contentType
- * @return bool
- */
- protected function isTextContentType(?string $contentType): bool
- {
- if (!$contentType) {
- return false;
- }
- return str_starts_with(strtolower($contentType), 'text/');
- }
- /**
- * 显示HTML内容
- *
- * @param string $content
- */
- protected function displayHtmlContent(string $content): void
- {
- // 检查是否包含错误页面标识
- if (str_contains($content, '<title>') && str_contains($content, '</title>')) {
- preg_match('/<title>(.*?)<\/title>/i', $content, $matches);
- $title = $matches[1] ?? '未知';
- $this->line("HTML页面标题: {$title}");
- }
- // 显示部分内容
- $preview = substr(strip_tags($content), 0, 500);
- $this->line("HTML内容预览: " . $preview . "...");
- // 检查是否为错误页面
- if (str_contains($content, 'error') || str_contains($content, 'Error') || str_contains($content, 'exception')) {
- $this->warn("检测到可能的错误页面");
- }
- }
- /**
- * 显示原始内容
- *
- * @param string $content
- */
- protected function displayRawContent(string $content): void
- {
- $this->line("原始响应内容:");
- if (strlen($content) > 1000) {
- $this->line(substr($content, 0, 1000) . "...");
- $this->line("(内容过长,已截断显示)");
- } else {
- $this->line($content);
- }
- }
- /**
- * 智能检测并显示内容
- *
- * @param string $content
- */
- protected function smartDisplayContent(string $content): void
- {
- // 尝试JSON解析
- $jsonData = json_decode($content, true);
- if ($jsonData !== null) {
- $this->line("内容可解析为JSON:");
- dump($jsonData);
- return;
- }
- // 检查是否为HTML
- if (str_contains($content, '<html') || str_contains($content, '<!DOCTYPE')) {
- $this->line("检测到HTML内容:");
- $this->displayHtmlContent($content);
- return;
- }
- // 检查是否为二进制数据
- if (!mb_check_encoding($content, 'UTF-8')) {
- $this->line("检测到二进制数据:");
- $this->line("数据长度: " . strlen($content) . " 字节");
- $this->line("Base64 编码: " . substr(base64_encode($content), 0, 200) . "...");
- return;
- }
- // 默认按文本显示
- $this->line("按文本格式显示:");
- $this->displayRawContent($content);
- }
- /**
- * 清空当前日志文件
- */
- protected function clearLogFiles(): void
- {
- Logger::clear_log();
- Logger::debug('旧的日志已经清理');
- }
- }
|