Compare commits

...

24 commits

Author SHA1 Message Date
d0c3f263c1 fixup! add log message when removing stale client 2024-11-21 13:07:59 +01:00
0b6b680cce reorder staleClients.go 2024-11-21 09:44:48 +01:00
45b18ae7ab move websocket vars and const to vars.go 2024-11-21 09:44:48 +01:00
6100526610 add log message when removing stale client 2024-11-21 09:12:42 +01:00
71427f2879 fix logging 2024-11-21 09:12:42 +01:00
c1f158f42a merge ping and stale check 2024-11-21 09:12:42 +01:00
80ddfe57f4 add timeout consts in new file 2024-11-21 09:12:42 +01:00
e8cc2d1808 refactor: drop SendMessage() and merge into SendPermanentBroadCastMessage() 2024-11-21 09:12:42 +01:00
df98628d91 move ping from SendMessage() to RemoveStaleClients() 2024-11-21 08:27:15 +01:00
2faa95c162 remove client from list if stale 2024-11-20 22:01:56 +01:00
a0463ad817 comment updates 2024-11-20 21:52:08 +01:00
0ab0884508 add more Mutex Locks for Clients map 2024-11-20 21:51:58 +01:00
bf9b818940 move stale client check to RemoveStaleClients() 2024-11-20 21:50:43 +01:00
f4b1e7c808 add client.IsStale() 2024-11-20 21:26:17 +01:00
8295208a0b skip client after closing unresponsive client 2024-11-20 20:41:50 +01:00
18accba19a optimize ping/pong code 2024-11-20 20:39:32 +01:00
62b6ab81a5 remove duplicate logging 2024-11-20 20:33:26 +01:00
ed6902def0 init LastPong 2024-11-20 20:27:20 +01:00
6f60423c03 add more log output 2024-11-20 20:21:22 +01:00
409fd741dd move check for unresponsive clients to additional loops 2024-11-20 20:18:41 +01:00
15f6b0227a try to check for last ping connect 2024-11-20 20:15:24 +01:00
201e5779e6 add ping query 2024-11-20 20:07:29 +01:00
2d8816f4ba another try to remove vanished clients 2024-11-20 19:53:40 +01:00
370469de36 fix: remove client from active connections after write deadline
- add a constant for timeout duration in seconds
- set write deadline for client connections
- remove client from active connections on error
- log additional information when broadcasting fails

🤖
2024-11-20 14:07:00 +01:00
7 changed files with 87 additions and 26 deletions

View file

@ -54,6 +54,7 @@ func Start() {
r := http.NewServeMux()
r.HandleFunc("/", websocket.HandleConnection)
go websocket.SendPermanentBroadCastMessage()
go websocket.RemoveStaleClients()
helper.Logger.Info("GoTomato started", "version", metadata.GoTomatoVersion)
helper.Logger.Info("Websocket listening", "address", listen)

View file

@ -12,6 +12,7 @@ import (
// Sends continous messages to all connected WebSocket clients
func SendPermanentBroadCastMessage() {
tick := time.NewTicker(time.Second)
for {
// Marshal the message into JSON format
jsonMessage, err := json.Marshal(shared.State)
@ -19,14 +20,19 @@ func SendPermanentBroadCastMessage() {
helper.Logger.Error("Error marshalling message:", "msg", err)
return
}
// Iterate over all connected clients and broadcast the message
mu.Lock()
for _, client := range Clients {
err := client.SendMessage(websocket.TextMessage, jsonMessage)
// Send message to client
client.Conn.SetWriteDeadline(time.Now().Add(SEND_TIMEOUT * time.Second))
err := client.Conn.WriteMessage(websocket.TextMessage, jsonMessage)
if err != nil {
helper.Logger.Error("Error broadcasting to client:", "msg", err)
// The client is responsible for closing itself on error
helper.Logger.Error("Error broadcasting to client:", "msg", err, "host", client.RealIP, "clients", len(Clients))
}
}
mu.Unlock()
<-tick.C
}
}

View file

@ -21,7 +21,10 @@ func handleClientCommands(c models.WebsocketClient) {
_, message, err := ws.ReadMessage()
if err != nil {
// remove client on error/disconnect
mu.Lock()
delete(Clients, ws.LocalAddr())
mu.Unlock()
helper.Logger.Info("Client disconnected:", "msg", err, "host", c.RealIP, "clients", len(Clients))
break
}

View file

@ -2,18 +2,13 @@ package websocket
import (
"github.com/gorilla/websocket"
"net"
"net/http"
"sync"
"time"
"git.smsvc.net/pomodoro/GoTomato/internal/helper"
"git.smsvc.net/pomodoro/GoTomato/pkg/models"
)
// Clients is a map of connected WebSocket clients, where each client is represented by the WebsocketClient struct
var Clients = make(map[net.Addr]*models.WebsocketClient)
var mu sync.Mutex // Mutex to protect access to the Clients map
// Upgrade HTTP requests to WebSocket connections
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool { return true },
@ -31,9 +26,15 @@ func HandleConnection(w http.ResponseWriter, r *http.Request) {
// Register the new client
client := models.WebsocketClient{
Conn: ws,
RealIP: r.RemoteAddr,
Conn: ws,
LastPong: time.Now(),
RealIP: r.RemoteAddr,
}
client.Conn.SetPongHandler(func(s string) error {
client.LastPong = time.Now()
return nil
})
mu.Lock()
Clients[ws.LocalAddr()] = &client
mu.Unlock()

View file

@ -0,0 +1,42 @@
package websocket
import (
"time"
"git.smsvc.net/pomodoro/GoTomato/internal/helper"
"git.smsvc.net/pomodoro/GoTomato/pkg/models"
"github.com/gorilla/websocket"
)
// Check and remove stale clients
func RemoveStaleClients() {
ticker := time.NewTicker(STALE_CHECK_INTERVALL * time.Second)
defer ticker.Stop()
for range ticker.C {
mu.Lock()
for _, client := range Clients {
if !sendPing(client) || isStale(client) {
client.Conn.Close()
delete(Clients, client.Conn.LocalAddr())
helper.Logger.Info("Removed stale client", "host", client.RealIP)
}
}
mu.Unlock()
}
}
func sendPing(client *models.WebsocketClient) bool {
client.Conn.SetWriteDeadline(time.Now().Add(SEND_TIMEOUT * time.Second))
err := client.Conn.WriteMessage(websocket.PingMessage, nil)
if err != nil {
return false
}
return true
}
func isStale(client *models.WebsocketClient) bool {
return time.Since(client.LastPong) > (STALE_CLIENT_TIMEOUT * time.Second)
}

View file

@ -0,0 +1,18 @@
package websocket
import (
"net"
"sync"
"git.smsvc.net/pomodoro/GoTomato/pkg/models"
)
const SEND_TIMEOUT = 10
const STALE_CLIENT_TIMEOUT = 90
const STALE_CHECK_INTERVALL = 30
// Clients is a map of connected WebSocket clients, where each client is represented by the WebsocketClient struct
var Clients = make(map[net.Addr]*models.WebsocketClient)
// Mutex to protect access to the Clients map
var mu sync.Mutex

View file

@ -1,9 +1,9 @@
package models
import (
"github.com/gorilla/websocket"
"time"
"git.smsvc.net/pomodoro/GoTomato/internal/helper"
"github.com/gorilla/websocket"
)
// Represents a command from the client (start/stop)
@ -15,17 +15,7 @@ type ClientCommand struct {
// Represents a single client
type WebsocketClient struct {
Conn *websocket.Conn
RealIP string
}
// Sends a message to the websocket.
// Automatically locks and unlocks the client mutex, to ensure that only one goroutine can write at a time.
func (c *WebsocketClient) SendMessage(messageType int, data []byte) error {
err := c.Conn.WriteMessage(messageType, data)
if err != nil {
helper.Logger.Error("Error writing to WebSocket:", "msg", err)
c.Conn.Close() // Close the connection on error
}
return err
Conn *websocket.Conn
LastPong time.Time
RealIP string
}