-
Notifications
You must be signed in to change notification settings - Fork 41
/
Copy pathclient.go
365 lines (317 loc) · 7.65 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
package gatews
import (
"context"
"crypto/tls"
"log"
"os"
"strings"
"sync"
"time"
mapset "github.com/deckarep/golang-set"
"github.com/gorilla/websocket"
)
type status int
const (
disconnected status = iota
connected
reconnecting
)
type WsService struct {
mu *sync.Mutex
Logger *log.Logger
Ctx context.Context
Client *websocket.Conn
once *sync.Once
loginOnce *sync.Once
msgChs *sync.Map // business chan
calls *sync.Map
conf *ConnConf
status status
clientMu *sync.Mutex
}
// ConnConf default URL is spot websocket
type ConnConf struct {
App string
subscribeMsg *sync.Map
URL string
Key string
Secret string
MaxRetryConn int
SkipTlsVerify bool
ShowReconnectMsg bool
PingInterval string
}
type ConfOptions struct {
App string
URL string
Key string
Secret string
MaxRetryConn int
SkipTlsVerify bool
ShowReconnectMsg bool
PingInterval string
}
func NewWsService(ctx context.Context, logger *log.Logger, conf *ConnConf) (*WsService, error) {
if logger == nil {
logger = log.New(os.Stdout, "", log.LstdFlags|log.Lshortfile)
}
if ctx == nil {
ctx = context.Background()
}
defaultConf := getInitConnConf()
if conf != nil {
conf = applyOptionConf(defaultConf, conf)
} else {
conf = defaultConf
}
stop := false
retry := 0
var conn *websocket.Conn
for !stop {
dialer := websocket.DefaultDialer
if conf.SkipTlsVerify {
dialer.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
}
c, _, err := dialer.Dial(conf.URL, nil)
if err != nil {
if retry >= conf.MaxRetryConn {
log.Printf("max reconnect time %d reached, give it up", conf.MaxRetryConn)
return nil, err
}
retry++
log.Printf("failed to connect to server for the %d time, try again later", retry)
time.Sleep(time.Millisecond * (time.Duration(retry) * 500))
continue
} else {
stop = true
conn = c
}
}
if retry > 0 {
log.Printf("reconnect succeeded after retrying %d times", retry)
}
ws := &WsService{
mu: new(sync.Mutex),
conf: conf,
Logger: logger,
Ctx: ctx,
Client: conn,
calls: new(sync.Map),
msgChs: new(sync.Map),
once: new(sync.Once),
loginOnce: new(sync.Once),
status: connected,
clientMu: new(sync.Mutex),
}
go ws.activePing()
return ws, nil
}
func getInitConnConf() *ConnConf {
return &ConnConf{
App: "spot",
subscribeMsg: new(sync.Map),
MaxRetryConn: MaxRetryConn,
Key: "",
Secret: "",
URL: BaseUrl,
SkipTlsVerify: false,
ShowReconnectMsg: true,
PingInterval: DefaultPingInterval,
}
}
func applyOptionConf(defaultConf, userConf *ConnConf) *ConnConf {
if userConf.App == "" {
userConf.App = defaultConf.App
}
if userConf.URL == "" {
userConf.URL = defaultConf.URL
}
if userConf.MaxRetryConn == 0 {
userConf.MaxRetryConn = defaultConf.MaxRetryConn
}
if userConf.PingInterval == "" {
userConf.PingInterval = defaultConf.PingInterval
}
return userConf
}
// NewConnConfFromOption conf from options, recommend using this
func NewConnConfFromOption(op *ConfOptions) *ConnConf {
if op.URL == "" {
op.URL = BaseUrl
}
if op.MaxRetryConn == 0 {
op.MaxRetryConn = MaxRetryConn
}
return &ConnConf{
App: op.App,
subscribeMsg: new(sync.Map),
MaxRetryConn: op.MaxRetryConn,
Key: op.Key,
Secret: op.Secret,
URL: op.URL,
SkipTlsVerify: op.SkipTlsVerify,
ShowReconnectMsg: op.ShowReconnectMsg,
PingInterval: op.PingInterval,
}
}
func (ws *WsService) GetConnConf() *ConnConf {
return ws.conf
}
func (ws *WsService) reconnect() error {
// avoid repeated reconnection
if ws.status == reconnecting {
return nil
}
ws.clientMu.Lock()
defer ws.clientMu.Unlock()
if ws.Client != nil {
ws.Client.Close()
}
ws.status = reconnecting
stop := false
retry := 0
for !stop {
c, _, err := websocket.DefaultDialer.Dial(ws.conf.URL, nil)
if err != nil {
if retry >= ws.conf.MaxRetryConn {
ws.Logger.Printf("max reconnect time %d reached, give it up", ws.conf.MaxRetryConn)
return err
}
retry++
log.Printf("failed to connect to server for the %d time, try again later", retry)
time.Sleep(time.Millisecond * (time.Duration(retry) * 500))
continue
} else {
stop = true
ws.Client = c
}
}
ws.status = connected
// resubscribe after reconnect
ws.conf.subscribeMsg.Range(func(key, value interface{}) bool {
// key is channel, value is []requestHistory
if _, ok := value.([]requestHistory); ok {
for _, req := range value.([]requestHistory) {
if req.op == nil {
req.op = &SubscribeOptions{
IsReConnect: true,
}
} else {
req.op.IsReConnect = true
}
if err := ws.baseSubscribe(req.Event, req.Channel, req.Payload, req.op); err != nil {
ws.Logger.Printf("after reconnect, subscribe channel[%s] err:%s", key.(string), err.Error())
} else {
if ws.conf.ShowReconnectMsg {
ws.Logger.Printf("reconnect channel[%s] with payload[%v] success", key.(string), req.Payload)
}
}
}
}
return true
})
return nil
}
func (ws *WsService) SetKey(key string) {
ws.conf.Key = key
}
func (ws *WsService) GetKey() string {
return ws.conf.Key
}
func (ws *WsService) SetSecret(secret string) {
ws.conf.Secret = secret
}
func (ws *WsService) GetSecret() string {
return ws.conf.Secret
}
func (ws *WsService) SetMaxRetryConn(max int) {
ws.conf.MaxRetryConn = max
}
func (ws *WsService) GetMaxRetryConn() int {
return ws.conf.MaxRetryConn
}
func (ws *WsService) GetChannelMarkets(channel string) []string {
var markets []string
set := mapset.NewSet()
if v, ok := ws.conf.subscribeMsg.Load(channel); ok {
for _, req := range v.([]requestHistory) {
payloads, ok := req.Payload.([]string)
if !ok {
continue
}
if req.Event == Subscribe {
for _, pl := range payloads {
if strings.Contains(pl, "_") {
set.Add(pl)
}
}
} else {
for _, pl := range payloads {
if strings.Contains(pl, "_") {
set.Remove(pl)
}
}
}
}
for _, v := range set.ToSlice() {
markets = append(markets, v.(string))
}
return markets
}
return markets
}
func (ws *WsService) GetChannels() []string {
var channels []string
ws.calls.Range(func(key, value interface{}) bool {
channels = append(channels, key.(string))
return true
})
return channels
}
func (ws *WsService) GetConnection() *websocket.Conn {
return ws.Client
}
func (ws *WsService) activePing() {
du, err := time.ParseDuration(ws.conf.PingInterval)
if err != nil {
ws.Logger.Printf("failed to parse ping interval: %s, use default ping interval 10s instead", ws.conf.PingInterval)
du, err = time.ParseDuration(DefaultPingInterval)
if err != nil {
du = time.Second * 10
}
}
ticker := time.NewTicker(du)
defer ticker.Stop()
for {
select {
case <-ws.Ctx.Done():
return
case <-ticker.C:
subscribeMap := map[string]int{}
ws.conf.subscribeMsg.Range(func(key, value interface{}) bool {
splits := strings.Split(key.(string), ".")
if len(splits) == 2 {
subscribeMap[splits[0]] = 1
}
return true
})
if ws.status != connected {
continue
}
for app := range subscribeMap {
channel := app + ".ping"
if err := ws.Subscribe(channel, nil); err != nil {
ws.Logger.Printf("subscribe channel[%s] failed: %v", channel, err)
}
}
}
}
}
var statusString = map[status]string{
disconnected: "disconnected",
connected: "connected",
reconnecting: "reconnecting",
}
func (ws *WsService) Status() string {
return statusString[ws.status]
}