Skip to content

Commit

Permalink
Automatically reconnect if keepalive keeps failing
Browse files Browse the repository at this point in the history
  • Loading branch information
tulir committed Jun 28, 2023
1 parent 12cd3cd commit 458b533
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 11 deletions.
10 changes: 9 additions & 1 deletion keepalive.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,13 @@ var (
KeepAliveIntervalMin = 20 * time.Second
// KeepAliveIntervalMax specifies the maximum interval for websocket keepalive pings.
KeepAliveIntervalMax = 30 * time.Second

// KeepAliveMaxFailTime specifies the maximum time to wait before forcing a reconnect if keepalives fail repeatedly.
KeepAliveMaxFailTime = 3 * time.Minute
)

func (cli *Client) keepAliveLoop(ctx context.Context) {
var lastSuccess time.Time
lastSuccess := time.Now()
var errorCount int
for {
interval := rand.Int63n(KeepAliveIntervalMax.Milliseconds()-KeepAliveIntervalMin.Milliseconds()) + KeepAliveIntervalMin.Milliseconds()
Expand All @@ -41,6 +44,11 @@ func (cli *Client) keepAliveLoop(ctx context.Context) {
ErrorCount: errorCount,
LastSuccess: lastSuccess,
})
if cli.EnableAutoReconnect && time.Since(lastSuccess) > KeepAliveMaxFailTime {
cli.Log.Debugf("Forcing reconnect due to keepalive failure")
cli.Disconnect()
go cli.autoReconnect()
}
} else {
if errorCount > 0 {
errorCount = 0
Expand Down
10 changes: 0 additions & 10 deletions mdtest/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -843,16 +843,6 @@ func handler(rawEvt interface{}) {
log.Debugf("App state event: %+v / %+v", evt.Index, evt.SyncActionValue)
case *events.KeepAliveTimeout:
log.Debugf("Keepalive timeout event: %+v", evt)
if evt.ErrorCount > 3 {
log.Debugf("Got >3 keepalive timeouts, forcing reconnect")
go func() {
cli.Disconnect()
err := cli.Connect()
if err != nil {
log.Errorf("Error force-reconnecting after keepalive timeouts: %v", err)
}
}()
}
case *events.KeepAliveRestored:
log.Debugf("Keepalive restored")
}
Expand Down

0 comments on commit 458b533

Please sign in to comment.