forked from antage/eventsource
-
Notifications
You must be signed in to change notification settings - Fork 0
/
eventsource.go
248 lines (210 loc) · 5.35 KB
/
eventsource.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
package eventsource
import (
"bytes"
"container/list"
"fmt"
"log"
"net/http"
"strings"
"sync"
"time"
)
type eventMessage struct {
id string
event string
data string
}
type retryMessage struct {
retry time.Duration
}
type eventSource struct {
customHeadersFunc func(*http.Request) [][]byte
sink chan message
staled chan *consumer
add chan *consumer
close chan bool
idleTimeout time.Duration
retry time.Duration
timeout time.Duration
closeOnTimeout bool
gzip bool
consumersLock sync.RWMutex
consumers *list.List
}
type Settings struct {
// SetTimeout sets the write timeout for individual messages. The
// default is 2 seconds.
Timeout time.Duration
// CloseOnTimeout sets whether a write timeout should close the
// connection or just drop the message.
//
// If the connection gets closed on a timeout, it's the client's
// responsibility to re-establish a connection. If the connection
// doesn't get closed, messages might get sent to a potentially dead
// client.
//
// The default is true.
CloseOnTimeout bool
// Sets the timeout for an idle connection. The default is 30 minutes.
IdleTimeout time.Duration
// Gzip sets whether to use gzip Content-Encoding for clients which
// support it.
//
// The default is true.
Gzip bool
}
func DefaultSettings() *Settings {
return &Settings{
Timeout: 2 * time.Second,
CloseOnTimeout: true,
IdleTimeout: 30 * time.Minute,
Gzip: true,
}
}
// EventSource interface provides methods for sending messages and closing all connections.
type EventSource interface {
// it should implement ServerHTTP method
http.Handler
// send message to all consumers
SendEventMessage(data, event, id string)
// send retry message to all consumers
SendRetryMessage(duration time.Duration)
// consumers count
ConsumersCount() int
// close and clear all consumers
Close()
}
type message interface {
// The message to be sent to clients
prepareMessage() []byte
}
func (m *eventMessage) prepareMessage() []byte {
var data bytes.Buffer
if len(m.id) > 0 {
data.WriteString(fmt.Sprintf("id: %s\n", strings.Replace(m.id, "\n", "", -1)))
}
if len(m.event) > 0 {
data.WriteString(fmt.Sprintf("event: %s\n", strings.Replace(m.event, "\n", "", -1)))
}
if len(m.data) > 0 {
lines := strings.Split(m.data, "\n")
for _, line := range lines {
data.WriteString(fmt.Sprintf("data: %s\n", line))
}
}
data.WriteString("\n")
return data.Bytes()
}
func controlProcess(es *eventSource) {
for {
select {
case em := <-es.sink:
message := em.prepareMessage()
func() {
es.consumersLock.RLock()
defer es.consumersLock.RUnlock()
for e := es.consumers.Front(); e != nil; e = e.Next() {
c := e.Value.(*consumer)
// Only send this message if the consumer isn't staled
if !c.staled {
select {
case c.in <- message:
default:
}
}
}
}()
case <-es.close:
close(es.sink)
close(es.add)
close(es.staled)
close(es.close)
func() {
es.consumersLock.RLock()
defer es.consumersLock.RUnlock()
for e := es.consumers.Front(); e != nil; e = e.Next() {
c := e.Value.(*consumer)
close(c.in)
}
}()
es.consumersLock.Lock()
defer es.consumersLock.Unlock()
es.consumers.Init()
return
case c := <-es.add:
func() {
es.consumersLock.Lock()
defer es.consumersLock.Unlock()
es.consumers.PushBack(c)
}()
case c := <-es.staled:
toRemoveEls := make([]*list.Element, 0, 1)
func() {
es.consumersLock.RLock()
defer es.consumersLock.RUnlock()
for e := es.consumers.Front(); e != nil; e = e.Next() {
if e.Value.(*consumer) == c {
toRemoveEls = append(toRemoveEls, e)
}
}
}()
func() {
es.consumersLock.Lock()
defer es.consumersLock.Unlock()
for _, e := range toRemoveEls {
es.consumers.Remove(e)
}
}()
close(c.in)
}
}
}
// New creates new EventSource instance.
func New(settings *Settings, customHeadersFunc func(*http.Request) [][]byte) EventSource {
if settings == nil {
settings = DefaultSettings()
}
es := new(eventSource)
es.customHeadersFunc = customHeadersFunc
es.sink = make(chan message, 1)
es.close = make(chan bool)
es.staled = make(chan *consumer, 1)
es.add = make(chan *consumer)
es.consumers = list.New()
es.timeout = settings.Timeout
es.idleTimeout = settings.IdleTimeout
es.closeOnTimeout = settings.CloseOnTimeout
es.gzip = settings.Gzip
go controlProcess(es)
return es
}
func (es *eventSource) Close() {
es.close <- true
}
// ServeHTTP implements http.Handler interface.
func (es *eventSource) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
cons, err := newConsumer(resp, req, es)
if err != nil {
log.Print("Can't create connection to a consumer: ", err)
return
}
es.add <- cons
}
func (es *eventSource) sendMessage(m message) {
es.sink <- m
}
func (es *eventSource) SendEventMessage(data, event, id string) {
em := &eventMessage{id, event, data}
es.sendMessage(em)
}
func (m *retryMessage) prepareMessage() []byte {
return []byte(fmt.Sprintf("retry: %d\n\n", m.retry/time.Millisecond))
}
func (es *eventSource) SendRetryMessage(t time.Duration) {
es.sendMessage(&retryMessage{t})
}
func (es *eventSource) ConsumersCount() int {
es.consumersLock.RLock()
defer es.consumersLock.RUnlock()
return es.consumers.Len()
}