Thanks to visit codestin.com
Credit goes to github.com

Skip to content
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
20 changes: 12 additions & 8 deletions grpc/src/client/load_balancing/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ impl ParsedJsonLbConfig {
pub fn new(json: &str) -> Result<Self, String> {
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}")),
}
}

Expand All @@ -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)
Expand Down Expand Up @@ -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(())
}
Expand Down Expand Up @@ -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})"),
}
}
}
Expand All @@ -324,17 +324,21 @@ impl LbState {
}
}

/// Type alias for the completion callback function.
pub type CompletionCallback = Box<dyn Fn(&Response) + Send + Sync>;

/// A collection of data used by the channel for routing a request.
pub struct Pick {
/// The Subchannel for the request.
pub subchannel: Arc<dyn Subchannel>,
// Metadata to be added to existing outgoing metadata.
pub metadata: MetadataMap,
// Callback to be invoked once the RPC completes.
pub on_complete: Option<Box<dyn Fn(&Response) + Send + Sync>>,
pub on_complete: Option<CompletionCallback>,
}

pub trait DynHash {
#[allow(clippy::redundant_allocation)]
fn dyn_hash(&self, state: &mut Box<&mut dyn Hasher>);
}

Expand Down Expand Up @@ -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);
}
}
Expand All @@ -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());
Expand Down
22 changes: 11 additions & 11 deletions grpc/src/client/name_resolution/backoff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand All @@ -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]
Expand All @@ -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]
Expand All @@ -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]
Expand All @@ -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]
Expand Down Expand Up @@ -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)));
}
}
10 changes: 5 additions & 5 deletions grpc/src/client/name_resolution/dns/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -311,7 +311,7 @@ fn parse_endpoint_and_authority(target: &Target) -> Result<ParseResult, String>
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.
Expand All @@ -323,7 +323,7 @@ fn parse_endpoint_and_authority(target: &Target) -> Result<ParseResult, String>
});
}
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,
Expand Down Expand Up @@ -351,7 +351,7 @@ fn parse_host_port(host_and_port: &str, default_port: u16) -> Result<Option<Host
// We need to use the https scheme otherwise url::Url::parse doesn't convert
// IP addresses to Host::Ipv4 or Host::Ipv6 if they could represent valid
// domains.
let url = format!("https://{}", host_and_port);
let url = format!("https://{host_and_port}");
let url = url.parse::<url::Url>().map_err(|err| err.to_string())?;
let port = url.port().unwrap_or(default_port);
let host = match url.host() {
Expand Down
49 changes: 23 additions & 26 deletions grpc/src/client/name_resolution/dns/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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]
Expand All @@ -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,
Expand All @@ -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)]
Expand Down Expand Up @@ -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,
Expand All @@ -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]
Expand Down Expand Up @@ -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,
Expand All @@ -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]
Expand Down Expand Up @@ -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,
Expand All @@ -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.");
Expand Down Expand Up @@ -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,
Expand All @@ -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]
Expand Down Expand Up @@ -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.
Expand Down
3 changes: 2 additions & 1 deletion grpc/src/client/name_resolution/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
}
Expand Down Expand Up @@ -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())
}
Expand Down
5 changes: 2 additions & 3 deletions grpc/src/client/name_resolution/registry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Loading
Loading