-
Notifications
You must be signed in to change notification settings - Fork 139
Expand file tree
/
Copy pathwebsocket.go
More file actions
304 lines (272 loc) · 7.09 KB
/
websocket.go
File metadata and controls
304 lines (272 loc) · 7.09 KB
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
package graphql
import (
"context"
"encoding/binary"
"encoding/json"
"fmt"
"net/http"
"strings"
"sync"
"time"
"github.com/google/uuid"
)
const (
webSocketMethod = "websocket"
webSocketTypeConnInit = "connection_init"
webSocketTypeConnAck = "connection_ack"
webSocketTypeSubscribe = "subscribe"
webSocketTypeNext = "next"
webSocketTypeError = "error"
webSocketTypeComplete = "complete"
websocketConnAckTimeOut = time.Second * 30
)
// Close codes defined in RFC 6455, section 11.7.
const (
closeNormalClosure = 1000
closeNoStatusReceived = 1005
)
// The message types are defined in RFC 6455, section 11.8.
const (
// textMessage denotes a text data message. The text message payload is
// interpreted as UTF-8 encoded text data.
textMessage = 1
// closeMessage denotes a close control message. The optional message
// payload contains a numeric code and text. Use the FormatCloseMessage
// function to format a close message payload.
closeMessage = 8
)
type webSocketClient struct {
Dialer Dialer
header http.Header
conn WSConn
connParams map[string]interface{}
errChan chan error
subscriptions subscriptionMap
endpoint string
isClosing bool
sync.Mutex
}
type webSocketInitMessage struct {
Payload map[string]interface{} `json:"payload"`
Type string `json:"type"`
}
type webSocketSendMessage struct {
Payload *Request `json:"payload"`
Type string `json:"type"`
ID string `json:"id"`
}
type webSocketReceiveMessage struct {
Type string `json:"type"`
ID string `json:"id"`
Payload json.RawMessage `json:"payload"`
}
func (w *webSocketClient) sendInit() error {
connInitMsg := webSocketInitMessage{
Type: webSocketTypeConnInit,
Payload: w.connParams,
}
return w.sendStructAsJSON(connInitMsg)
}
func (w *webSocketClient) sendStructAsJSON(object any) error {
jsonBytes, err := json.Marshal(object)
if err != nil {
return err
}
return w.conn.WriteMessage(textMessage, jsonBytes)
}
func (w *webSocketClient) waitForConnAck() error {
var connAckReceived bool
var err error
start := time.Now()
for !connAckReceived {
connAckReceived, err = w.receiveWebSocketConnAck()
if err != nil {
return err
}
if time.Since(start) > websocketConnAckTimeOut {
return fmt.Errorf("timed out while waiting for connAck (> %v)", websocketConnAckTimeOut)
}
}
return nil
}
func (w *webSocketClient) handleErr(err error) {
w.Lock()
defer w.Unlock()
if !w.isClosing {
// Send while holding lock to prevent Close() from closing
// the channel between our check and our send
w.errChan <- err
}
}
func (w *webSocketClient) listenWebSocket() {
for {
w.Lock()
isClosing := w.isClosing
w.Unlock()
if isClosing {
return
}
_, message, err := w.conn.ReadMessage()
if err != nil {
w.handleErr(err)
return
}
err = w.forwardWebSocketData(message)
if err != nil {
w.handleErr(err)
return
}
}
}
func (w *webSocketClient) forwardWebSocketData(message []byte) error {
var wsMsg webSocketReceiveMessage
err := json.Unmarshal(message, &wsMsg)
if err != nil {
return err
}
if wsMsg.ID == "" { // e.g. keep-alive messages
return nil
}
w.Lock()
sub := w.subscriptions.get(wsMsg.ID)
if sub == nil {
w.Unlock()
return fmt.Errorf("received message for unknown subscription ID '%s'", wsMsg.ID)
}
if sub.closed {
// Already closed, ignore message
w.Unlock()
return nil
}
if wsMsg.Type == webSocketTypeComplete {
// Server is telling us the subscription is complete
w.subscriptions.closeChannel(wsMsg.ID)
w.subscriptions.delete(wsMsg.ID)
w.Unlock()
return nil
}
// Forward the data to the subscription channel.
// We release the lock while calling the forward function to avoid holding
// the lock while doing potentially slow user code.
w.Unlock()
return sub.forwardDataFunc(sub.interfaceChan, wsMsg.Payload)
}
func (w *webSocketClient) receiveWebSocketConnAck() (bool, error) {
_, message, err := w.conn.ReadMessage()
if err != nil {
return false, err
}
return checkConnectionAckReceived(message)
}
func checkConnectionAckReceived(message []byte) (bool, error) {
wsMessage := &webSocketSendMessage{}
err := json.Unmarshal(message, wsMessage)
if err != nil {
return false, err
}
return wsMessage.Type == webSocketTypeConnAck, nil
}
func (w *webSocketClient) Start(ctx context.Context) (errChan chan error, err error) {
w.conn, err = w.Dialer.DialContext(ctx, w.endpoint, w.header)
if err != nil {
return nil, err
}
err = w.sendInit()
if err != nil {
w.conn.Close()
return nil, err
}
err = w.waitForConnAck()
if err != nil {
w.conn.Close()
return nil, err
}
go w.listenWebSocket()
return w.errChan, err
}
func (w *webSocketClient) Close() error {
if w.conn == nil {
return nil
}
err := w.UnsubscribeAll()
if err != nil {
return fmt.Errorf("failed to unsubscribe: %w", err)
}
err = w.conn.WriteMessage(closeMessage, formatCloseMessage(closeNormalClosure, ""))
if err != nil {
return fmt.Errorf("failed to send closure message: %w", err)
}
w.Lock()
defer w.Unlock()
w.isClosing = true
close(w.errChan)
return w.conn.Close()
}
func (w *webSocketClient) Subscribe(req *Request, interfaceChan interface{}, forwardDataFunc ForwardDataFunction) (string, error) {
if req.Query != "" {
if strings.HasPrefix(strings.TrimSpace(req.Query), "query") {
return "", fmt.Errorf("client does not support queries")
}
if strings.HasPrefix(strings.TrimSpace(req.Query), "mutation") {
return "", fmt.Errorf("client does not support mutations")
}
}
subscriptionID := uuid.NewString()
w.Lock()
w.subscriptions.create(subscriptionID, interfaceChan, forwardDataFunc)
w.Unlock()
subscriptionMsg := webSocketSendMessage{
Type: webSocketTypeSubscribe,
Payload: req,
ID: subscriptionID,
}
err := w.sendStructAsJSON(subscriptionMsg)
if err != nil {
w.Lock()
w.subscriptions.delete(subscriptionID)
w.Unlock()
return "", err
}
return subscriptionID, nil
}
func (w *webSocketClient) Unsubscribe(subscriptionID string) error {
completeMsg := webSocketSendMessage{
Type: webSocketTypeComplete,
ID: subscriptionID,
}
err := w.sendStructAsJSON(completeMsg)
if err != nil {
return err
}
w.Lock()
defer w.Unlock()
w.subscriptions.closeChannel(subscriptionID)
w.subscriptions.delete(subscriptionID)
return nil
}
func (w *webSocketClient) UnsubscribeAll() error {
w.Lock()
subscriptionIDs := w.subscriptions.getAllIDs()
w.Unlock()
for _, subscriptionID := range subscriptionIDs {
err := w.Unsubscribe(subscriptionID)
if err != nil {
return err
}
}
return nil
}
// formatCloseMessage formats closeCode and text as a WebSocket close message.
// An empty message is returned for code CloseNoStatusReceived.
func formatCloseMessage(closeCode int, text string) []byte {
if closeCode == closeNoStatusReceived {
// Return empty message because it's illegal to send
// CloseNoStatusReceived. Return non-nil value in case application
// checks for nil.
return []byte{}
}
buf := make([]byte, 2+len(text))
binary.BigEndian.PutUint16(buf, uint16(closeCode))
copy(buf[2:], text)
return buf
}