diff --git a/pkg/app/app.go b/pkg/app/app.go index e543504..69013a2 100644 --- a/pkg/app/app.go +++ b/pkg/app/app.go @@ -593,6 +593,19 @@ func (a *App) setupServer() error { return nil } +// startWorkers starts the background loops that live as long as ctx. +func (a *App) startWorkers(ctx context.Context) { + // Without the event loop the broadcast channel fills after 256 events and websocket clients never register. + a.wsServer.Start(ctx) + + // Start download data aggregation worker (runs every hour) + go a.startAggregationWorker(ctx) + + // Start periodic stats broadcaster (every 30s) so connected WS clients + // see live counter updates without polling. + go a.startStatsBroadcaster(ctx) +} + func (a *App) Run() error { // Cancellable worker context: aggregation + stats broadcaster goroutines // watch ctx.Done() and exit, so Shutdown can stop them before closing @@ -601,12 +614,7 @@ func (a *App) Run() error { a.cancel = cancel defer cancel() - // Start download data aggregation worker (runs every hour) - go a.startAggregationWorker(ctx) - - // Start periodic stats broadcaster (every 30s) so connected WS clients - // see live counter updates without polling. - go a.startStatsBroadcaster(ctx) + a.startWorkers(ctx) // Start Fiber server in goroutine. Branch on TLS to pick Listen vs ListenTLS. errChan := make(chan error, 1) diff --git a/pkg/app/workers_test.go b/pkg/app/workers_test.go new file mode 100644 index 0000000..83caac2 --- /dev/null +++ b/pkg/app/workers_test.go @@ -0,0 +1,30 @@ +package app + +import ( + "context" + "testing" + "time" +) + +// TestWorkersDrainTheBroadcastChannel pins that the app starts the websocket +// event loop: without it the 256-slot broadcast channel fills and every later +// event is dropped. +func TestWorkersDrainTheBroadcastChannel(t *testing.T) { + a := newTestApp(t, nil) + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + a.startWorkers(ctx) + + const events = 1000 + for i := 0; i < events; i++ { + a.wsServer.BroadcastEvent("cache_hit", map[string]interface{}{"i": i}) + if i%200 == 0 { + time.Sleep(5 * time.Millisecond) + } + } + + if dropped := a.wsServer.Dropped(); dropped != 0 { + t.Fatalf("dropped %d of %d events; the broadcast loop is not draining the channel", dropped, events) + } +} diff --git a/pkg/metrics/metrics.go b/pkg/metrics/metrics.go index 4417b5e..7d95a92 100644 --- a/pkg/metrics/metrics.go +++ b/pkg/metrics/metrics.go @@ -62,6 +62,14 @@ var ( []string{"reason"}, // ttl, lru, manual ) + // WebSocketEventsDropped counts realtime events dropped because the broadcast channel was full. + WebSocketEventsDropped = promauto.NewCounter( + prometheus.CounterOpts{ + Name: "gohoarder_websocket_events_dropped_total", + Help: "Realtime dashboard events dropped because the broadcast channel was full", + }, + ) + // Storage metrics StorageOperations = promauto.NewCounterVec( prometheus.CounterOpts{ diff --git a/pkg/websocket/server.go b/pkg/websocket/server.go index e01340f..56d1bed 100644 --- a/pkg/websocket/server.go +++ b/pkg/websocket/server.go @@ -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