/
conn.go
276 lines (246 loc) · 5.43 KB
/
conn.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
package ws
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"log/slog"
"net/url"
"sync/atomic"
"time"
"golang.org/x/sync/errgroup"
"nhooyr.io/websocket"
)
// ChannelType
type ChannelType string
const (
PublicChannelType = "public"
PrivateChannelType = "private"
BusinessChannelType = "business"
)
// newConn new conn
func newConn(ctx context.Context, baseURL string, path ChannelType, handler MessageHandler) (*conn, error) {
if handler == nil {
handler = NoopMessageHandler{}
}
c := &conn{
baseURL: baseURL,
path: string(path),
handler: handler,
}
return c, c.init(ctx)
}
// conn connection
//
// https://www.okx.com/docs-v5/en/#overview-websocket-connect
type conn struct {
baseURL string
path string
url string
// used websocket connection
*websocket.Conn
// last activity's unix time (the number of milliseconds)
lastActive atomic.Int64
handler MessageHandler
reqId atomic.Uint64
respId atomic.Uint64
pushDataId atomic.Uint64
closed atomic.Bool
}
// Run run conn
func (c *conn) Run(ctx context.Context) error {
eg, ctx := errgroup.WithContext(ctx)
eg.Go(func() error {
return c.periodicPing(ctx)
})
eg.Go(func() error {
return c.consume(ctx)
})
return eg.Wait()
}
func (c *conn) init(ctx context.Context) error {
u, err := url.Parse(c.baseURL)
if err != nil {
return err
}
u = u.JoinPath(c.path)
c.url = u.String()
c.Conn, err = dial(ctx, u.String())
if err != nil {
return err
}
return nil
}
func (c *conn) Read(ctx context.Context) (websocket.MessageType, []byte, error) {
typ, b, err := c.Conn.Read(ctx)
if err != nil {
return typ, b, err
}
c.refreshLastActive()
return typ, b, nil
}
func (c *conn) Write(ctx context.Context, typ websocket.MessageType, p []byte) error {
err := c.Conn.Write(ctx, typ, p)
if err != nil {
return err
}
c.refreshLastActive()
return nil
}
// periodicPing periodic ping
//
// https://www.okx.com/docs-v5/en/#overview-websocket-connect
func (c *conn) periodicPing(ctx context.Context) error {
timeout := (30 - 5) * time.Second
ticker := time.NewTicker(timeout)
defer ticker.Stop()
for i := 0; ; i++ {
select {
case <-ctx.Done():
return context.Cause(ctx)
case <-ticker.C:
// no-op
}
if c.closed.Load() {
return nil
}
err := c.Write(ctx, websocket.MessageText, []byte("ping"))
if err != nil {
slog.ErrorContext(ctx, "ping failed",
slog.Group("okxapi",
slog.String("err", err.Error()),
slog.String("url", c.url),
))
continue
}
slog.InfoContext(ctx, "ping successful",
slog.Group("okxapi",
slog.String("url", c.url),
))
}
}
func (c *conn) consume(ctx context.Context) error {
for {
select {
case <-ctx.Done():
return context.Cause(ctx)
default:
// no-op
}
msg, rawMsg, err := read[message](ctx, c)
if err != nil {
slog.ErrorContext(ctx, "read websocket message failed",
slog.Any("error", err))
continue
}
if string(rawMsg) == "pong" {
continue
}
switch msg.Event {
case "":
c.handler.HandlePushData(ctx, PushData[ChannelRawMessage, json.RawMessage]{
Arg: msg.Arg,
Data: msg.Data,
rawMessage: rawMsg,
})
case "subscribe", "unsubscribe", "error":
c.handler.HandleResponse(ctx, message2Response(*msg))
default:
c.handler.HandleUnknownMessage(ctx, rawMsg)
}
}
}
// message2Response
func message2Response(msg message) Response[ChannelRawMessage] {
return Response[ChannelRawMessage]{
Event: msg.Event,
Arg: msg.Arg,
Code: msg.Code,
Msg: msg.Msg,
ConnId: msg.ConnId,
}
}
// refreshLastActive refresh conn's last activity time
func (c *conn) refreshLastActive() {
c.lastActive.Swap(time.Now().UnixMilli())
}
// Close close conn
func (c *conn) Close() (err error) {
if c == nil || c.Conn == nil {
return nil
}
c.closed.Swap(true)
return c.Conn.Close(websocket.StatusNormalClosure, "")
}
// dial
func dial(ctx context.Context, url string) (*websocket.Conn, error) {
conn, _, err := websocket.Dial(ctx, url, nil)
if err != nil {
const format = "dial websocket server(addr: %q) failed"
return nil, errors.Join(fmt.Errorf(format, url), err)
}
return conn, err
}
// write
func write[T any](ctx context.Context, conn *conn, req Request[T]) (err error) {
defer func() {
if err != nil {
err = errors.Join(fmt.Errorf("failed to write"))
}
}()
if conn == nil {
return fmt.Errorf("websocket connection is nil")
}
err = validate(req.Args...)
if err != nil {
return err
}
b, err := json.Marshal(&req)
if err != nil {
return err
}
return conn.Write(ctx, websocket.MessageText, b)
}
type message struct {
// Operation
// login
// error
Event string `json:"event"`
Arg ChannelRawMessage `json:"arg"`
Data []json.RawMessage `json:"data"`
// Error code
Code string `json:"code"`
// Error message
Msg string `json:"msg"`
// WebSocket connection ID
ConnId string `json:"connId"`
}
// read read from conn
func read[Message any](ctx context.Context, conn *conn) (_ *Message, _ []byte, err error) {
for {
select {
case <-ctx.Done():
return nil, nil, context.Cause(ctx)
default:
// no-op
}
var msg Message
typ, b, err := conn.Read(ctx)
if err != nil {
return nil, nil, err
}
if typ != websocket.MessageText {
slog.InfoContext(ctx, fmt.Sprintf("got %s type message", typ))
continue
}
if string(b) == "pong" {
return nil, b, nil
}
err = json.NewDecoder(bytes.NewReader(b)).Decode(&msg)
if err != nil {
return nil, nil, err
}
return &msg, b, nil
}
}