2024-11-20 20:50:43 +00:00
|
|
|
package websocket
|
|
|
|
|
|
|
|
import (
|
|
|
|
"time"
|
2024-11-21 07:27:15 +00:00
|
|
|
|
2024-11-21 07:57:43 +00:00
|
|
|
"git.smsvc.net/pomodoro/GoTomato/internal/helper"
|
2024-11-21 07:27:15 +00:00
|
|
|
"git.smsvc.net/pomodoro/GoTomato/pkg/models"
|
|
|
|
"github.com/gorilla/websocket"
|
2024-11-20 20:50:43 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// Check and remove stale clients
|
|
|
|
func RemoveStaleClients() {
|
2024-11-21 07:44:50 +00:00
|
|
|
ticker := time.NewTicker(STALE_CHECK_INTERVALL * time.Second)
|
2024-11-20 20:50:43 +00:00
|
|
|
defer ticker.Stop()
|
|
|
|
|
|
|
|
for range ticker.C {
|
|
|
|
mu.Lock()
|
|
|
|
for _, client := range Clients {
|
2024-11-21 07:47:58 +00:00
|
|
|
if !sendPing(client) || isStale(client) {
|
2024-11-20 20:50:43 +00:00
|
|
|
client.Conn.Close()
|
2024-11-20 21:01:56 +00:00
|
|
|
delete(Clients, client.Conn.LocalAddr())
|
2024-11-21 18:29:44 +00:00
|
|
|
helper.Logger.Info("Removed stale client", "host", client.RealIP, "lastPong", client.LastPong)
|
2024-11-20 20:50:43 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
mu.Unlock()
|
|
|
|
}
|
|
|
|
}
|
2024-11-21 08:34:19 +00:00
|
|
|
|
|
|
|
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 {
|
2024-11-21 18:52:18 +00:00
|
|
|
helper.Logger.Info("ping failed", "host", client.RealIP)
|
2024-11-21 08:34:19 +00:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
func isStale(client *models.WebsocketClient) bool {
|
|
|
|
return time.Since(client.LastPong) > (STALE_CLIENT_TIMEOUT * time.Second)
|
|
|
|
}
|