Browse Source

添加长链接日志与地址

yanqiliang 2 weeks ago
parent
commit
705daad15d

+ 2 - 1
.gitignore

@@ -24,4 +24,5 @@ yarn.lock
 *.sln
 *.sw?
 .codebuddy
-openspec
+openspec
+dosc

+ 3 - 1
src/api/index.js

@@ -518,7 +518,8 @@ export const initSocket = (obj, getMessage, onSocketStatus) => {
       });
   };
   let isRecreatingSocket = false;
-  window.socket = io(obj.serverIP + ':' + obj.serverPort, {
+  const connectionAddress = obj.serverIP + ':' + obj.serverPort;
+  window.socket = io(connectionAddress, {
     reconnection: true,
     reconnectionAttempts: MAX_RECONNECTION_ATTEMPTS,
     reconnectionDelay: 1000,
@@ -532,6 +533,7 @@ export const initSocket = (obj, getMessage, onSocketStatus) => {
     forceNew: true,
   });
   window.socket.__socketKey = socketKey;
+  window.socket.__connectionAddress = connectionAddress;
   window.socket.__getMessage = getMessage;
   window.socket.__onSocketStatus = onSocketStatus;
   const currentSocket = window.socket;

+ 27 - 0
src/assets/scss/style.scss

@@ -193,6 +193,33 @@ html{
     font-size: 12px;
   }
 }
+.debug-request-toggle {
+  display: block;
+  width: 100%;
+  padding: 6px 0;
+  border: 0;
+  background: transparent;
+  color: #0d2764;
+  font: inherit;
+  font-weight: 600;
+  text-align: left;
+  overflow-wrap: break-word;
+  cursor: pointer;
+}
+.debug-response-json {
+  max-height: 300px;
+  margin: 8px 0;
+  padding: 10px;
+  overflow: auto;
+  border: 1px solid #eee;
+  border-radius: 4px;
+  background: #f7f8fa;
+  color: #222;
+  font-family: Consolas, Monaco, monospace;
+  font-size: 12px;
+  white-space: pre-wrap;
+  word-break: break-all;
+}
 .debug-log-list {
   max-height: 180px;
   overflow-y: auto;

+ 3 - 2
src/components/login/Index.jsx

@@ -1,5 +1,6 @@
 import React from 'react';
 import { Input, Form, Modal, Selector, Toast } from 'antd-mobile';
+import { observeRequest } from '@utils/requestDiagnostics.js';
 const formRef = React.createRef();
 /**
  * @刘丹: 登录公用
@@ -272,7 +273,7 @@ class Login extends React.Component {
     this.setState({
       bindingDevice: true,
     });
-    const request = React.$fetchPost('04150006', {
+    const request = observeRequest('04150006', () => React.$fetchPost('04150006', {
       params: [{
         hospID: cacheData.hospital[0] || '',  // 医院ID
         deviceDesc: '叫号屏', // 设备名称
@@ -282,7 +283,7 @@ class Login extends React.Component {
         rebindFlag: flag || item.rebindFlag || '',
         deviceDataID: cacheData.room[0] || '', // 诊室设ID
       }],
-    }, false) || Promise.reject(new Error('请先配置请求地址'));
+    }, false), this.props.onRequestDiagnostic) || Promise.reject(new Error('请先配置请求地址'));
     return request.then((res) => {
       localStorage.setItem('ZZJ-base', JSON.stringify(cacheData));
       if (window.socket) {

+ 61 - 3
src/pages/home/Index.jsx

@@ -8,6 +8,7 @@ import FingerprintJS from '@fingerprintjs/fingerprintjs';
 import { forceRecreateSocket as recreateSocket, initSocket } from '@api/index.js';
 import { AntOutline, ContentOutline, SetOutline } from 'antd-mobile-icons';
 import { Modal } from 'antd-mobile';
+import { observeRequest } from '@utils/requestDiagnostics.js';
 
 class Home extends React.Component {
   // 音频播放容错常量(与 openspec/changes/fix-audio-playback-deadlock 对齐)
@@ -61,10 +62,13 @@ class Home extends React.Component {
         updatedAt: '',
       },
       debugPanelVisible: false,
+      requestDiagnostics: {},
+      expandedRequestDiagnostics: {},
       debugInfo: {
         socketStatus: 'unknown',
         socketConnected: false,
         socketId: '',
+        socketAddress: '',
         lastConnectAt: '',
         lastDisconnectAt: '',
         lastDisconnectReason: '',
@@ -245,7 +249,7 @@ class Home extends React.Component {
   };
 
   openDebugPanel = () => {
-    this.setState({ debugPanelVisible: true });
+    this.setState({ debugPanelVisible: true, expandedRequestDiagnostics: {} });
   };
 
   hideDebugPanel = () => {
@@ -453,6 +457,55 @@ class Home extends React.Component {
     </div>
   );
 
+  handleRequestDiagnostic = (record) => {
+    this.setState((prevState) => {
+      const previous = prevState.requestDiagnostics[record.code];
+      // 并发调用时,较早请求的迟到响应不能覆盖最新请求。
+      if (previous && previous.requestId > record.requestId) {
+        return null;
+      }
+      return {
+        requestDiagnostics: { ...prevState.requestDiagnostics, [record.code]: record },
+      };
+    });
+  };
+
+  renderRequestDiagnostic = (code, label) => {
+    const record = this.state.requestDiagnostics[code];
+    const expanded = !!this.state.expandedRequestDiagnostics[code];
+    const formatTime = (time) => time == null ? '-' : new Date(time).toLocaleString('zh-CN', { hour12: false });
+    const statusText = { pending: '请求中', success: '成功', error: '失败' };
+    return (
+      <div className="debug-section debug-request-section">
+        <button
+          type="button"
+          className="debug-request-toggle"
+          aria-expanded={expanded}
+          aria-controls={`debug-response-${code}`}
+          onClick={() => this.setState((prevState) => ({
+            expandedRequestDiagnostics: {
+              ...prevState.expandedRequestDiagnostics,
+              [code]: !prevState.expandedRequestDiagnostics[code],
+            },
+          }))}
+        >
+          {expanded ? '▼' : '▶'} {code} {label}({record ? `请求:${formatTime(record.requestedAt)}` : '暂无返回值'})
+        </button>
+        {expanded && (
+          <div id={`debug-response-${code}`}>
+            {record ? <>
+              {this.renderDebugRow('请求时间', formatTime(record.requestedAt))}
+              {this.renderDebugRow('响应时间', formatTime(record.respondedAt))}
+              {this.renderDebugRow('耗时', record.durationMs == null ? '-' : `${record.durationMs} ms`)}
+              {this.renderDebugRow('请求状态', statusText[record.status])}
+              <pre className="debug-response-json">{record.responseText || '等待接口返回…'}</pre>
+            </> : <div className="debug-empty">暂无返回值</div>}
+          </div>
+        )}
+      </div>
+    );
+  };
+
   renderDebugPanel = () => {
     const { debugInfo } = this.state;
     const socketText = debugInfo.socketConnected ? '已连接' : '未连接';
@@ -464,6 +517,7 @@ class Home extends React.Component {
             <div className="debug-section-title">设备与连接</div>
             {this.renderDebugRow('设备ID', this.state.deviceID, 'long')}
             {this.renderDebugRow('连接状态', `${socketText} / ${debugInfo.socketStatus}`)}
+            {this.renderDebugRow('连接地址', debugInfo.socketAddress, 'long')}
             {this.renderDebugRow('Socket ID', debugInfo.socketId, 'long')}
             {this.renderDebugRow('最后连接', debugInfo.lastConnectAt)}
             {this.renderDebugRow('最后断开', debugInfo.lastDisconnectAt)}
@@ -496,6 +550,8 @@ class Home extends React.Component {
             {this.renderDebugRow('音频地址', debugInfo.lastAudioUrl, 'long')}
           </div>
         </div>
+        {this.renderRequestDiagnostic('04150006', '绑定返回值')}
+        {this.renderRequestDiagnostic('04150020', '登录返回值')}
         <div className="debug-section debug-log-section">
           <div className="debug-section-title">最近日志</div>
           <div className="debug-log-list">
@@ -959,6 +1015,7 @@ class Home extends React.Component {
     const socketConnected = this.getSocketConnected() || socketStatus === 'connected';
     const debugPatch = {
       socketStatus,
+      socketAddress: window.socket?.__connectionAddress || this.state.debugInfo.socketAddress,
       socketConnected: status.socketConnected ?? socketConnected,
       socketId,
     };
@@ -1190,7 +1247,7 @@ class Home extends React.Component {
       this.openLogin();
       return;
     }
-    return React.$fetchPost(
+    return observeRequest('04150020', () => React.$fetchPost(
       '04150020',
       {
         params: [
@@ -1201,7 +1258,7 @@ class Home extends React.Component {
         ],
       },
       true,
-    ).then((data) => {
+    ), this.handleRequestDiagnostic).then((data) => {
       if (data) {
         const obj = {
           Loc: 'area',
@@ -1242,6 +1299,7 @@ class Home extends React.Component {
             hideLogin={this.hideLogin}
             loginInit={this.loginInit}
             deviceID={this.state.deviceID}
+            onRequestDiagnostic={this.handleRequestDiagnostic}
           />
           <Modal
             visible={this.state.socketStatus.visible}

+ 51 - 0
src/utils/requestDiagnostics.js

@@ -0,0 +1,51 @@
+let diagnosticRequestId = 0;
+
+// 旁路记录诊断信息,返回原始请求 Promise,不改变业务调用的结果或错误。
+export const observeRequest = (code, requestFactory, onDiagnostic) => {
+  if (!onDiagnostic) {
+    return requestFactory();
+  }
+  const requestedAt = Date.now();
+  const requestId = ++diagnosticRequestId;
+  const publish = (status, value) => {
+    try {
+      const respondedAt = status === 'pending' ? null : Date.now();
+      let response = value;
+      if (value instanceof Error) {
+        response = { ...value, name: value.name, message: value.message };
+      } else if (value && typeof value.status === 'number' && typeof value.text === 'function') {
+        // HTTP 错误不额外读取响应体,避免干扰原有请求处理。
+        response = { status: value.status, statusText: value.statusText, url: value.url };
+      }
+      onDiagnostic({
+        code,
+        requestId,
+        requestedAt,
+        respondedAt,
+        durationMs: respondedAt === null ? null : respondedAt - requestedAt,
+        status,
+        // 当场生成快照,防止业务后续给 result 添加字段后影响原始返回值。
+        responseText: response === undefined ? '' : JSON.stringify(response, null, 2),
+      });
+    } catch (error) {
+      console.warn('记录接口诊断信息失败', error);
+    }
+  };
+  publish('pending');
+  let request;
+  try {
+    request = requestFactory();
+  } catch (error) {
+    publish('error', error);
+    throw error;
+  }
+  if (request && typeof request.then === 'function') {
+    request.then(
+      (data) => publish('success', data),
+      (error) => publish('error', error),
+    );
+  } else {
+    publish('error', { message: '请求未发起,请检查请求地址配置' });
+  }
+  return request;
+};