Compare commits

...

25 commits

Author SHA1 Message Date
92260b44db feat: introduce const for broadcast interval
- change ticker to use BROADCAST_INTERVAL constant
- define BROADCAST_INTERVAL as 1 second

🤖
2024-11-21 18:54:08 +01:00
efc34b57b2 feat: improve broadcast message handling
- rename tick to ticker for clarity
- change infinite loop to range over ticker channel
- add defer statement to stop the ticker properly
- remove unnecessary channel receive operation

🤖
2024-11-21 18:51:09 +01:00
2c3ccc86c3 reorder staleClients.go 2024-11-21 18:50:00 +01:00
68b5784255 move websocket vars and const to vars.go 2024-11-21 18:50:00 +01:00
2d469a0b86 add log message when removing stale client 2024-11-21 18:50:00 +01:00
19df804235 fix logging 2024-11-21 18:50:00 +01:00
58ac2d2950 merge ping and stale check 2024-11-21 18:50:00 +01:00
c76ea3628b add timeout consts in new file 2024-11-21 18:50:00 +01:00
51b08b66e0 refactor: drop SendMessage() and merge into SendPermanentBroadCastMessage() 2024-11-21 18:50:00 +01:00
2f18b472f6 move ping from SendMessage() to RemoveStaleClients() 2024-11-21 18:50:00 +01:00
b4eff894b8 remove client from list if stale 2024-11-21 18:50:00 +01:00
84b9e0afd6 comment updates 2024-11-21 18:50:00 +01:00
b5e1b5cc88 add more Mutex Locks for Clients map 2024-11-21 18:50:00 +01:00
7e5b0659b4 move stale client check to RemoveStaleClients() 2024-11-21 18:50:00 +01:00
ccd0c38b58 add client.IsStale() 2024-11-21 18:50:00 +01:00
a25ee424aa skip client after closing unresponsive client 2024-11-21 18:50:00 +01:00
32e00480f8 optimize ping/pong code 2024-11-21 18:50:00 +01:00
d975034680 remove duplicate logging 2024-11-21 18:50:00 +01:00
c348049209 init LastPong 2024-11-21 18:50:00 +01:00
c63ef3c12a add more log output 2024-11-21 18:50:00 +01:00
2ddc1ef9e4 move check for unresponsive clients to additional loops 2024-11-21 18:50:00 +01:00
9fa740b2c6 try to check for last ping connect 2024-11-21 18:50:00 +01:00
df965e633d add ping query 2024-11-21 18:50:00 +01:00
03d94d5999 another try to remove vanished clients 2024-11-21 18:50:00 +01:00
75b3ae87d6 feat: 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-21 18:49:58 +01:00
7 changed files with 90 additions and 29 deletions

View file

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

View file

@ -11,22 +11,27 @@ import (
// Sends continous messages to all connected WebSocket clients // Sends continous messages to all connected WebSocket clients
func SendPermanentBroadCastMessage() { func SendPermanentBroadCastMessage() {
tick := time.NewTicker(time.Second) ticker := time.NewTicker(BROADCAST_INTERVAL * time.Second)
for { defer ticker.Stop()
for range ticker.C {
// Marshal the message into JSON format // Marshal the message into JSON format
jsonMessage, err := json.Marshal(shared.State) jsonMessage, err := json.Marshal(shared.State)
if err != nil { if err != nil {
helper.Logger.Error("Error marshalling message:", "msg", err) helper.Logger.Error("Error marshalling message:", "msg", err)
return return
} }
// Iterate over all connected clients and broadcast the message // Iterate over all connected clients and broadcast the message
mu.Lock()
for _, client := range Clients { 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 { if err != nil {
helper.Logger.Error("Error broadcasting to client:", "msg", err) helper.Logger.Error("Error broadcasting to client:", "msg", err, "host", client.RealIP, "clients", len(Clients))
// The client is responsible for closing itself on error
} }
} }
<-tick.C mu.Unlock()
} }
} }

View file

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

View file

@ -2,18 +2,13 @@ package websocket
import ( import (
"github.com/gorilla/websocket" "github.com/gorilla/websocket"
"net"
"net/http" "net/http"
"sync" "time"
"git.smsvc.net/pomodoro/GoTomato/internal/helper" "git.smsvc.net/pomodoro/GoTomato/internal/helper"
"git.smsvc.net/pomodoro/GoTomato/pkg/models" "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 // Upgrade HTTP requests to WebSocket connections
var upgrader = websocket.Upgrader{ var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool { return true }, CheckOrigin: func(r *http.Request) bool { return true },
@ -32,8 +27,14 @@ func HandleConnection(w http.ResponseWriter, r *http.Request) {
// Register the new client // Register the new client
client := models.WebsocketClient{ client := models.WebsocketClient{
Conn: ws, Conn: ws,
LastPong: time.Now(),
RealIP: r.RemoteAddr, RealIP: r.RemoteAddr,
} }
client.Conn.SetPongHandler(func(s string) error {
client.LastPong = time.Now()
return nil
})
mu.Lock() mu.Lock()
Clients[ws.LocalAddr()] = &client Clients[ws.LocalAddr()] = &client
mu.Unlock() 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,19 @@
package websocket
import (
"net"
"sync"
"git.smsvc.net/pomodoro/GoTomato/pkg/models"
)
const BROADCAST_INTERVAL = 1
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 package models
import ( 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) // Represents a command from the client (start/stop)
@ -16,16 +16,6 @@ type ClientCommand struct {
// Represents a single client // Represents a single client
type WebsocketClient struct { type WebsocketClient struct {
Conn *websocket.Conn Conn *websocket.Conn
LastPong time.Time
RealIP string 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
}