/
client.go
548 lines (441 loc) · 11.2 KB
/
client.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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
package wsclient
import (
"bytes"
"net/http"
"net/url"
"strings"
"sync"
"time"
"github.com/gorilla/websocket"
"github.com/influx6/octo"
"github.com/influx6/octo/consts"
"github.com/influx6/octo/netutils"
"github.com/influx6/octo/streams/client"
"github.com/influx6/octo/utils"
)
// Attr defines a struct which holds configuration options for the websocket
// client.
type Attr struct {
MaxReconnets int
MaxDrops int
Authenticate bool
Addr string
Clusters []string
EnableCompression bool
Headers map[string]string
Dialer *websocket.Dialer
}
// WebSocketPod defines a websocket implementation which connects
// to a provided websocket endpoint for making requests.
type WebSocketPod struct {
attr Attr
instruments octo.Instrumentation
pub *client.Pub
servers []*srvAddr
curAddr *srvAddr
bm bytes.Buffer
wg sync.WaitGroup
system client.SystemServer
encoding octo.MessageEncoding
cnl sync.Mutex
doClose bool
started bool
conn *WebsocketConn
}
// New returns a new instance of the websocket pod.
func New(insts octo.Instrumentation, attr Attr) (*WebSocketPod, error) {
if attr.MaxDrops <= 0 {
attr.MaxDrops = consts.MaxTotalConnectionFailure
}
if attr.MaxReconnets <= 0 {
attr.MaxReconnets = consts.MaxTotalReconnection
}
var pod WebSocketPod
pod.attr = attr
pod.instruments = insts
pod.pub = client.NewPub()
// Prepare all server registering and validate paths.
if err := pod.prepareServers(); err != nil {
return nil, err
}
return &pod, nil
}
// Listen calls the connection to be create and begins serving requests.
func (w *WebSocketPod) Listen(sm client.SystemServer, encoding octo.MessageEncoding) error {
w.cnl.Lock()
if w.started {
return nil
}
w.cnl.Unlock()
w.system = sm
w.encoding = encoding
if err := w.reconnect(); err != nil {
return err
}
return nil
}
// Close closes the websocket connection.
func (w *WebSocketPod) Close() error {
if w.isClose() {
return consts.ErrClosedConnection
}
w.notify(client.ClosedHandler, nil)
w.cnl.Lock()
w.doClose = true
w.cnl.Unlock()
if err := w.conn.Close(); err != nil {
w.notify(client.ErrorHandler, err)
w.cnl.Lock()
w.conn = nil
w.cnl.Unlock()
return err
}
w.wg.Wait()
w.cnl.Lock()
w.conn = nil
w.cnl.Unlock()
return nil
}
// Register registers the handler for a given handler.
func (w *WebSocketPod) Register(tm client.StateHandlerType, hmi interface{}) {
w.pub.Register(tm, hmi)
}
// notify calls the giving callbacks for each different type of state.
func (w *WebSocketPod) notify(n client.StateHandlerType, err error) {
var cm octo.Contact
if w.curAddr != nil {
cm = w.curAddr.contact
}
w.pub.Notify(n, cm, w, err)
}
// Send delivers the giving message to the underline websocket connection.
func (w *WebSocketPod) Send(data interface{}, flush bool) error {
// Encode outside of lock to reduce contention.
dataBytes, err := w.encoding.Encode(data)
if err != nil {
return err
}
w.cnl.Lock()
if w.curAddr != nil && !w.curAddr.connected && !w.curAddr.reconnecting {
w.cnl.Unlock()
w.bm.Write(dataBytes)
return nil
}
w.cnl.Unlock()
if w.bm.Len() > 0 {
w.conn.Write(w.bm.Bytes(), false)
w.bm.Reset()
}
return w.conn.Write(dataBytes, flush)
}
// srvAddr defines a struct for storing addr details.
type srvAddr struct {
index int
drops int
recons int
ep *url.URL
addr string
connected bool
reconnecting bool
contact octo.Contact
}
// prepareServers registered all provided address from the attribute as cycling
// items in a server lists for reducing load on a new server.
func (w *WebSocketPod) prepareServers() error {
// Add the main addr if provided.
if w.attr.Addr != "" {
w.attr.Addr = netutils.GetAddr(w.attr.Addr)
ep, err := url.Parse(w.attr.Addr)
// fmt.Printf("Preping: %q -> %+q <- %q", w.attr.Addr, ep, err)
if err != nil {
return err
}
w.servers = append(w.servers, &srvAddr{
index: 0,
ep: ep,
addr: w.attr.Addr,
contact: utils.NewContact(w.attr.Addr),
})
}
total := len(w.servers)
for _, addr := range w.attr.Clusters {
addr = netutils.GetAddr(addr)
ep, err := url.Parse(addr)
if err != nil {
return err
}
w.servers = append(w.servers, &srvAddr{
index: total,
ep: ep,
addr: addr,
contact: utils.NewContact(addr),
})
total++
}
return nil
}
// getNextServer gets the next server in the lists setting it as the main server
// if the giving server has not reach the maximumum reconnection limit.
func (w *WebSocketPod) getNextServer() error {
var indx int
var chosen *srvAddr
// Run through the servers and attempt to find another.
for index, srv := range w.servers {
if srv == nil {
continue
}
// If the MaxTotalConnectionFailure is reached, nil this server has bad.
if w.attr.MaxDrops > 0 && srv.drops >= w.attr.MaxDrops {
w.servers[index] = nil
continue
}
// If the Maximum allow reconnection reached, nil and continue.
if w.attr.MaxReconnets > 0 && srv.recons >= w.attr.MaxReconnets {
w.servers[index] = nil
continue
}
chosen = srv
indx = index
break
}
if chosen == nil {
w.servers = nil
return consts.ErrNoServerFound
}
// Set the new server for usage.
w.cnl.Lock()
w.curAddr = chosen
w.cnl.Unlock()
w.servers = append(w.servers, chosen)
w.servers = append(w.servers[:indx], w.servers[indx+1:]...)
return nil
}
// reconnect attempts to retrieve a new server after a failure to connect and then
// begins message passing.
func (w *WebSocketPod) reconnect() error {
if w.attr.Authenticate && w.attr.Headers != nil {
if _, ok := w.attr.Headers["Authorization"]; !ok {
return consts.ErrNoAuthorizationHeader
}
}
w.cnl.Lock()
if w.started {
w.notify(client.DisconnectHandler, nil)
}
w.cnl.Unlock()
if err := w.getNextServer(); err != nil {
return err
}
var addr string
w.cnl.Lock()
{
w.curAddr.reconnecting = true
w.curAddr.connected = false
w.curAddr.recons++
if w.curAddr.ep != nil {
addr = w.curAddr.ep.String()
} else {
addr = w.curAddr.addr
}
}
w.cnl.Unlock()
// fmt.Printf("NewConn: %q\n", w.attr.Addr)
conn, err := NewWebsocketConn(addr, WebsocketAttr{
Headers: w.attr.Headers,
Dialer: w.attr.Dialer,
EnableCompression: w.attr.EnableCompression,
})
// fmt.Printf("NewConn: %q -> %+q\n", w.attr.Addr, err)
if err != nil {
w.notify(client.DisconnectHandler, err)
w.curAddr.drops++
return w.reconnect()
}
w.cnl.Lock()
w.started = true
w.conn = conn
w.curAddr.connected = true
w.curAddr.reconnecting = false
w.cnl.Unlock()
w.notify(client.ConnectHandler, nil)
go w.acceptRequests()
return nil
}
// acceptRequests processing the connections for incoming messages.
func (w *WebSocketPod) acceptRequests() {
w.wg.Add(1)
defer w.wg.Done()
for !w.shouldClose() {
w.conn.SetReadDeadline(time.Now().Add(consts.WSReadTimeout))
// fmt.Printf("StartWSSocket:Reading Accept: \n")
data, err := w.conn.Read()
// fmt.Printf("Accept::Err: %+q\n", err)
if err != nil {
w.notify(client.ErrorHandler, err)
if err == consts.ErrAbitraryCloseConnection || err == consts.ErrClosedConnection || err == consts.ErrUnstableRead {
go w.reconnect()
return
}
continue
}
val, err := w.encoding.Decode(data)
if err != nil {
w.notify(client.ErrorHandler, err)
continue
}
if err := w.system.Serve(val, w); err != nil {
w.notify(client.ErrorHandler, err)
continue
}
}
}
// shouldClose returns true/false if the giving connection should close.
func (w *WebSocketPod) shouldClose() bool {
w.cnl.Lock()
if w.doClose {
w.cnl.Unlock()
return true
}
w.cnl.Unlock()
return false
}
// isClose returns true/false if the connection is already closed.
func (w *WebSocketPod) isClose() bool {
w.cnl.Lock()
{
if w.conn == nil {
w.cnl.Unlock()
return true
}
}
w.cnl.Unlock()
return false
}
//================================================================================
// WebsocketAttr defines a struct which holds configuration options for the websocket
// client.
type WebsocketAttr struct {
EnableCompression bool
Headers map[string]string
Dialer *websocket.Dialer
}
// WebsocketConn defines a struct which handles the underline connection procedure
// for communicating through websocket connections.
type WebsocketConn struct {
addr string
attr WebsocketAttr
cl sync.Mutex
conn *websocket.Conn
res *http.Response
header http.Header
bu bytes.Buffer
}
// NewWebsocketConn returns a new WebsocketConn intance using the provided WebsocketAttr.
func NewWebsocketConn(addr string, attr WebsocketAttr) (*WebsocketConn, error) {
if attr.Dialer == nil {
attr.Dialer = &websocket.Dialer{
Proxy: http.ProxyFromEnvironment,
}
}
header := make(http.Header)
for key, val := range attr.Headers {
header.Set(key, val)
}
var socket WebsocketConn
socket.attr = attr
socket.header = header
socket.addr = addr
conn, res, err := attr.Dialer.Dial(addr, socket.header)
if err != nil {
return nil, err
}
if attr.EnableCompression {
conn.EnableWriteCompression(attr.EnableCompression)
}
socket.conn = conn
socket.res = res
return &socket, nil
}
// Write writes the byte slice read from the websocket connections.
func (t *WebsocketConn) Write(bm []byte, flush bool) error {
if t.isClosed() {
return consts.ErrClosedConnection
}
// t.cl.Lock()
t.bu.Write(bm)
if flush {
t.conn.WriteMessage(websocket.BinaryMessage, t.bu.Bytes())
t.bu.Reset()
}
// t.cl.RLock()
return nil
}
// Read returns the byte slice read from the websocket connections.
func (t *WebsocketConn) Read() ([]byte, error) {
if t.isClosed() {
return nil, consts.ErrClosedConnection
}
// t.cl.Lock()
mtype, msg, err := t.conn.ReadMessage()
if err != nil {
// t.cl.Unlock()
return nil, err
}
// t.cl.Unlock()
switch mtype {
case websocket.BinaryMessage:
return msg, nil
case websocket.TextMessage:
return msg, nil
case websocket.CloseMessage:
go t.Close()
return nil, consts.ErrClosedConnection
case -1:
if strings.Contains(err.Error(), "websocket: close") {
go t.Close()
return nil, consts.ErrAbitraryCloseConnection
}
}
return nil, consts.ErrUnstableRead
}
// SetWriteDeadline sets the read deadline of the connection.
func (t *WebsocketConn) SetWriteDeadline(tl time.Time) {
t.cl.Lock()
t.conn.SetWriteDeadline(tl)
t.cl.Unlock()
}
// SetReadDeadline sets the read deadline of the connection.
func (t *WebsocketConn) SetReadDeadline(tl time.Time) {
t.cl.Lock()
t.conn.SetReadDeadline(tl)
t.cl.Unlock()
}
// Close ends and disposes of the internal connection, closing it and
// all reads and writers.
func (t *WebsocketConn) Close() error {
var err error
t.cl.Lock()
{
if t.conn == nil {
t.cl.Unlock()
return nil
}
// Send Close message to websocket.
t.conn.WriteControl(websocket.CloseMessage, nil, time.Now().Add(consts.WSReadTimeout))
err = t.conn.Close()
t.conn = nil
t.res = nil
}
t.cl.Unlock()
return err
}
// isClosed returns true/false if the connection has been closed.
func (t *WebsocketConn) isClosed() bool {
var closed bool
t.cl.Lock()
{
closed = (t.conn == nil)
}
t.cl.Unlock()
return closed
}