All files / src/server/routes sse.ts

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

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                                                                     
import type express from 'express'
import { addSSEClient, removeSSEClient, sendSSEMessage } from '../state/sse'
import { sseTracker } from './sse-diagnostics'
 
export function registerHealthAndSSE(app: express.Express) {
  // 健康检查
  app.get('/ping', (_req, res) => res.send('pong'))
 
  // SSE 事件流
  app.get('/events', (req, res) => {
    const connectionId = `tasks-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
 
    res.writeHead(200, {
      'Content-Type': 'text/event-stream',
      'Cache-Control': 'no-cache',
      'Connection': 'keep-alive',
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Headers': 'Cache-Control',
    })
 
    // 注册到统一跟踪器
    sseTracker.addConnection(connectionId, 'tasks', res, req)
 
    res.write(`data: ${JSON.stringify({ type: 'connected', timestamp: Date.now(), message: 'SSE connection established', connectionId })}\n\n`)
    addSSEClient(res)
 
    req.on('close', () => {
      removeSSEClient(res)
      sseTracker.removeConnection(connectionId)
    })
  })
}
 
export { sendSSEMessage }