Skip to content

Commit

Permalink
feat: start sending pings with a random initial jitter
Browse files Browse the repository at this point in the history
  • Loading branch information
palkan committed Aug 10, 2023
1 parent 0d03bf9 commit cecc3fe
Showing 1 changed file with 15 additions and 1 deletion.
16 changes: 15 additions & 1 deletion node/session.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package node
import (
"encoding/json"
"errors"
"math/rand"
"sync"
"time"

Expand Down Expand Up @@ -151,7 +152,7 @@ func NewSession(node *Node, conn Connection, url string, headers *map[string]str
}

if session.pingInterval > 0 {
session.addPing()
session.startPing()
}

if !session.handshakeDeadline.IsZero() {
Expand Down Expand Up @@ -591,6 +592,19 @@ func (s *Session) sendPing() {
s.addPing()
}

func (s *Session) startPing() {
s.mu.Lock()
defer s.mu.Unlock()

// Calculate the minimum and maximum durations
minDuration := s.pingInterval / 2
maxDuration := s.pingInterval * 3 / 2

initialInterval := time.Duration(rand.Int63n(int64(maxDuration-minDuration))) + minDuration // nolint:gosec

s.pingTimer = time.AfterFunc(initialInterval, s.sendPing)
}

func (s *Session) addPing() {
s.mu.Lock()
defer s.mu.Unlock()
Expand Down

0 comments on commit cecc3fe

Please sign in to comment.