All files / src/server/routes sse-diagnostics.ts

0% Statements 0/159
0% Branches 0/1
0% Functions 0/1
0% Lines 0/159

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213                                                                                                                                                                                                                                                                                                                                                                                                                                         
import type express from 'express'
import { pluginLogger } from '@dalidev/core'
 
// SSE连接统计和诊断
interface SSEConnectionStats {
  totalConnections: number
  connectionsByType: Record<string, number>
  connectionDetails: Array<{
    id: string
    type: string
    connectedAt: Date
    lastActivity: Date
    userAgent?: string
    remoteAddress?: string
  }>
}
 
// 全局SSE连接跟踪
class SSEConnectionTracker {
  private connections = new Map<string, {
    id: string
    type: string
    connectedAt: Date
    lastActivity: Date
    userAgent?: string
    remoteAddress?: string
    res: express.Response
  }>()
 
  addConnection(id: string, type: string, res: express.Response, req: express.Request) {
    this.connections.set(id, {
      id,
      type,
      connectedAt: new Date(),
      lastActivity: new Date(),
      userAgent: req.headers['user-agent'],
      remoteAddress: req.socket.remoteAddress,
      res,
    })
 
    pluginLogger.info('SSE', `新连接建立: ${type}`, {
      connectionId: id,
      totalConnections: this.connections.size,
    })
  }
 
  removeConnection(id: string) {
    const connection = this.connections.get(id)
    if (connection) {
      this.connections.delete(id)
      pluginLogger.info('SSE', `连接关闭: ${connection.type}`, {
        connectionId: id,
        duration: Date.now() - connection.connectedAt.getTime(),
        totalConnections: this.connections.size,
      })
    }
  }
 
  updateActivity(id: string) {
    const connection = this.connections.get(id)
    if (connection) {
      connection.lastActivity = new Date()
    }
  }
 
  getStats(): SSEConnectionStats {
    const connectionsByType: Record<string, number> = {}
    const connectionDetails = Array.from(this.connections.values()).map(conn => ({
      id: conn.id,
      type: conn.type,
      connectedAt: conn.connectedAt,
      lastActivity: conn.lastActivity,
      userAgent: conn.userAgent,
      remoteAddress: conn.remoteAddress,
    }))
 
    connectionDetails.forEach((conn) => {
      connectionsByType[conn.type] = (connectionsByType[conn.type] || 0) + 1
    })
 
    return {
      totalConnections: this.connections.size,
      connectionsByType,
      connectionDetails,
    }
  }
 
  // 清理超时连接
  cleanupStaleConnections(timeoutMs: number = 300000) { // 5分钟
    const now = Date.now()
    const staleConnections: string[] = []
 
    this.connections.forEach((connection, id) => {
      const lastActivity = connection.lastActivity.getTime()
      if (now - lastActivity > timeoutMs) {
        staleConnections.push(id)
      }
    })
 
    staleConnections.forEach((id) => {
      const connection = this.connections.get(id)
      if (connection) {
        try {
          // 尝试关闭连接
          connection.res.end()
        }
        catch (error) {
          pluginLogger.warn('SSE', '关闭超时连接失败', { connectionId: id, error })
        }
        this.removeConnection(id)
      }
    })
 
    if (staleConnections.length > 0) {
      pluginLogger.info('SSE', '清理超时连接', {
        cleanedCount: staleConnections.length,
        timeoutMs,
      })
    }
 
    return staleConnections.length
  }
 
  // 强制关闭所有连接
  closeAllConnections() {
    const connectionIds = Array.from(this.connections.keys())
 
    connectionIds.forEach((id) => {
      const connection = this.connections.get(id)
      if (connection) {
        try {
          connection.res.end()
        }
        catch (error) {
          pluginLogger.warn('SSE', '强制关闭连接失败', { connectionId: id, error })
        }
        this.removeConnection(id)
      }
    })
 
    pluginLogger.info('SSE', '强制关闭所有连接', { count: connectionIds.length })
    return connectionIds.length
  }
}
 
// 全局实例
export const sseTracker = new SSEConnectionTracker()
 
// 注册诊断路由
export function registerSSEDiagnostics(app: express.Express) {
  // 获取SSE连接统计
  app.get('/api/sse/stats', (req, res) => {
    try {
      const stats = sseTracker.getStats()
      res.json({
        success: true,
        data: stats,
      })
    }
    catch (error) {
      pluginLogger.error('SSE', '获取SSE统计失败', { error })
      res.status(500).json({
        success: false,
        error: error instanceof Error ? error.message : String(error),
      })
    }
  })
 
  // 清理超时连接
  app.post('/api/sse/cleanup', (req, res) => {
    try {
      const { timeout = 300000 } = req.body
      const cleanedCount = sseTracker.cleanupStaleConnections(timeout)
 
      res.json({
        success: true,
        data: {
          cleanedCount,
          timeoutMs: timeout,
        },
      })
    }
    catch (error) {
      pluginLogger.error('SSE', 'SSE连接清理失败', { error })
      res.status(500).json({
        success: false,
        error: error instanceof Error ? error.message : String(error),
      })
    }
  })
 
  // 强制关闭所有连接
  app.post('/api/sse/close-all', (req, res) => {
    try {
      const closedCount = sseTracker.closeAllConnections()
 
      res.json({
        success: true,
        data: {
          closedCount,
        },
      })
    }
    catch (error) {
      pluginLogger.error('SSE', '强制关闭SSE连接失败', { error })
      res.status(500).json({
        success: false,
        error: error instanceof Error ? error.message : String(error),
      })
    }
  })
}