From 0fef66c739c4a359ac438414d502d21ff1510fd2 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?P=C3=A9ter=20Szil=C3=A1gyi?= <peterke@gmail.com>
Date: Mon, 20 Jul 2020 11:11:38 +0300
Subject: [PATCH] ethstats: fix reconnection issue, implement primus pings

---
 ethstats/ethstats.go | 21 +++++++++++++++++++--
 1 file changed, 19 insertions(+), 2 deletions(-)

diff --git a/ethstats/ethstats.go b/ethstats/ethstats.go
index 4d2c2edb6..b60ac56ea 100644
--- a/ethstats/ethstats.go
+++ b/ethstats/ethstats.go
@@ -280,8 +280,10 @@ func (s *Service) loop() {
 				}
 			}
 			fullReport.Stop()
-			// Make sure the connection is closed
+
+			// Close the current connection and establish a new one
 			conn.Close()
+			errTimer.Reset(0)
 		}
 	}
 }
@@ -296,8 +298,23 @@ func (s *Service) readLoop(conn *websocket.Conn) {
 
 	for {
 		// Retrieve the next generic network packet and bail out on error
+		var blob json.RawMessage
+		if err := conn.ReadJSON(&blob); err != nil {
+			log.Warn("Failed to retrieve stats server message", "err", err)
+			return
+		}
+		// If the network packet is a system ping, respond to it directly
+		var ping string
+		if err := json.Unmarshal(blob, &ping); err == nil && strings.HasPrefix(ping, "primus::ping::") {
+			if err := conn.WriteJSON(strings.Replace(ping, "ping", "pong", -1)); err != nil {
+				log.Warn("Failed to respond to system ping message", "err", err)
+				return
+			}
+			continue
+		}
+		// Not a system ping, try to decode an actual state message
 		var msg map[string][]interface{}
-		if err := conn.ReadJSON(&msg); err != nil {
+		if err := json.Unmarshal(blob, &msg); err != nil {
 			log.Warn("Failed to decode stats server message", "err", err)
 			return
 		}
-- 
GitLab