-
Notifications
You must be signed in to change notification settings - Fork 0
/
ws.go
150 lines (127 loc) · 3.18 KB
/
ws.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
package relayergosdk
import (
"context"
"log"
"net/url"
"strings"
"time"
"github.com/Yggdrasil-Protocol/Relayer-Go-SDK/config"
"github.com/fasthttp/websocket"
)
type WS struct {
url *url.URL
dataEventsChan chan DataFeed
infoEventsChan chan SubscriptionMsg
dialer *websocket.Dialer
logger *log.Logger
conn *websocket.Conn
done chan struct{}
}
func NewWS(feedIDs []string, logger *log.Logger, dialer *websocket.Dialer) *WS {
ws := &WS{
url: &url.URL{
Scheme: "wss",
Host: config.BaseWSUrl,
Path: config.EndpointUrl,
RawQuery: "feedIDs=" + strings.Join(feedIDs, ","),
},
dataEventsChan: make(chan DataFeed, config.EventChanSize),
infoEventsChan: make(chan SubscriptionMsg, config.EventChanSize),
logger: logger,
conn: nil,
}
if dialer == nil {
ws.dialer = websocket.DefaultDialer
ws.dialer.EnableCompression = true
}
return ws
}
func (ws *WS) Subscribe(ctx context.Context) error {
conn, resp, err := ws.dialer.DialContext(ctx, ws.url.String(), nil)
if err != nil {
ws.logger.Printf("Failed to connect to %s: %v", ws.url.String(), err)
return err
}
ws.conn = conn
ws.done = make(chan struct{}, 1)
if resp.StatusCode != 101 {
ws.logger.Printf("Failed to upgrade connection to websocket: %v", resp.Status)
return err
}
defer resp.Body.Close()
conn.NetConn().SetDeadline(time.Now().Add(config.PingTimeout))
conn.SetPongHandler(func(string) error {
ws.logger.Println("Hearbeat Pong Received")
conn.NetConn().SetDeadline(time.Now().Add(config.PingTimeout))
return nil
})
go ws.read()
go ws.ping(ctx)
return nil
}
func (ws *WS) Consume() (<-chan DataFeed, <-chan SubscriptionMsg) {
return ws.dataEventsChan, ws.infoEventsChan
}
func (ws *WS) read() {
defer ws.Close()
for {
msgType, data, err := ws.conn.ReadMessage()
if isClosed(ws.done) {
return
}
if err != nil {
ws.logger.Printf("Failed to read message (type=%v): %v", msgType, err)
return
}
err = sendEvent(data, ws.dataEventsChan, ws.infoEventsChan)
if err != nil {
ws.logger.Printf("Failed to send event to chan: %v", err)
return
}
}
}
func (ws *WS) ping(ctx context.Context) {
defer ws.Close()
ticker := time.NewTicker(config.PingInterval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
ws.logger.Println("Context Done")
return
case <-ws.done:
return
case <-ticker.C:
if err := ws.conn.WriteMessage(websocket.PingMessage, []byte("PING")); err != nil {
ws.logger.Printf("Failed to write ping message: %v", err)
return
} else {
ws.logger.Println("Hearbeat Ping Sent")
ws.conn.NetConn().SetDeadline(time.Now().Add(config.PingTimeout))
}
}
}
}
func isClosed(ch <-chan struct{}) bool {
select {
case <-ch:
return true
default:
}
return false
}
func (ws *WS) Close() {
if isClosed(ws.done) {
return
}
close(ws.done)
err := ws.conn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
if err != nil {
ws.logger.Printf("Failed to write close message: %v", err)
} else {
ws.logger.Println("Connection closed")
}
ws.conn.Close()
close(ws.dataEventsChan)
close(ws.infoEventsChan)
}