Skip to content
This repository has been archived by the owner on Nov 15, 2023. It is now read-only.

Make unbounded channels size warning exact (part 2) #13504

Merged
merged 9 commits into from
Mar 7, 2023
15 changes: 14 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

58 changes: 30 additions & 28 deletions client/consensus/common/src/import_queue/basic_queue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,8 +118,8 @@ impl<B: BlockT> BasicQueueHandle<B> {
}

pub fn close(&mut self) {
self.justification_sender.close_channel();
self.block_import_sender.close_channel();
self.justification_sender.close();
self.block_import_sender.close();
}
}

Expand Down Expand Up @@ -597,11 +597,11 @@ mod tests {
fn prioritizes_finality_work_over_block_import() {
let (result_sender, mut result_port) = buffered_link::buffered_link(100_000);

let (worker, mut finality_sender, mut block_import_sender) =
let (worker, finality_sender, block_import_sender) =
BlockImportWorker::new(result_sender, (), Box::new(()), Some(Box::new(())), None);
futures::pin_mut!(worker);

let mut import_block = |n| {
let import_block = |n| {
let header = Header {
parent_hash: Hash::random(),
number: n,
Expand All @@ -612,35 +612,37 @@ mod tests {

let hash = header.hash();

block_on(block_import_sender.send(worker_messages::ImportBlocks(
BlockOrigin::Own,
vec![IncomingBlock {
hash,
header: Some(header),
body: None,
indexed_body: None,
justifications: None,
origin: None,
allow_missing_state: false,
import_existing: false,
state: None,
skip_execution: false,
}],
)))
.unwrap();
block_import_sender
.unbounded_send(worker_messages::ImportBlocks(
BlockOrigin::Own,
vec![IncomingBlock {
hash,
header: Some(header),
body: None,
indexed_body: None,
justifications: None,
origin: None,
allow_missing_state: false,
import_existing: false,
state: None,
skip_execution: false,
}],
))
.unwrap();

hash
};

let mut import_justification = || {
let import_justification = || {
let hash = Hash::random();
block_on(finality_sender.send(worker_messages::ImportJustification(
libp2p::PeerId::random(),
hash,
1,
(*b"TEST", Vec::new()),
)))
.unwrap();
finality_sender
.unbounded_send(worker_messages::ImportJustification(
libp2p::PeerId::random(),
hash,
1,
(*b"TEST", Vec::new()),
))
.unwrap();

hash
};
Expand Down
4 changes: 2 additions & 2 deletions client/consensus/common/src/import_queue/buffered_link.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ use super::BlockImportResult;
/// can be used to buffer commands, and the receiver can be used to poll said commands and transfer
/// them to another link. `queue_size_warning` sets the warning threshold of the channel queue size.
pub fn buffered_link<B: BlockT>(
queue_size_warning: i64,
queue_size_warning: usize,
) -> (BufferedLinkSender<B>, BufferedLinkReceiver<B>) {
let (tx, rx) = tracing_unbounded("mpsc_buffered_link", queue_size_warning);
let tx = BufferedLinkSender { tx };
Expand Down Expand Up @@ -166,7 +166,7 @@ impl<B: BlockT> BufferedLinkReceiver<B> {
}

/// Close the channel.
pub fn close(&mut self) {
pub fn close(&mut self) -> bool {
self.rx.get_mut().close()
}
}
Expand Down
2 changes: 1 addition & 1 deletion client/service/src/task_manager/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -281,7 +281,7 @@ impl SpawnEssentialTaskHandle {
let essential_failed = self.essential_failed_tx.clone();
let essential_task = std::panic::AssertUnwindSafe(task).catch_unwind().map(move |_| {
log::error!("Essential task `{}` failed. Shutting down service.", name);
let _ = essential_failed.close_channel();
let _ = essential_failed.close();
});

let _ = self.inner.spawn_inner(name, group, essential_task, task_type);
Expand Down
1 change: 1 addition & 0 deletions client/service/test/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ repository = "https://github.com/paritytech/substrate/"
targets = ["x86_64-unknown-linux-gnu"]

[dependencies]
async-channel = "1.8.0"
array-bytes = "4.1"
fdlimit = "0.2.1"
futures = "0.3.21"
Expand Down
20 changes: 11 additions & 9 deletions client/service/test/src/client/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

use async_channel::TryRecvError;
use futures::executor::block_on;
use parity_scale_codec::{Decode, Encode, Joiner};
use sc_block_builder::BlockBuilderProvider;
Expand Down Expand Up @@ -175,16 +176,17 @@ fn finality_notification_check(
finalized: &[Hash],
stale_heads: &[Hash],
) {
match notifications.try_next() {
Ok(Some(notif)) => {
match notifications.try_recv() {
Ok(notif) => {
let stale_heads_expected: HashSet<_> = stale_heads.iter().collect();
let stale_heads: HashSet<_> = notif.stale_heads.iter().collect();
assert_eq!(notif.tree_route.as_ref(), &finalized[..finalized.len() - 1]);
assert_eq!(notif.hash, *finalized.last().unwrap());
assert_eq!(stale_heads, stale_heads_expected);
},
Ok(None) => panic!("unexpected notification result, client send channel was closed"),
Err(_) => assert!(finalized.is_empty()),
Err(TryRecvError::Closed) =>
panic!("unexpected notification result, client send channel was closed"),
Err(TryRecvError::Empty) => assert!(finalized.is_empty()),
}
}

Expand Down Expand Up @@ -983,7 +985,7 @@ fn import_with_justification() {

finality_notification_check(&mut finality_notifications, &[a1.hash(), a2.hash()], &[]);
finality_notification_check(&mut finality_notifications, &[a3.hash()], &[]);
assert!(finality_notifications.try_next().is_err());
assert!(matches!(finality_notifications.try_recv().unwrap_err(), TryRecvError::Empty));
}

#[test]
Expand Down Expand Up @@ -1038,7 +1040,7 @@ fn importing_diverged_finalized_block_should_trigger_reorg() {
assert_eq!(client.chain_info().finalized_hash, b1.hash());

finality_notification_check(&mut finality_notifications, &[b1.hash()], &[a2.hash()]);
assert!(finality_notifications.try_next().is_err());
assert!(matches!(finality_notifications.try_recv().unwrap_err(), TryRecvError::Empty));
}

#[test]
Expand Down Expand Up @@ -1124,7 +1126,7 @@ fn finalizing_diverged_block_should_trigger_reorg() {

finality_notification_check(&mut finality_notifications, &[b1.hash()], &[]);
finality_notification_check(&mut finality_notifications, &[b2.hash(), b3.hash()], &[a2.hash()]);
assert!(finality_notifications.try_next().is_err());
assert!(matches!(finality_notifications.try_recv().unwrap_err(), TryRecvError::Empty));
}

#[test]
Expand Down Expand Up @@ -1227,7 +1229,7 @@ fn finality_notifications_content() {

finality_notification_check(&mut finality_notifications, &[a1.hash(), a2.hash()], &[c1.hash()]);
finality_notification_check(&mut finality_notifications, &[d3.hash(), d4.hash()], &[b2.hash()]);
assert!(finality_notifications.try_next().is_err());
assert!(matches!(finality_notifications.try_recv().unwrap_err(), TryRecvError::Empty));
}

#[test]
Expand Down Expand Up @@ -1437,7 +1439,7 @@ fn doesnt_import_blocks_that_revert_finality() {

finality_notification_check(&mut finality_notifications, &[a3.hash()], &[b2.hash()]);

assert!(finality_notifications.try_next().is_err());
assert!(matches!(finality_notifications.try_recv().unwrap_err(), TryRecvError::Empty));
}

#[test]
Expand Down
3 changes: 2 additions & 1 deletion client/utils/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,14 @@ description = "I/O for Substrate runtimes"
readme = "README.md"

[dependencies]
backtrace = "0.3.67"
async-channel = "1.8.0"
futures = "0.3.21"
futures-timer = "3.0.2"
lazy_static = "1.4.0"
log = "0.4"
parking_lot = "0.12.1"
prometheus = { version = "0.13.0", default-features = false }
sp-arithmetic = { version = "6.0.0", default-features = false, path = "../../primitives/arithmetic" }

[features]
default = ["metered"]
Expand Down
17 changes: 6 additions & 11 deletions client/utils/README.md
Original file line number Diff line number Diff line change
@@ -1,16 +1,11 @@
Utilities Primitives for Substrate
# Utilities Primitives for Substrate

## Features
This crate provides `mpsc::tracing_unbounded` function that returns wrapper types to
`async_channel::Sender<T>` and `async_channel::Receiver<T>`, which register every
`send`/`received`/`dropped` action happened on the channel.

### metered

This feature changes the behaviour of the function `mpsc::tracing_unbounded`.
With the disabled feature this function is an alias to `futures::channel::mpsc::unbounded`.
However, when the feature is enabled it creates wrapper types to `UnboundedSender<T>`
and `UnboundedReceiver<T>` to register every `send`/`received`/`dropped` action happened on
the channel.

Also this feature creates and registers a prometheus vector with name `unbounded_channel_len` and labels:
Also this wrapper creates and registers a prometheus vector with name `unbounded_channel_len`
and labels:

| Label | Description |
| ------------ | --------------------------------------------- |
Expand Down
14 changes: 4 additions & 10 deletions client/utils/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,17 +18,11 @@

//! Utilities Primitives for Substrate
//!
//! # Features
//! This crate provides `mpsc::tracing_unbounded` function that returns wrapper types to
//! `async_channel::Sender<T>` and `async_channel::Receiver<T>`, which register every
//! `send`/`received`/`dropped` action happened on the channel.
//!
//! ## metered
//!
//! This feature changes the behaviour of the function `mpsc::tracing_unbounded`.
//! With the disabled feature this function is an alias to `futures::channel::mpsc::unbounded`.
//! However, when the feature is enabled it creates wrapper types to `UnboundedSender<T>`
//! and `UnboundedReceiver<T>` to register every `send`/`received`/`dropped` action happened on
//! the channel.
//!
//! Also this feature creates and registers a prometheus vector with name `unbounded_channel_len`
//! Also this wrapper creates and registers a prometheus vector with name `unbounded_channel_len`
//! and labels:
//!
//! | Label | Description |
Expand Down
4 changes: 0 additions & 4 deletions client/utils/src/metrics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ use prometheus::{
Error as PrometheusError, Registry,
};

#[cfg(feature = "metered")]
use prometheus::{core::GenericCounterVec, Opts};

lazy_static! {
Expand All @@ -36,7 +35,6 @@ lazy_static! {
.expect("Creating of statics doesn't fail. qed");
}

#[cfg(feature = "metered")]
lazy_static! {
pub static ref UNBOUNDED_CHANNELS_COUNTER : GenericCounterVec<AtomicU64> = GenericCounterVec::new(
Opts::new("substrate_unbounded_channel_len", "Items in each mpsc::unbounded instance"),
Expand All @@ -49,8 +47,6 @@ lazy_static! {
pub fn register_globals(registry: &Registry) -> Result<(), PrometheusError> {
registry.register(Box::new(TOKIO_THREADS_ALIVE.clone()))?;
registry.register(Box::new(TOKIO_THREADS_TOTAL.clone()))?;

#[cfg(feature = "metered")]
registry.register(Box::new(UNBOUNDED_CHANNELS_COUNTER.clone()))?;

Ok(())
Expand Down
Loading