🚨 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>> -> anyhow::Result <Response <Body>>
{ {
let req_id = rusty_ulid::generate_ulid_string (); 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); 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); let (tx, rx) = mpsc::channel (1);
spawn ({ spawn ({
let req_id = req_id.clone (); let _req_id = req_id.clone ();
let proxy_filter = state.proxy_filter.clone (); let proxy_filter = state.proxy_filter.clone ();
async move { async move {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -4,7 +4,7 @@ pub async fn read_git_version () -> Option <String> {
io::AsyncReadExt, 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 mut f = File::open ("git_version.txt").await.ok ()?;
let bytes_read = f.read (&mut buf).await.ok ()?; let bytes_read = f.read (&mut buf).await.ok ()?;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -244,7 +244,7 @@ pub async fn serve_all (
resp 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"), Favicon => serve_error (StatusCode::NotFound, "Not found\n"),
Forbidden => serve_error (StatusCode::Forbidden, "403 Forbidden\n"), Forbidden => serve_error (StatusCode::Forbidden, "403 Forbidden\n"),
MethodNotAllowed => serve_error (StatusCode::MethodNotAllowed, "Unsupported method\n"), MethodNotAllowed => serve_error (StatusCode::MethodNotAllowed, "Unsupported method\n"),