-
Notifications
You must be signed in to change notification settings - Fork 10
/
websocket.go
453 lines (367 loc) · 8.78 KB
/
websocket.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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
package phx
import (
"errors"
"fmt"
"github.com/gorilla/websocket"
"net/http"
"net/url"
"path"
"sync"
"time"
)
// Websocket is a Transport that connects to the server via Websockets. It is based on
// [gorilla.Websocket](https://pkg.go.dev/github.com/gorilla/websocket). The Dialer defaults to websocket.DefaultDialer.
type Websocket struct {
Dialer *websocket.Dialer
Handler TransportHandler
conn *websocket.Conn
endPoint *url.URL
requestHeader http.Header
connectTimeout time.Duration
done chan any
close chan bool
reconnect chan bool
closeMsg chan bool
send chan []byte
connectionTries int
mu sync.RWMutex
started bool
closing bool
reconnecting bool
waitingForClose bool
}
func NewWebsocket(handler TransportHandler) *Websocket {
return &Websocket{
Dialer: websocket.DefaultDialer,
Handler: handler,
}
}
// implements Transport
func (w *Websocket) Connect(endPoint *url.URL, requestHeader http.Header, connectTimeout time.Duration) error {
if w.isStarted() {
return errors.New("connect was already called")
}
// Copy the passed in endpoint so we can modify it
newEndpoint := *endPoint
newEndpoint.Path = path.Join(newEndpoint.Path, "websocket")
if newEndpoint.Scheme == "" {
if newEndpoint.Port() == "443" {
newEndpoint.Scheme = "wss"
} else {
newEndpoint.Scheme = "ws"
}
} else if newEndpoint.Scheme == "http" {
newEndpoint.Scheme = "ws"
} else if newEndpoint.Scheme == "https" {
newEndpoint.Scheme = "wss"
}
if newEndpoint.Scheme != "ws" && newEndpoint.Scheme != "wss" {
return errors.New("invalid scheme for websocket transport, must be 'ws://' or 'wss://'")
}
w.endPoint = &newEndpoint
w.requestHeader = requestHeader
w.connectTimeout = connectTimeout
w.startup()
return nil
}
func (w *Websocket) Disconnect() error {
if !w.isStarted() {
return errors.New("not connected")
}
if w.connIsSet() {
w.sendClose()
} else {
w.shutdown()
}
return nil
}
func (w *Websocket) Reconnect() error {
if !w.isStarted() {
return errors.New("not connected")
}
w.sendReconnect()
return nil
}
func (w *Websocket) IsConnected() bool {
return w.connIsReady()
}
func (w *Websocket) ConnectionState() ConnectionState {
if w.connIsReady() {
return ConnectionOpen
} else if !w.isStarted() {
return ConnectionClosed
} else if w.isClosing() {
return ConnectionClosing
} else {
return ConnectionConnecting
}
}
func (w *Websocket) Send(msg []byte) error {
if w.isClosing() {
return errors.New("cannot Send when closing connection")
}
if !w.isStarted() {
return errors.New("cannot Send when not connected or connecting")
}
w.send <- msg
return nil
}
func (w *Websocket) startup() {
w.connectionTries = 0
w.done = make(chan any)
w.close = make(chan bool)
w.closeMsg = make(chan bool)
w.reconnect = make(chan bool)
w.send = make(chan []byte, messageQueueLength)
w.setReconnecting(false)
w.setClosing(false)
go w.connectionManager()
go w.connectionWriter()
go w.connectionReader()
w.setStarted(true)
}
func (w *Websocket) shutdown() {
//fmt.Println("shutdown")
// Tell the goroutines to exit
close(w.done)
close(w.close)
close(w.closeMsg)
close(w.reconnect)
close(w.send)
w.setStarted(false)
w.setReconnecting(false)
w.setClosing(false)
}
func (w *Websocket) dial() error {
w.Dialer.HandshakeTimeout = w.connectTimeout
conn, _, err := w.Dialer.Dial(w.endPoint.String(), w.requestHeader)
if err != nil {
return err
}
//w.socket.Logger.Debugf("Connected conn: %+v\n\n", conn)
//w.socket.Logger.Debugf("Connected resp: %+v\n", resp)
w.setConn(conn)
w.setReconnecting(false)
w.Handler.onConnOpen()
return nil
}
func (w *Websocket) closeConn() {
//fmt.Println("closeConn")
if w.connIsSet() {
// attempt to gracefully close the connection by sending a close websocket message
err := w.conn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
if err == nil {
// Wait for a close message to be received by `connectionReader`, or time out after 5 seconds
w.setWaitingForClose(true)
select {
case <-w.closeMsg:
case <-time.After(3 * time.Second):
}
}
}
if w.connIsSet() {
err := w.conn.Close()
if err != nil {
w.Handler.onConnError(err)
}
w.setConn(nil)
}
w.Handler.onConnClose()
w.setClosing(false)
}
func (w *Websocket) writeToConn(data []byte) error {
if !w.connIsReady() {
return errors.New("connection is not open")
}
return w.conn.WriteMessage(websocket.TextMessage, data)
}
func (w *Websocket) readFromConn() ([]byte, error) {
if !w.connIsReady() {
return nil, errors.New("connection is not open")
}
messageType, data, err := w.conn.ReadMessage()
if err != nil {
return nil, err
}
if messageType != websocket.TextMessage {
return nil, errors.New(fmt.Sprint("Got unsupported websocket message type", messageType))
}
return data, nil
}
func (w *Websocket) connectionManager() {
//fmt.Println("connectionManager started")
//defer fmt.Println("connectionManager stopped")
for {
// Check if we have been told to finish
select {
case <-w.done:
return
default:
}
if !w.isClosing() && !w.connIsSet() {
err := w.dial()
if err != nil {
w.Handler.onConnError(err)
w.setReconnecting(true)
w.connectionTries++
delay := w.Handler.reconnectAfter(w.connectionTries)
select {
case <-w.done:
case <-time.After(delay):
}
continue
}
}
select {
case <-w.done:
return
case <-w.close:
w.closeConn()
w.shutdown()
case <-w.reconnect:
w.closeConn()
}
}
}
func (w *Websocket) connectionWriter() {
//fmt.Println("connectionWriter started")
//defer fmt.Println("connectionWriter stopped")
for {
// Check if we have been told to finish
select {
case <-w.done:
return
default:
}
if !w.connIsReady() {
time.Sleep(busyWait)
continue
}
select {
case <-w.done:
return
case data := <-w.send:
// If there is a message to send, but we're not connected, then wait until we are.
if !w.connIsReady() {
time.Sleep(busyWait)
continue
}
// Send the message
err := w.writeToConn(data)
// If there were any errors sending, then tell the connectionManager to reconnect
if err != nil {
w.Handler.onWriteError(err)
w.sendReconnect()
time.Sleep(busyWait)
continue
}
}
}
}
func (w *Websocket) connectionReader() {
//fmt.Println("connectionReader started")
//defer fmt.Println("connectionReader stopped")
for {
// Check if we have been told to finish
select {
case <-w.done:
//fmt.Println("connectionReader stopping")
return
default:
}
// Wait until we're connected
if !w.connIsReady() {
time.Sleep(busyWait)
continue
}
// Read the next message from the websocket. This blocks until there is a message or error
data, err := w.readFromConn()
// If there were any errors, tell the connectionManager to reconnect
if err != nil {
//fmt.Printf("read error %e %v\n", err, err)
if websocket.IsCloseError(err, 1000) && w.isWaitingForClose() {
// tell the connectionManager that we got the close message
w.closeMsg <- true
} else {
w.Handler.onReadError(err)
w.sendReconnect()
}
time.Sleep(busyWait)
continue
}
w.Handler.onConnMessage(data)
}
}
func (w *Websocket) setStarted(started bool) {
w.mu.Lock()
defer w.mu.Unlock()
w.started = started
}
func (w *Websocket) isStarted() bool {
w.mu.RLock()
defer w.mu.RUnlock()
return w.started
}
func (w *Websocket) setClosing(closing bool) {
w.mu.Lock()
defer w.mu.Unlock()
w.closing = closing
}
func (w *Websocket) isClosing() bool {
w.mu.RLock()
defer w.mu.RUnlock()
return w.closing
}
func (w *Websocket) sendClose() {
w.mu.Lock()
defer w.mu.Unlock()
if w.closing == true {
return
}
w.closing = true
w.close <- true
}
func (w *Websocket) setReconnecting(reconnecting bool) {
w.mu.Lock()
defer w.mu.Unlock()
w.reconnecting = reconnecting
}
func (w *Websocket) isReconnecting() bool {
w.mu.RLock()
defer w.mu.RUnlock()
return w.reconnecting
}
func (w *Websocket) sendReconnect() {
w.mu.Lock()
defer w.mu.Unlock()
if w.reconnecting || w.closing {
return
}
w.reconnecting = true
w.reconnect <- true
}
func (w *Websocket) setConn(conn *websocket.Conn) {
w.mu.Lock()
defer w.mu.Unlock()
w.conn = conn
}
func (w *Websocket) connIsSet() bool {
w.mu.RLock()
defer w.mu.RUnlock()
return w.conn != nil
}
func (w *Websocket) connIsReady() bool {
w.mu.RLock()
defer w.mu.RUnlock()
return w.started && !w.closing && !w.reconnecting && w.conn != nil
}
func (w *Websocket) setWaitingForClose(waitingForClose bool) {
w.mu.Lock()
defer w.mu.Unlock()
w.waitingForClose = waitingForClose
}
func (w *Websocket) isWaitingForClose() bool {
w.mu.RLock()
defer w.mu.RUnlock()
return w.waitingForClose
}