1
0
mirror of https://github.com/axllent/mailpit.git synced 2026-05-18 10:01:26 +02:00

Chore: Refactor Hub to use atomic clientCount for safe concurrent client tracking

This commit is contained in:
Ralph Slooten
2026-05-09 17:01:47 +12:00
parent 034a480a39
commit b997fff7eb
+8 -1
View File
@@ -3,6 +3,7 @@ package websockets
import (
"encoding/json"
"sync/atomic"
"time"
"github.com/axllent/mailpit/internal/logger"
@@ -22,6 +23,9 @@ type Hub struct {
// Unregister requests from clients.
unregister chan *Client
// clientCount is an atomic count of connected clients, safe for concurrent reads.
clientCount atomic.Int64
}
// WebsocketNotification struct for responses
@@ -48,12 +52,14 @@ func (h *Hub) Run() {
if _, ok := h.Clients[client]; !ok {
logger.Log().Debugf("[websocket] client %s connected", client.conn.RemoteAddr().String())
h.Clients[client] = true
h.clientCount.Add(1)
}
case client := <-h.unregister:
if _, ok := h.Clients[client]; ok {
logger.Log().Debugf("[websocket] client %s disconnected", client.conn.RemoteAddr().String())
delete(h.Clients, client)
close(client.send)
h.clientCount.Add(-1)
}
case message := <-h.Broadcast:
for client := range h.Clients {
@@ -62,6 +68,7 @@ func (h *Hub) Run() {
default:
close(client.send)
delete(h.Clients, client)
h.clientCount.Add(-1)
}
}
}
@@ -70,7 +77,7 @@ func (h *Hub) Run() {
// Broadcast will spawn a broadcast message to all connected clients
func Broadcast(t string, msg any) {
if MessageHub == nil || len(MessageHub.Clients) == 0 {
if MessageHub == nil || MessageHub.clientCount.Load() == 0 {
return
}