-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathclient.go
348 lines (283 loc) · 6.77 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
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
package broadcaster
import (
"errors"
"fmt"
"net/url"
"sync"
"time"
"go.uber.org/atomic"
)
type CloseError struct {
Code int
Text string
}
func (e *CloseError) Error() string {
return fmt.Sprintf("Closed: %d %s", e.Code, e.Text)
}
// Client connection mode.
type ClientMode int
// Connection modes, can be used to force a specific connection type.
const (
ClientModeAuto ClientMode = 0
ClientModeWebsocket ClientMode = 1
ClientModeLongPoll ClientMode = 2
)
type messageChan chan ClientMessage
type Client struct {
Mode ClientMode
// Data passed when authenticating
AuthData map[string]interface{}
// Set when disconnecting
Error error
// Incoming messages
Messages chan ClientMessage
// Receives true when disconnected
Disconnected chan bool
// Timeout
Timeout time.Duration
// Ping interval
PingInterval time.Duration
// Reconnection attempts
MaxAttempts int
// Can be overwritten
UserAgent string
// Connection params
host string
path string
secure bool
// Only used while testing
skip_auth bool
// Internal bits
transport clientTransport
results map[string]messageChan
results_lock sync.Mutex
should_disconnect *atomic.Bool
attempts int
channels map[string]bool
channels_lock sync.Mutex
disconnect_lock sync.Mutex
disconnect_done bool
}
func NewClient(urlStr string) (*Client, error) {
u, err := url.Parse(urlStr)
if err != nil {
return nil, err
}
return &Client{
host: u.Host,
path: u.Path,
secure: u.Scheme == "https",
Timeout: 30 * time.Second,
PingInterval: 30 * time.Second,
MaxAttempts: 10,
channels: make(map[string]bool),
results: make(map[string]messageChan),
Messages: make(messageChan, 10),
Disconnected: make(chan bool),
should_disconnect: atomic.NewBool(false),
}, nil
}
func (c *Client) url(mode ClientMode) string {
scheme := "ws"
if mode == ClientModeLongPoll {
scheme = "http"
}
if c.secure {
scheme += "s"
}
return fmt.Sprintf("%s://%s%s", scheme, c.host, c.path)
}
func (c *Client) Connect() error {
c.should_disconnect.Store(false)
if c.Mode == ClientModeAuto || c.Mode == ClientModeWebsocket {
c.transport = newWebsocketClientTransport(c)
err := c.transport.Connect(c.AuthData)
if err != nil {
if c.Mode == ClientModeAuto {
c.transport = newlongpollClientTransport(c)
err := c.transport.Connect(c.AuthData)
if err != nil {
return err
}
} else {
return err
}
}
} else if c.Mode == ClientModeLongPoll {
c.transport = newlongpollClientTransport(c)
err := c.transport.Connect(c.AuthData)
if err != nil {
return err
}
} else {
return fmt.Errorf("Unknown client mode: %d", c.Mode)
}
if !c.skip_auth {
m, err := c.transport.Receive()
if err != nil {
return err
}
if m.Type() == AuthFailedMessage {
return &CloseError{
Code: 4401,
Text: m.Reason(),
}
} else if m.Type() != AuthOKMessage {
return fmt.Errorf("Expected %s or %s, got %s instead", AuthOKMessage, AuthFailedMessage, m.Type())
}
}
go c.listen()
c.channels_lock.Lock()
toSubscribe := make([]string, 0)
for channel, _ := range c.channels {
toSubscribe = append(toSubscribe, channel)
}
c.channels_lock.Unlock()
for _, channel := range toSubscribe {
err := c.Subscribe(channel)
if err != nil {
return err
}
}
return nil
}
func (c *Client) Disconnect() error {
c.should_disconnect.Store(true)
c.disconnect_lock.Lock()
defer c.disconnect_lock.Unlock()
if c.disconnect_done {
return nil
}
err := c.transport.Close()
if err != nil && c.Error == nil {
c.Error = err
}
c.results_lock.Lock()
for _, r := range c.results {
close(r)
}
c.results_lock.Unlock()
close(c.Messages)
c.disconnect_done = true
return c.Error
}
func (c *Client) disconnected() {
should_disconnect := c.should_disconnect.Load()
if should_disconnect {
return
}
if c.attempts == c.MaxAttempts {
c.Error = errors.New("Disconnected")
c.Disconnected <- true
}
c.attempts++
err := c.Connect()
if err == nil {
// Connected!
return
}
// Back off
<-time.After(time.Duration(c.attempts-1) * time.Second)
c.disconnected()
}
func (c *Client) listen() {
c.transport.onConnect()
for {
m, err := c.receive()
if err != nil {
c.disconnected()
return
}
if m.Type() == MessageMessage {
c.relay(m)
} else {
c.results_lock.Lock()
channel, ok := c.results[m.ResultId()]
c.results_lock.Unlock()
if !ok {
// Unrequested result?
} else {
channel <- m
}
}
}
}
// Prevents sending messages after we've disconnected
func (c *Client) relay(m ClientMessage) {
c.disconnect_lock.Lock()
defer c.disconnect_lock.Unlock()
if !c.disconnect_done {
c.Messages <- m
}
}
func (c *Client) send(msg string, data ClientMessage) error {
if data == nil {
data = make(ClientMessage)
}
data["__type"] = msg
return c.transport.Send(data)
}
func (c *Client) receive() (ClientMessage, error) {
return c.transport.Receive()
}
func (c *Client) resultChan(format string, args ...interface{}) chan ClientMessage {
name := fmt.Sprintf(format, args...)
channel := make(chan ClientMessage, 1)
c.results_lock.Lock()
c.results[name] = channel
c.results_lock.Unlock()
return channel
}
func (c *Client) call(msgType string, msg ClientMessage) (ClientMessage, error) {
result := c.resultChan("%s_%s", msgType, msg["channel"])
err := c.send(msgType, msg)
if err != nil {
return nil, err
}
m, ok := <-result
if !ok {
return nil, c.Error
}
return m, nil
}
func (c *Client) Subscribe(channel string) error {
m, err := c.call(SubscribeMessage, ClientMessage{"channel": channel})
if err != nil {
return err
}
if m.Type() == SubscribeErrorMessage {
return fmt.Errorf("Subscribe error: %s", m["reason"])
} else if m.Type() != SubscribeOKMessage {
return fmt.Errorf("Expected %s or %s, got %s instead", SubscribeOKMessage, SubscribeErrorMessage, m.Type())
}
if m["channel"] != channel {
return fmt.Errorf("Expected channel %s, got %s instead", channel, m["channel"])
}
c.channels_lock.Lock()
c.channels[channel] = true
c.channels_lock.Unlock()
return nil
}
func (c *Client) Unsubscribe(channel string) error {
m, err := c.call(UnsubscribeMessage, ClientMessage{"channel": channel})
if err != nil {
return err
}
if m.Type() != UnsubscribeOKMessage {
return fmt.Errorf("Expected %s, got %s instead", UnsubscribeOKMessage, m.Type())
}
if m["channel"] != channel {
return fmt.Errorf("Expected channel %s, got %s instead", channel, m["channel"])
}
c.channels_lock.Lock()
c.channels[channel] = false
c.channels_lock.Unlock()
return nil
}
type clientTransport interface {
Connect(authData ClientMessage) error
Close() error
Send(data ClientMessage) error
Receive() (ClientMessage, error)
onConnect()
}