Skip to content

Commit 9d8d1ef

Browse files
committed
pool: update ping-pong logic
* Convert u64 nonce to big-endian bytes instead of string * Break `receiver_message_handler` loop if pong fail Signed-off-by: Yuki Kishimoto <[email protected]>
1 parent e0b7db5 commit 9d8d1ef

File tree

1 file changed

+30
-19
lines changed

1 file changed

+30
-19
lines changed

crates/nostr-relay-pool/src/relay/internal.rs

Lines changed: 30 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -615,7 +615,7 @@ impl InternalRelay {
615615
let nonce: u64 = *rx_ping.borrow_and_update();
616616

617617
// Compose ping message
618-
let msg = WsMessage::Ping(nonce.to_string().as_bytes().to_vec());
618+
let msg = WsMessage::Ping(nonce.to_be_bytes().to_vec());
619619

620620
// Send WebSocket message
621621
match send_ws_msgs(&mut ws_tx, [msg]).await {
@@ -670,25 +670,36 @@ impl InternalRelay {
670670
#[cfg(not(target_arch = "wasm32"))]
671671
WsMessage::Pong(bytes) => {
672672
if self.opts.flags.has_ping() {
673-
match String::from_utf8(bytes) {
674-
Ok(nonce) => match nonce.parse::<u64>() {
675-
Ok(nonce) => {
676-
if self.stats.ping.last_nonce() == nonce {
677-
tracing::debug!(
678-
"Pong from '{}' match nonce: {}",
679-
self.url,
680-
nonce
681-
);
682-
self.stats.ping.set_replied(true);
683-
let sent_at = self.stats.ping.sent_at().await;
684-
self.stats.save_latency(sent_at.elapsed()).await;
685-
} else {
686-
tracing::error!("Pong nonce not match: received={nonce}, expected={}", self.stats.ping.last_nonce());
687-
}
673+
match bytes.try_into() {
674+
Ok(nonce) => {
675+
// Nonce from big-endian bytes
676+
let nonce: u64 = u64::from_be_bytes(nonce);
677+
678+
// Get last nonce
679+
let last_nonce: u64 = self.stats.ping.last_nonce();
680+
681+
// Check if last nonce not match the current one
682+
if last_nonce != nonce {
683+
tracing::error!("Pong nonce not match: received={nonce}, expected={last_nonce}");
684+
break;
688685
}
689-
Err(e) => tracing::error!("{e}"),
690-
},
691-
Err(e) => tracing::error!("{e}"),
686+
687+
tracing::debug!(
688+
"Pong from '{}' match nonce: {nonce}",
689+
self.url
690+
);
691+
692+
// Set ping as replied
693+
self.stats.ping.set_replied(true);
694+
695+
// Save latency
696+
let sent_at = self.stats.ping.sent_at().await;
697+
self.stats.save_latency(sent_at.elapsed()).await;
698+
}
699+
Err(e) => {
700+
tracing::error!("Can't parse pong nonce: {e:?}");
701+
break;
702+
}
692703
}
693704
}
694705
}

0 commit comments

Comments
 (0)