|
| 1 | +package realtime |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/json" |
| 6 | + "log/slog" |
| 7 | + "net/http" |
| 8 | + "sync" |
| 9 | + "time" |
| 10 | + |
| 11 | + "github.com/RandomCodeSpace/Project-Argus/internal/storage" |
| 12 | + "github.com/coder/websocket" |
| 13 | +) |
| 14 | + |
| 15 | +// LiveSnapshot is the data payload pushed to all event WS clients. |
| 16 | +type LiveSnapshot struct { |
| 17 | + Type string `json:"type"` |
| 18 | + Dashboard *storage.DashboardStats `json:"dashboard"` |
| 19 | + Traffic []storage.TrafficPoint `json:"traffic"` |
| 20 | + Traces *storage.TracesResponse `json:"traces"` |
| 21 | + ServiceMap *storage.ServiceMapMetrics `json:"service_map"` |
| 22 | +} |
| 23 | + |
| 24 | +// clientFilter tracks a client's active service filter. |
| 25 | +// Empty string = all services (no filter). |
| 26 | +type clientFilter struct { |
| 27 | + service string |
| 28 | +} |
| 29 | + |
| 30 | +// EventHub manages WebSocket clients and pushes live data snapshots |
| 31 | +// filtered per-client's selected service. Debounces rapid ingestion |
| 32 | +// bursts and only computes snapshots every flush interval. |
| 33 | +type EventHub struct { |
| 34 | + repo *storage.Repository |
| 35 | + onConn func() |
| 36 | + onDisc func() |
| 37 | + |
| 38 | + mu sync.Mutex |
| 39 | + clients map[*websocket.Conn]*clientFilter |
| 40 | + pending bool |
| 41 | +} |
| 42 | + |
| 43 | +// NewEventHub creates a new event notification hub. |
| 44 | +func NewEventHub(repo *storage.Repository, onConnect, onDisconnect func()) *EventHub { |
| 45 | + return &EventHub{ |
| 46 | + repo: repo, |
| 47 | + onConn: onConnect, |
| 48 | + onDisc: onDisconnect, |
| 49 | + clients: make(map[*websocket.Conn]*clientFilter), |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +// Start begins the periodic flush loop. Call in a goroutine. |
| 54 | +func (h *EventHub) Start(ctx context.Context, interval time.Duration) { |
| 55 | + ticker := time.NewTicker(interval) |
| 56 | + defer ticker.Stop() |
| 57 | + for { |
| 58 | + select { |
| 59 | + case <-ctx.Done(): |
| 60 | + return |
| 61 | + case <-ticker.C: |
| 62 | + h.flush() |
| 63 | + } |
| 64 | + } |
| 65 | +} |
| 66 | + |
| 67 | +// NotifyRefresh marks that new data has arrived. The actual broadcast |
| 68 | +// happens on the next ticker flush to debounce rapid ingestion bursts. |
| 69 | +func (h *EventHub) NotifyRefresh() { |
| 70 | + h.mu.Lock() |
| 71 | + h.pending = true |
| 72 | + h.mu.Unlock() |
| 73 | +} |
| 74 | + |
| 75 | +// HandleWebSocket upgrades an HTTP request to a WebSocket connection, |
| 76 | +// registers it as an event client, and listens for filter messages. |
| 77 | +func (h *EventHub) HandleWebSocket(w http.ResponseWriter, r *http.Request) { |
| 78 | + conn, err := websocket.Accept(w, r, &websocket.AcceptOptions{ |
| 79 | + InsecureSkipVerify: true, |
| 80 | + }) |
| 81 | + if err != nil { |
| 82 | + slog.Error("Event WS accept failed", "error", err) |
| 83 | + return |
| 84 | + } |
| 85 | + |
| 86 | + // Check for initial service filter from query params |
| 87 | + initialService := r.URL.Query().Get("service") |
| 88 | + h.addClient(conn, initialService) |
| 89 | + |
| 90 | + // Send immediate snapshot so the client has data right away |
| 91 | + h.sendSnapshotTo(conn, initialService) |
| 92 | + |
| 93 | + // Read loop: client can send {"service":"xxx"} to change filter |
| 94 | + for { |
| 95 | + _, msg, readErr := conn.Read(r.Context()) |
| 96 | + if readErr != nil { |
| 97 | + break |
| 98 | + } |
| 99 | + var filterMsg struct { |
| 100 | + Service string `json:"service"` |
| 101 | + } |
| 102 | + if json.Unmarshal(msg, &filterMsg) == nil { |
| 103 | + h.updateClientFilter(conn, filterMsg.Service) |
| 104 | + } |
| 105 | + } |
| 106 | + |
| 107 | + h.removeClient(conn) |
| 108 | + conn.Close(websocket.StatusNormalClosure, "bye") |
| 109 | +} |
| 110 | + |
| 111 | +func (h *EventHub) addClient(c *websocket.Conn, service string) { |
| 112 | + h.mu.Lock() |
| 113 | + h.clients[c] = &clientFilter{service: service} |
| 114 | + h.mu.Unlock() |
| 115 | + if h.onConn != nil { |
| 116 | + h.onConn() |
| 117 | + } |
| 118 | +} |
| 119 | + |
| 120 | +func (h *EventHub) removeClient(c *websocket.Conn) { |
| 121 | + h.mu.Lock() |
| 122 | + delete(h.clients, c) |
| 123 | + h.mu.Unlock() |
| 124 | + if h.onDisc != nil { |
| 125 | + h.onDisc() |
| 126 | + } |
| 127 | +} |
| 128 | + |
| 129 | +func (h *EventHub) updateClientFilter(c *websocket.Conn, service string) { |
| 130 | + h.mu.Lock() |
| 131 | + if cf, ok := h.clients[c]; ok { |
| 132 | + cf.service = service |
| 133 | + } |
| 134 | + h.mu.Unlock() |
| 135 | +} |
| 136 | + |
| 137 | +// flush computes per-service snapshots and pushes to matching clients. |
| 138 | +func (h *EventHub) flush() { |
| 139 | + h.mu.Lock() |
| 140 | + if !h.pending { |
| 141 | + h.mu.Unlock() |
| 142 | + return |
| 143 | + } |
| 144 | + h.pending = false |
| 145 | + |
| 146 | + if len(h.clients) == 0 { |
| 147 | + h.mu.Unlock() |
| 148 | + return |
| 149 | + } |
| 150 | + |
| 151 | + // Group clients by service filter |
| 152 | + groups := make(map[string][]*websocket.Conn) |
| 153 | + for c, cf := range h.clients { |
| 154 | + groups[cf.service] = append(groups[cf.service], c) |
| 155 | + } |
| 156 | + h.mu.Unlock() |
| 157 | + |
| 158 | + // Compute one snapshot per unique filter, push to matching clients |
| 159 | + for service, clients := range groups { |
| 160 | + snapshot := h.computeSnapshot(service) |
| 161 | + if snapshot == nil { |
| 162 | + continue |
| 163 | + } |
| 164 | + msg, err := json.Marshal(snapshot) |
| 165 | + if err != nil { |
| 166 | + slog.Error("Event WS marshal failed", "error", err) |
| 167 | + continue |
| 168 | + } |
| 169 | + |
| 170 | + for _, conn := range clients { |
| 171 | + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) |
| 172 | + if err := conn.Write(ctx, websocket.MessageText, msg); err != nil { |
| 173 | + slog.Debug("Event WS send failed, removing client", "error", err) |
| 174 | + h.removeClient(conn) |
| 175 | + conn.Close(websocket.StatusGoingAway, "write error") |
| 176 | + } |
| 177 | + cancel() |
| 178 | + } |
| 179 | + } |
| 180 | +} |
| 181 | + |
| 182 | +// sendSnapshotTo sends a snapshot to a single client. |
| 183 | +func (h *EventHub) sendSnapshotTo(conn *websocket.Conn, service string) { |
| 184 | + snapshot := h.computeSnapshot(service) |
| 185 | + if snapshot == nil { |
| 186 | + return |
| 187 | + } |
| 188 | + msg, err := json.Marshal(snapshot) |
| 189 | + if err != nil { |
| 190 | + return |
| 191 | + } |
| 192 | + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) |
| 193 | + defer cancel() |
| 194 | + conn.Write(ctx, websocket.MessageText, msg) |
| 195 | +} |
| 196 | + |
| 197 | +// computeSnapshot queries the DB for the last 15 minutes of data, |
| 198 | +// optionally filtered by a single service name. |
| 199 | +func (h *EventHub) computeSnapshot(service string) *LiveSnapshot { |
| 200 | + now := time.Now() |
| 201 | + start := now.Add(-15 * time.Minute) |
| 202 | + |
| 203 | + var serviceNames []string |
| 204 | + if service != "" { |
| 205 | + serviceNames = []string{service} |
| 206 | + } |
| 207 | + |
| 208 | + snapshot := &LiveSnapshot{Type: "live_snapshot"} |
| 209 | + |
| 210 | + if stats, err := h.repo.GetDashboardStats(start, now, serviceNames); err == nil { |
| 211 | + snapshot.Dashboard = stats |
| 212 | + } |
| 213 | + |
| 214 | + if traffic, err := h.repo.GetTrafficMetrics(start, now, serviceNames); err == nil { |
| 215 | + snapshot.Traffic = traffic |
| 216 | + } |
| 217 | + |
| 218 | + if traces, err := h.repo.GetTracesFiltered(start, now, serviceNames, "", "", 25, 0, "timestamp", "desc"); err == nil { |
| 219 | + snapshot.Traces = traces |
| 220 | + } |
| 221 | + |
| 222 | + if smap, err := h.repo.GetServiceMapMetrics(start, now); err == nil { |
| 223 | + snapshot.ServiceMap = smap |
| 224 | + } |
| 225 | + |
| 226 | + return snapshot |
| 227 | +} |
0 commit comments