-
Notifications
You must be signed in to change notification settings - Fork 101
/
Copy pathclient.go
270 lines (227 loc) · 5.42 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
package deribit
import (
"context"
"encoding/json"
"errors"
"fmt"
"github.com/chuckpreslar/emission"
"github.com/frankrap/deribit-api/models"
"github.com/sourcegraph/jsonrpc2"
"log"
"net/http"
"nhooyr.io/websocket"
"strings"
"sync"
"time"
)
const (
RealBaseURL = "wss://www.deribit.com/ws/api/v2/"
TestBaseURL = "wss://test.deribit.com/ws/api/v2/"
)
const (
MaxTryTimes = 10000
)
var (
ErrAuthenticationIsRequired = errors.New("authentication is required")
)
// Event is wrapper of received event
type Event struct {
Channel string `json:"channel"`
Data json.RawMessage `json:"data"`
}
type Configuration struct {
Ctx context.Context
Addr string `json:"addr"`
ApiKey string `json:"api_key"`
SecretKey string `json:"secret_key"`
AutoReconnect bool `json:"auto_reconnect"`
DebugMode bool `json:"debug_mode"`
}
type Client struct {
ctx context.Context
addr string
apiKey string
secretKey string
autoReconnect bool
debugMode bool
conn *websocket.Conn
rpcConn *jsonrpc2.Conn
mu sync.RWMutex
heartCancel chan struct{}
isConnected bool
auth struct {
token string
refresh string
}
subscriptions []string
subscriptionsMap map[string]struct{}
emitter *emission.Emitter
}
func New(cfg *Configuration) *Client {
ctx := cfg.Ctx
if ctx == nil {
ctx = context.Background()
}
client := &Client{
ctx: ctx,
addr: cfg.Addr,
apiKey: cfg.ApiKey,
secretKey: cfg.SecretKey,
autoReconnect: cfg.AutoReconnect,
debugMode: cfg.DebugMode,
subscriptionsMap: make(map[string]struct{}),
emitter: emission.NewEmitter(),
}
err := client.start()
if err != nil {
log.Fatal(err)
}
return client
}
// setIsConnected sets state for isConnected
func (c *Client) setIsConnected(state bool) {
c.mu.Lock()
defer c.mu.Unlock()
c.isConnected = state
}
// IsConnected returns the WebSocket connection state
func (c *Client) IsConnected() bool {
c.mu.RLock()
defer c.mu.RUnlock()
return c.isConnected
}
func (c *Client) Subscribe(channels []string) {
c.subscriptions = append(c.subscriptions, channels...)
c.subscribe(channels)
}
func (c *Client) subscribe(channels []string) {
var publicChannels []string
var privateChannels []string
for _, v := range c.subscriptions {
if _, ok := c.subscriptionsMap[v]; ok {
continue
}
if strings.HasPrefix(v, "user.") {
privateChannels = append(privateChannels, v)
} else {
publicChannels = append(publicChannels, v)
}
}
if len(publicChannels) > 0 {
c.PublicSubscribe(&models.SubscribeParams{
Channels: publicChannels,
})
}
if len(privateChannels) > 0 {
c.PrivateSubscribe(&models.SubscribeParams{
Channels: privateChannels,
})
}
allChannels := append(publicChannels, privateChannels...)
for _, v := range allChannels {
c.subscriptionsMap[v] = struct{}{}
}
}
func (c *Client) start() error {
c.setIsConnected(false)
c.subscriptionsMap = make(map[string]struct{})
c.conn = nil
c.rpcConn = nil
c.heartCancel = make(chan struct{})
for i := 0; i < MaxTryTimes; i++ {
conn, _, err := c.connect()
if err != nil {
log.Println(err)
tm := (i + 1) * 5
log.Printf("Sleep %vs", tm)
time.Sleep(time.Duration(tm) * time.Second)
continue
}
c.conn = conn
break
}
if c.conn == nil {
return errors.New("connect fail")
}
c.rpcConn = jsonrpc2.NewConn(context.Background(), NewObjectStream(c.conn), c)
c.setIsConnected(true)
// auth
if c.apiKey != "" && c.secretKey != "" {
if err := c.Auth(c.apiKey, c.secretKey); err != nil {
log.Printf("auth error: %v", err)
}
}
// subscribe
c.subscribe(c.subscriptions)
c.SetHeartbeat(&models.SetHeartbeatParams{Interval: 30})
if c.autoReconnect {
go c.reconnect()
}
go c.heartbeat()
return nil
}
// Call issues JSONRPC v2 calls
func (c *Client) Call(method string, params interface{}, result interface{}) (err error) {
defer func() {
if r := recover(); r != nil {
err = errors.New(fmt.Sprintf("%v", r))
}
}()
if !c.IsConnected() {
return errors.New("not connected")
}
if params == nil {
params = emptyParams
}
if token, ok := params.(privateParams); ok {
if c.auth.token == "" {
return ErrAuthenticationIsRequired
}
token.setToken(c.auth.token)
}
return c.rpcConn.Call(c.ctx, method, params, result)
}
// Handle implements jsonrpc2.Handler
func (c *Client) Handle(ctx context.Context, conn *jsonrpc2.Conn, req *jsonrpc2.Request) {
//log.Printf("Handle %v", req.Method)
if req.Method == "subscription" {
// update events
if req.Params != nil && len(*req.Params) > 0 {
var event Event
if err := json.Unmarshal(*req.Params, &event); err != nil {
//c.setError(err)
return
}
c.subscriptionsProcess(&event)
}
}
}
func (c *Client) heartbeat() {
t := time.NewTicker(3 * time.Second)
for {
select {
case <-t.C:
c.Test()
case <-c.heartCancel:
return
}
}
}
func (c *Client) reconnect() {
notify := c.rpcConn.DisconnectNotify()
<-notify
c.setIsConnected(false)
log.Println("disconnect, reconnect...")
close(c.heartCancel)
time.Sleep(1 * time.Second)
c.start()
}
func (c *Client) connect() (*websocket.Conn, *http.Response, error) {
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
//defer cancel()
conn, resp, err := websocket.Dial(ctx, c.addr, &websocket.DialOptions{})
if err == nil {
conn.SetReadLimit(32768 * 64)
}
return conn, resp, err
}