mirror of
https://github.com/lukaszraczylo/gohoarder.git
synced 2026-11-26 06:37:07 +00:00
fix(websocket): start the event loop and throttle drop warnings
The app built the websocket server but never called Start, so nothing read the 256-slot broadcast channel. After the first 256 events every event was dropped with a warning, and dashboard clients blocked forever on the unbuffered register channel, leaking a goroutine per connection and never receiving events. Run now starts the loop with the other workers. Dropped events are counted in gohoarder_websocket_events_dropped_total and warned about at most once a minute.
This commit is contained in:
+26
-1
@@ -7,10 +7,13 @@ import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
"github.com/rs/zerolog/log"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metrics"
|
||||
)
|
||||
|
||||
// EventType represents the type of event being broadcast
|
||||
@@ -59,6 +62,8 @@ type Server struct {
|
||||
unregister chan *Client
|
||||
upgrader websocket.Upgrader
|
||||
mu sync.RWMutex
|
||||
dropped atomic.Uint64
|
||||
lastWarn atomic.Int64
|
||||
}
|
||||
|
||||
// Config holds WebSocket server configuration
|
||||
@@ -222,10 +227,30 @@ func (s *Server) Broadcast(eventType EventType, data map[string]interface{}) {
|
||||
select {
|
||||
case s.broadcast <- event:
|
||||
default:
|
||||
log.Warn().Msg("Broadcast channel full - dropping event")
|
||||
s.recordDrop()
|
||||
}
|
||||
}
|
||||
|
||||
// dropWarnInterval bounds the drop warning to one line per interval, so a burst does not flood the log.
|
||||
const dropWarnInterval = time.Minute
|
||||
|
||||
// recordDrop counts a dropped event and warns at most once per dropWarnInterval.
|
||||
func (s *Server) recordDrop() {
|
||||
total := s.dropped.Add(1)
|
||||
metrics.WebSocketEventsDropped.Inc()
|
||||
now := time.Now().UnixNano()
|
||||
last := s.lastWarn.Load()
|
||||
if now-last < int64(dropWarnInterval) || !s.lastWarn.CompareAndSwap(last, now) {
|
||||
return
|
||||
}
|
||||
log.Warn().Uint64("dropped_total", total).Msg("Broadcast channel full - dropping events")
|
||||
}
|
||||
|
||||
// Dropped returns how many events were dropped because the broadcast channel was full.
|
||||
func (s *Server) Dropped() uint64 {
|
||||
return s.dropped.Load()
|
||||
}
|
||||
|
||||
// BroadcastEvent satisfies the events.Broadcaster contract used by
|
||||
// cache/scanner sub-systems. It accepts a string event type and an
|
||||
// arbitrary payload (typically map[string]any) and forwards to the
|
||||
|
||||
Reference in New Issue
Block a user