forked from gateio/gatews
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchannel.go
316 lines (263 loc) · 6.96 KB
/
channel.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
package gatews
import (
"crypto/hmac"
"crypto/sha512"
"encoding/hex"
"encoding/json"
"fmt"
"strconv"
"strings"
"time"
"github.com/gorilla/websocket"
)
type SubscribeOptions struct {
ID int64 `json:"id"`
IsReConnect bool `json:"-"`
}
func (ws *WsService) Subscribe(channel string, payload []string) error {
if (ws.conf.Key == "" || ws.conf.Secret == "") && authChannel[channel] {
return newAuthEmptyErr()
}
msgCh, ok := ws.msgChs.Load(channel)
if !ok {
msgCh = make(chan *UpdateMsg, 1)
go ws.receiveCallMsg(channel, msgCh.(chan *UpdateMsg))
}
return ws.newBaseChannel(channel, payload, msgCh.(chan *UpdateMsg), nil)
}
func (ws *WsService) SubscribeWithOption(channel string, payload any, op *SubscribeOptions) error {
if (ws.conf.Key == "" || ws.conf.Secret == "") && authChannel[channel] {
return newAuthEmptyErr()
}
msgCh, ok := ws.msgChs.Load(channel)
if !ok {
msgCh = make(chan *UpdateMsg, 1)
go ws.receiveCallMsg(channel, msgCh.(chan *UpdateMsg))
}
return ws.newBaseChannel(channel, payload, msgCh.(chan *UpdateMsg), op)
}
func (ws *WsService) UnSubscribe(channel string, payload []string) error {
return ws.baseSubscribe(UnSubscribe, channel, payload, nil)
}
func (ws *WsService) newBaseChannel(channel string, payload any, bch chan *UpdateMsg, op *SubscribeOptions) error {
err := ws.baseSubscribe(Subscribe, channel, payload, op)
if err != nil {
return err
}
if _, ok := ws.msgChs.Load(channel); !ok {
ws.msgChs.Store(channel, bch)
}
ws.readMsg()
return nil
}
func (ws *WsService) baseSubscribe(event, channel string, payload any, op *SubscribeOptions) error {
ts := time.Now().Unix()
hash := hmac.New(sha512.New, []byte(ws.conf.Secret))
hash.Write([]byte(fmt.Sprintf("channel=%s&event=%s&time=%d", channel, Subscribe, ts)))
req := Request{
Time: ts,
Channel: channel,
Event: event,
Payload: payload,
Auth: Auth{
Method: AuthMethodApiKey,
Key: ws.conf.Key,
Secret: hex.EncodeToString(hash.Sum(nil)),
},
}
// options
if op != nil {
req.Id = &op.ID
}
byteReq, err := json.Marshal(req)
if err != nil {
ws.Logger.Printf("req Marshal err:%s", err.Error())
return err
}
ws.mu.Lock()
defer ws.mu.Unlock()
err = ws.Client.WriteMessage(websocket.TextMessage, byteReq)
if err != nil {
ws.Logger.Printf("wsWrite [%s] err:%s", channel, err.Error())
return err
}
if strings.HasSuffix(channel, "ping") {
return nil
}
if v, ok := ws.conf.subscribeMsg.Load(channel); ok {
if op != nil && op.IsReConnect {
return nil
}
reqs := v.([]requestHistory)
reqs = append(reqs, requestHistory{
Channel: channel,
Event: event,
Payload: payload,
})
ws.conf.subscribeMsg.Store(channel, reqs)
} else {
// avoid saving invalid subscribe msg
if strings.HasSuffix(channel, ".ping") || strings.HasSuffix(channel, ".time") {
return nil
}
ws.conf.subscribeMsg.Store(channel, []requestHistory{{
Channel: channel,
Event: event,
Payload: payload,
}})
}
return nil
}
// readMsg only run once to read message
func (ws *WsService) readMsg() {
ws.once.Do(func() {
go func() {
defer ws.Client.Close()
for {
select {
case <-ws.Ctx.Done():
ws.Logger.Printf("closing reader")
return
default:
_, rawMsg, err := ws.Client.ReadMessage()
if err != nil {
ws.Logger.Printf("websocket err: %s", err.Error())
if e := ws.reconnect(); e != nil {
ws.Logger.Printf("reconnect err:%s", err.Error())
return
}
ws.Logger.Println("reconnect success, continue read message")
continue
}
var msg UpdateMsg
if err := json.Unmarshal(rawMsg, &msg); err != nil {
continue
}
channel := msg.GetChannel()
if channel == "" {
ws.Logger.Printf("channel is empty in message %v", msg)
return
}
if bch, ok := ws.msgChs.Load(channel); ok {
select {
case <-ws.Ctx.Done():
return
default:
if _, ok := ws.msgChs.Load(channel); ok {
bch.(chan *UpdateMsg) <- &msg
}
}
}
}
}
}()
})
}
type CallBack func(*UpdateMsg)
func NewCallBack(f func(*UpdateMsg)) func(*UpdateMsg) {
return f
}
func (ws *WsService) SetCallBack(channel string, call CallBack) {
if call == nil {
return
}
ws.calls.Store(channel, call)
}
func (ws *WsService) receiveCallMsg(channel string, msgCh chan *UpdateMsg) {
// avoid send closed channel error
// defer close(msgCh)
for {
select {
case <-ws.Ctx.Done():
ws.Logger.Printf("received parent context exit")
return
case msg := <-msgCh:
if call, ok := ws.calls.Load(channel); ok {
call.(CallBack)(msg)
}
}
}
}
func (ws *WsService) APIRequest(channel string, payload any, keyVals map[string]any) error {
var err error
ws.loginOnce.Do(func() {
err = ws.login()
})
if err != nil {
return err
}
if (ws.conf.Key == "" || ws.conf.Secret == "") && authChannel[channel] {
return newAuthEmptyErr()
}
msgCh, ok := ws.msgChs.Load(channel)
if !ok {
msgCh = make(chan *UpdateMsg, 1)
go ws.receiveCallMsg(channel, msgCh.(chan *UpdateMsg))
}
if _, ok := ws.msgChs.Load(channel); !ok {
ws.msgChs.Store(channel, msgCh)
}
ws.readMsg()
return ws.apiRequest(channel, payload, keyVals)
}
func (ws *WsService) login() error {
if ws.conf.Key == "" || ws.conf.Secret == "" {
return newAuthEmptyErr()
}
channel := ChannelSpotLogin
if ws.conf.App == "futures" {
channel = ChannelFutureLogin
}
msgCh, ok := ws.msgChs.Load(channel)
if !ok {
msgCh = make(chan *UpdateMsg, 1)
go ws.receiveCallMsg(channel, msgCh.(chan *UpdateMsg))
}
if _, ok := ws.msgChs.Load(channel); !ok {
ws.msgChs.Store(channel, msgCh)
}
ws.readMsg()
return ws.apiRequest(channel, nil, nil)
}
func (ws *WsService) apiRequest(channel string, payload any, keyVals map[string]any) error {
req := Request{
Time: time.Now().Unix(),
Channel: channel,
Event: API,
Payload: ws.generateAPIRequest(channel, payload, keyVals),
}
byteReq, err := json.Marshal(req)
if err != nil {
ws.Logger.Printf("req Marshal err:%s", err.Error())
return err
}
ws.mu.Lock()
defer ws.mu.Unlock()
return ws.Client.WriteMessage(websocket.TextMessage, byteReq)
}
func (ws *WsService) generateAPIRequest(channel string, placeParam any, keyVals map[string]any) any {
reqID := "req_id"
gateChannelID := "T_channel_id"
if v, ok := keyVals["req_id"]; ok {
reqID, _ = v.(string)
}
if v, ok := keyVals["X-Gate-Channel-Id"]; ok {
gateChannelID, _ = v.(string)
}
now := time.Now().Unix()
reqParam, _ := json.Marshal(placeParam)
message := fmt.Sprintf("api\n%s\n%s\n%d", channel, reqParam, now)
return APIReq{
ApiKey: ws.conf.Key,
Signature: calculateSignature(ws.conf.Secret, message),
Timestamp: strconv.Itoa(int(now)),
ReqId: reqID,
ReqHeader: json.RawMessage(fmt.Sprintf(`{"X-Gate-Channel-Id":"%s"}`, gateChannelID)),
ReqParam: reqParam,
}
}
func calculateSignature(secret string, message string) string {
h := hmac.New(sha512.New, []byte(secret))
h.Write([]byte(message))
return hex.EncodeToString(h.Sum(nil))
}