session.go 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. package ws
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "eta/eta_api/utils"
  6. "fmt"
  7. "github.com/gorilla/websocket"
  8. "sync"
  9. "time"
  10. )
  11. // Session 会话结构
  12. type Session struct {
  13. Id string
  14. UserId int
  15. Conn *websocket.Conn
  16. LastActive time.Time
  17. Latency *LatencyMeasurer
  18. History []json.RawMessage
  19. CloseChan chan struct{}
  20. MessageChan chan string
  21. mu sync.RWMutex
  22. sessionOnce sync.Once
  23. }
  24. type Message struct {
  25. KbName string `json:"KbName"`
  26. Query string `json:"Query"`
  27. LastTopics []json.RawMessage `json:"LastTopics"`
  28. }
  29. // readPump 处理读操作
  30. func (s *Session) readPump() {
  31. defer func() {
  32. fmt.Printf("读进程session %s closed", s.Id)
  33. manager.RemoveSession(s.Id)
  34. }()
  35. s.Conn.SetReadLimit(maxMessageSize)
  36. _ = s.Conn.SetReadDeadline(time.Now().Add(ReadTimeout))
  37. for {
  38. _, message, err := s.Conn.ReadMessage()
  39. if err != nil {
  40. fmt.Printf("websocket 错误关闭 %s closed", err.Error())
  41. handleCloseError(err)
  42. return
  43. }
  44. // 更新活跃时间
  45. s.UpdateActivity()
  46. // 处理消息
  47. if err = manager.HandleMessage(s.UserId, s.Id, message); err != nil {
  48. //写应答
  49. _ = s.writeWithTimeout(err.Error())
  50. }
  51. }
  52. }
  53. // UpdateActivity 跟新最近活跃时间
  54. func (s *Session) UpdateActivity() {
  55. s.mu.Lock()
  56. defer s.mu.Unlock()
  57. s.LastActive = time.Now()
  58. }
  59. func (s *Session) Close() {
  60. s.sessionOnce.Do(func() {
  61. // 控制关闭顺序
  62. close(s.CloseChan)
  63. close(s.MessageChan)
  64. s.forceClose()
  65. })
  66. }
  67. // 带超时的安全写入
  68. func (s *Session) writeWithTimeout(msg string) error {
  69. s.mu.Lock()
  70. defer s.mu.Unlock()
  71. if s.Conn == nil {
  72. return errors.New("connection closed")
  73. }
  74. // 设置写超时
  75. if err := s.Conn.SetWriteDeadline(time.Now().Add(writeWaitTimeout)); err != nil {
  76. return err
  77. }
  78. return s.Conn.WriteMessage(websocket.TextMessage, []byte(msg))
  79. }
  80. // writePump 处理写操作
  81. func (s *Session) writePump() {
  82. ticker := time.NewTicker(basePingInterval)
  83. defer func() {
  84. fmt.Printf("写继进程:session %s closed", s.Id)
  85. manager.RemoveSession(s.Id)
  86. ticker.Stop()
  87. }()
  88. for {
  89. select {
  90. case message, ok := <-s.MessageChan:
  91. if !ok {
  92. return
  93. }
  94. _ = s.writeWithTimeout(message)
  95. case <-ticker.C:
  96. _ = s.Latency.SendPing(s.Conn)
  97. ticker.Reset(s.Latency.lastLatency)
  98. case <-s.CloseChan:
  99. return
  100. }
  101. }
  102. }
  103. func handleCloseError(err error) {
  104. if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway) {
  105. var wsErr *websocket.CloseError
  106. if !errors.As(err, &wsErr) {
  107. fmt.Printf("websocket未知错误 %s", err.Error())
  108. utils.FileLog.Error("未知错误 %s", err.Error())
  109. } else {
  110. switch wsErr.Code {
  111. case websocket.CloseNormalClosure:
  112. fmt.Println("websocket正常关闭连接")
  113. utils.FileLog.Info("正常关闭连接")
  114. default:
  115. fmt.Printf("websocket关闭代码 %d:%s", wsErr.Code, wsErr.Text)
  116. utils.FileLog.Error("关闭代码:%d:%s", wsErr.Code, wsErr.Text)
  117. }
  118. }
  119. }
  120. }
  121. // 强制关闭连接
  122. func (s *Session) forceClose() {
  123. // 添加互斥锁保护
  124. s.mu.Lock()
  125. defer s.mu.Unlock()
  126. // 发送关闭帧
  127. _ = s.Conn.WriteControl(websocket.CloseMessage,
  128. websocket.FormatCloseMessage(websocket.ClosePolicyViolation, "heartbeat failed"),
  129. time.Now().Add(writeWaitTimeout))
  130. _ = s.Conn.Close()
  131. s.Conn = nil // 标记连接已关闭
  132. utils.FileLog.Info("连接已强制关闭",
  133. "user", s.UserId,
  134. "session", s.Id)
  135. }
  136. func NewSession(userId int, sessionId string, conn *websocket.Conn) (session *Session) {
  137. session = &Session{
  138. UserId: userId,
  139. Id: sessionId,
  140. Conn: conn,
  141. LastActive: time.Now(),
  142. CloseChan: make(chan struct{}),
  143. MessageChan: make(chan string, 10),
  144. }
  145. session.Latency = SetupLatencyMeasurement(conn)
  146. go session.readPump()
  147. go session.writePump()
  148. return
  149. }