forked from HuaweiTech/lattice
-
Notifications
You must be signed in to change notification settings - Fork 0
/
event_source.go
218 lines (170 loc) · 4.38 KB
/
event_source.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
package sse
import (
"fmt"
"io"
"net/http"
"sync"
"time"
)
type BadResponseError struct {
Response *http.Response
}
func (err BadResponseError) Error() string {
return fmt.Sprintf("bad response from event source: %s", err.Response.Status)
}
// EventSource behaves like the EventSource interface from the Server-Sent
// Events spec implemented in many browsers. See
// http://www.w3.org/TR/eventsource/#the-eventsource-interface for details.
//
// To use, optionally call Connect(), and then call Next(). If Next() is called
// prior to Connect(), it will connect for you.
//
// Next() is often called asynchronously in a loop so that the event source can
// be closed. Next() will block on reading from the server.
//
// If Close() is called while reading an event, Next() will return early, and
// subsequent calls to Next() will return early. To read new events, Connect()
// must be called.
//
// If an EOF is received, Next() returns io.EOF, and subsequent calls to Next()
// will return early. To read new events, Connect() must be called.
type EventSource struct {
client *http.Client
createRequest func() *http.Request
currentReadCloser *ReadCloser
lastEventID string
retryInterval time.Duration
lock sync.Mutex
closeOnce *sync.Once
closed chan struct{}
}
func NewEventSource(client *http.Client, defaultRetryInterval time.Duration, requestCreator func() *http.Request) *EventSource {
return &EventSource{
client: client,
createRequest: requestCreator,
retryInterval: defaultRetryInterval,
closeOnce: new(sync.Once),
closed: make(chan struct{}),
}
}
func Connect(client *http.Client, defaultRetryInterval time.Duration, requestCreator func() *http.Request) (*EventSource, error) {
source := NewEventSource(client, defaultRetryInterval, requestCreator)
readCloser, err := source.establishConnection()
if err != nil {
return nil, err
}
source.currentReadCloser = readCloser
return source, nil
}
func (source *EventSource) Next() (Event, error) {
select {
case <-source.closed:
return Event{}, ErrSourceClosed
default:
}
for {
readCloser, err := source.ensureReadCloser()
if err != nil {
return Event{}, err
}
event, err := readCloser.Next()
if err == nil {
source.lastEventID = event.ID
if event.Retry != 0 {
source.retryInterval = event.Retry
}
return event, nil
}
if err == io.EOF {
return Event{}, err
}
readCloser.Close()
if err := source.waitForRetry(); err != nil {
return Event{}, err
}
}
panic("unreachable")
}
func (source *EventSource) Close() error {
source.lock.Lock()
defer source.lock.Unlock()
source.closeOnce.Do(func() {
close(source.closed)
})
if source.currentReadCloser != nil {
err := source.currentReadCloser.Close()
if err != nil {
return err
}
source.currentReadCloser = nil
}
return nil
}
func (source *EventSource) ensureReadCloser() (*ReadCloser, error) {
source.lock.Lock()
if source.currentReadCloser == nil {
source.lock.Unlock()
newReadCloser, err := source.establishConnection()
if err != nil {
return nil, err
}
source.lock.Lock()
select {
case <-source.closed:
source.lock.Unlock()
newReadCloser.Close()
return nil, ErrSourceClosed
default:
source.currentReadCloser = newReadCloser
}
}
readCloser := source.currentReadCloser
source.lock.Unlock()
return readCloser, nil
}
func (source *EventSource) establishConnection() (*ReadCloser, error) {
for {
req := source.createRequest()
req.Header.Set("Last-Event-ID", source.lastEventID)
res, err := source.client.Do(req)
if err != nil {
err := source.waitForRetry()
if err != nil {
return nil, err
}
continue
}
switch res.StatusCode {
case http.StatusOK:
return NewReadCloser(res.Body), nil
// reestablish the connection
case http.StatusInternalServerError,
http.StatusBadGateway,
http.StatusServiceUnavailable,
http.StatusGatewayTimeout:
res.Body.Close()
err := source.waitForRetry()
if err != nil {
return nil, err
}
continue
// fail the connection
default:
res.Body.Close()
return nil, BadResponseError{
Response: res,
}
}
}
}
func (source *EventSource) waitForRetry() error {
source.lock.Lock()
source.currentReadCloser = nil
source.lock.Unlock()
select {
case <-time.After(source.retryInterval):
return nil
case <-source.closed:
return ErrSourceClosed
}
}