forked from koding/kite
/
xhr.go
262 lines (210 loc) · 5.39 KB
/
xhr.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
package sockjsclient
import (
"bufio"
"bytes"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/http/cookiejar"
"sync"
)
// the implementation of New() doesn't have any error to be returned yet it
// returns, so it's totally safe to neglect the error
var cookieJar, _ = cookiejar.New(nil)
type XHRSession struct {
mu sync.Mutex
client *http.Client
sessionURL string
sessionID string
messages []string
abort chan struct{}
opened bool
closed bool
}
// NewXHRSession returns a new XHRSession, a SockJS client which supports
// xhr-polling
// http://sockjs.github.io/sockjs-protocol/sockjs-protocol-0.3.3.html#section-74
func NewXHRSession(opts *DialOptions) (*XHRSession, error) {
client := opts.Client()
// following /server_id/session_id should always be the same for every session
serverID := threeDigits()
sessionID := randomStringLength(20)
sessionURL := opts.BaseURL + "/" + serverID + "/" + sessionID
// start the initial session handshake
sessionResp, err := client.Post(sessionURL+"/xhr", "text/plain", nil)
if err != nil {
return nil, err
}
defer sessionResp.Body.Close()
if sessionResp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("Starting new session failed. Want: %d Got: %d",
http.StatusOK, sessionResp.StatusCode)
}
buf := bufio.NewReader(sessionResp.Body)
frame, err := buf.ReadByte()
if err != nil {
return nil, err
}
if frame != 'o' {
return nil, fmt.Errorf("can't start session, invalid frame: %s", frame)
}
return &XHRSession{
client: client,
sessionID: sessionID,
sessionURL: sessionURL,
opened: true,
abort: make(chan struct{}, 1),
}, nil
}
func (x *XHRSession) ID() string {
return x.sessionID
}
func (x *XHRSession) Recv() (string, error) {
type requestCanceler interface {
CancelRequest(*http.Request)
}
// Return previously received messages if there is any.
if len(x.messages) > 0 {
msg := x.messages[0]
x.messages = x.messages[1:]
return msg, nil
}
if x.isClosed() {
return "", ErrSessionClosed
}
// start to poll from the server until we receive something
for {
req, err := http.NewRequest("POST", x.sessionURL+"/xhr", nil)
if err != nil {
return "", fmt.Errorf("Receiving data failed: %s", err)
}
req.Header.Set("Content-Type", "text/plain")
select {
case <-x.abort:
if cn, ok := x.client.Transport.(requestCanceler); ok {
cn.CancelRequest(req)
}
return "", fmt.Errorf("session aborted by server")
case res := <-x.do(req):
if res.Error != nil {
return "", fmt.Errorf("Receiving data failed: %s", res.Error)
}
msg, ok, err := x.handleResp(res.Response)
if err != nil {
return "", err
}
if ok {
continue
}
return msg, nil
}
}
}
func (x *XHRSession) handleResp(resp *http.Response) (msg string, again bool, err error) {
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", false, fmt.Errorf("Receiving data failed. Want: %d Got: %d",
http.StatusOK, resp.StatusCode)
}
buf := bufio.NewReader(resp.Body)
// returns an error if buffer is empty
frame, err := buf.ReadByte()
if err != nil {
return "", false, err
}
switch frame {
case 'o':
x.mu.Lock()
x.opened = true
x.mu.Unlock()
return "", true, nil
case 'a':
// received an array of messages
var messages []string
if err := json.NewDecoder(buf).Decode(&messages); err != nil {
return "", false, err
}
x.messages = append(x.messages, messages...)
if len(x.messages) == 0 {
return "", false, errors.New("no message")
}
// Return first message in slice, and remove it from the slice, so
// next time the others will be picked
msg := x.messages[0]
x.messages = x.messages[1:]
return msg, false, nil
case 'h':
// heartbeat received
return "", true, nil
case 'c':
x.mu.Lock()
x.opened = false
x.mu.Unlock()
return "", false, errors.New("session closed")
default:
return "", false, errors.New("invalid frame type")
}
}
func (x *XHRSession) Send(frame string) error {
if !x.isOpened() {
return errors.New("session is not opened yet")
}
if x.isClosed() {
return ErrSessionClosed
}
// Need's to be JSON encoded array of string messages (SockJS protocol
// requirement)
message := []string{frame}
body, err := json.Marshal(&message)
if err != nil {
return err
}
resp, err := x.client.Post(x.sessionURL+"/xhr_send", "text/plain", bytes.NewReader(body))
if err != nil {
return err
}
if resp.StatusCode == http.StatusNotFound {
x.Close(0, "") // invalidate session - see details: sockjs/sockjs-client#66
return fmt.Errorf("XHR session does not exist: %s", x.sessionID)
}
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusNoContent {
return fmt.Errorf("Sending data failed. Want: %d Got: %d",
http.StatusOK, resp.StatusCode)
}
return nil
}
func (x *XHRSession) Close(status uint32, reason string) error {
x.mu.Lock()
x.opened = false
x.closed = true
x.mu.Unlock()
select {
case x.abort <- struct{}{}:
default:
}
return nil
}
func (x *XHRSession) isOpened() bool {
x.mu.Lock()
defer x.mu.Unlock()
return x.opened
}
func (x *XHRSession) isClosed() bool {
x.mu.Lock()
defer x.mu.Unlock()
return x.closed
}
type doResult struct {
Response *http.Response
Error error
}
func (x *XHRSession) do(req *http.Request) <-chan doResult {
ch := make(chan doResult)
go func() {
var res doResult
res.Response, res.Error = x.client.Do(req)
ch <- res
}()
return ch
}