|
| 1 | +package api |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "fmt" |
| 6 | + "net/http" |
| 7 | + "sync" |
| 8 | + "time" |
| 9 | + |
| 10 | + "github.com/gorilla/websocket" |
| 11 | +) |
| 12 | + |
| 13 | +const ( |
| 14 | + ActionSubscribe = "subscribe" |
| 15 | + ActionUnsubscribe = "unsubscribe" |
| 16 | +) |
| 17 | + |
| 18 | +// SubscriptionResponse is the response sent back to the client after an action is processed. |
| 19 | +type ClientResponse struct { |
| 20 | + Status string `json:"status"` |
| 21 | + Message string `json:"message,omitempty"` |
| 22 | + Data *string `json:"data,omitempty"` |
| 23 | +} |
| 24 | + |
| 25 | +type WebsocketHandler struct { |
| 26 | + mu sync.Mutex |
| 27 | + writeQueue chan []byte |
| 28 | + conn *websocket.Conn |
| 29 | + closeChan chan struct{} |
| 30 | +} |
| 31 | + |
| 32 | +// **NewWebsocketHandler initializes WebsocketHandler** |
| 33 | +func NewWebsocketHandler(conn *websocket.Conn) *WebsocketHandler { |
| 34 | + handler := &WebsocketHandler{ |
| 35 | + writeQueue: make(chan []byte, 100), |
| 36 | + conn: conn, |
| 37 | + closeChan: make(chan struct{}), |
| 38 | + } |
| 39 | + |
| 40 | + go handler.startWriter() // Start dedicated writer goroutine |
| 41 | + return handler |
| 42 | +} |
| 43 | + |
| 44 | +// **Sends response safely** |
| 45 | +func (h *WebsocketHandler) sendResponse(response *ClientResponse) { |
| 46 | + resp, err := json.Marshal(response) |
| 47 | + if err != nil { |
| 48 | + fmt.Printf("Error marshaling response: %v\n", err) |
| 49 | + return |
| 50 | + } |
| 51 | + |
| 52 | + select { |
| 53 | + case h.writeQueue <- resp: |
| 54 | + default: |
| 55 | + fmt.Println("Warning: writeQueue is full, dropping message") |
| 56 | + } |
| 57 | +} |
| 58 | + |
| 59 | +// **Dedicated writer goroutine** |
| 60 | +func (h *WebsocketHandler) startWriter() { |
| 61 | + for { |
| 62 | + select { |
| 63 | + case msg := <-h.writeQueue: |
| 64 | + h.mu.Lock() |
| 65 | + err := h.conn.WriteMessage(websocket.TextMessage, msg) |
| 66 | + h.mu.Unlock() |
| 67 | + |
| 68 | + if err != nil { |
| 69 | + fmt.Printf("Error writing response: %v\n", err) |
| 70 | + return |
| 71 | + } |
| 72 | + |
| 73 | + case <-h.closeChan: |
| 74 | + fmt.Println("Writer goroutine stopped") |
| 75 | + return |
| 76 | + } |
| 77 | + } |
| 78 | +} |
| 79 | + |
| 80 | +// **Close WebSocket connection and stop writer** |
| 81 | +func (h *WebsocketHandler) closeConnection() { |
| 82 | + close(h.closeChan) |
| 83 | + h.conn.Close() |
| 84 | +} |
| 85 | + |
| 86 | +// **WebSocket handler function** |
| 87 | +func (h *APIHandler) HandleWebSocket(w http.ResponseWriter, r *http.Request) { |
| 88 | + type wsMessage struct { |
| 89 | + Service string `json:"service"` |
| 90 | + Action string `json:"action"` |
| 91 | + } |
| 92 | + |
| 93 | + upgrader := websocket.Upgrader{ |
| 94 | + CheckOrigin: func(r *http.Request) bool { return true }, |
| 95 | + } |
| 96 | + |
| 97 | + conn, err := upgrader.Upgrade(w, r, nil) |
| 98 | + if err != nil { |
| 99 | + fmt.Println("WebSocket upgrade failed:", err) |
| 100 | + return |
| 101 | + } |
| 102 | + defer conn.Close() |
| 103 | + |
| 104 | + handler := NewWebsocketHandler(conn) |
| 105 | + defer handler.closeConnection() |
| 106 | + |
| 107 | + channel := make(chan []byte) |
| 108 | + |
| 109 | + // **Goroutine to forward messages from the channel to the client** |
| 110 | + go func() { |
| 111 | + for { |
| 112 | + select { |
| 113 | + case <-r.Context().Done(): |
| 114 | + return |
| 115 | + case <-handler.closeChan: // Graceful shutdown |
| 116 | + return |
| 117 | + case message := <-channel: |
| 118 | + handler.sendResponse(&ClientResponse{ |
| 119 | + Status: "success", |
| 120 | + Message: string(message), |
| 121 | + }) |
| 122 | + } |
| 123 | + } |
| 124 | + }() |
| 125 | + |
| 126 | + // **Enable Ping/Pong Handling** |
| 127 | + conn.SetPongHandler(func(appData string) error { |
| 128 | + return nil |
| 129 | + }) |
| 130 | + |
| 131 | + go func() { |
| 132 | + ticker := time.NewTicker(10 * time.Second) |
| 133 | + defer ticker.Stop() |
| 134 | + |
| 135 | + for { |
| 136 | + select { |
| 137 | + case <-handler.closeChan: |
| 138 | + return |
| 139 | + case <-ticker.C: |
| 140 | + handler.mu.Lock() |
| 141 | + err := conn.WriteMessage(websocket.PingMessage, nil) |
| 142 | + handler.mu.Unlock() |
| 143 | + |
| 144 | + if err != nil { |
| 145 | + fmt.Println("Ping failed, closing connection:", err) |
| 146 | + handler.closeConnection() |
| 147 | + return |
| 148 | + } |
| 149 | + } |
| 150 | + } |
| 151 | + }() |
| 152 | + |
| 153 | + for { |
| 154 | + _, msg, err := conn.ReadMessage() |
| 155 | + if err != nil { |
| 156 | + fmt.Println("Error reading message:", err) |
| 157 | + break |
| 158 | + } |
| 159 | + fmt.Printf("Received: %s\n", msg) |
| 160 | + |
| 161 | + client, err := h.findNodeClient(r) |
| 162 | + if err != nil { |
| 163 | + handler.sendResponse(&ClientResponse{ |
| 164 | + Status: "error", |
| 165 | + Message: "Client not found: " + err.Error(), |
| 166 | + }) |
| 167 | + return |
| 168 | + } |
| 169 | + |
| 170 | + var inMsg wsMessage |
| 171 | + if err := json.Unmarshal(msg, &inMsg); err != nil { |
| 172 | + handler.sendResponse(&ClientResponse{ |
| 173 | + Status: "error", |
| 174 | + Message: "Invalid JSON: " + err.Error(), |
| 175 | + }) |
| 176 | + continue |
| 177 | + } |
| 178 | + |
| 179 | + switch inMsg.Action { |
| 180 | + case ActionSubscribe: |
| 181 | + go client.Subscribe(r.Context(), channel, inMsg.Service) |
| 182 | + case ActionUnsubscribe: |
| 183 | + client.Unsubscribe(r.Context(), channel, inMsg.Service) |
| 184 | + default: |
| 185 | + handler.sendResponse(&ClientResponse{ |
| 186 | + Status: "error", |
| 187 | + Message: "Unknown action " + inMsg.Action, |
| 188 | + }) |
| 189 | + } |
| 190 | + } |
| 191 | +} |
0 commit comments