From 23289d9f09704ea861099a270dc77cef04953953 Mon Sep 17 00:00:00 2001 From: 0x1d Date: Sun, 19 Oct 2025 13:11:36 +0200 Subject: [PATCH] fix: latency calculation --- src/spore/core/ClusterManager.cpp | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/src/spore/core/ClusterManager.cpp b/src/spore/core/ClusterManager.cpp index 5b084ed..8a3c996 100644 --- a/src/spore/core/ClusterManager.cpp +++ b/src/spore/core/ClusterManager.cpp @@ -174,10 +174,10 @@ void ClusterManager::onNodeUpdate(const char* msg) { } if (respondingNode) { - // Calculate latency if we recently sent a heartbeat + // Calculate latency only if we recently sent a heartbeat (within last 1 second) unsigned long latency = 0; - if (lastHeartbeatSentAt != 0) { - unsigned long now = millis(); + unsigned long now = millis(); + if (lastHeartbeatSentAt != 0 && (now - lastHeartbeatSentAt) < 1000) { // 1 second window latency = now - lastHeartbeatSentAt; lastHeartbeatSentAt = 0; // Reset for next calculation } @@ -201,11 +201,15 @@ void ClusterManager::onNodeUpdate(const char* msg) { } } - respondingNode->lastSeen = millis(); + respondingNode->lastSeen = now; respondingNode->status = NodeInfo::ACTIVE; - respondingNode->latency = latency; - LOG_DEBUG("Cluster", String("Updated responding node ") + respondingNode->hostname + " @ " + respondingNodeIP.toString() + " | latency: " + String(latency) + "ms"); + // Update latency if we calculated it (preserve existing value if not) + if (latency > 0) { + respondingNode->latency = latency; + } + + LOG_DEBUG("Cluster", String("Updated responding node ") + respondingNode->hostname + " @ " + respondingNodeIP.toString() + " | latency: " + String(latency > 0 ? String(latency) + "ms" : "not calculated")); } else { LOG_WARN("Cluster", String("Received NODE_UPDATE from unknown node: ") + respondingNodeIP.toString()); } @@ -314,17 +318,18 @@ void ClusterManager::onRawMessage(const char* msg) { void ClusterManager::addOrUpdateNode(const String& nodeHost, IPAddress nodeIP) { auto& memberList = *ctx.memberList; - + // O(1) lookup instead of O(n) search auto it = memberList.find(nodeHost); if (it != memberList.end()) { - // Update existing node + // Update existing node - preserve all existing field values it->second.ip = nodeIP; it->second.lastSeen = millis(); + // Note: Other fields like latency, uptime, labels, etc. are preserved //fetchNodeInfo(nodeIP); // Do not fetch here, handled by periodic task return; } - + // Add new node NodeInfo newNode; newNode.hostname = nodeHost;