Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: connections can become stale when reconnecting #4310

Merged
merged 3 commits into from
Dec 14, 2023
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 11 additions & 5 deletions engine/src/p2p/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -385,7 +385,7 @@ impl P2PContext {
// This is guaranteed by construction of `active_connections`:
assert_eq!(peer.info.account_id, account_id);

self.connect_to_peer(peer.info.clone());
self.connect_to_peer(peer.info.clone(), Some(peer.last_activity.get()));
self.send_message(account_id, payload);
},
}
Expand Down Expand Up @@ -479,7 +479,7 @@ impl P2PContext {
match peer.state {
ConnectionState::ReconnectionScheduled => {
info!("Reconnecting to peer: {account_id}");
self.connect_to_peer(peer.info.clone());
self.connect_to_peer(peer.info.clone(), Some(peer.last_activity.get()));
},
ConnectionState::Connected(_) => {
// It is possible that while we were waiting to reconnect,
Expand All @@ -506,7 +506,7 @@ impl P2PContext {
}
}

fn connect_to_peer(&mut self, peer: PeerInfo) {
fn connect_to_peer(&mut self, peer: PeerInfo, previous_activity: Option<tokio::time::Instant>) {
let account_id = peer.account_id.clone();

let socket = OutgoingSocket::new(&self.zmq_context, &self.key);
Expand All @@ -520,7 +520,9 @@ impl P2PContext {
ConnectionStateInfo {
state: ConnectionState::Connected(connected_socket),
info: peer,
last_activity: Cell::new(tokio::time::Instant::now()),
last_activity: Cell::new(
previous_activity.unwrap_or_else(tokio::time::Instant::now),
),
},
) {
if !matches!(connection.state, ConnectionState::Stale) {
Expand All @@ -539,13 +541,17 @@ impl P2PContext {
return
}

let mut previous_activity = None;
j4m1ef0rd marked this conversation as resolved.
Show resolved Hide resolved

if let Some(existing_peer_state) = self.active_connections.remove(&peer.account_id) {
debug!(
peer_info = peer.to_string(),
"Received info for known peer with account id {}, updating info and reconnecting",
&peer.account_id
);

previous_activity = Some(existing_peer_state.last_activity.get());

match existing_peer_state.state {
ConnectionState::Connected(socket) => {
disconnect_socket(socket);
Expand All @@ -571,7 +577,7 @@ impl P2PContext {

self.x25519_to_account_id.insert(peer.pubkey, peer.account_id.clone());

self.connect_to_peer(peer);
self.connect_to_peer(peer, previous_activity);
}

/// Start listening for incoming p2p messages on a separate thread
Expand Down