-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler.go
242 lines (206 loc) · 5.44 KB
/
handler.go
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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
package sse
import (
"encoding/json"
"errors"
"fmt"
"iter"
"net/http"
"time"
"github.com/softwarespot/replay"
)
type empty struct{}
// Handler is a generic Server-Sent Events (SSE) handler.
type Handler[T any] struct {
cfg *Config[T]
closingCh chan empty
completeCh chan empty
clientRegisterCh chan chan []T
clientUnregisterCh chan chan []T
clientEvtsChs map[chan []T]empty
evtsReplay *replay.Replay[T]
evtsCh chan []T
evtsEncoder func([]T) ([]byte, error)
}
// New initializes a Server-Sent Events (SSE) handler, with an optional configuration.
// If the provided configuration is nil, then it uses the default configuration.
func New[T any](cfg *Config[T]) *Handler[T] {
if cfg == nil {
cfg = NewConfig[T]()
}
h := &Handler[T]{
cfg: cfg,
closingCh: make(chan empty),
completeCh: make(chan empty),
clientRegisterCh: make(chan chan []T),
clientUnregisterCh: make(chan chan []T),
clientEvtsChs: map[chan []T]empty{},
evtsReplay: replay.New[T](cfg.Replay.Maximum, cfg.Replay.Expiry),
evtsCh: make(chan []T),
evtsEncoder: defaultEventsEncoder[T],
}
if h.cfg.Encoder != nil {
h.evtsEncoder = h.cfg.Encoder
}
go h.start()
return h
}
func (h *Handler[T]) start() {
flushTicker := time.NewTicker(h.cfg.FlushFrequency)
defer flushTicker.Stop()
var (
isClosing bool
cleanup = func() bool {
isCleanable := isClosing && len(h.clientEvtsChs) == 0
if !isCleanable {
return false
}
close(h.clientRegisterCh)
close(h.clientUnregisterCh)
close(h.evtsCh)
close(h.completeCh)
return true
}
flushableEvts []T
)
for {
select {
case <-h.closingCh:
isClosing = true
if cleanup() {
return
}
case clientEvtsCh := <-h.clientRegisterCh:
h.clientEvtsChs[clientEvtsCh] = empty{}
for evts := range h.replayedEvents() {
clientEvtsCh <- evts
}
case clientEvtsCh := <-h.clientUnregisterCh:
close(clientEvtsCh)
delete(h.clientEvtsChs, clientEvtsCh)
if cleanup() {
return
}
case evts := <-h.evtsCh:
flushableEvts = append(flushableEvts, evts...)
case <-flushTicker.C:
if len(flushableEvts) == 0 {
break
}
for clientEvtsCh := range h.clientEvtsChs {
clientEvtsCh <- flushableEvts
}
h.evtsReplay.Add(flushableEvts...)
flushableEvts = nil
}
}
}
// Close closes the Server-Sent Events (SSE) handler.
// It waits for all the clients to close/complete, with a timeout defined in the configuration.
func (h *Handler[T]) Close() error {
if h.isClosing() {
return errors.New("sse-handler: handler is closed")
}
h.closingCh <- empty{}
close(h.closingCh)
// Wait for all the clients to close/complete or on timeout
select {
case <-h.completeCh:
h.evtsReplay.Clear()
return nil
case <-time.After(h.cfg.CloseTimeout):
return errors.New("sse-handler: timeout waiting for clients to close")
}
}
func (h *Handler[T]) isClosing() bool {
select {
case <-h.closingCh:
return true
case <-h.completeCh:
return true
default:
return false
}
}
// ServeHTTP implements the http.Handler interface for the Server-Sent Events (SSE) handler.
// It calls ServeSSE and handles any errors by writing an HTTP error response with status code 500.
func (h *Handler[T]) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if err := h.ServeSSE(w, r); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
// ServeSSE serves the Server-Sent Events (SSE) to the HTTP response writer.
// It sets the appropriate headers and streams events to the client until the connection is closed.
func (h *Handler[T]) ServeSSE(w http.ResponseWriter, r *http.Request) error {
flusher, ok := w.(http.Flusher)
if !ok {
return errors.New("sse-handler: not supported")
}
if h.isClosing() {
return errors.New("sse-handler: handler is closed")
}
hdrs := w.Header()
hdrs.Set("Content-Type", "text/event-stream")
hdrs.Set("Cache-Control", "no-cache")
hdrs.Set("Connection", "keep-alive")
clientEvtsCh := h.register()
defer h.unregister(clientEvtsCh)
for {
select {
case <-r.Context().Done():
return nil
case <-h.closingCh:
return nil
case evts := <-clientEvtsCh:
data, err := h.evtsEncoder(evts)
if err != nil {
return err
}
if _, err := fmt.Fprintf(w, "data: %s\n\n", data); err != nil {
return fmt.Errorf("sse-handler: unable to write events: %w", err)
}
flusher.Flush()
}
}
}
func (h *Handler[T]) register() chan []T {
clientEvtsCh := make(chan []T)
h.clientRegisterCh <- clientEvtsCh
return clientEvtsCh
}
func (h *Handler[T]) unregister(clientEvtsCh chan []T) {
h.clientUnregisterCh <- clientEvtsCh
}
func (h *Handler[T]) replayedEvents() iter.Seq[[]T] {
return func(yield func([]T) bool) {
chunk := make([]T, 0, h.cfg.Replay.Initial)
for evt := range h.evtsReplay.All() {
chunk = append(chunk, evt)
if len(chunk) == h.cfg.Replay.Initial {
if !yield(chunk) {
return
}
// Reset the underlying array, so the length is 0
chunk = chunk[:0]
}
}
if len(chunk) > 0 {
yield(chunk)
}
}
}
// Broadcast broadcasts one or more events to all the connected clients.
// It returns an error if the handler is closed.
func (h *Handler[T]) Broadcast(evts ...T) error {
if h.isClosing() {
return errors.New("sse-handler: handler is closed")
}
h.evtsCh <- evts
return nil
}
func defaultEventsEncoder[T any](evts []T) ([]byte, error) {
b, err := json.Marshal(evts)
if err != nil {
return nil, fmt.Errorf("sse-handler: unable to encode events: %w", err)
}
return b, nil
}