🚨 fix a bunch of easy clippy warnings

main
_ 2021-03-21 03:34:47 +00:00
parent f1f13d6e17
commit 50fc509c8b
14 changed files with 57 additions and 57 deletions

View File

@ -94,7 +94,7 @@ async fn handle_all <PF: 'static + ProxyFilter + Sync + Send> (req: Request <Bod
-> anyhow::Result <Response <Body>>
{
let req_id = rusty_ulid::generate_ulid_string ();
let (head, mut body) = req.into_parts ();
let (head, body) = req.into_parts ();
tracing::debug! ("{} Got URI {}", req_id, head.uri);
@ -114,7 +114,7 @@ async fn handle_all <PF: 'static + ProxyFilter + Sync + Send> (req: Request <Bod
let (tx, rx) = mpsc::channel (1);
spawn ({
let req_id = req_id.clone ();
let _req_id = req_id.clone ();
let proxy_filter = state.proxy_filter.clone ();
async move {

View File

@ -62,16 +62,13 @@ impl RequestParts {
headers: hyper::HeaderMap <hyper::header::HeaderValue>
) -> Result <Self, Error>
{
use std::iter::FromIterator;
let method = Method::try_from (method)?;
let headers = HashMap::from_iter (
headers.into_iter ()
.filter_map (|(k, v)| {
let (k, v) = k.map (|k| (k, v))?;
Some ((String::from (k.as_str ()), v.as_bytes ().to_vec ()))
})
);
let headers = headers.into_iter ()
.filter_map (|(k, v)| {
let (k, v) = k.map (|k| (k, v))?;
Some ((String::from (k.as_str ()), v.as_bytes ().to_vec ()))
})
.collect ();
Ok (Self {
method,

View File

@ -17,12 +17,7 @@ pub const PTTH_MAGIC_HEADER: &str = "X-PTTH-2LJYXWC4";
#[must_use]
pub fn prefix_match <'a> (prefix: &str, hay: &'a str) -> Option <&'a str>
{
if hay.starts_with (prefix) {
Some (&hay [prefix.len ()..])
}
else {
None
}
hay.strip_prefix (prefix)
}
#[cfg (test)]

View File

@ -80,17 +80,12 @@ struct EstablishedConnection {
server_down: String,
}
#[derive (Default)]
pub struct HttpService {
state: Arc <RelayState>
}
impl HttpService {
pub fn new () -> Self {
Self {
state: Arc::new (RelayState::default ()),
}
}
pub async fn serve (&self, port: u16) -> Result <(), hyper::Error> {
use std::net::SocketAddr;
@ -140,7 +135,7 @@ impl HttpService {
async fn handle_gets (req: Request <Body>, state: &RelayState)
-> Result <Response <Body>, anyhow::Error>
{
let (mut tx, rx) = mpsc::channel (1);
let (tx, rx) = mpsc::channel (1);
spawn (async move {
let id = rusty_ulid::generate_ulid_string ();
@ -196,7 +191,7 @@ async fn main () -> Result <(), anyhow::Error> {
.init ()
;
let service = HttpService::new ();
let service = HttpService::default ();
info! ("Starting relay");
Ok (service.serve (4003).await?)

View File

@ -97,10 +97,9 @@ impl Store {
-> Self
where I: Iterator <Item = (Vec <u8>, StatusQuotas)>
{
let status_dirs = HashMap::from_iter (
status_dirs
.map (|(name, quotas)| (name, StatusKeyDirectory::new (quotas)))
);
let status_dirs = status_dirs
.map (|(name, quotas)| (name, StatusKeyDirectory::new (quotas)))
.collect ();
Self {
status_dirs,

View File

@ -4,13 +4,15 @@
use std::{
collections::HashMap,
convert::{TryFrom},
iter::FromIterator,
path::Path,
};
use crate::{
errors::ConfigError,
key_validity::*,
key_validity::{
ScraperKey,
Valid30Days,
},
};
// Stuff we need to load from the config file and use to
@ -19,7 +21,11 @@ use crate::{
pub mod file {
use serde::Deserialize;
use crate::key_validity::*;
use crate::key_validity::{
BlakeHashWrapper,
ScraperKey,
Valid30Days,
};
#[derive (Deserialize)]
pub struct Server {
@ -76,11 +82,11 @@ impl TryFrom <file::Config> for Config {
let servers = f.servers.unwrap_or_else (|| vec! []);
let servers = servers.into_iter ().map (|server| Ok::<_, ConfigError> ((server.name.clone (), server)));
let servers = itertools::process_results (servers, |i| HashMap::from_iter (i))?;
let servers = itertools::process_results (servers, |i| i.collect ())?;
let scraper_keys = f.scraper_keys.unwrap_or_else (|| vec! []);
let scraper_keys = if f.iso.enable_scraper_api {
HashMap::from_iter (scraper_keys.into_iter ().map (|key| (key.hash.encode_base64 (), key)))
scraper_keys.into_iter ().map (|key| (key.hash.encode_base64 (), key)).collect ()
}
else {
Default::default ()

View File

@ -4,7 +4,7 @@ pub async fn read_git_version () -> Option <String> {
io::AsyncReadExt,
};
let mut buf = vec! [0u8; 512];
let mut buf = vec! [0_u8; 512];
let mut f = File::open ("git_version.txt").await.ok ()?;
let bytes_read = f.read (&mut buf).await.ok ()?;

View File

@ -24,10 +24,12 @@ impl Debug for BlakeHashWrapper {
}
impl BlakeHashWrapper {
#[must_use]
pub fn from_key (bytes: &[u8]) -> Self {
Self (blake3::hash (bytes))
}
#[must_use]
pub fn encode_base64 (&self) -> String {
base64::encode (self.as_bytes ())
}
@ -126,6 +128,7 @@ impl <V: MaxValidDuration> ScraperKey <V> {
}
impl <V: MaxValidDuration> ScraperKey <V> {
#[must_use]
pub fn is_valid (&self, now: DateTime <Utc>, input: &[u8]) -> KeyValidity {
use KeyValidity::*;
@ -156,7 +159,7 @@ impl <V: MaxValidDuration> ScraperKey <V> {
return ClockIsBehind;
}
return Valid;
Valid
}
}

View File

@ -69,7 +69,10 @@ pub use config::Config;
pub use errors::*;
pub use relay_state::RelayState;
use relay_state::*;
use relay_state::{
RejectedServer,
RequestRendezvous,
};
fn ok_reply <B: Into <Body>> (b: B)
-> Result <Response <Body>, http::Error>
@ -323,7 +326,7 @@ async fn handle_unregistered_servers_internal (state: &Arc <RelayState>)
let last_seen = match pretty_print_last_seen (now, x.seen) {
Negative => "Error (negative time)".into (),
Connected => "Recently".into (),
Description (s) => s.into (),
Description (s) => s,
};
UnregisteredServer {
@ -398,7 +401,7 @@ async fn handle_endless_source (gib: usize, throttle: Option <usize>)
use rand::RngCore;
let mut rng = rand::thread_rng ();
let mut block = vec! [0u8; 64 * 1024];
let mut block = vec! [0_u8; 64 * 1024];
rng.fill_bytes (&mut block);
block
};
@ -413,7 +416,7 @@ async fn handle_endless_source (gib: usize, throttle: Option <usize>)
for _ in 0..throttle.unwrap_or (1) {
let item = Ok::<_, Infallible> (random_block.clone ());
if let Err (_) = tx.send (item).await {
if tx.send (item).await.is_err () {
debug! ("Endless source dropped");
return;
}
@ -472,7 +475,7 @@ async fn handle_all (
else if let Some (rest) = prefix_match ("/frontend/servers/", &path) {
// DRY T4H76LB3
if rest == "" {
if rest.is_empty () {
Ok (handle_server_list (state, handlebars).await?)
}
else if let Some (idx) = rest.find ('/') {
@ -490,7 +493,7 @@ async fn handle_all (
Ok (handle_unregistered_servers (state, handlebars).await?)
}
else if let Some (rest) = prefix_match ("/frontend/debug/", &path) {
if rest == "" {
if rest.is_empty () {
let s = handlebars.render ("debug", &())?;
Ok (ok_reply (s)?)
}

View File

@ -1,6 +1,5 @@
use std::{
collections::HashMap,
iter::FromIterator,
sync::Arc,
};
@ -23,7 +22,10 @@ use tracing::{
use crate::{
RequestError,
error_reply,
key_validity::*,
key_validity::{
BlakeHashWrapper,
KeyValidity,
},
prefix_match,
relay_state::RelayState,
};
@ -80,7 +82,7 @@ pub async fn v1_server_list (state: &Arc <RelayState>)
(k.clone (), display_name)
});
HashMap::from_iter (servers)
servers.collect ()
};
// name --> status

View File

@ -174,7 +174,10 @@ pub async fn handle_response (
let mut shutdown_watch_rx = state.shutdown_watch_rx.clone ();
let relay_task = spawn (async move {
if *shutdown_watch_rx.borrow () == false {
if *shutdown_watch_rx.borrow () {
debug! ("Can't relay bytes, relay is shutting down");
}
else {
loop {
let item = body.next ().await;
@ -184,7 +187,7 @@ pub async fn handle_response (
}
futures::select! {
x = body_tx.send (item).fuse () => if let Err (_) = x {
x = body_tx.send (item).fuse () => if x.is_err () {
info! ("Body closed while relaying. (Client hung up?)");
body_finished_tx.send (ClientDisconnected).map_err (|_| LostServer)?;
break;
@ -202,9 +205,6 @@ pub async fn handle_response (
}
}
}
else {
debug! ("Can't relay bytes, relay is shutting down");
}
Ok::<(), HandleHttpResponseError> (())
});

View File

@ -61,7 +61,7 @@ async fn main () -> Result <(), anyhow::Error> {
let config_file: ConfigFile = match load_toml::load (&path) {
Err (ptth_server::errors::LoadTomlError::Io (_)) => if opt.auto_gen_key {
use rand::RngCore;
let mut buffer = vec! [0u8; 64];
let mut buffer = vec! [0_u8; 64];
rand::thread_rng ().fill_bytes (&mut buffer);
let api_key = base64::encode (&buffer);
@ -73,7 +73,7 @@ async fn main () -> Result <(), anyhow::Error> {
permissions.set_mode (0o600);
f.set_permissions (permissions)?;
f.write (format! ("api_key = \"{}\"\n", api_key).as_bytes ())?;
f.write_all (format! ("api_key = \"{}\"\n", api_key).as_bytes ())?;
}
load_toml::load (&path)?

View File

@ -110,8 +110,6 @@ impl Interval {
{
use uom::si::ratio::percent;
let mut interval = tokio::time::interval (Duration::from_secs (60));
#[derive (Default)]
struct Window {
window_length: u64,
@ -124,7 +122,7 @@ impl Interval {
Window {
window_length,
next_interval: 0,
last_metrics: Default::default (),
last_metrics: Arc::default (),
}
}
@ -149,6 +147,8 @@ impl Interval {
}
}
let mut interval = tokio::time::interval (Duration::from_secs (60));
let mut counter = 0_u64;
let mut windows = [1, 5, 10, 60, 1440]
@ -171,7 +171,7 @@ impl Interval {
let new_interval_metrics = Arc::new (Some (new_interval_metrics));
for window in windows.iter_mut () {
for window in &mut windows {
window.update (counter, &new_interval_metrics);
}

View File

@ -244,7 +244,7 @@ pub async fn serve_all (
resp
}
Ok (match internal::serve_all (root, method, uri, headers, state.hidden_path.as_ref ().map (|p| p.as_path ())).await? {
Ok (match internal::serve_all (root, method, uri, headers, state.hidden_path.as_deref ()).await? {
Favicon => serve_error (StatusCode::NotFound, "Not found\n"),
Forbidden => serve_error (StatusCode::Forbidden, "403 Forbidden\n"),
MethodNotAllowed => serve_error (StatusCode::MethodNotAllowed, "Unsupported method\n"),