-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.go
264 lines (210 loc) · 5.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
package xwebsocket
import (
"context"
"errors"
"fmt"
"time"
"github.com/go-x-pkg/log"
"github.com/gorilla/websocket"
"go.uber.org/zap"
)
type ReaderCb func(t int, raw []byte) error
var ErrChanIsFull = errors.New("chan is full")
type Client struct {
conn *websocket.Conn
ctx context.Context
cancel context.CancelFunc
isZapLogger bool
rawMsgChan chan *RawMsg
}
// RawMsgSend send RawMsg.
func (wsc *Client) RawMsgSend(msg *RawMsg) {
wsc.rawMsgChan <- msg
}
// TextMsgSend sends text message.
func (wsc *Client) TextMsgSend(text []byte) {
wsc.TextMsgSendWithDone(text, nil)
}
// TextMsgSendWithDone sends text message with done send chan.
func (wsc *Client) TextMsgSendWithDone(text []byte, done chan error) {
wsc.rawMsgChan <- &RawMsg{
Type: websocket.TextMessage,
Data: text,
Done: done,
}
}
// RawMsgSendNonBlock sends msg and do not block.
func (wsc *Client) RawMsgSendNonBlock(msg *RawMsg) {
select {
case wsc.rawMsgChan <- msg:
case <-wsc.ctx.Done():
default:
select {
case msg.Done <- ErrChanIsFull:
case <-wsc.ctx.Done():
}
}
}
// Disconnect cancel ctx.
// y d better cancel parent context in order to disconnect.
func (wsc *Client) Disconnect() { wsc.cancel() }
// WriteWorker handles all writes operations for websocket connection.
// Some ws endpoints don't support ping/pong.
// enablePing == false. pingPeriod, writeTimeout are useless.
// enablePongHandler == false. readTimeout is useless.
func (wsc *Client) WriteWorker(fnLog log.FnT, traceID string,
// ping
enablePing bool,
pingPeriod,
writeTimeout time.Duration,
// pong
enablePongHandler bool,
readTimeout time.Duration,
) {
lastPingAt := time.Now()
var chanPing <-chan time.Time
if enablePing {
ticker := time.NewTicker(pingPeriod)
chanPing = ticker.C
defer ticker.Stop()
}
defer func() {
wsc.cancel()
if err := wsc.conn.Close(); err != nil {
fnLog(log.Error, "error close websocket connection",
zap.String("traceId", traceID),
zap.Error(err))
}
}()
start := time.Now()
fnLog(log.Info, "writer start",
zap.Bool("enablePing", enablePing),
zap.Duration("pingPeriod", pingPeriod),
zap.Duration("writeTimeout", writeTimeout),
zap.Bool("enablePongHandler", enablePongHandler),
zap.Duration("readTimeout", readTimeout),
zap.String("traceId", traceID))
defer func() {
fnLog(log.Info, "writer stop",
zap.Duration("uptime", time.Since(start)),
zap.String("traceId", traceID))
}()
if enablePongHandler {
wsc.conn.SetPongHandler(func(string) error {
if err := wsc.conn.SetReadDeadline(time.Now().Add(readTimeout)); err != nil {
err := fmt.Errorf("error set read deadline: %w")
fnLog(log.Debug, "set read deadline",
zap.Duration("latency", time.Since(lastPingAt)),
zap.String("traceId", traceID),
zap.Error(err))
return err
}
fnLog(log.Debug, "pong",
zap.Duration("latency", time.Since(lastPingAt)),
zap.String("traceId", traceID))
return nil
})
}
for {
select {
case msg := <-wsc.rawMsgChan:
if msg.Data != nil {
fnLog(log.Debug, "message write",
zap.ByteString("data", msg.Data),
zap.String("traceId", traceID))
}
err := wsc.conn.WriteMessage(msg.Type, msg.Data)
if err != nil {
fnLog(log.Error, "write error",
zap.String("traceId", traceID),
zap.Error(err))
}
if msg.Done != nil {
msg.Done <- err
}
case <-chanPing:
if err := wsc.conn.SetWriteDeadline(time.Now().Add(writeTimeout)); err != nil {
fnLog(log.Error, "error set write deadline",
zap.Duration("writeTimeout", writeTimeout),
zap.String("traceId", traceID),
zap.Error(err))
}
if err := wsc.conn.WriteMessage(websocket.PingMessage, []byte{}); err != nil {
if err != websocket.ErrCloseSent {
err = fmt.Errorf("write ping message error: %w", err)
fnLog(log.Error, "ping error",
zap.String("traceId", traceID),
zap.Error(err))
}
return
}
lastPingAt = time.Now()
fnLog(log.Debug, "ping",
zap.Duration("period", pingPeriod),
zap.String("traceId", traceID))
case <-wsc.ctx.Done():
return
}
}
}
// ReadWorker handles all reads operations for websocket connection.
//
// prefix => log-prefix.
func (wsc *Client) ReadWorker(fnLog log.FnT, traceID string, cb ReaderCb) {
defer func() {
wsc.cancel()
}()
for {
select {
case <-wsc.ctx.Done():
return
default:
}
t, raw, err := wsc.conn.ReadMessage()
if err != nil {
if !websocket.IsCloseError(
err,
// 1001 indicates that an endpoint is "going away", such as a server
// going down or a browser having navigated away from a page.
websocket.CloseGoingAway,
) {
select {
case <-wsc.ctx.Done():
// websocket read message error: "read tcp ...: use of closed network connection"
default:
fnLog(log.Error, "websocket read message error",
zap.String("traceId", traceID),
zap.Error(err))
}
}
break
}
if t != websocket.TextMessage {
fnLog(log.Warn, "got unsupported websocket message type",
zap.String("traceId", traceID))
continue
}
if cb != nil {
fnLog(log.Debug, "message read",
zap.Int("type", t),
zap.ByteString("data", raw),
zap.String("traceId", traceID))
// execute callback
if err := cb(t, raw); err != nil {
fnLog(log.Error, "websocket processing message error",
zap.String("traceId", traceID),
zap.Error(err))
return
}
}
}
}
// OnWSUpgrade should be triggered whe websocket upgraded.
func (wsc *Client) OnWSUpgrade(ctx context.Context, conn *websocket.Conn, rawMsgChan chan *RawMsg) {
if ctx == nil {
ctx = context.Background()
}
wsc.ctx, wsc.cancel = context.WithCancel(ctx)
wsc.conn = conn
wsc.rawMsgChan = rawMsgChan
}