diff options
| author | MatthieuCoder <matthieu@matthieu-dev.xyz> | 2023-01-14 17:45:48 +0400 | 
|---|---|---|
| committer | MatthieuCoder <matthieu@matthieu-dev.xyz> | 2023-01-14 17:45:48 +0400 | 
| commit | 3f342846149c0b1f8d1ac1f0b857a9d9fdf2034b (patch) | |
| tree | 5ad087639ade0998ec0af0e0532c71a59b92993a /exes/rest | |
| parent | ee58b30800527306ab024da926121c085a0978fa (diff) | |
clippy, tests and a bit of docs
Diffstat (limited to 'exes/rest')
| -rw-r--r-- | exes/rest/src/config.rs | 2 | ||||
| -rw-r--r-- | exes/rest/src/handler.rs | 10 | ||||
| -rw-r--r-- | exes/rest/src/lib.rs | 16 | ||||
| -rw-r--r-- | exes/rest/src/ratelimit_client/mod.rs | 22 | ||||
| -rw-r--r-- | exes/rest/src/ratelimit_client/remote_hashring.rs | 6 | 
5 files changed, 35 insertions, 21 deletions
diff --git a/exes/rest/src/config.rs b/exes/rest/src/config.rs index e87757c..9593ac8 100644 --- a/exes/rest/src/config.rs +++ b/exes/rest/src/config.rs @@ -23,7 +23,7 @@ pub struct Discord {  }  #[derive(Debug, Deserialize, Clone, Default)] -pub struct ReverseProxyConfig { +pub struct ReverseProxy {      pub server: ServerSettings,      pub discord: Discord,      pub ratelimiter_address: String, diff --git a/exes/rest/src/handler.rs b/exes/rest/src/handler.rs index a8f43cd..ab158fe 100644 --- a/exes/rest/src/handler.rs +++ b/exes/rest/src/handler.rs @@ -58,7 +58,7 @@ pub async fn handle_request(          let request_path = request.uri().path();          let (api_path, trimmed_path) = normalize_path(request_path); -        let mut uri_string = format!("http://127.0.0.1:9999{}{}", api_path, trimmed_path); +        let mut uri_string = format!("http://127.0.0.1:9999{api_path}{trimmed_path}");          if let Some(query) = request.uri().query() {              uri_string.push('?');              uri_string.push_str(query); @@ -103,12 +103,12 @@ pub async fn handle_request(              .expect("Failed to check header")              .starts_with("Bot")          { -            *auth = HeaderValue::from_str(&format!("Bot {}", token))?; +            *auth = HeaderValue::from_str(&format!("Bot {token}"))?;          }      } else {          request.headers_mut().insert(              AUTHORIZATION, -            HeaderValue::from_str(&format!("Bot {}", token))?, +            HeaderValue::from_str(&format!("Bot {token}"))?,          );      } @@ -132,12 +132,12 @@ pub async fn handle_request(      let headers = resp          .headers()          .into_iter() -        .map(|(k, v)| (k.to_string(), v.to_str().map(|f| f.to_string()))) +        .map(|(k, v)| (k.to_string(), v.to_str().map(std::string::ToString::to_string)))          .filter(|f| f.1.is_ok())          .map(|f| (f.0, f.1.expect("errors should be filtered")))          .collect(); -    let _ = ratelimiter +    let _submit_headers = ratelimiter          .submit_headers(hash, headers)          .instrument(info_span!("submitting headers"))          .await; diff --git a/exes/rest/src/lib.rs b/exes/rest/src/lib.rs index 53ab12a..174bea0 100644 --- a/exes/rest/src/lib.rs +++ b/exes/rest/src/lib.rs @@ -1,4 +1,16 @@ -use config::ReverseProxyConfig; +#![deny( +    clippy::all, +    clippy::correctness, +    clippy::suspicious, +    clippy::style, +    clippy::complexity, +    clippy::perf, +    clippy::pedantic, +    clippy::nursery, +    unsafe_code +)] + +use config::ReverseProxy;  use handler::handle_request;  use hyper::{ @@ -20,7 +32,7 @@ mod ratelimit_client;  pub struct ReverseProxyServer {}  impl Component for ReverseProxyServer { -    type Config = ReverseProxyConfig; +    type Config = ReverseProxy;      const SERVICE_NAME: &'static str = "rest";      fn start( diff --git a/exes/rest/src/ratelimit_client/mod.rs b/exes/rest/src/ratelimit_client/mod.rs index c9bd52e..e2f7e0e 100644 --- a/exes/rest/src/ratelimit_client/mod.rs +++ b/exes/rest/src/ratelimit_client/mod.rs @@ -1,4 +1,4 @@ -use crate::config::ReverseProxyConfig; +use crate::config::ReverseProxy;  use self::remote_hashring::{HashRingWrapper, MetadataMap, VNode};  use anyhow::anyhow; @@ -23,7 +23,7 @@ pub struct RemoteRatelimiter {      current_remotes: Vec<String>,      stop: Arc<tokio::sync::broadcast::Sender<()>>, -    config: ReverseProxyConfig, +    config: ReverseProxy,  }  impl Drop for RemoteRatelimiter { @@ -41,15 +41,15 @@ impl RemoteRatelimiter {          // get list of dns responses          let responses: Vec<String> = dns_lookup::lookup_host(&self.config.ratelimiter_address)?              .into_iter() -            .filter(|address| address.is_ipv4()) +            .filter(std::net::IpAddr::is_ipv4)              .map(|address| address.to_string())              .collect();          let mut write = self.remotes.write().await;          for ip in &responses { -            if !self.current_remotes.contains(&ip) { -                let a = VNode::new(ip.to_owned(), self.config.ratelimiter_port).await?; +            if !self.current_remotes.contains(ip) { +                let a = VNode::new(ip.clone(), self.config.ratelimiter_port).await?;                  write.add(a.clone());              }          } @@ -58,13 +58,13 @@ impl RemoteRatelimiter {      }      #[must_use] -    pub fn new(config: ReverseProxyConfig) -> Self { +    pub fn new(config: ReverseProxy) -> Self {          let (rx, mut tx) = broadcast::channel(1);          let obj = Self {              remotes: Arc::new(RwLock::new(HashRingWrapper::default())),              stop: Arc::new(rx),              config, -            current_remotes: vec![] +            current_remotes: vec![],          };          let obj_clone = obj.clone(); @@ -75,7 +75,7 @@ impl RemoteRatelimiter {                  match obj_clone.get_ratelimiters().await {                      Ok(_) => { -                        debug!("refreshed ratelimiting servers") +                        debug!("refreshed ratelimiting servers");                      }                      Err(err) => {                          error!("refreshing ratelimiting servers failed {}", err); @@ -122,7 +122,7 @@ impl RemoteRatelimiter {                  let context = span.context();                  let mut request = Request::new(BucketSubmitTicketRequest { path });                  global::get_text_map_propagator(|propagator| { -                    propagator.inject_context(&context, &mut MetadataMap(request.metadata_mut())) +                    propagator.inject_context(&context, &mut MetadataMap(request.metadata_mut()));                  });                  // Requesting @@ -158,13 +158,15 @@ impl RemoteRatelimiter {              let time = SystemTime::now()                  .duration_since(SystemTime::UNIX_EPOCH)?                  .as_millis(); +            // truncation is expected +            #[allow(clippy::cast_possible_truncation)]              let mut request = Request::new(HeadersSubmitRequest {                  path,                  precise_time: time as u64,                  headers,              });              global::get_text_map_propagator(|propagator| { -                propagator.inject_context(&context, &mut MetadataMap(request.metadata_mut())) +                propagator.inject_context(&context, &mut MetadataMap(request.metadata_mut()));              });              node.submit_headers(request).await?; diff --git a/exes/rest/src/ratelimit_client/remote_hashring.rs b/exes/rest/src/ratelimit_client/remote_hashring.rs index ac025c8..b99276d 100644 --- a/exes/rest/src/ratelimit_client/remote_hashring.rs +++ b/exes/rest/src/ratelimit_client/remote_hashring.rs @@ -38,7 +38,7 @@ impl Hash for VNode {  pub struct MetadataMap<'a>(pub &'a mut tonic::metadata::MetadataMap);  impl<'a> Injector for MetadataMap<'a> { -    /// Set a key and value in the MetadataMap.  Does nothing if the key or value are not valid inputs +    /// Set a key and value in the `MetadataMap`.  Does nothing if the key or value are not valid inputs      fn set(&mut self, key: &str, value: String) {          if let Ok(key) = tonic::metadata::MetadataKey::from_bytes(key.as_bytes()) {              if let Ok(val) = tonic::metadata::MetadataValue::try_from(&value) { @@ -50,11 +50,11 @@ impl<'a> Injector for MetadataMap<'a> {  impl VNode {      pub async fn new(address: String, port: u16) -> Result<Self, tonic::transport::Error> { -        let host = format!("http://{}:{}", address.clone(), port); +        let host = format!("http://{}:{port}", address.clone());          debug!("connecting to {}", host);          let client = RatelimiterClient::connect(host).await?; -        Ok(VNode { client, address }) +        Ok(Self { address, client })      }  }  | 
