-
Notifications
You must be signed in to change notification settings - Fork 2
/
websocket_session.go
285 lines (248 loc) · 6.79 KB
/
websocket_session.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
package common
import (
"context"
"encoding/json"
"fmt"
"sync"
"sync/atomic"
"nhooyr.io/websocket"
)
type websocketSession struct {
client WebsocketClient
handler WebsocketSessionHandler
globalRequestID uint64
pendingRequests map[uint64]*websocketSessionRequest
requestLock sync.Mutex
messagePatterns []*websocketSessionMessagePattern
}
type websocketSessionRequest struct {
WebsocketRequest
reply WebsocketReply
done chan error
}
func newWebsocketSessionRequest() *websocketSessionRequest {
return &websocketSessionRequest{
done: make(chan error),
}
}
type WebsocketSession interface {
// Loop hold this websocket connection until the connection disconnected or got error
// from message processor. return error same as SessionHandler.OnClose function.
Loop() (err error)
// RunLoop create new go routine and call IOLoop function.
RunLoop() chan error
Subscribe(ctx context.Context, streams ...string) (reply *WebsocketReply, err error)
SubscribeNoReply(ctx context.Context, streams ...string) (err error)
RegisterMessageHandler(factory WebsocketSessionMessageFactory, callback WebsocketSessionMessageCallback,
checker ...WebsocketSessionMessageChecker)
RequireMapHasAllKeys(keys ...string) WebsocketSessionMessageChecker
RequireMapKeyValue(key, value string) WebsocketSessionMessageChecker
}
type MockWebsocketSession interface {
WebsocketSession
MockProcessMessage(data []byte) error
}
type WebsocketSessionHandler interface {
OnUnknownMessage([]byte, interface{}) error
OnClose(err error)
}
type (
WebsocketSessionMessageChecker func(m interface{}) bool
WebsocketSessionMessageFactory func() interface{}
WebsocketSessionMessageCallback func(m interface{})
)
func WebsocketSessionMessageFactoryBuild[T any]() WebsocketSessionMessageFactory {
return func() interface{} {
return new(T)
}
}
func WebsocketSessionMessageHandlerBuild[T any](f func(*T)) WebsocketSessionMessageCallback {
return func(m interface{}) {
x := m.(*T)
f(x)
}
}
type websocketSessionMessagePattern struct {
Check []WebsocketSessionMessageChecker
New WebsocketSessionMessageFactory
Callback WebsocketSessionMessageCallback
}
func NewWebsocketSession(client WebsocketClient, handler WebsocketSessionHandler) WebsocketSession {
return &websocketSession{
client: client,
handler: handler,
pendingRequests: make(map[uint64]*websocketSessionRequest),
}
}
func NewMockWebsocketSession(handler WebsocketSessionHandler) MockWebsocketSession {
return &websocketSession{
handler: handler,
pendingRequests: make(map[uint64]*websocketSessionRequest),
}
}
func (ws *websocketSession) RequireMapHasAllKeys(keys ...string) WebsocketSessionMessageChecker {
return func(m interface{}) bool {
switch result := m.(type) {
case map[string]interface{}:
return MapHasAllKeys(result, keys...)
}
return false
}
}
func (ws *websocketSession) RequireMapKeyValue(key, value string) WebsocketSessionMessageChecker {
return func(m interface{}) bool {
switch result := m.(type) {
case map[string]interface{}:
x, ok := result[key]
if !ok {
return false
}
stringValue, ok := x.(string)
if !ok {
return false
}
return stringValue == value
}
return false
}
}
func (ws *websocketSession) RegisterMessageHandler(factory WebsocketSessionMessageFactory,
callback WebsocketSessionMessageCallback, checker ...WebsocketSessionMessageChecker,
) {
ws.messagePatterns = append(ws.messagePatterns, &websocketSessionMessagePattern{
Check: checker,
New: factory,
Callback: callback,
})
}
func (ws *websocketSession) MockProcessMessage(data []byte) error {
return ws.onMessage(websocket.MessageText, data)
}
func (ws *websocketSession) onMessage(messageType websocket.MessageType, data []byte) (err error) {
defer func() {
if err == nil {
return
}
err = fmt.Errorf("wssession handle message failed: %w", err)
}()
var unpackResult interface{}
if err = json.Unmarshal(data, &unpackResult); err != nil {
return err
}
return ws.processMessage(unpackResult, data)
}
func (ws *websocketSession) processMessage(m interface{}, data []byte) (err error) {
switch result := m.(type) {
case map[string]interface{}:
if MapHasKeys(result, "id", "method", "code") {
return ws.onRequestReply(data)
}
CHECK_LOOP:
for _, p := range ws.messagePatterns {
for _, c := range p.Check {
if !c(result) {
continue CHECK_LOOP
}
}
x := p.New()
if err = json.Unmarshal(data, x); err != nil {
return err
}
p.Callback(x)
return nil
}
case []interface{}:
var list []json.RawMessage
if err = json.Unmarshal(data, &list); err != nil {
return err
}
for idx, x := range result {
if err = ws.processMessage(x, list[idx]); err != nil {
return err
}
}
return nil
}
return ws.handler.OnUnknownMessage(data, m)
}
func (ws *websocketSession) onRequestReply(data []byte) (err error) {
var reply WebsocketReply
if err = json.Unmarshal(data, &reply); err != nil {
return err
}
ws.requestLock.Lock()
request, ok := ws.pendingRequests[reply.ID]
if ok {
delete(ws.pendingRequests, reply.ID)
}
ws.requestLock.Unlock()
if !ok {
return nil
}
request.reply = reply
close(request.done)
return
}
func (ws *websocketSession) request(request *websocketSessionRequest) (err error) {
request.ID = atomic.AddUint64(&ws.globalRequestID, 1)
d, err := json.Marshal(request.WebsocketRequest)
if err != nil {
return fmt.Errorf("wssession build request failed: %w", err)
}
ws.requestLock.Lock()
ws.pendingRequests[request.ID] = request
ws.requestLock.Unlock()
ws.client.Write(d)
return
}
func (ws *websocketSession) Loop() (err error) {
if err = ws.client.Loop(ws.onMessage); err == nil {
return
}
ws.handler.OnClose(err)
var pendingRequest []*websocketSessionRequest
ws.requestLock.Lock()
for _, req := range ws.pendingRequests {
pendingRequest = append(pendingRequest, req)
}
ws.pendingRequests = make(map[uint64]*websocketSessionRequest)
ws.requestLock.Unlock()
for _, req := range pendingRequest {
select {
case req.done <- err:
default:
}
}
return
}
func (ws *websocketSession) RunLoop() chan error {
c := make(chan error, 1)
go func() { c <- ws.Loop() }()
return c
}
func (ws *websocketSession) Subscribe(ctx context.Context, streams ...string) (
reply *WebsocketReply, err error,
) {
request := newWebsocketSessionRequest()
request.Method = "SUBSCRIBE"
request.Params = streams
if err = ws.request(request); err != nil {
return nil, err
}
select {
case <-ctx.Done():
return nil, ctx.Err()
case err = <-request.done:
return &request.reply, err
}
}
func (ws *websocketSession) SubscribeNoReply(ctx context.Context, streams ...string) (err error) {
reply, err := ws.Subscribe(ctx, streams...)
if err != nil {
return err
}
if err = reply.OK(); err != nil {
return err
}
return nil
}