-
Notifications
You must be signed in to change notification settings - Fork 927
/
wsapi.go
223 lines (184 loc) · 3.91 KB
/
wsapi.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
package discordgo
import (
"encoding/json"
"net"
"sync"
"sync/atomic"
"time"
"github.com/gobwas/ws"
"github.com/gobwas/ws/wsutil"
)
type wsWriter struct {
session *Session
conn net.Conn
closer chan interface{}
incoming chan outgoingEvent
sendCloseQueue chan []byte
readyRecv chan bool
waitingForIdentify bool
queuedEvents []*outgoingEvent
writer *wsutil.Writer
sendRatelimiter chan bool
}
func newWSWriter(conn net.Conn, session *Session, closer chan interface{}) *wsWriter {
return &wsWriter{
conn: conn,
session: session,
closer: closer,
incoming: make(chan outgoingEvent, 10),
sendCloseQueue: make(chan []byte),
readyRecv: make(chan bool),
}
}
func (w *wsWriter) Run() {
w.sendRatelimiter = make(chan bool)
go w.runSendRatelimiter()
w.writer = wsutil.NewWriter(w.conn, ws.StateClientSide, ws.OpText)
for {
select {
case <-w.closer:
select {
// Ensure we send the close frame
case body := <-w.sendCloseQueue:
w.sendClose(body)
default:
}
return
case msg := <-w.incoming:
if w.waitingForIdentify {
w.queuedEvents = append(w.queuedEvents, &msg)
continue
}
if msg.Operation == GatewayOPIdentify {
w.waitingForIdentify = true
}
err := w.writeJson(msg)
if err != nil {
w.session.log(LogError, "Error writing to gateway: %s", err.Error())
return
}
case body := <-w.sendCloseQueue:
w.sendClose(body)
case <-w.readyRecv:
w.waitingForIdentify = false
for _, msg := range w.queuedEvents {
err := w.writeJson(msg)
if err != nil {
w.session.log(LogError, "Error writing to gateway: %s", err.Error())
return
}
}
w.queuedEvents = nil
}
}
}
func (w *wsWriter) runSendRatelimiter() {
tc := time.NewTicker(time.Millisecond * 500)
defer tc.Stop()
defer func() {
close(w.sendRatelimiter)
}()
for {
select {
case <-tc.C:
select {
case w.sendRatelimiter <- true:
case <-w.closer:
return
}
case <-w.closer:
return
}
}
}
func (w *wsWriter) writeJson(data interface{}) error {
serialized, err := json.Marshal(data)
if err != nil {
return err
}
return w.writeRaw(serialized)
}
func (w *wsWriter) writeRaw(data []byte) error {
<-w.sendRatelimiter
_, err := w.writer.WriteThrough(data)
if err != nil {
return err
}
return w.writer.Flush()
}
func (w *wsWriter) sendClose(body []byte) error {
_, err := w.conn.Write(body)
return err
}
func (w *wsWriter) Queue(data outgoingEvent) {
select {
case <-time.After(time.Second * 10):
case <-w.closer:
case w.incoming <- data:
}
}
func (w *wsWriter) QueueClose(body []byte) {
select {
case <-time.After(time.Second * 10):
case <-w.closer:
case w.sendCloseQueue <- body:
}
}
type wsHeartBeater struct {
sync.Mutex
writer *wsWriter
sequence *int64
receivedAck bool
missedAcks int
stop chan interface{}
// Called when we received no Ack from last heartbeat
onNoAck func()
lastAck time.Time
lastSend time.Time
}
func (wh *wsHeartBeater) ReceivedAck() {
wh.Lock()
wh.receivedAck = true
wh.missedAcks = 0
wh.lastAck = time.Now()
wh.Unlock()
}
func (wh *wsHeartBeater) UpdateSequence(seq int64) {
atomic.StoreInt64(wh.sequence, seq)
}
func (wh *wsHeartBeater) Run(interval time.Duration) {
ticker := time.NewTicker(interval)
for {
select {
case <-ticker.C:
wh.Lock()
hasReceivedAck := wh.receivedAck
wh.receivedAck = false
wh.Unlock()
if !hasReceivedAck {
wh.onNoAck()
} else {
wh.SendBeat()
}
case <-wh.stop:
return
}
}
}
func (wh *wsHeartBeater) SendBeat() {
wh.Lock()
wh.lastSend = time.Now()
wh.Unlock()
seq := atomic.LoadInt64(wh.sequence)
wh.writer.Queue(outgoingEvent{
Operation: GatewayOPHeartbeat,
Data: seq,
})
}
func (wh *wsHeartBeater) Times() (send time.Time, ack time.Time) {
wh.Lock()
send = wh.lastSend
ack = wh.lastAck
wh.Unlock()
return
}