feat: WebSocket upgrader, hub, send, broadcast, handler con tests (issue 0011 fase 3-4)

This commit is contained in:
2026-04-18 17:29:37 +02:00
parent 637bc8fd34
commit e35ec39c10
11 changed files with 784 additions and 0 deletions
+13
View File
@@ -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)))
}
}
}