Skip to content

Commit

Permalink
Add HeartbeatLatency method (bwmarrin#593)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
cxnky authored and iopred committed Sep 26, 2018
1 parent 6d2c944 commit c855447
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 0 deletions.
3 changes: 3 additions & 0 deletions structs.go
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
8 changes: 8 additions & 0 deletions wsapi.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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) {
Expand Down

0 comments on commit c855447

Please sign in to comment.