From 058430e2257f7cb5fff4ba19bb6a621ae7de3861 Mon Sep 17 00:00:00 2001 From: Lucio Franco Date: Mon, 28 Jul 2025 09:15:52 -0400 Subject: [PATCH] chore: fix clippy lints --- grpc/src/client/load_balancing/mod.rs | 20 +++++---- grpc/src/client/name_resolution/backoff.rs | 22 ++++----- grpc/src/client/name_resolution/dns/mod.rs | 10 ++--- grpc/src/client/name_resolution/dns/test.rs | 49 ++++++++++----------- grpc/src/client/name_resolution/mod.rs | 3 +- grpc/src/client/name_resolution/registry.rs | 5 +-- grpc/src/client/subchannel.rs | 7 +-- grpc/src/client/transport/registry.rs | 2 +- grpc/src/inmemory/mod.rs | 5 +-- grpc/src/rt/tokio/hickory_resolver.rs | 2 +- grpc/src/rt/tokio/mod.rs | 2 +- tests/integration_tests/tests/load_shed.rs | 4 +- tonic-prost-build/src/tests.rs | 36 ++++++--------- 13 files changed, 78 insertions(+), 89 deletions(-) diff --git a/grpc/src/client/load_balancing/mod.rs b/grpc/src/client/load_balancing/mod.rs index 16b4cafbe..b91950c31 100644 --- a/grpc/src/client/load_balancing/mod.rs +++ b/grpc/src/client/load_balancing/mod.rs @@ -89,7 +89,7 @@ impl ParsedJsonLbConfig { pub fn new(json: &str) -> Result { match serde_json::from_str(json) { Ok(value) => Ok(ParsedJsonLbConfig { value }), - Err(e) => Err(format!("failed to parse LB config JSON: {}", e)), + Err(e) => Err(format!("failed to parse LB config JSON: {e}")), } } @@ -108,7 +108,7 @@ impl ParsedJsonLbConfig { let res: T = match serde_json::from_value(self.value.clone()) { Ok(v) => v, Err(e) => { - return Err(format!("{}", e).into()); + return Err(format!("{e}").into()); } }; Ok(res) @@ -209,7 +209,7 @@ impl Display for SubchannelState { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "connectivity_state: {}", self.connectivity_state)?; if let Some(err) = &self.last_connection_error { - write!(f, ", last_connection_error: {}", err)?; + write!(f, ", last_connection_error: {err}")?; } Ok(()) } @@ -301,8 +301,8 @@ impl Display for PickResult { match self { Self::Pick(_) => write!(f, "Pick"), Self::Queue => write!(f, "Queue"), - Self::Fail(st) => write!(f, "Fail({})", st), - Self::Drop(st) => write!(f, "Drop({})", st), + Self::Fail(st) => write!(f, "Fail({st})"), + Self::Drop(st) => write!(f, "Drop({st})"), } } } @@ -324,6 +324,9 @@ impl LbState { } } +/// Type alias for the completion callback function. +pub type CompletionCallback = Box; + /// A collection of data used by the channel for routing a request. pub struct Pick { /// The Subchannel for the request. @@ -331,10 +334,11 @@ pub struct Pick { // Metadata to be added to existing outgoing metadata. pub metadata: MetadataMap, // Callback to be invoked once the RPC completes. - pub on_complete: Option>, + pub on_complete: Option, } pub trait DynHash { + #[allow(clippy::redundant_allocation)] fn dyn_hash(&self, state: &mut Box<&mut dyn Hasher>); } @@ -502,7 +506,7 @@ impl Subchannel for ExternalSubchannel { } fn connect(&self) { - println!("connect called for subchannel: {}", self); + println!("connect called for subchannel: {self}"); self.isc.as_ref().unwrap().connect(false); } } @@ -517,7 +521,7 @@ impl Drop for ExternalSubchannel { let isc = self.isc.take(); let _ = self.work_scheduler.send(WorkQueueItem::Closure(Box::new( move |c: &mut InternalChannelController| { - println!("unregistering connectivity state watcher for {:?}", address); + println!("unregistering connectivity state watcher for {address:?}"); isc.as_ref() .unwrap() .unregister_connectivity_state_watcher(watcher.unwrap()); diff --git a/grpc/src/client/name_resolution/backoff.rs b/grpc/src/client/name_resolution/backoff.rs index 6507ffc7e..8725706e2 100644 --- a/grpc/src/client/name_resolution/backoff.rs +++ b/grpc/src/client/name_resolution/backoff.rs @@ -125,7 +125,7 @@ mod tests { #[test] fn default_config_is_valid() { let result = ExponentialBackoff::new(DEFAULT_EXPONENTIAL_CONFIG.clone()); - assert_eq!(result.is_ok(), true); + assert!(result.is_ok()); } #[test] @@ -149,7 +149,7 @@ mod tests { max_delay: Duration::from_secs(10), }; let result = ExponentialBackoff::new(config); - assert_eq!(result.is_err(), true); + assert!(result.is_err()); } #[test] @@ -161,7 +161,7 @@ mod tests { max_delay: Duration::from_secs(100), }; let result = ExponentialBackoff::new(config); - assert_eq!(result.is_err(), true); + assert!(result.is_err()); } #[test] @@ -173,7 +173,7 @@ mod tests { max_delay: Duration::from_secs(100), }; let result = ExponentialBackoff::new(config); - assert_eq!(result.is_err(), true); + assert!(result.is_err()); } #[test] @@ -185,7 +185,7 @@ mod tests { max_delay: Duration::from_secs(100), }; let result = ExponentialBackoff::new(config); - assert_eq!(result.is_err(), true); + assert!(result.is_err()); } #[test] @@ -227,15 +227,15 @@ mod tests { let mut backoff = ExponentialBackoff::new(config.clone()).unwrap(); // 0.8 <= duration <= 1.2. let duration = backoff.backoff_duration(); - assert_eq!(duration.gt(&Duration::from_secs_f64(0.8 - EPSILON)), true); - assert_eq!(duration.lt(&Duration::from_secs_f64(1.2 + EPSILON)), true); + assert!(duration.gt(&Duration::from_secs_f64(0.8 - EPSILON))); + assert!(duration.lt(&Duration::from_secs_f64(1.2 + EPSILON))); // 1.6 <= duration <= 2.4. let duration = backoff.backoff_duration(); - assert_eq!(duration.gt(&Duration::from_secs_f64(1.6 - EPSILON)), true); - assert_eq!(duration.lt(&Duration::from_secs_f64(2.4 + EPSILON)), true); + assert!(duration.gt(&Duration::from_secs_f64(1.6 - EPSILON))); + assert!(duration.lt(&Duration::from_secs_f64(2.4 + EPSILON))); // 3.2 <= duration <= 4.8. let duration = backoff.backoff_duration(); - assert_eq!(duration.gt(&Duration::from_secs_f64(3.2 - EPSILON)), true); - assert_eq!(duration.lt(&Duration::from_secs_f64(4.8 + EPSILON)), true); + assert!(duration.gt(&Duration::from_secs_f64(3.2 - EPSILON))); + assert!(duration.lt(&Duration::from_secs_f64(4.8 + EPSILON))); } } diff --git a/grpc/src/client/name_resolution/dns/mod.rs b/grpc/src/client/name_resolution/dns/mod.rs index 5c05127fd..461b6d02b 100644 --- a/grpc/src/client/name_resolution/dns/mod.rs +++ b/grpc/src/client/name_resolution/dns/mod.rs @@ -162,7 +162,7 @@ impl DnsResolver { work_scheduler.schedule_work(); channel_updated_rx.notified().await; let channel_response = { state.lock().channel_response.take() }; - let next_resoltion_time = if let Some(_) = channel_response { + let next_resoltion_time = if channel_response.is_some() { SystemTime::now() .checked_add(backoff.backoff_duration()) .unwrap() @@ -233,7 +233,7 @@ impl ResolverBuilder for Builder { fn is_valid_uri(&self, target: &Target) -> bool { if let Err(err) = parse_endpoint_and_authority(target) { - eprintln!("{}", err); + eprintln!("{err}"); false } else { true @@ -311,7 +311,7 @@ fn parse_endpoint_and_authority(target: &Target) -> Result let endpoint = target.path(); let endpoint = endpoint.strip_prefix("/").unwrap_or(endpoint); let parse_result = parse_host_port(endpoint, DEFAULT_PORT) - .map_err(|err| format!("Failed to parse target {}: {}", target, err))?; + .map_err(|err| format!("Failed to parse target {target}: {err}"))?; let endpoint = parse_result.ok_or("Received empty endpoint host.".to_string())?; // Parse the authority. @@ -323,7 +323,7 @@ fn parse_endpoint_and_authority(target: &Target) -> Result }); } let parse_result = parse_host_port(&authority, DEFAULT_DNS_PORT) - .map_err(|err| format!("Failed to parse DNS authority {}: {}", target, err))?; + .map_err(|err| format!("Failed to parse DNS authority {target}: {err}"))?; let Some(authority) = parse_result else { return Ok(ParseResult { endpoint, @@ -351,7 +351,7 @@ fn parse_host_port(host_and_port: &str, default_port: u16) -> Result().map_err(|err| err.to_string())?; let port = url.port().unwrap_or(default_port); let host = match url.host() { diff --git a/grpc/src/client/name_resolution/dns/test.rs b/grpc/src/client/name_resolution/dns/test.rs index 952e30f86..beda2ea32 100644 --- a/grpc/src/client/name_resolution/dns/test.rs +++ b/grpc/src/client/name_resolution/dns/test.rs @@ -207,7 +207,7 @@ pub async fn dns_basic() { let mut resolver = builder.build(target, opts); // Wait for schedule work to be called. - let _ = work_rx.recv().await.unwrap(); + work_rx.recv().await.unwrap(); let (update_tx, mut update_rx) = mpsc::unbounded_channel(); let mut channel_controller = FakeChannelController { update_tx, @@ -216,7 +216,7 @@ pub async fn dns_basic() { resolver.work(&mut channel_controller); // A successful endpoint update should be received. let update = update_rx.recv().await.unwrap(); - assert_eq!(update.endpoints.unwrap().len() > 1, true); + assert!(update.endpoints.unwrap().len() > 1); } #[tokio::test] @@ -236,7 +236,7 @@ pub async fn invalid_target() { let mut resolver = builder.build(target, opts); // Wait for schedule work to be called. - let _ = work_rx.recv().await.unwrap(); + work_rx.recv().await.unwrap(); let (update_tx, mut update_rx) = mpsc::unbounded_channel(); let mut channel_controller = FakeChannelController { update_tx, @@ -245,14 +245,11 @@ pub async fn invalid_target() { resolver.work(&mut channel_controller); // An error endpoint update should be received. let update = update_rx.recv().await.unwrap(); - assert_eq!( - update - .endpoints - .err() - .unwrap() - .contains(&target.to_string()), - true - ); + assert!(update + .endpoints + .err() + .unwrap() + .contains(&target.to_string())); } #[derive(Clone)] @@ -319,7 +316,7 @@ pub async fn dns_lookup_error() { let mut resolver = builder.build(target, opts); // Wait for schedule work to be called. - let _ = work_rx.recv().await.unwrap(); + work_rx.recv().await.unwrap(); let (update_tx, mut update_rx) = mpsc::unbounded_channel(); let mut channel_controller = FakeChannelController { update_tx, @@ -328,7 +325,7 @@ pub async fn dns_lookup_error() { resolver.work(&mut channel_controller); // An error endpoint update should be received. let update = update_rx.recv().await.unwrap(); - assert_eq!(update.endpoints.err().unwrap().contains("test_error"), true); + assert!(update.endpoints.err().unwrap().contains("test_error")); } #[tokio::test] @@ -360,7 +357,7 @@ pub async fn dns_lookup_timeout() { let mut resolver = DnsResolver::new(Box::new(dns_client), opts, dns_opts); // Wait for schedule work to be called. - let _ = work_rx.recv().await.unwrap(); + work_rx.recv().await.unwrap(); let (update_tx, mut update_rx) = mpsc::unbounded_channel(); let mut channel_controller = FakeChannelController { update_tx, @@ -370,7 +367,7 @@ pub async fn dns_lookup_timeout() { // An error endpoint update should be received. let update = update_rx.recv().await.unwrap(); - assert_eq!(update.endpoints.err().unwrap().contains("Timed out"), true); + assert!(update.endpoints.err().unwrap().contains("Timed out")); } #[tokio::test] @@ -398,7 +395,7 @@ pub async fn rate_limit() { let mut resolver = DnsResolver::new(dns_client, opts, dns_opts); // Wait for schedule work to be called. - let event = work_rx.recv().await.unwrap(); + work_rx.recv().await.unwrap(); let (update_tx, mut update_rx) = mpsc::unbounded_channel(); let mut channel_controller = FakeChannelController { update_tx, @@ -407,14 +404,14 @@ pub async fn rate_limit() { resolver.work(&mut channel_controller); // A successful endpoint update should be received. let update = update_rx.recv().await.unwrap(); - assert_eq!(update.endpoints.unwrap().len() > 1, true); + assert!(update.endpoints.unwrap().len() > 1); // Call resolve_now repeatedly, new updates should not be produced. for _ in 0..5 { resolver.resolve_now(); tokio::select! { _ = work_rx.recv() => { - panic!("Received unexpected work request from resolver: {:?}", event); + panic!("Received unexpected work request from resolver"); } _ = tokio::time::sleep(DEFAULT_TEST_SHORT_TIMEOUT) => { println!("No work requested from resolver."); @@ -448,7 +445,7 @@ pub async fn re_resolution_after_success() { let mut resolver = DnsResolver::new(dns_client, opts, dns_opts); // Wait for schedule work to be called. - let _ = work_rx.recv().await.unwrap(); + work_rx.recv().await.unwrap(); let (update_tx, mut update_rx) = mpsc::unbounded_channel(); let mut channel_controller = FakeChannelController { update_tx, @@ -457,14 +454,14 @@ pub async fn re_resolution_after_success() { resolver.work(&mut channel_controller); // A successful endpoint update should be received. let update = update_rx.recv().await.unwrap(); - assert_eq!(update.endpoints.unwrap().len() > 1, true); + assert!(update.endpoints.unwrap().len() > 1); // Call resolve_now, a new update should be produced. resolver.resolve_now(); - let _ = work_rx.recv().await.unwrap(); + work_rx.recv().await.unwrap(); resolver.work(&mut channel_controller); let update = update_rx.recv().await.unwrap(); - assert_eq!(update.endpoints.unwrap().len() > 1, true); + assert!(update.endpoints.unwrap().len() > 1); } #[tokio::test] @@ -507,18 +504,18 @@ pub async fn backoff_on_error() { // As the channel returned an error to the resolver, the resolver will // backoff and re-attempt resolution. for _ in 0..5 { - let _ = work_rx.recv().await.unwrap(); + work_rx.recv().await.unwrap(); resolver.work(&mut channel_controller); let update = update_rx.recv().await.unwrap(); - assert_eq!(update.endpoints.unwrap().len() > 1, true); + assert!(update.endpoints.unwrap().len() > 1); } // This time the channel accepts the resolver update. channel_controller.update_result = Ok(()); - let _ = work_rx.recv().await.unwrap(); + work_rx.recv().await.unwrap(); resolver.work(&mut channel_controller); let update = update_rx.recv().await.unwrap(); - assert_eq!(update.endpoints.unwrap().len() > 1, true); + assert!(update.endpoints.unwrap().len() > 1); // Since the channel controller returns Ok(), the resolver will stop // producing more updates. diff --git a/grpc/src/client/name_resolution/mod.rs b/grpc/src/client/name_resolution/mod.rs index d6b4383c2..6898f5d13 100644 --- a/grpc/src/client/name_resolution/mod.rs +++ b/grpc/src/client/name_resolution/mod.rs @@ -107,7 +107,7 @@ impl Target { let host = self.authority_host(); let port = self.authority_port(); if let Some(port) = port { - format!("{}:{}", host, port) + format!("{host}:{port}") } else { host.to_owned() } @@ -319,6 +319,7 @@ impl Hash for Address { } impl Display for Address { + #[allow(clippy::to_string_in_format_args)] fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "{}:{}", self.network_type, self.address.to_string()) } diff --git a/grpc/src/client/name_resolution/registry.rs b/grpc/src/client/name_resolution/registry.rs index aeb0331c9..eb216538c 100644 --- a/grpc/src/client/name_resolution/registry.rs +++ b/grpc/src/client/name_resolution/registry.rs @@ -66,15 +66,14 @@ impl ResolverRegistry { let scheme = builder.scheme(); if scheme.chars().any(|c| c.is_ascii_uppercase()) { return Err(format!( - "Scheme must not contain uppercase characters: {}", - scheme + "Scheme must not contain uppercase characters: {scheme}" )); } self.inner .lock() .unwrap() .insert(scheme.to_string(), Arc::from(builder)); - return Ok(()); + Ok(()) } /// Returns the resolver builder registered for the given scheme, if any. diff --git a/grpc/src/client/subchannel.rs b/grpc/src/client/subchannel.rs index d325257e1..d9bef839b 100644 --- a/grpc/src/client/subchannel.rs +++ b/grpc/src/client/subchannel.rs @@ -456,6 +456,7 @@ impl SubchannelKey { } impl Display for SubchannelKey { + #[allow(clippy::to_string_in_format_args)] fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.address.address.to_string()) } @@ -479,7 +480,7 @@ impl InternalSubchannelPool { } pub(super) fn lookup_subchannel(&self, key: &SubchannelKey) -> Option> { - println!("looking up subchannel for: {:?} in the pool", key); + println!("looking up subchannel for: {key:?} in the pool"); if let Some(weak_isc) = self.subchannels.read().unwrap().get(key) { if let Some(isc) = weak_isc.upgrade() { return Some(isc); @@ -493,7 +494,7 @@ impl InternalSubchannelPool { key: &SubchannelKey, isc: Arc, ) -> Arc { - println!("registering subchannel for: {:?} with the pool", key); + println!("registering subchannel for: {key:?} with the pool"); self.subchannels .write() .unwrap() @@ -507,7 +508,7 @@ impl InternalSubchannelPool { if let Some(isc) = weak_isc.upgrade() { return; } - println!("removing subchannel for: {:?} from the pool", key); + println!("removing subchannel for: {key:?} from the pool"); subchannels.remove(key); return; } diff --git a/grpc/src/client/transport/registry.rs b/grpc/src/client/transport/registry.rs index 3af6d7de5..cde2dadee 100644 --- a/grpc/src/client/transport/registry.rs +++ b/grpc/src/client/transport/registry.rs @@ -18,7 +18,7 @@ impl std::fmt::Debug for TransportRegistry { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let m = self.m.lock().unwrap(); for key in m.keys() { - write!(f, "k: {:?}", key)? + write!(f, "k: {key:?}")? } Ok(()) } diff --git a/grpc/src/inmemory/mod.rs b/grpc/src/inmemory/mod.rs index 6884f4d68..1c5878f87 100644 --- a/grpc/src/inmemory/mod.rs +++ b/grpc/src/inmemory/mod.rs @@ -88,10 +88,7 @@ impl crate::server::Listener for Arc { async fn accept(&self) -> Option { let mut recv = self.r.lock().await; let r = recv.recv().await; - if r.is_none() { - // Listener was closed. - return None; - } + r.as_ref()?; r.unwrap() } } diff --git a/grpc/src/rt/tokio/hickory_resolver.rs b/grpc/src/rt/tokio/hickory_resolver.rs index 343aa2315..5f8f3a1d7 100644 --- a/grpc/src/rt/tokio/hickory_resolver.rs +++ b/grpc/src/rt/tokio/hickory_resolver.rs @@ -228,7 +228,7 @@ mod tests { let addr = socket.local_addr().unwrap(); server.register_socket(socket); - println!("DNS server running on {}", addr); + println!("DNS server running on {addr}"); let (tx, rx) = oneshot::channel::<()>(); let server_task = tokio::spawn(async move { diff --git a/grpc/src/rt/tokio/mod.rs b/grpc/src/rt/tokio/mod.rs index 25d6cdb82..b0a66ae39 100644 --- a/grpc/src/rt/tokio/mod.rs +++ b/grpc/src/rt/tokio/mod.rs @@ -48,7 +48,7 @@ impl DnsResolver for TokioDefaultDnsResolver { async fn lookup_host_name(&self, name: &str) -> Result, String> { let name_with_port = match name.parse::() { Ok(ip) => SocketAddr::new(ip, 0).to_string(), - Err(_) => format!("{}:0", name), + Err(_) => format!("{name}:0"), }; let ips = tokio::net::lookup_host(name_with_port) .await diff --git a/tests/integration_tests/tests/load_shed.rs b/tests/integration_tests/tests/load_shed.rs index 746d6a1be..630c7f4a6 100644 --- a/tests/integration_tests/tests/load_shed.rs +++ b/tests/integration_tests/tests/load_shed.rs @@ -7,7 +7,7 @@ use tonic::{transport::Server, Code, Request, Response, Status}; async fn service_resource_exhausted() { let addr = run_service_in_background(0).await; - let mut client = test_client::TestClient::connect(format!("http://{}", addr)) + let mut client = test_client::TestClient::connect(format!("http://{addr}")) .await .unwrap(); @@ -22,7 +22,7 @@ async fn service_resource_exhausted() { async fn service_resource_not_exhausted() { let addr = run_service_in_background(1).await; - let mut client = test_client::TestClient::connect(format!("http://{}", addr)) + let mut client = test_client::TestClient::connect(format!("http://{addr}")) .await .unwrap(); diff --git a/tonic-prost-build/src/tests.rs b/tonic-prost-build/src/tests.rs index 230793e91..6551545d3 100644 --- a/tonic-prost-build/src/tests.rs +++ b/tonic-prost-build/src/tests.rs @@ -49,14 +49,12 @@ fn test_request_response_name_google_types_not_compiled() { assert_eq!( request.to_string(), expected.to_string(), - "Failed for input type: {}", - type_name + "Failed for input type: {type_name}" ); assert_eq!( response.to_string(), expected.to_string(), - "Failed for output type: {}", - type_name + "Failed for output type: {type_name}" ); } } @@ -84,14 +82,12 @@ fn test_request_response_name_google_types_compiled() { assert_eq!( request.to_string(), expected_path, - "Failed for input type: {}", - type_name + "Failed for input type: {type_name}" ); assert_eq!( response.to_string(), expected_path, - "Failed for output type: {}", - type_name + "Failed for output type: {type_name}" ); } } @@ -124,20 +120,18 @@ fn test_request_response_name_extern_types() { "::my_crate::MyType" => ":: my_crate :: MyType", "crate::module::MyType" => "crate :: module :: MyType", "::external::lib::Type" => ":: external :: lib :: Type", - _ => panic!("Unknown test case: {}", type_name), + _ => panic!("Unknown test case: {type_name}"), }; assert_eq!( request.to_string(), expected, - "Failed for input type: {}", - type_name + "Failed for input type: {type_name}" ); assert_eq!( response.to_string(), expected, - "Failed for output type: {}", - type_name + "Failed for output type: {type_name}" ); } } @@ -162,14 +156,12 @@ fn test_request_response_name_regular_protobuf_types() { assert_eq!( request.to_string(), expected, - "Failed for input type: {}", - input + "Failed for input type: {input}" ); assert_eq!( response.to_string(), expected, - "Failed for output type: {}", - input + "Failed for output type: {input}" ); } } @@ -194,7 +186,7 @@ fn test_request_response_name_different_proto_paths() { proto_path.replace("::", " :: ") ) } else { - format!("{} :: mypackage :: MyMessage", proto_path) + format!("{proto_path} :: mypackage :: MyMessage") }; let expected_response = if proto_path.contains("::") { format!( @@ -202,20 +194,18 @@ fn test_request_response_name_different_proto_paths() { proto_path.replace("::", " :: ") ) } else { - format!("{} :: mypackage :: MyResponse", proto_path) + format!("{proto_path} :: mypackage :: MyResponse") }; assert_eq!( request.to_string(), expected_request, - "Failed for proto_path: {}", - proto_path + "Failed for proto_path: {proto_path}" ); assert_eq!( response.to_string(), expected_response, - "Failed for proto_path: {}", - proto_path + "Failed for proto_path: {proto_path}" ); } }