-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
websocket.go
151 lines (128 loc) · 3.84 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
package client
import (
"encoding/json"
"fmt"
"io"
"net/http/httptest"
"reflect"
"strings"
"github.com/gorilla/websocket"
)
const (
connectionInitMsg = "connection_init" // Client -> Server
startMsg = "start" // Client -> Server
connectionAckMsg = "connection_ack" // Server -> Client
connectionKaMsg = "ka" // Server -> Client
dataMsg = "data" // Server -> Client
errorMsg = "error" // Server -> Client
)
type operationMessage struct {
Payload json.RawMessage `json:"payload,omitempty"`
ID string `json:"id,omitempty"`
Type string `json:"type"`
}
type Subscription struct {
Close func() error
Next func(response interface{}) error
}
func errorSubscription(err error) *Subscription {
return &Subscription{
Close: func() error { return nil },
Next: func(response interface{}) error {
return err
},
}
}
func (p *Client) Websocket(query string, options ...Option) *Subscription {
return p.WebsocketWithPayload(query, nil, options...)
}
// Grab a single response from a websocket based query
func (p *Client) WebsocketOnce(query string, resp interface{}, options ...Option) error {
sock := p.Websocket(query, options...)
defer sock.Close()
if reflect.ValueOf(resp).Kind() == reflect.Ptr {
return sock.Next(resp)
}
//TODO: verify this is never called and remove it
return sock.Next(&resp)
}
func (p *Client) WebsocketWithPayload(query string, initPayload map[string]interface{}, options ...Option) *Subscription {
r, err := p.newRequest(query, options...)
if err != nil {
return errorSubscription(fmt.Errorf("request: %w", err))
}
requestBody, err := io.ReadAll(r.Body)
if err != nil {
return errorSubscription(fmt.Errorf("parse body: %w", err))
}
srv := httptest.NewServer(p.h)
host := strings.ReplaceAll(srv.URL, "http://", "ws://")
c, resp, err := websocket.DefaultDialer.Dial(host+r.URL.Path, r.Header)
if err != nil {
return errorSubscription(fmt.Errorf("dial: %w", err))
}
defer resp.Body.Close()
initMessage := operationMessage{Type: connectionInitMsg}
if initPayload != nil {
initMessage.Payload, err = json.Marshal(initPayload)
if err != nil {
return errorSubscription(fmt.Errorf("parse payload: %w", err))
}
}
if err = c.WriteJSON(initMessage); err != nil {
return errorSubscription(fmt.Errorf("init: %w", err))
}
var ack operationMessage
if err = c.ReadJSON(&ack); err != nil {
return errorSubscription(fmt.Errorf("ack: %w", err))
}
if ack.Type != connectionAckMsg {
return errorSubscription(fmt.Errorf("expected ack message, got %#v", ack))
}
var ka operationMessage
if err = c.ReadJSON(&ka); err != nil {
return errorSubscription(fmt.Errorf("ack: %w", err))
}
if ka.Type != connectionKaMsg {
return errorSubscription(fmt.Errorf("expected ack message, got %#v", ack))
}
if err = c.WriteJSON(operationMessage{Type: startMsg, ID: "1", Payload: requestBody}); err != nil {
return errorSubscription(fmt.Errorf("start: %w", err))
}
return &Subscription{
Close: func() error {
srv.Close()
return c.Close()
},
Next: func(response interface{}) error {
for {
var op operationMessage
err := c.ReadJSON(&op)
if err != nil {
return err
}
switch op.Type {
case dataMsg:
break
case connectionKaMsg:
continue
case errorMsg:
return fmt.Errorf(string(op.Payload))
default:
return fmt.Errorf("expected data message, got %#v", op)
}
var respDataRaw Response
err = json.Unmarshal(op.Payload, &respDataRaw)
if err != nil {
return fmt.Errorf("decode: %w", err)
}
// we want to unpack even if there is an error, so we can see partial responses
unpackErr := unpack(respDataRaw.Data, response)
if respDataRaw.Errors != nil {
return RawJsonError{respDataRaw.Errors}
}
return unpackErr
}
},
}
}