diff --git a/rust-toolchain.toml b/rust-toolchain.toml index b17b8f8436..2b78fed2e9 100644 --- a/rust-toolchain.toml +++ b/rust-toolchain.toml @@ -13,5 +13,5 @@ # limitations under the License. [toolchain] -channel = "1.57.0" +channel = "1.58.1" components = ["rustfmt", "clippy"] diff --git a/src/config.rs b/src/config.rs index 1ee8c00fba..37419868e6 100644 --- a/src/config.rs +++ b/src/config.rs @@ -470,7 +470,7 @@ dynamic: for config in configs { let result = Config::from_reader(config.as_bytes()); let error = result.unwrap_err(); - assert!(format!("{:?}", error).contains("unknown field")); + assert!(format!("{error:?}").contains("unknown field")); } } } diff --git a/src/config/config_type.rs b/src/config/config_type.rs index 252b708041..09788a9559 100644 --- a/src/config/config_type.rs +++ b/src/config/config_type.rs @@ -61,9 +61,7 @@ impl ConfigType<'_> { .and_then(|raw_config| serde_yaml::from_str::(raw_config.as_str())) .map_err(|err| { Error::DeserializeFailed(format!( - "filter `{}`: failed to YAML deserialize config: {}", - filter_name, - err.to_string() + "filter `{filter_name}`: failed to YAML deserialize config: {err}", )) }) .and_then(|config| { @@ -73,9 +71,7 @@ impl ConfigType<'_> { ConfigType::Dynamic(config) => prost::Message::decode(Bytes::from(config.value)) .map_err(|err| { Error::DeserializeFailed(format!( - "filter `{}`: config decode error: {}", - filter_name, - err.to_string() + "filter `{filter_name}`: config decode error: {err}", )) }) .and_then(|config| Static::try_from(config).map_err(Error::ConvertProtoConfig)) @@ -93,9 +89,7 @@ impl ConfigType<'_> { { serde_json::to_value(config).map_err(|err| { Error::DeserializeFailed(format!( - "filter `{}`: failed to serialize config to json: {}", - filter_name, - err.to_string() + "filter `{filter_name}`: failed to serialize config to json: {err}", )) }) } diff --git a/src/endpoint.rs b/src/endpoint.rs index 86cb9026a7..6284e680c6 100644 --- a/src/endpoint.rs +++ b/src/endpoint.rs @@ -339,8 +339,8 @@ impl<'a> Iterator for UpstreamEndpointsIter<'a> { mod tests { use super::*; - fn ep(id: usize) -> Endpoint { - Endpoint::new(format!("127.0.0.{}:8080", id).parse().unwrap()) + fn ep(id: u8) -> Endpoint { + Endpoint::new(([127, 0, 0, id], 8080u16).into()) } #[test] @@ -392,7 +392,7 @@ mod tests { let mut up: UpstreamEndpoints = Endpoints::new(initial_endpoints.clone()).unwrap().into(); - let items = up.retain(|ep| ep.address.to_string().as_str() != "127.0.0.2:8080"); + let items = up.retain(|ep| ep.address != ([127, 0, 0, 2], 8080).into()); assert!(matches!(items, RetainedItems::Some(3))); assert_eq!(up.size(), 3); assert_eq!( @@ -400,7 +400,7 @@ mod tests { up.iter().cloned().collect::>() ); - let items = up.retain(|ep| ep.address.to_string().as_str() != "127.0.0.3:8080"); + let items = up.retain(|ep| ep.address != ([127, 0, 0, 3], 8080).into()); assert!(matches!(items, RetainedItems::Some(2))); assert_eq!(up.size(), 2); assert_eq!(vec![ep(1), ep(4)], up.iter().cloned().collect::>()); diff --git a/src/filters/error.rs b/src/filters/error.rs index c8e3571e86..f8d47648da 100644 --- a/src/filters/error.rs +++ b/src/filters/error.rs @@ -55,7 +55,7 @@ impl From for Error { #[derive(Debug, PartialEq, thiserror::Error)] #[error( "{}failed to convert protobuf config: {}", - self.field.as_ref().map(|f| format!("Field `{}` ", f)).unwrap_or_default(), + self.field.as_ref().map(|f| format!("Field `{f}`")).unwrap_or_default(), reason )] pub struct ConvertProtoConfigError { @@ -92,7 +92,7 @@ macro_rules! enum_no_match_error { $( (stringify!($allowed_value), <$enum_type>::$allowed_value as i32) ),+ ] .into_iter() - .map(|(a, b)| format!("{} => {}", a, b as i32)) + .map(|(a, b)| format!("{a} => {}", b as i32)) .collect::>() .join(", ") ), diff --git a/src/filters/firewall/config.rs b/src/filters/firewall/config.rs index b40f3d03d8..8e5776588d 100644 --- a/src/filters/firewall/config.rs +++ b/src/filters/firewall/config.rs @@ -183,21 +183,20 @@ impl TryFrom for Config { fn convert_port(range: &ProtoPortRange) -> Result { let min = u16::try_from(range.min).map_err(|err| { ConvertProtoConfigError::new( - format!("min too large: {}", err), + format!("min too large: {err}"), Some("port.min".into()), ) })?; let max = u16::try_from(range.max).map_err(|err| { ConvertProtoConfigError::new( - format!("max too large: {}", err), + format!("max too large: {err}"), Some("port.max".into()), ) })?; - PortRange::new(min, max).map_err(|err| { - ConvertProtoConfigError::new(format!("{}", err), Some("ports".into())) - }) + PortRange::new(min, max) + .map_err(|err| ConvertProtoConfigError::new(format!("{err}"), Some("ports".into()))) } fn convert_rule(rule: &ProtoRule) -> Result { @@ -211,7 +210,7 @@ impl TryFrom for Config { let source = IpNetwork::try_from(rule.source.as_str()).map_err(|err| { ConvertProtoConfigError::new( - format!("invalid source: {:?}", err), + format!("invalid source: {err:?}"), Some("source".into()), ) })?; diff --git a/src/filters/load_balancer.rs b/src/filters/load_balancer.rs index 5272ffa36d..dc981c9911 100644 --- a/src/filters/load_balancer.rs +++ b/src/filters/load_balancer.rs @@ -66,7 +66,7 @@ impl FilterFactory for LoadBalancerFilterFactory { #[cfg(test)] mod tests { - use std::collections::HashSet; + use std::{collections::HashSet, net::Ipv4Addr}; use crate::{ endpoint::{Endpoint, EndpointAddress, Endpoints}, @@ -190,12 +190,12 @@ policy: RANDOM #[test] fn hash_load_balancer_policy() { let addresses: Vec = vec![ - "127.0.0.1:8080".parse().unwrap(), - "127.0.0.2:8080".parse().unwrap(), - "127.0.0.3:8080".parse().unwrap(), + ([127, 0, 0, 1], 8080).into(), + ([127, 0, 0, 2], 8080).into(), + ([127, 0, 0, 3], 8080).into(), ]; - let source_ips = vec!["127.1.1.1", "127.2.2.2", "127.3.3.3"]; - let source_ports = vec!["11111", "22222", "33333", "44444", "55555"]; + let source_ips = vec![[127u8, 1, 1, 1], [127, 2, 2, 2], [127, 3, 3, 3]]; + let source_ports = vec![11111u16, 22222, 33333, 44444, 55555]; let yaml = " policy: HASH @@ -210,7 +210,7 @@ policy: HASH get_response_addresses( filter.as_ref(), &addresses, - "127.0.0.1:8080".parse().unwrap(), + (Ipv4Addr::LOCALHOST, 8080).into(), ) }) .collect::>(); @@ -231,13 +231,13 @@ policy: HASH // Run a few selection rounds through the address // this time vary the port for a single IP let mut result_sequences = vec![]; - for port in &source_ports { + for port in source_ports.iter().copied() { let sequence = (0..addresses.len()) .map(|_| { get_response_addresses( filter.as_ref(), &addresses, - format!("127.0.0.1:{}", port).parse().unwrap(), + (Ipv4Addr::LOCALHOST, port).into(), ) }) .collect::>(); @@ -259,15 +259,9 @@ policy: HASH // This time vary the source IP and port let mut result_sequences = vec![]; for ip in source_ips { - for port in &source_ports { + for port in source_ports.iter().copied() { let sequence = (0..addresses.len()) - .map(|_| { - get_response_addresses( - filter.as_ref(), - &addresses, - format!("{}:{}", ip, port).parse().unwrap(), - ) - }) + .map(|_| get_response_addresses(filter.as_ref(), &addresses, (ip, port).into())) .collect::>(); result_sequences.push(sequence); } @@ -291,7 +285,5 @@ policy: HASH .any(|seq| seq != &result_sequences[0]), "the same sequence of addresses were chosen for hash load balancer" ); - - // } } diff --git a/src/filters/local_rate_limit.rs b/src/filters/local_rate_limit.rs index 9024a66838..cbcc3c6a0f 100644 --- a/src/filters/local_rate_limit.rs +++ b/src/filters/local_rate_limit.rs @@ -281,7 +281,7 @@ period: 0 }) .err() .unwrap(); - assert!(format!("{:?}", err).contains("value must be at least 1 second")); + assert!(format!("{err:?}").contains("value must be at least 1 second")); } #[test] diff --git a/src/filters/token_router.rs b/src/filters/token_router.rs index f810e1305d..ad52972bc7 100644 --- a/src/filters/token_router.rs +++ b/src/filters/token_router.rs @@ -81,8 +81,7 @@ impl FilterFactory for TokenRouterFactory { serde_json::to_value(&config) .map_err(|err| { Error::DeserializeFailed(format!( - "failed to JSON deserialize default config: {}", - err + "failed to JSON deserialize default config: {err}", )) }) .map(|config_json| (config_json, config)) diff --git a/src/main.rs b/src/main.rs index 56ec295afe..301d58e8b7 100644 --- a/src/main.rs +++ b/src/main.rs @@ -25,7 +25,7 @@ async fn main() -> quilkin::Result<()> { tracing_subscriber::fmt().json().with_target(false).init(); stable_eyre::install()?; let version: std::borrow::Cow<'static, str> = if cfg!(debug_assertions) { - format!("{}+debug", VERSION).into() + format!("{VERSION}+debug").into() } else { VERSION.into() }; diff --git a/src/metrics.rs b/src/metrics.rs index 61f8ca1db6..083259802d 100644 --- a/src/metrics.rs +++ b/src/metrics.rs @@ -49,7 +49,7 @@ pub fn histogram_opts( /// Create a generic metrics options for a filter. pub fn filter_opts(name: &str, filter_name: &str, description: &str) -> Opts { - opts(name, &format!("filter_{}", filter_name), description) + opts(name, &format!("filter_{filter_name}"), description) } /// Registers the current metric collector with the provided registry. diff --git a/src/proxy/builder.rs b/src/proxy/builder.rs index bd2f83967d..8a11235e2f 100644 --- a/src/proxy/builder.rs +++ b/src/proxy/builder.rs @@ -269,7 +269,7 @@ mod tests { .validate() { Err(Error::InvalidConfig(err)) => err, - Err(err) => unreachable!(format!("expected ValidationError, got {}", err)), + Err(err) => unreachable!(format!("expected ValidationError, got {err}")), Ok(_) => unreachable!("config validation should have failed!"), } } diff --git a/src/proxy/config_dump.rs b/src/proxy/config_dump.rs index bafa6ac784..fb3fd2fc37 100644 --- a/src/proxy/config_dump.rs +++ b/src/proxy/config_dump.rs @@ -61,7 +61,7 @@ pub(crate) fn handle_request( } Err(err) => { *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from(format!("failed to create config dump: {}", err)); + *response.body_mut() = Body::from(format!("failed to create config dump: {err}")); } } diff --git a/src/proxy/server/resource_manager.rs b/src/proxy/server/resource_manager.rs index 89c971c726..764f4a8f2f 100644 --- a/src/proxy/server/resource_manager.rs +++ b/src/proxy/server/resource_manager.rs @@ -49,7 +49,7 @@ impl StaticResourceManagers { ) -> Result { Ok(Self { cluster_manager: ClusterManager::fixed(metrics_registry, endpoints) - .map_err(|err| InitializeError::Message(format!("{:?}", err)))?, + .map_err(|err| InitializeError::Message(format!("{err:?}")))?, filter_manager: FilterManager::fixed(filter_chain), }) } @@ -97,11 +97,11 @@ impl DynamicResourceManagers { let cluster_manager = ClusterManager::dynamic(&metrics_registry, cluster_updates_rx, shutdown_rx.clone()) - .map_err(|err| InitializeError::Message(format!("{:?}", err)))?; + .map_err(|err| InitializeError::Message(format!("{err:?}")))?; let filter_manager = FilterManager::dynamic(&metrics_registry, filter_chain_updates_rx, shutdown_rx) - .map_err(|err| InitializeError::Message(format!("{:?}", err)))?; + .map_err(|err| InitializeError::Message(format!("{err:?}")))?; Ok(Self { cluster_manager, @@ -125,7 +125,7 @@ impl DynamicResourceManagers { } = args; let client = AdsClient::new(&metrics_registry).map_err(|err| { - InitializeError::Message(format!("failed to initialize xDS client: {:?}", err)) + InitializeError::Message(format!("failed to initialize xDS client: {err:?}")) })?; tokio::spawn(async move { let result = client diff --git a/src/test_utils.rs b/src/test_utils.rs index 1c0697a815..a85333908a 100644 --- a/src/test_utils.rs +++ b/src/test_utils.rs @@ -301,7 +301,7 @@ pub fn config_with_dummy_endpoint() -> ConfigBuilder { /// Creates a dummy endpoint with `id` as a suffix. pub fn ep(id: u8) -> Endpoint { Endpoint { - address: format!("127.0.0.{}:8080", id).parse().unwrap(), + address: ([127, 0, 0, id], 8080).into(), ..<_>::default() } } diff --git a/src/xds/ads_client.rs b/src/xds/ads_client.rs index c26901203d..3b9e298cda 100644 --- a/src/xds/ads_client.rs +++ b/src/xds/ads_client.rs @@ -129,7 +129,7 @@ impl AdsClient { // Do not retry if this is an invalid URL error that we cannot recover from. // Need to use {:?} as the Display output only returns 'transport error' - let err_description = format!("{:?}", error); + let err_description = format!("{error:?}"); if err_description.to_lowercase().contains("invalid url") { RetryPolicy::Break } else { diff --git a/src/xds/cluster.rs b/src/xds/cluster.rs index 2f89ea475a..9a0fb54c74 100644 --- a/src/xds/cluster.rs +++ b/src/xds/cluster.rs @@ -371,7 +371,6 @@ mod tests { use prost_types::Struct as ProstStruct; use prost_types::Value as ProstValue; use std::collections::{HashMap, HashSet}; - use std::net::SocketAddr; use tokio::sync::mpsc; type ClusterState = HashMap; @@ -433,17 +432,15 @@ mod tests { let _ = recv_cluster_and_endpoint_reqs(&mut discovery_req_rx).await; - let mut version = 4; - let mut nonce = 9; + let mut version = 4u8; + let mut nonce = 9u8; for _ in 0..3 { let v = &version.to_string(); let n = &nonce.to_string(); - let new_address = format!("127.0.0.{}", nonce); - let new_port = 2020 + nonce; - let expected_socket_addr = format!("{}:{}", new_address, new_port) - .parse::() - .unwrap(); + let new_address = std::net::Ipv4Addr::from([127, 0, 0, nonce]); + let new_port = 2020 + nonce as u16; + let expected_socket_addr = (new_address, new_port); cm.on_cluster_load_assignment_response(endpoint_discovery_response_with_update( v, n, @@ -455,10 +452,12 @@ mod tests { address: Some(Address { address: Some(address::Address::SocketAddress(SocketAddress { protocol: 1, - address: new_address.clone(), + address: new_address.to_string(), resolver_name: "".into(), ipv4_compat: true, - port_specifier: Some(PortSpecifier::PortValue(new_port)), + port_specifier: Some(PortSpecifier::PortValue( + new_port as u32, + )), })), }), health_check_config: None, @@ -794,7 +793,7 @@ mod tests { assert_eq!(dyn_metadata.len(), 1); let value = dyn_metadata - .get(&format!("key-{}", cluster_name).into()) + .get(&format!("key-{cluster_name}").into()) .unwrap(); assert_eq!( value, diff --git a/src/xds/listener.rs b/src/xds/listener.rs index 0bbafb2653..8819ae694c 100644 --- a/src/xds/listener.rs +++ b/src/xds/listener.rs @@ -411,7 +411,7 @@ mod tests { for (i, (filter, expected_payload)) in test_cases.into_iter().enumerate() { // Send a response with a filter chain. let lds_listener = create_lds_listener( - format!("test-listener-{}", i), + format!("test-listener-{i}"), vec![create_lds_filter_chain(filter)], ); let mut buf = vec![]; @@ -421,7 +421,7 @@ mod tests { value: buf, }; - let (version_info, nonce) = (format!("version-{}", i), format!("nonce-{}", i)); + let (version_info, nonce) = (format!("version-{i}"), format!("nonce-{i}")); // Send the proto message as a DiscoveryResponse to the manager. manager .on_listener_response(DiscoveryResponse { diff --git a/tests/compress.rs b/tests/compress.rs index fdcb77e3bc..e39c22c245 100644 --- a/tests/compress.rs +++ b/tests/compress.rs @@ -14,7 +14,7 @@ * limitations under the License. */ -use std::net::SocketAddr; +use std::net::{Ipv4Addr, SocketAddr}; use tokio::time::{timeout, Duration}; @@ -62,9 +62,7 @@ on_write: DECOMPRESS name: compress::factory().name().into(), config: serde_yaml::from_str(yaml).unwrap(), }], - vec![Endpoint::new( - format!("127.0.0.1:{}", server_port).parse().unwrap(), - )], + vec![Endpoint::new((Ipv4Addr::LOCALHOST, server_port).into())], ) .build(); // Run client proxy. @@ -74,7 +72,7 @@ on_write: DECOMPRESS let (mut rx, tx) = t.open_socket_and_recv_multiple_packets().await; // game_client - let local_addr: SocketAddr = format!("127.0.0.1:{}", client_port).parse().unwrap(); + let local_addr = SocketAddr::from((Ipv4Addr::LOCALHOST, client_port)); tracing::info!(address = %local_addr, "Sending hello"); tx.send_to(b"hello", &local_addr).await.unwrap(); diff --git a/tests/filter_order.rs b/tests/filter_order.rs index 53adb2b3eb..7eee3ea0db 100644 --- a/tests/filter_order.rs +++ b/tests/filter_order.rs @@ -15,7 +15,7 @@ */ ///! Complex integration tests that incorporate multiple elements -use std::{net::SocketAddr, str::from_utf8}; +use std::{net::Ipv4Addr, str::from_utf8}; use tokio::time::{timeout, Duration}; @@ -81,7 +81,7 @@ on_write: DECOMPRESS // let's send the packet let (mut recv_chan, socket) = t.open_socket_and_recv_multiple_packets().await; - let local_addr: SocketAddr = format!("127.0.0.1:{}", server_port).parse().unwrap(); + let local_addr = (Ipv4Addr::LOCALHOST, server_port); socket.send_to(b"hello", &local_addr).await.unwrap(); assert_eq!( diff --git a/tests/xds.rs b/tests/xds.rs index 87d0866774..2ce950762b 100644 --- a/tests/xds.rs +++ b/tests/xds.rs @@ -282,7 +282,7 @@ dynamic: // Open a socket we can use to talk to the proxy and receive response back on. let (mut response_rx, socket) = t.open_socket_and_recv_multiple_packets().await; - let expected_response = format!("a{}{}", b1, b2); + let expected_response = format!("a{b1}{b2}"); let mut interval = time::interval(Duration::from_millis(10)); loop { // Send a packet, it should be suffixed with the new filter configs.