1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
|
package server
import (
"encoding/json"
"fmt"
"log/slog"
"net/http"
"sync"
"time"
)
// SSEHub manages Server-Sent Events connections and broadcasts
type SSEHub struct {
mu sync.RWMutex
clients map[*sseClient]struct{}
logger *slog.Logger
closed bool
closedCh chan struct{}
}
type sseClient struct {
ch chan []byte
doneCh chan struct{}
clientIP string
}
// NewSSEHub creates a new SSE hub for managing client connections
func NewSSEHub(logger *slog.Logger) *SSEHub {
return &SSEHub{
clients: make(map[*sseClient]struct{}),
logger: logger,
closedCh: make(chan struct{}),
}
}
// ServeHTTP handles SSE connections
func (h *SSEHub) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Check if the response writer supports flushing
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "SSE not supported", http.StatusInternalServerError)
return
}
// Set SSE headers
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
w.Header().Set("X-Accel-Buffering", "no") // Disable nginx buffering
// Create client
client := &sseClient{
ch: make(chan []byte, 64), // Buffered to prevent blocking broadcasts
doneCh: make(chan struct{}),
clientIP: r.RemoteAddr,
}
// Register client
h.addClient(client)
defer h.removeClient(client)
h.logger.Debug("SSE client connected", "remote_addr", r.RemoteAddr)
// Send initial connection event
fmt.Fprintf(w, "event: connected\ndata: {\"status\":\"connected\"}\n\n")
flusher.Flush()
// Keepalive ticker (send comment every 30s to keep connection alive)
ticker := time.NewTicker(30 * time.Second)
defer ticker.Stop()
// Stream events to client
for {
select {
case <-r.Context().Done():
h.logger.Debug("SSE client disconnected", "remote_addr", r.RemoteAddr)
return
case <-h.closedCh:
// Hub is closing
return
case data := <-client.ch:
// Send data event
fmt.Fprintf(w, "event: update\ndata: %s\n\n", data)
flusher.Flush()
case <-ticker.C:
// Send keepalive comment (not an event, just keeps connection alive)
fmt.Fprintf(w, ": keepalive\n\n")
flusher.Flush()
}
}
}
// Broadcast sends data to all connected clients
func (h *SSEHub) Broadcast(data any) {
h.mu.RLock()
if h.closed {
h.mu.RUnlock()
return
}
clientCount := len(h.clients)
if clientCount == 0 {
h.mu.RUnlock()
return
}
// Marshal data to JSON
jsonData, err := json.Marshal(data)
if err != nil {
h.mu.RUnlock()
h.logger.Error("failed to marshal SSE broadcast data", "error", err)
return
}
// Send to all clients (non-blocking)
for client := range h.clients {
select {
case client.ch <- jsonData:
// Sent successfully
default:
// Client buffer full, skip this update
h.logger.Debug("SSE client buffer full, skipping update", "remote_addr", client.clientIP)
}
}
h.mu.RUnlock()
h.logger.Debug("SSE broadcast sent", "clients", clientCount, "bytes", len(jsonData))
}
// ClientCount returns the number of connected clients
func (h *SSEHub) ClientCount() int {
h.mu.RLock()
defer h.mu.RUnlock()
return len(h.clients)
}
// Close shuts down the hub and disconnects all clients
func (h *SSEHub) Close() {
h.mu.Lock()
defer h.mu.Unlock()
if h.closed {
return
}
h.closed = true
close(h.closedCh)
// Close all client channels
for client := range h.clients {
close(client.doneCh)
}
h.clients = nil
h.logger.Info("SSE hub closed")
}
func (h *SSEHub) addClient(client *sseClient) {
h.mu.Lock()
defer h.mu.Unlock()
if h.closed {
return
}
h.clients[client] = struct{}{}
h.logger.Debug("SSE client registered", "total_clients", len(h.clients))
}
func (h *SSEHub) removeClient(client *sseClient) {
h.mu.Lock()
defer h.mu.Unlock()
if _, ok := h.clients[client]; ok {
delete(h.clients, client)
close(client.ch)
h.logger.Debug("SSE client unregistered", "total_clients", len(h.clients))
}
}
// SSEPageData is the data structure sent via SSE for page updates
type SSEPageData struct {
Type string `json:"type"` // "init" for initial load, "update" for changes
Monitors map[string]APIMonitorData `json:"monitors"`
OverallStatus string `json:"overall_status"`
Counts StatusCounts `json:"counts"`
LastUpdated time.Time `json:"last_updated"`
// Additional fields for initial load
Groups []SSEGroupData `json:"groups,omitempty"`
Incidents []SSEIncidentData `json:"incidents,omitempty"`
Site *SSESiteData `json:"site,omitempty"`
}
// SSEGroupData contains group info for initial SSE load
type SSEGroupData struct {
Name string `json:"name"`
MonitorIDs []string `json:"monitor_ids"`
DefaultCollapsed bool `json:"default_collapsed"`
ShowGroupUptime bool `json:"show_group_uptime"`
GroupUptime float64 `json:"group_uptime"`
}
// SSEIncidentData contains incident info for SSE
type SSEIncidentData struct {
Title string `json:"title"`
Status string `json:"status"`
Message string `json:"message"`
IsActive bool `json:"is_active"`
IsScheduled bool `json:"is_scheduled"`
ScheduledStart *time.Time `json:"scheduled_start,omitempty"`
ScheduledEnd *time.Time `json:"scheduled_end,omitempty"`
CreatedAt *time.Time `json:"created_at,omitempty"`
}
// SSESiteData contains site info for initial SSE load
type SSESiteData struct {
Name string `json:"name"`
Description string `json:"description"`
}
|