-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebsocket.go
405 lines (348 loc) · 9.04 KB
/
websocket.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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
package graphqltogo
import (
"encoding/json"
"fmt"
"io"
"net/http"
"strconv"
"sync/atomic"
"time"
"github.com/gorilla/websocket"
)
const maxRetries = 5
const retryInterval = 2 * time.Second
type webSocketMessage struct {
Type string `json:"type"`
ID string `json:"id,omitempty"`
Payload map[string]interface{} `json:"payload,omitempty"`
}
func (client *GraphQLClient) openWebSocket() error {
client.mu.Lock()
if client.wsConn != nil {
client.mu.Unlock()
return nil
}
client.mu.Unlock() // Unlock before dialing
header := http.Header{}
header.Set("Sec-WebSocket-Protocol", "graphql-transport-ws")
conn, err := client.dialWebSocket(header)
if err != nil {
return err
}
client.mu.Lock()
client.wsConn = conn
client.connectionReady = false
client.mu.Unlock()
if err := client.sendInitMessage(); err != nil {
return err
}
go client.listen()
return nil
}
func (client *GraphQLClient) dialWebSocket(header http.Header) (*websocket.Conn, error) {
var conn *websocket.Conn
var resp *http.Response
var err error
for i := 0; i < maxRetries; i++ {
fmt.Println("Connecting to WebSocket endpoint:", client.wsEndpoint)
conn, resp, err = websocket.DefaultDialer.Dial(client.wsEndpoint, header)
if err == nil {
if resp != nil {
defer resp.Body.Close()
}
break
}
client.logDialError(resp, err)
fmt.Printf("Retrying in %v...\n", retryInterval)
time.Sleep(retryInterval)
}
if err != nil {
return nil, fmt.Errorf("failed to dial WebSocket after %d attempts: %w", maxRetries, err)
}
return conn, nil
}
func (client *GraphQLClient) logDialError(resp *http.Response, err error) {
if resp != nil {
fmt.Println("Handshake failed with status:", resp.Status)
body, _ := io.ReadAll(resp.Body)
fmt.Println("Response body:", string(body))
} else {
fmt.Println("Dial error:", err)
}
}
func (client *GraphQLClient) sendInitMessage() error {
initMessage := map[string]interface{}{
"type": "connection_init",
"payload": map[string]interface{}{
"Authorization": client.headers["Authorization"],
},
}
if err := client.wsConn.WriteJSON(initMessage); err != nil {
return fmt.Errorf("failed to send init message: %w", err)
}
return nil
}
func (client *GraphQLClient) listen() {
client.wg.Add(1)
defer client.wg.Done()
for {
client.mu.Lock()
conn := client.wsConn
client.mu.Unlock()
if conn == nil {
fmt.Println("WebSocket connection is nil, stopping listen goroutine")
return
}
var result webSocketMessage
if err := conn.ReadJSON(&result); err != nil {
client.handleReadError(err)
return
}
client.handleMessage(result)
}
}
func (client *GraphQLClient) handleReadError(err error) {
client.mu.Lock()
client.wsConn = nil
client.mu.Unlock()
if websocket.IsCloseError(err, websocket.CloseNormalClosure, websocket.CloseGoingAway) {
fmt.Println("WebSocket closed:", err)
return
}
if websocket.IsCloseError(err, 4403) {
fmt.Println("Authentication error:", err)
if client.authErrorHandler != nil {
client.authErrorHandler()
}
client.reconnect()
} else {
fmt.Println("WebSocket read error:", err)
client.closeWebSocket()
}
}
func (client *GraphQLClient) handleMessage(result webSocketMessage) {
switch result.Type {
case "next", "error":
client.handleDataMessage(result)
case "complete":
client.handleCompleteMessage(result.ID)
case "connection_ack":
fmt.Println("WebSocket connection established")
client.mu.Lock()
client.connectionReady = true
client.mu.Unlock()
case "ping":
client.sendPong()
case "pong":
// No action needed
default:
fmt.Println("Unknown message type:", result.Type)
}
}
func (client *GraphQLClient) handleDataMessage(result webSocketMessage) {
subID := result.ID
payload := result.Payload
client.mu.Lock()
sub, ok := client.subs[subID]
client.mu.Unlock()
if !ok {
fmt.Println("Subscription not found for ID:", subID)
return
}
target := sub.NewTarget()
jsonData, err := json.Marshal(payload)
if err != nil {
fmt.Println("Error serializing payload:", err)
return
}
err = json.Unmarshal(jsonData, target)
if err != nil {
fmt.Println("Error deserializing payload:", err)
return
}
sub.Channel <- target
}
func (client *GraphQLClient) handleCompleteMessage(subID string) {
fmt.Println("Subscription completed")
client.mu.Lock()
if sub, ok := client.subs[subID]; ok {
close(sub.Channel)
delete(client.subs, subID)
}
shouldClose := len(client.subs) == 0
client.mu.Unlock()
if shouldClose {
client.closeWebSocket()
}
}
func (client *GraphQLClient) sendPong() {
client.mu.Lock()
defer client.mu.Unlock()
pongMessage := webSocketMessage{
Type: "pong",
}
if err := client.wsConn.WriteJSON(pongMessage); err != nil {
fmt.Println("Failed to send pong message:", err)
}
}
func (client *GraphQLClient) reconnect() {
client.mu.Lock()
if client.wsConn != nil {
client.mu.Unlock()
return
}
client.mu.Unlock()
for {
fmt.Println("Attempting to reconnect...")
if err := client.openWebSocket(); err == nil {
client.resubscribeAll()
return
}
fmt.Printf("Retrying in %v...\n", retryInterval)
time.Sleep(retryInterval)
}
}
func (client *GraphQLClient) resubscribeAll() {
client.mu.Lock()
defer client.mu.Unlock()
for subID, sub := range client.subs {
startMessage := map[string]interface{}{
"id": subID,
"type": "subscribe",
"payload": map[string]interface{}{
"query": sub.Query,
"variables": sub.Variables,
},
}
if err := client.wsConn.WriteJSON(startMessage); err != nil {
fmt.Printf("Failed to resubscribe to %s: %v\n", subID, err)
close(sub.Channel)
delete(client.subs, subID)
}
}
}
func (client *GraphQLClient) closeWebSocket() {
client.mu.Lock()
defer client.wg.Wait()
defer client.mu.Unlock()
if client.wsConn != nil {
closeMessage := map[string]interface{}{
"type": "connection_terminate",
}
if err := client.wsConn.WriteJSON(closeMessage); err != nil {
fmt.Println("Failed to send close message:", err)
}
if err := client.wsConn.Close(); err != nil {
fmt.Println("Failed to close WebSocket connection:", err)
}
client.wsConn = nil
fmt.Println("WebSocket connection closed")
}
}
func (client *GraphQLClient) generateUniqueID() string {
return strconv.FormatInt(atomic.AddInt64(&client.counter, 1), 10)
}
func (client *GraphQLClient) subscribe(operation string, variables map[string]interface{}, newTarget func() interface{}) (<-chan interface{}, func() error, error) {
client.mu.Lock()
if client.wsConn == nil {
client.mu.Unlock()
if err := client.openWebSocket(); err != nil {
return nil, nil, err
}
client.mu.Lock()
}
subID := client.generateUniqueID()
subChan := make(chan interface{})
client.subs[subID] = subscription{
Channel: subChan,
Query: operation,
Variables: variables,
NewTarget: newTarget,
}
client.mu.Unlock()
// Wait for connection_ack before sending subscribe message
for {
client.mu.Lock()
if client.connectionReady {
client.mu.Unlock()
break
}
client.mu.Unlock()
time.Sleep(100 * time.Millisecond)
}
client.mu.Lock()
defer client.mu.Unlock()
if err := client.sendSubscribeMessage(subID, operation, variables); err != nil {
client.cleanupSubscription(subID)
return nil, nil, err
}
return subChan, func() error {
return client.unsubscribe(subID)
}, nil
}
func (client *GraphQLClient) sendSubscribeMessage(subID, operation string, variables map[string]interface{}) error {
startMessage := webSocketMessage{
ID: subID,
Type: "subscribe",
Payload: map[string]interface{}{
"query": operation,
"variables": variables,
},
}
if err := client.wsConn.WriteJSON(startMessage); err != nil {
return fmt.Errorf("failed to send start message: %w", err)
}
return nil
}
func (client *GraphQLClient) cleanupSubscription(subID string) {
client.mu.Lock()
delete(client.subs, subID)
shouldClose := len(client.subs) == 0
client.mu.Unlock()
if shouldClose {
client.closeWebSocket()
}
}
func (client *GraphQLClient) unsubscribe(subID string) error {
client.mu.Lock()
defer client.mu.Unlock()
if client.wsConn == nil {
return fmt.Errorf("no active WebSocket connection")
}
stopMessage := webSocketMessage{
ID: subID,
Type: "complete",
}
fmt.Println("Unsubscribing from subscription:", subID)
if err := client.wsConn.WriteJSON(stopMessage); err != nil {
return fmt.Errorf("failed to send stop message: %w", err)
}
return nil
}
func (client *GraphQLClient) Close() {
client.mu.Lock()
if client.wsConn != nil {
client.mu.Unlock()
client.closeWebSocket()
} else {
client.mu.Unlock()
}
}
func Subscribe[T interface{}](client *GraphQLClient, operation string, variables map[string]interface{}) (<-chan *GraphQLResponse[T], func() error, error) {
subChan, subId, err := client.subscribe(operation, variables, func() interface{} {
return new(GraphQLResponse[T])
})
if err != nil {
return nil, nil, err
}
typedChan := make(chan *GraphQLResponse[T])
client.wg.Add(1)
go func() {
defer client.wg.Done()
defer close(typedChan)
for msg := range subChan {
typedChan <- msg.(*GraphQLResponse[T])
}
}()
return typedChan, subId, nil
}