|
| 1 | +package server |
| 2 | + |
| 3 | +import ( |
| 4 | + "io" |
| 5 | + "net/http" |
| 6 | + "sync" |
| 7 | + |
| 8 | + polochon "github.com/odwrtw/polochon/lib" |
| 9 | + "github.com/sirupsen/logrus" |
| 10 | +) |
| 11 | + |
| 12 | +const sseModuleName = "sse" |
| 13 | + |
| 14 | +// Compile-time assertion. |
| 15 | +var _ polochon.Notifier = (*sseHub)(nil) |
| 16 | + |
| 17 | +type sseHub struct { |
| 18 | + mu sync.Mutex |
| 19 | + clients map[chan struct{}]struct{} |
| 20 | +} |
| 21 | + |
| 22 | +func newSSEHub() *sseHub { |
| 23 | + return &sseHub{ |
| 24 | + clients: make(map[chan struct{}]struct{}), |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +// Module interface. |
| 29 | +func (h *sseHub) Init(_ []byte) error { return nil } |
| 30 | +func (h *sseHub) Name() string { return sseModuleName } |
| 31 | +func (h *sseHub) Status() (polochon.ModuleStatus, error) { return polochon.StatusOK, nil } |
| 32 | + |
| 33 | +// Notifier interface. |
| 34 | +func (h *sseHub) Notify(_ any, _ *logrus.Entry) error { |
| 35 | + h.broadcast() |
| 36 | + return nil |
| 37 | +} |
| 38 | + |
| 39 | +func (h *sseHub) subscribe() chan struct{} { |
| 40 | + ch := make(chan struct{}, 1) |
| 41 | + h.mu.Lock() |
| 42 | + h.clients[ch] = struct{}{} |
| 43 | + h.mu.Unlock() |
| 44 | + return ch |
| 45 | +} |
| 46 | + |
| 47 | +func (h *sseHub) unsubscribe(ch chan struct{}) { |
| 48 | + h.mu.Lock() |
| 49 | + delete(h.clients, ch) |
| 50 | + h.mu.Unlock() |
| 51 | + close(ch) |
| 52 | +} |
| 53 | + |
| 54 | +func (h *sseHub) broadcast() { |
| 55 | + h.mu.Lock() |
| 56 | + defer h.mu.Unlock() |
| 57 | + for ch := range h.clients { |
| 58 | + // Non-blocking send to coalesce duplicate events. |
| 59 | + select { |
| 60 | + case ch <- struct{}{}: |
| 61 | + default: |
| 62 | + } |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +func (s *Server) events(w http.ResponseWriter, r *http.Request) { |
| 67 | + flusher, ok := w.(http.Flusher) |
| 68 | + if !ok { |
| 69 | + http.Error(w, "streaming not supported", http.StatusInternalServerError) |
| 70 | + return |
| 71 | + } |
| 72 | + |
| 73 | + ch := s.hub.subscribe() |
| 74 | + defer s.hub.unsubscribe(ch) |
| 75 | + |
| 76 | + w.Header().Set("Content-Type", "text/event-stream") |
| 77 | + w.Header().Set("Cache-Control", "no-cache") |
| 78 | + w.Header().Set("Connection", "keep-alive") |
| 79 | + flusher.Flush() |
| 80 | + |
| 81 | + for { |
| 82 | + select { |
| 83 | + case <-ch: |
| 84 | + _, _ = io.WriteString(w, "data:\n\n") |
| 85 | + flusher.Flush() |
| 86 | + case <-r.Context().Done(): |
| 87 | + return |
| 88 | + } |
| 89 | + } |
| 90 | +} |
0 commit comments