websocket.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. package event
  2. import (
  3. "context"
  4. "encoding/json"
  5. "net/http"
  6. "sync"
  7. "time"
  8. "github.com/0xJacky/Nginx-UI/internal/cache"
  9. "github.com/0xJacky/Nginx-UI/internal/cert"
  10. "github.com/0xJacky/Nginx-UI/internal/helper"
  11. "github.com/0xJacky/Nginx-UI/internal/kernel"
  12. "github.com/0xJacky/Nginx-UI/internal/notification"
  13. "github.com/0xJacky/Nginx-UI/model"
  14. "github.com/gin-gonic/gin"
  15. "github.com/gorilla/websocket"
  16. "github.com/uozi-tech/cosy/logger"
  17. )
  18. // WebSocketMessage represents the structure of messages sent to the client
  19. type WebSocketMessage struct {
  20. Event string `json:"event"`
  21. Data interface{} `json:"data"`
  22. }
  23. // Client represents a WebSocket client connection
  24. type Client struct {
  25. conn *websocket.Conn
  26. send chan WebSocketMessage
  27. ctx context.Context
  28. cancel context.CancelFunc
  29. mutex sync.RWMutex
  30. }
  31. // Hub maintains the set of active clients and broadcasts messages to them
  32. type Hub struct {
  33. clients map[*Client]bool
  34. broadcast chan WebSocketMessage
  35. register chan *Client
  36. unregister chan *Client
  37. mutex sync.RWMutex
  38. }
  39. var (
  40. hub *Hub
  41. hubOnce sync.Once
  42. )
  43. // GetHub returns the singleton hub instance
  44. func GetHub() *Hub {
  45. hubOnce.Do(func() {
  46. hub = &Hub{
  47. clients: make(map[*Client]bool),
  48. broadcast: make(chan WebSocketMessage, 256),
  49. register: make(chan *Client),
  50. unregister: make(chan *Client),
  51. }
  52. go hub.run()
  53. })
  54. return hub
  55. }
  56. // run handles the main hub loop
  57. func (h *Hub) run() {
  58. for {
  59. select {
  60. case client := <-h.register:
  61. h.mutex.Lock()
  62. h.clients[client] = true
  63. h.mutex.Unlock()
  64. logger.Debug("Client connected, total clients:", len(h.clients))
  65. case client := <-h.unregister:
  66. h.mutex.Lock()
  67. if _, ok := h.clients[client]; ok {
  68. delete(h.clients, client)
  69. close(client.send)
  70. }
  71. h.mutex.Unlock()
  72. logger.Debug("Client disconnected, total clients:", len(h.clients))
  73. case message := <-h.broadcast:
  74. h.mutex.RLock()
  75. for client := range h.clients {
  76. select {
  77. case client.send <- message:
  78. default:
  79. close(client.send)
  80. delete(h.clients, client)
  81. }
  82. }
  83. h.mutex.RUnlock()
  84. }
  85. }
  86. }
  87. // BroadcastMessage sends a message to all connected clients
  88. func (h *Hub) BroadcastMessage(event string, data interface{}) {
  89. message := WebSocketMessage{
  90. Event: event,
  91. Data: data,
  92. }
  93. select {
  94. case h.broadcast <- message:
  95. default:
  96. logger.Warn("Broadcast channel full, message dropped")
  97. }
  98. }
  99. // WebSocket upgrader configuration
  100. var upgrader = websocket.Upgrader{
  101. CheckOrigin: func(r *http.Request) bool {
  102. return true
  103. },
  104. ReadBufferSize: 1024,
  105. WriteBufferSize: 1024,
  106. }
  107. // EventBus handles the main WebSocket connection for the event bus
  108. func EventBus(c *gin.Context) {
  109. ws, err := upgrader.Upgrade(c.Writer, c.Request, nil)
  110. if err != nil {
  111. logger.Error("Failed to upgrade connection:", err)
  112. return
  113. }
  114. defer ws.Close()
  115. ctx, cancel := context.WithCancel(context.Background())
  116. defer cancel()
  117. client := &Client{
  118. conn: ws,
  119. send: make(chan WebSocketMessage, 256),
  120. ctx: ctx,
  121. cancel: cancel,
  122. }
  123. hub := GetHub()
  124. hub.register <- client
  125. // Start goroutines for handling subscriptions
  126. go client.handleNotifications()
  127. go client.handleProcessingStatus()
  128. go client.handleNginxLogStatus()
  129. // Start write and read pumps
  130. go client.writePump()
  131. client.readPump()
  132. }
  133. // handleNotifications subscribes to notification events
  134. func (c *Client) handleNotifications() {
  135. evtChan := make(chan *model.Notification, 10)
  136. wsManager := notification.GetWebSocketManager()
  137. wsManager.Subscribe(evtChan)
  138. defer func() {
  139. wsManager.Unsubscribe(evtChan)
  140. }()
  141. for {
  142. select {
  143. case n := <-evtChan:
  144. hub.BroadcastMessage("notification", n)
  145. case <-c.ctx.Done():
  146. return
  147. }
  148. }
  149. }
  150. // handleProcessingStatus subscribes to processing status events
  151. func (c *Client) handleProcessingStatus() {
  152. indexScanning := cache.SubscribeScanningStatus()
  153. defer cache.UnsubscribeScanningStatus(indexScanning)
  154. autoCert := cert.SubscribeProcessingStatus()
  155. defer cert.UnsubscribeProcessingStatus(autoCert)
  156. status := struct {
  157. IndexScanning bool `json:"index_scanning"`
  158. AutoCertProcessing bool `json:"auto_cert_processing"`
  159. }{
  160. IndexScanning: false,
  161. AutoCertProcessing: false,
  162. }
  163. for {
  164. select {
  165. case indexStatus, ok := <-indexScanning:
  166. if !ok {
  167. return
  168. }
  169. status.IndexScanning = indexStatus
  170. // Send processing status event
  171. hub.BroadcastMessage("processing_status", status)
  172. // Also send nginx log status event for backward compatibility
  173. hub.BroadcastMessage("nginx_log_status", gin.H{
  174. "scanning": indexStatus,
  175. })
  176. case certStatus, ok := <-autoCert:
  177. if !ok {
  178. return
  179. }
  180. status.AutoCertProcessing = certStatus
  181. hub.BroadcastMessage("processing_status", status)
  182. case <-c.ctx.Done():
  183. return
  184. }
  185. }
  186. }
  187. // handleNginxLogStatus subscribes to nginx log scanning status events
  188. // Note: This uses the same cache.SubscribeScanningStatus as handleProcessingStatus
  189. // but sends different event types for different purposes
  190. func (c *Client) handleNginxLogStatus() {
  191. // We don't need a separate subscription here since handleProcessingStatus
  192. // already handles the index scanning status. This function is kept for
  193. // potential future nginx-specific log status that might be different
  194. // from the general index scanning status.
  195. // For now, this is handled by handleProcessingStatus
  196. <-c.ctx.Done()
  197. }
  198. // writePump pumps messages from the hub to the websocket connection
  199. func (c *Client) writePump() {
  200. ticker := time.NewTicker(30 * time.Second)
  201. defer func() {
  202. ticker.Stop()
  203. c.conn.Close()
  204. }()
  205. for {
  206. select {
  207. case message, ok := <-c.send:
  208. c.conn.SetWriteDeadline(time.Now().Add(10 * time.Second))
  209. if !ok {
  210. c.conn.WriteMessage(websocket.CloseMessage, []byte{})
  211. return
  212. }
  213. if err := c.conn.WriteJSON(message); err != nil {
  214. logger.Error("Failed to write message:", err)
  215. if helper.IsUnexpectedWebsocketError(err) {
  216. return
  217. }
  218. }
  219. case <-ticker.C:
  220. c.conn.SetWriteDeadline(time.Now().Add(10 * time.Second))
  221. if err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil {
  222. logger.Error("Failed to write ping:", err)
  223. return
  224. }
  225. case <-c.ctx.Done():
  226. return
  227. case <-kernel.Context.Done():
  228. return
  229. }
  230. }
  231. }
  232. // readPump pumps messages from the websocket connection to the hub
  233. func (c *Client) readPump() {
  234. defer func() {
  235. hub := GetHub()
  236. hub.unregister <- c
  237. c.conn.Close()
  238. c.cancel()
  239. }()
  240. c.conn.SetReadLimit(512)
  241. c.conn.SetReadDeadline(time.Now().Add(60 * time.Second))
  242. c.conn.SetPongHandler(func(string) error {
  243. c.conn.SetReadDeadline(time.Now().Add(60 * time.Second))
  244. return nil
  245. })
  246. for {
  247. var msg json.RawMessage
  248. err := c.conn.ReadJSON(&msg)
  249. if err != nil {
  250. if helper.IsUnexpectedWebsocketError(err) {
  251. logger.Error("Unexpected WebSocket error:", err)
  252. }
  253. break
  254. }
  255. // Handle incoming messages if needed
  256. // For now, this is a one-way communication (server to client)
  257. }
  258. }