Skip to content

Commit

Permalink
Merge branch 'main' into regex-filter
Browse files Browse the repository at this point in the history
  • Loading branch information
XAMPPRocky authored Jan 25, 2022
2 parents 3bf397a + 96c3231 commit 2828b86
Show file tree
Hide file tree
Showing 21 changed files with 57 additions and 76 deletions.
2 changes: 1 addition & 1 deletion rust-toolchain.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,5 @@
# limitations under the License.

[toolchain]
channel = "1.57.0"
channel = "1.58.1"
components = ["rustfmt", "clippy"]
2 changes: 1 addition & 1 deletion src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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"));
}
}
}
12 changes: 3 additions & 9 deletions src/config/config_type.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,9 +61,7 @@ impl ConfigType<'_> {
.and_then(|raw_config| serde_yaml::from_str::<Static>(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| {
Expand All @@ -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))
Expand All @@ -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}",
))
})
}
Expand Down
8 changes: 4 additions & 4 deletions src/endpoint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down Expand Up @@ -392,15 +392,15 @@ 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!(
vec![ep(1), ep(3), ep(4)],
up.iter().cloned().collect::<Vec<_>>()
);

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::<Vec<_>>());
Expand Down
4 changes: 2 additions & 2 deletions src/filters/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ impl From<MetricsError> 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 {
Expand Down Expand Up @@ -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::<Vec<_>>()
.join(", ")
),
Expand Down
11 changes: 5 additions & 6 deletions src/filters/firewall/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -183,21 +183,20 @@ impl TryFrom<ProtoConfig> for Config {
fn convert_port(range: &ProtoPortRange) -> Result<PortRange, ConvertProtoConfigError> {
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<Rule, ConvertProtoConfigError> {
Expand All @@ -211,7 +210,7 @@ impl TryFrom<ProtoConfig> 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()),
)
})?;
Expand Down
30 changes: 11 additions & 19 deletions src/filters/load_balancer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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},
Expand Down Expand Up @@ -190,12 +190,12 @@ policy: RANDOM
#[test]
fn hash_load_balancer_policy() {
let addresses: Vec<EndpointAddress> = 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
Expand All @@ -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::<Vec<_>>();
Expand All @@ -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::<Vec<_>>();
Expand All @@ -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::<Vec<_>>();
result_sequences.push(sequence);
}
Expand All @@ -291,7 +285,5 @@ policy: HASH
.any(|seq| seq != &result_sequences[0]),
"the same sequence of addresses were chosen for hash load balancer"
);

//
}
}
2 changes: 1 addition & 1 deletion src/filters/local_rate_limit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
3 changes: 1 addition & 2 deletions src/filters/token_router.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
2 changes: 1 addition & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
};
Expand Down
2 changes: 1 addition & 1 deletion src/metrics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion src/proxy/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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!"),
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/proxy/config_dump.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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}"));
}
}

Expand Down
8 changes: 4 additions & 4 deletions src/proxy/server/resource_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ impl StaticResourceManagers {
) -> Result<StaticResourceManagers, InitializeError> {
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),
})
}
Expand Down Expand Up @@ -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,
Expand All @@ -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
Expand Down
2 changes: 1 addition & 1 deletion src/test_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/xds/ads_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
21 changes: 10 additions & 11 deletions src/xds/cluster.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String, ProxyCluster>;
Expand Down Expand Up @@ -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::<SocketAddr>()
.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,
Expand All @@ -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,
Expand Down Expand Up @@ -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,
Expand Down
4 changes: 2 additions & 2 deletions src/xds/listener.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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![];
Expand All @@ -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 {
Expand Down
Loading

0 comments on commit 2828b86

Please sign in to comment.