🚑 Fix concurrent writes in websocket connection

This commit is contained in:
2024-12-16 21:26:14 +01:00
parent f2f0962b81
commit 35681102b4

11
api.go
View File

@ -14,6 +14,7 @@ var upgrader = websocket.Upgrader{}
type WsClient struct {
SendUpdates bool
WriteMutex *sync.Mutex
}
var wsClientsMutex = new(sync.Mutex)
@ -405,7 +406,9 @@ func wsSendRes(conn *websocket.Conn, res gin.H, err gin.H, request *WebsocketMes
RequestMethod: request.Method,
ResponseData: err,
})
wsClients[conn].WriteMutex.Lock()
conn.WriteMessage(1, data)
wsClients[conn].WriteMutex.Unlock()
return
}
@ -420,7 +423,9 @@ func wsSendRes(conn *websocket.Conn, res gin.H, err gin.H, request *WebsocketMes
}
data, _ := json.Marshal(response)
wsClients[conn].WriteMutex.Lock()
conn.WriteMessage(1, data)
wsClients[conn].WriteMutex.Unlock()
}
func handleWs(c *gin.Context) {
@ -431,7 +436,7 @@ func handleWs(c *gin.Context) {
}
wsClientsMutex.Lock()
wsClients[conn] = WsClient{SendUpdates: false}
wsClients[conn] = WsClient{SendUpdates: false, WriteMutex: new(sync.Mutex)}
wsClientsMutex.Unlock()
for {
@ -481,7 +486,9 @@ func onPortChange(port *Port) {
continue
}
jsonData, _ := json.Marshal(WebsocketResponse{Type: "portChange", ResponseData: port})
wsClients[conn].WriteMutex.Lock()
conn.WriteMessage(1, jsonData)
wsClients[conn].WriteMutex.Unlock()
}
wsClientsMutex.Unlock()
}
@ -496,7 +503,9 @@ func onPortListChange() {
Type: "portListChange",
ResponseData: gin.H{"inputs": portConfig.Input, "outputs": portConfig.Output},
})
wsClients[conn].WriteMutex.Lock()
conn.WriteMessage(1, jsonData)
wsClients[conn].WriteMutex.Unlock()
}
wsClientsMutex.Unlock()
}