-
Notifications
You must be signed in to change notification settings - Fork 0
/
connection.go
371 lines (299 loc) · 6.48 KB
/
connection.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
package twitchpubsub
import (
"encoding/json"
"fmt"
"sync"
"time"
"github.com/gorilla/websocket"
"github.com/pajbot/utils"
)
type connection struct {
host string
wsConn *websocket.Conn
connectedMutex sync.Mutex
connected bool
writer chan []byte
writerStop chan bool
reader chan []byte
readerStop chan bool
pongMutex sync.Mutex
lastPong time.Time
messageBus chan sharedMessage
doReconnect bool
topics []*websocketTopic
}
func newConnection(host string, messageBus messageBusType) *connection {
return &connection{
host: host,
writer: make(chan []byte, writerBufferLength),
writerStop: make(chan bool),
reader: make(chan []byte, readerBufferLength),
readerStop: make(chan bool),
messageBus: messageBus,
}
}
func (c *connection) startReader() {
defer func() {
c.doReconnect = true
c.setConnected(false)
c.stopWriter()
c.wsConn.Close()
c.onDisconnect()
}()
// Read
go func() {
for {
messageType, payloadBytes, err := c.wsConn.ReadMessage()
if err != nil {
c.readerStop <- true
return
}
if messageType == websocket.TextMessage {
c.reader <- payloadBytes
}
}
}()
for {
select {
case payloadBytes := <-c.reader:
if err := c.parse(payloadBytes); err != nil {
fmt.Println("Error parsing received websocket message:", err)
}
case <-c.readerStop:
return
}
}
}
func (c *connection) onPong() {
c.pongMutex.Lock()
c.lastPong = time.Now()
c.pongMutex.Unlock()
}
func (c *connection) lastPongWithinLimits(pingTime time.Time) bool {
c.pongMutex.Lock()
defer c.pongMutex.Unlock()
return c.lastPong.Sub(pingTime) < pongDeadlineTime
}
func (c *connection) writeMessage(msg interface{}) error {
b, err := json.Marshal(msg)
if err != nil {
return err
}
c.writer <- b
return nil
}
func (c *connection) ping() error {
msg := &Base{
Type: "PING",
}
pingTime := time.Now()
err := c.writeMessage(msg)
if err != nil {
return err
}
time.AfterFunc(pongDeadlineTime, func() {
if !c.lastPongWithinLimits(pingTime) {
fmt.Println("[go-twitch-pubsub] Lost connection, will try to reconnect")
c.doReconnect = true
c.onDisconnect()
}
})
return nil
}
func (c *connection) startPing() {
time.AfterFunc(pingInterval, func() {
_ = c.ping()
c.startPing()
})
}
func (c *connection) setConnected(newConnectedState bool) {
c.connectedMutex.Lock()
c.connected = newConnectedState
c.connectedMutex.Unlock()
}
func (c *connection) stopWriter() {
c.writerStop <- true
for len(c.writer) > 0 {
<-c.writer
}
}
// IsConnected returns the current connection state
func (c *connection) IsConnected() bool {
c.connectedMutex.Lock()
defer c.connectedMutex.Unlock()
return c.connected
}
func (c *connection) Disconnect() {
c.stopReader()
// when stopReader has finished, it will stop the writer
c.wsConn.Close()
}
func (c *connection) stopReader() {
c.readerStop <- true
for len(c.reader) > 0 {
<-c.reader
}
}
func (c *connection) connect() error {
var err error
c.wsConn, _, err = websocket.DefaultDialer.Dial(c.host, nil)
if err != nil {
c.doReconnect = true
c.onDisconnect()
return err
}
c.setConnected(true)
go c.startReader()
go c.startWriter()
c.onConnected()
return nil
}
func (c *connection) onConnected() {
go c.startPing()
}
func (c *connection) onDisconnect() {
if !c.doReconnect {
// Do full closes
return
}
time.AfterFunc(reconnectInterval, func() {
c.tryReconnect()
})
}
func (c *connection) tryReconnect() error {
return c.connect()
}
func (c *connection) startWriter() {
for {
select {
case payload := <-c.writer:
c.wsConn.WriteMessage(websocket.TextMessage, payload)
case <-c.writerStop:
return
}
}
}
func (c *connection) parse(b []byte) (err error) {
baseMsg := Base{}
err = json.Unmarshal(b, &baseMsg)
if err != nil {
return
}
switch baseMsg.Type {
case "PONG":
c.onPong()
return
case "reward-redeemed":
fmt.Println("this is redeemed")
return
case "MESSAGE":
return c.parseMessage(b)
case "RESPONSE":
return c.parseResponse(b)
default:
// fmt.Println("Received unknown message:", string(b))
return
}
}
func (c *connection) parseMessage(b []byte) error {
type message struct {
Data struct {
Topic string `json:"topic"`
// Message is an escaped json string
Message string `json:"message"`
} `json:"data"`
}
msg := message{}
if err := json.Unmarshal(b, &msg); err != nil {
fmt.Println("[go-twitch-pubsub] Error unmarshalling incoming message:", err)
return nil
}
innerMessageBytes := []byte(msg.Data.Message)
switch getMessageType(msg.Data.Topic) {
case messageTypeModerationAction:
d, err := parseModerationAction(innerMessageBytes)
if err != nil {
return err
}
c.messageBus <- sharedMessage{
Topic: msg.Data.Topic,
Message: d,
}
case messageTypeBitsEvent:
d, err := parseBitsEvent(innerMessageBytes)
if err != nil {
return err
}
c.messageBus <- sharedMessage{
Topic: msg.Data.Topic,
Message: d,
}
case messageTypePointsEvent:
d, err := parsePointsEvent(innerMessageBytes)
if err != nil {
return err
}
c.messageBus <- sharedMessage{
Topic: msg.Data.Topic,
Message: d,
}
case messageTypePointsAction:
d, err := parsePointsAction(innerMessageBytes)
if err != nil {
return err
}
c.messageBus <- sharedMessage{
Topic: msg.Data.Topic,
Message: d,
}
default:
fallthrough
case messageTypeUnknown:
// This can be used while implementing new message types
}
return nil
}
func (c *connection) sendListen(topic *websocketTopic) {
nonce, _ := utils.GenerateRandomString(32)
msg := Listen{
Base: Base{
Type: TypeListen,
},
Nonce: nonce,
Data: ListenData{
Topics: []string{topic.name},
AuthToken: topic.authToken,
},
}
topic.nonce = nonce
c.topics = append(c.topics, topic)
c.writeMessage(msg)
}
func (c *connection) parseResponse(b []byte) error {
// A "RESPONSE" type message means it's a response to something we sent
// Most likely, this will be a response to a "LISTEN" message we sent earlier
var msg ResponseMessage
if err := json.Unmarshal(b, &msg); err != nil {
return err
}
if msg.Error == "" {
for _, topic := range c.topics {
if topic.nonce == msg.Nonce {
topic.connected = true
return nil
}
}
} else {
for _, topic := range c.topics {
if topic.nonce == msg.Nonce {
fmt.Println("[go-twitch-pubsub] Error connecting to", topic.hash)
topic.connected = true
return nil
}
}
}
return nil
}
func (c *connection) numTopics() int {
return len(c.topics)
}