forked from donovanhide/eventsource
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathserver.go
356 lines (327 loc) · 11.5 KB
/
server.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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
package eventsource
import (
"net/http"
"strings"
"sync"
"time"
)
type subscription struct {
channel string
lastEventID string
out chan<- eventOrComment
}
type eventOrComment interface{}
type outbound struct {
channels []string
eventOrComment eventOrComment
ackCh chan<- struct{}
}
type registration struct {
channel string
repository Repository
}
type unregistration struct {
channel string
forceDisconnect bool
}
type comment struct {
value string
}
type eventBatch struct {
events <-chan Event
}
// Server manages any number of event-publishing channels and allows subscribers to consume them.
// To use it within an HTTP server, create a handler for each channel with Handler().
type Server struct {
AllowCORS bool // Enable all handlers to be accessible from any origin
ReplayAll bool // Replay repository even if there's no Last-Event-Id specified
BufferSize int // How many messages do we let the client get behind before disconnecting
Gzip bool // Enable compression if client can accept it
MaxConnTime time.Duration // If non-zero, HTTP connections will be automatically closed after this time
Logger Logger // Logger is a logger that, when set, will be used for logging debug messages
registrations chan *registration
unregistrations chan *unregistration
pub chan *outbound
subs chan *subscription
unsubs chan *subscription
quit chan bool
isClosed bool
isClosedMutex sync.RWMutex
}
// NewServer creates a new Server instance.
func NewServer() *Server {
srv := &Server{
registrations: make(chan *registration),
unregistrations: make(chan *unregistration),
pub: make(chan *outbound),
subs: make(chan *subscription),
unsubs: make(chan *subscription, 2),
quit: make(chan bool),
BufferSize: 128,
}
go srv.run()
return srv
}
// Close permanently shuts down the Server. It will no longer allow new subscriptions.
func (srv *Server) Close() {
srv.quit <- true
srv.markServerClosed()
}
// Handler creates a new HTTP handler for serving a specified channel.
//
// The channel does not have to have been previously registered with Register, but if it has been, the
// handler may replay events from the registered Repository depending on the setting of server.ReplayAll
// and the Last-Event-Id header of the request.
func (srv *Server) Handler(channel string) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
h := w.Header()
h.Set("Content-Type", "text/event-stream; charset=utf-8")
h.Set("Cache-Control", "no-cache, no-store, must-revalidate")
h.Set("Connection", "keep-alive")
if srv.AllowCORS {
h.Set("Access-Control-Allow-Origin", "*")
}
useGzip := srv.Gzip && strings.Contains(req.Header.Get("Accept-Encoding"), "gzip")
if useGzip {
h.Set("Content-Encoding", "gzip")
}
w.WriteHeader(http.StatusOK)
// If the Handler is still active even though the server is closed, stop here.
// Otherwise the Handler will block while publishing to srv.subs indefinitely.
if srv.isServerClosed() {
return
}
var maxConnTimeCh <-chan time.Time
if srv.MaxConnTime > 0 {
t := time.NewTimer(srv.MaxConnTime)
defer t.Stop()
maxConnTimeCh = t.C
}
eventCh := make(chan eventOrComment, srv.BufferSize)
sub := &subscription{
channel: channel,
lastEventID: req.Header.Get("Last-Event-ID"),
out: eventCh,
}
srv.subs <- sub
flusher := w.(http.Flusher)
flusher.Flush()
enc := NewEncoder(w, useGzip)
writeEventOrComment := func(ec eventOrComment) bool {
if err := enc.Encode(ec); err != nil {
srv.unsubs <- sub
if srv.Logger != nil {
srv.Logger.Println(err)
}
return false // if this happens, we'll end the handler early because something's clearly broken
}
flusher.Flush()
return true
}
// The logic below works as follows:
// - Normally, the handler is reading from eventCh. Server.run() accesses this channel through sub.out
// and sends published events to it.
// - However, if a Repository is being used, the Server might get a whole batch of events that the
// Repository provides through its Replay method. The Repository provides these in the form of a
// channel that it writes to. Since we don't know how many events there will be or how long it will
// take to write them, we do not want to block Server.run() for this.
// - Previous implementations of sending events from Replay used a separate goroutine. That was unsafe,
// due to a race condition where Server.run() might close the channel while the Replay goroutine is
// still writing to it.
// - So, instead, Server.run() now takes the channel from Replay and wraps it in an eventBatch. When
// the handler sees an eventBatch, it switches over to reading events from that channel until the
// channel is closed. Then it switches back to reading events from the regular channel.
// - The Server can close eventCh at any time to indicate that the stream is done. The handler exits.
// - If the client closes the connection, or if MaxConnTime elapses, the handler exits after telling
// the Server to stop publishing events to it.
var readMainCh <-chan eventOrComment = eventCh
var readBatchCh <-chan Event
closedNormally := false
closeNotify := req.Context().Done()
ReadLoop:
for {
select {
case <-closeNotify:
break ReadLoop
case <-maxConnTimeCh: // if MaxConnTime was not set, this is a nil channel and has no effect on the select
break ReadLoop
case ev, ok := <-readMainCh:
if !ok {
closedNormally = true
break ReadLoop
}
if batch, ok := ev.(eventBatch); ok {
readBatchCh = batch.events
readMainCh = nil
} else if !writeEventOrComment(ev) {
break ReadLoop
}
case ev, ok := <-readBatchCh:
if !ok { // end of batch
readBatchCh = nil
readMainCh = eventCh
} else if !writeEventOrComment(ev) {
break ReadLoop
}
}
}
if !closedNormally {
srv.unsubs <- sub // the server didn't tell us to close, so we must tell it that we're closing
}
}
}
// Register registers a Repository to be used for the specified channel. The Repository will be used to
// determine whether new subscribers should receive data that was generated before they subscribed.
//
// Channels do not have to be registered unless you want to specify a Repository. An unregistered channel can
// still be subscribed to with Handler, and published to with Publish.
func (srv *Server) Register(channel string, repo Repository) {
srv.registrations <- ®istration{
channel: channel,
repository: repo,
}
}
// Unregister removes a channel registration that was created by Register. If forceDisconnect is true, it also
// causes all currently active handlers for that channel to close their connections. If forceDisconnect is false,
// those connections will remain open until closed by their clients but will not receive any more events.
//
// This will not prevent creating new channel subscriptions for the same channel with Handler, or publishing
// events to that channel with Publish. It is the caller's responsibility to avoid using channels that are no
// longer supposed to be used.
func (srv *Server) Unregister(channel string, forceDisconnect bool) {
srv.unregistrations <- &unregistration{
channel: channel,
forceDisconnect: forceDisconnect,
}
}
// Publish publishes an event to one or more channels.
func (srv *Server) Publish(channels []string, ev Event) {
srv.pub <- &outbound{
channels: channels,
eventOrComment: ev,
}
}
// PublishWithAcknowledgment publishes an event to one or more channels, returning a channel that will receive
// a value after the event has been processed by the server.
//
// This can be used to ensure a well-defined ordering of operations. Since each Server method is handled
// asynchronously via a separate channel, if you call server.Publish and then immediately call server.Close,
// there is no guarantee that the server execute the Close operation only after the event has been published.
// If you instead call PublishWithAcknowledgement, and then read from the returned channel before calling
// Close, you can be sure that the event was published before the server was closed.
func (srv *Server) PublishWithAcknowledgment(channels []string, ev Event) <-chan struct{} {
ackCh := make(chan struct{}, 1)
srv.pub <- &outbound{
channels: channels,
eventOrComment: ev,
ackCh: ackCh,
}
return ackCh
}
// PublishComment publishes a comment to one or more channels.
func (srv *Server) PublishComment(channels []string, text string) {
srv.pub <- &outbound{
channels: channels,
eventOrComment: comment{value: text},
}
}
func (srv *Server) run() {
// All access to the subs and repos maps is done from the same goroutine, so modifications are safe.
subs := make(map[string]map[*subscription]struct{})
repos := make(map[string]Repository)
trySend := func(sub *subscription, ec eventOrComment) {
if !sub.send(ec) {
sub.close()
delete(subs[sub.channel], sub)
}
}
for {
select {
case reg := <-srv.registrations:
repos[reg.channel] = reg.repository
case unreg := <-srv.unregistrations:
delete(repos, unreg.channel)
previousSubs := subs[unreg.channel]
delete(subs, unreg.channel)
if unreg.forceDisconnect {
for s := range previousSubs {
s.close()
}
}
case sub := <-srv.unsubs:
delete(subs[sub.channel], sub)
case pub := <-srv.pub:
for _, c := range pub.channels {
for s := range subs[c] {
trySend(s, pub.eventOrComment)
}
}
if pub.ackCh != nil {
select {
// It shouldn't be possible for this channel to block since it is created for a single use, but
// we'll do a non-blocking push just to be safe
case pub.ackCh <- struct{}{}:
default:
}
}
case sub := <-srv.subs:
if _, ok := subs[sub.channel]; !ok {
subs[sub.channel] = make(map[*subscription]struct{})
}
subs[sub.channel][sub] = struct{}{}
if srv.ReplayAll || len(sub.lastEventID) > 0 {
repo, ok := repos[sub.channel]
if ok {
batchCh := repo.Replay(sub.channel, sub.lastEventID)
if batchCh != nil {
trySend(sub, eventBatch{events: batchCh})
}
}
}
case <-srv.quit:
for _, sub := range subs {
for s := range sub {
s.close()
}
}
return
}
}
}
func (srv *Server) isServerClosed() bool {
srv.isClosedMutex.RLock()
defer srv.isClosedMutex.RUnlock()
return srv.isClosed
}
func (srv *Server) markServerClosed() {
srv.isClosedMutex.Lock()
defer srv.isClosedMutex.Unlock()
srv.isClosed = true
}
// Attempts to send an event or comment to the subscription's channel.
//
// We do not want to block the main Server goroutine, so this is a non-blocking send. If it fails,
// we return false to tell the Server that the subscriber has fallen behind and should be removed;
// we also immediately close the channel in that case. If the send succeeds-- or if we didn't need
// to attempt a send, because the channel was already closed-- we return true.
//
// This should be called only from the Server.run() goroutine.
func (s *subscription) send(e eventOrComment) bool {
if s.out == nil {
return true
}
select {
case s.out <- e:
return true
default:
s.close()
return false
}
}
// Closes a subscription's channel and sets it to nil.
//
// This should be called only from the Server.run() goroutine.
func (s *subscription) close() {
close(s.out)
s.out = nil
}