Clean up ready timing, fix potential race with starting heartbeats.

This commit is contained in:
Chris Rhodes 2016-01-21 09:33:05 -08:00
parent c4869d7a43
commit e8d8f03214

View file

@ -214,9 +214,9 @@ func (s *Session) event(messageType int, message []byte) (err error) {
switch e.Type { switch e.Type {
case "READY": case "READY":
s.DataReady = true
var st *Ready var st *Ready
if err = unmarshalEvent(e, &st); err == nil { if err = unmarshalEvent(e, &st); err == nil {
go s.heartbeat(st.HeartbeatInterval)
if s.StateEnabled { if s.StateEnabled {
s.State.OnReady(st) s.State.OnReady(st)
} }
@ -224,7 +224,6 @@ func (s *Session) event(messageType int, message []byte) (err error) {
s.OnReady(s, st) s.OnReady(s, st)
} }
} }
go s.heartbeat(st.HeartbeatInterval)
if s.OnReady != nil { if s.OnReady != nil {
return return
} }
@ -575,9 +574,21 @@ func (s *Session) sendHeartbeat() error {
// is still connected. If you do not send these heartbeats Discord will // is still connected. If you do not send these heartbeats Discord will
// disconnect the websocket connection after a few seconds. // disconnect the websocket connection after a few seconds.
func (s *Session) heartbeat(i time.Duration) { func (s *Session) heartbeat(i time.Duration) {
s.Lock()
// We have been closed between the first Ready event, abort.
if s.listening == nil {
s.Unlock()
return
}
// Keep a reference, as s.listening can be nilled out. // Keep a reference, as s.listening can be nilled out.
listening := s.listening listening := s.listening
s.DataReady = true
s.Unlock()
// Send first heartbeat immediately because lag could put the // Send first heartbeat immediately because lag could put the
// first heartbeat outside the required heartbeat interval window. // first heartbeat outside the required heartbeat interval window.
err := s.sendHeartbeat() err := s.sendHeartbeat()