Skip to content

notifications: Exit protocols on handle drop to save up CPU of minimal-relay-chains #376

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

Merged
merged 4 commits into from
Apr 23, 2025
Merged
Show file tree
Hide file tree
Changes from all 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
19 changes: 14 additions & 5 deletions src/protocol/notification/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1606,7 +1606,9 @@ impl NotificationProtocol {
}

/// Handle next notification event.
async fn next_event(&mut self) {
///
/// Returns `true` when the user command stream was dropped.
async fn next_event(&mut self) -> bool {
// biased select is used because the substream events must be prioritized above other events
// that is because a closed substream is detected by either `substreams` or `negotiation`
// and if that event is not handled with priority but, e.g., inbound substream is
Expand Down Expand Up @@ -1783,9 +1785,16 @@ impl NotificationProtocol {
);
}
}

// User commands.
command = self.command_rx.recv() => match command {
None => {
tracing::debug!(target: LOG_TARGET, "user protocol has exited, exiting");
tracing::debug!(
target: LOG_TARGET,
protocol = %self.protocol,
"user protocol has exited, exiting"
);
return true;
}
Some(command) => match command {
NotificationCommand::OpenSubstream { peers } => {
Expand All @@ -1811,14 +1820,14 @@ impl NotificationProtocol {
}
},
}

false
}

/// Start [`NotificationProtocol`] event loop.
pub(crate) async fn run(mut self) {
tracing::debug!(target: LOG_TARGET, "starting notification event loop");

loop {
self.next_event().await;
}
while !self.next_event().await {}
}
}
19 changes: 19 additions & 0 deletions src/protocol/notification/tests/notification.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1117,3 +1117,22 @@ async fn second_inbound_substream_opened_while_outbound_substream_was_opening()
state => panic!("invalid state for peer: {state:?}"),
}
}

#[tokio::test]
async fn drop_handle_exits_protocol() {
let _ = tracing_subscriber::fmt()
.with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
.try_init();

let (mut protocol, handle, _sender, _tx) = make_notification_protocol();

// Simulate a handle drop.
drop(handle);

// Call `next_event` and ensure it returns true.
let result = protocol.next_event().await;
assert!(
result,
"Expected `next_event` to return true when `command_rx` is dropped"
);
}
Loading