feat: WebSocket upgrader, hub, send, broadcast, handler con tests (issue 0011 fase 3-4)
This commit is contained in:
@@ -1,5 +1,7 @@
|
||||
package infra
|
||||
|
||||
import "sync/atomic"
|
||||
|
||||
// WSHub gestiona el ciclo de vida de conexiones WebSocket.
|
||||
// Mantiene un mapa de clientes activos y canales para registro,
|
||||
// desregistro y broadcast. Se ejecuta como goroutine via su Run().
|
||||
@@ -9,6 +11,13 @@ type WSHub struct {
|
||||
Register chan *WSClient
|
||||
Unregister chan *WSClient
|
||||
done chan struct{}
|
||||
count atomic.Int64
|
||||
}
|
||||
|
||||
// ClientCount retorna el numero de clientes registrados de forma thread-safe.
|
||||
// Util para metricas, dashboards y tests.
|
||||
func (h *WSHub) ClientCount() int {
|
||||
return int(h.count.Load())
|
||||
}
|
||||
|
||||
// NewWSHub crea un WSHub vacio con canales inicializados.
|
||||
@@ -35,13 +44,16 @@ func (h *WSHub) Run() {
|
||||
delete(h.Clients, client)
|
||||
close(client.Send)
|
||||
}
|
||||
h.count.Store(0)
|
||||
return
|
||||
case client := <-h.Register:
|
||||
h.Clients[client] = true
|
||||
h.count.Store(int64(len(h.Clients)))
|
||||
case client := <-h.Unregister:
|
||||
if _, ok := h.Clients[client]; ok {
|
||||
delete(h.Clients, client)
|
||||
close(client.Send)
|
||||
h.count.Store(int64(len(h.Clients)))
|
||||
}
|
||||
case msg := <-h.Broadcast:
|
||||
for client := range h.Clients {
|
||||
@@ -53,6 +65,7 @@ func (h *WSHub) Run() {
|
||||
close(client.Send)
|
||||
}
|
||||
}
|
||||
h.count.Store(int64(len(h.Clients)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user