Add HeartbeatLatency method (#593)

* Latency method

* fixed typo

* fixed linter error

* Renamed Latency to HeartbeatLatency

* HeartbeatLatency now returns time.Time

* return time.Duration instead, since .Sub() returns that

* Add full-stops to end of comments
This commit is contained in:
Connor Wright 2018-09-26 13:22:21 -07:00 committed by Chris Rhodes
parent 6d2c944ad6
commit c8554477e4
2 changed files with 11 additions and 0 deletions

View file

@ -85,6 +85,9 @@ type Session struct {
// Stores the last HeartbeatAck that was recieved (in UTC)
LastHeartbeatAck time.Time
// Stores the last Heartbeat sent (in UTC)
LastHeartbeatSent time.Time
// used to deal with rate limits
Ratelimiter *RateLimiter

View file

@ -267,6 +267,13 @@ type helloOp struct {
// FailedHeartbeatAcks is the Number of heartbeat intervals to wait until forcing a connection restart.
const FailedHeartbeatAcks time.Duration = 5 * time.Millisecond
// HeartbeatLatency returns the latency between heartbeat acknowledgement and heartbeat send.
func (s *Session) HeartbeatLatency() time.Duration {
return s.LastHeartbeatAck.Sub(s.LastHeartbeatSent)
}
// heartbeat sends regular heartbeats to Discord so it knows the client
// is still connected. If you do not send these heartbeats Discord will
// disconnect the websocket connection after a few seconds.
@ -289,6 +296,7 @@ func (s *Session) heartbeat(wsConn *websocket.Conn, listening <-chan interface{}
sequence := atomic.LoadInt64(s.sequence)
s.log(LogDebug, "sending gateway websocket heartbeat seq %d", sequence)
s.wsMutex.Lock()
s.LastHeartbeatSent = time.Now().UTC()
err = wsConn.WriteJSON(heartbeatOp{1, sequence})
s.wsMutex.Unlock()
if err != nil || time.Now().UTC().Sub(last) > (heartbeatIntervalMsec*FailedHeartbeatAcks) {