feat: handle cluster events
This commit is contained in:
@@ -602,6 +602,52 @@ func (wss *WebSocketServer) GetClientCount() int {
|
||||
return len(wss.clients)
|
||||
}
|
||||
|
||||
// BroadcastClusterEvent sends cluster events to all connected clients
|
||||
func (wss *WebSocketServer) BroadcastClusterEvent(topic string, data interface{}) {
|
||||
wss.mutex.RLock()
|
||||
clients := make([]*websocket.Conn, 0, len(wss.clients))
|
||||
for client := range wss.clients {
|
||||
clients = append(clients, client)
|
||||
}
|
||||
wss.mutex.RUnlock()
|
||||
|
||||
if len(clients) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
message := struct {
|
||||
Topic string `json:"topic"`
|
||||
Data interface{} `json:"data"`
|
||||
Timestamp string `json:"timestamp"`
|
||||
}{
|
||||
Topic: topic,
|
||||
Data: data,
|
||||
Timestamp: time.Now().Format(time.RFC3339),
|
||||
}
|
||||
|
||||
messageData, err := json.Marshal(message)
|
||||
if err != nil {
|
||||
wss.logger.WithError(err).Error("Failed to marshal cluster event")
|
||||
return
|
||||
}
|
||||
|
||||
wss.logger.WithFields(log.Fields{
|
||||
"topic": topic,
|
||||
"clients": len(clients),
|
||||
}).Debug("Broadcasting cluster event to WebSocket clients")
|
||||
|
||||
// Send to all clients with write synchronization
|
||||
wss.writeMutex.Lock()
|
||||
defer wss.writeMutex.Unlock()
|
||||
|
||||
for _, client := range clients {
|
||||
client.SetWriteDeadline(time.Now().Add(5 * time.Second))
|
||||
if err := client.WriteMessage(websocket.TextMessage, messageData); err != nil {
|
||||
wss.logger.WithError(err).Error("Failed to send cluster event to client")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Shutdown gracefully shuts down the WebSocket server
|
||||
func (wss *WebSocketServer) Shutdown(ctx context.Context) error {
|
||||
wss.logger.Info("Shutting down WebSocket server")
|
||||
|
||||
Reference in New Issue
Block a user