refactor: misc clippy suggestions

This commit is contained in:
Greg Heartsfield 2022-09-24 09:01:09 -05:00
parent ccf9b8d47b
commit a98708ba47
7 changed files with 42 additions and 32 deletions

View File

@ -23,10 +23,10 @@ pub struct Close {
impl From<CloseCmd> for Result<Close> { impl From<CloseCmd> for Result<Close> {
fn from(cc: CloseCmd) -> Result<Close> { fn from(cc: CloseCmd) -> Result<Close> {
// ensure command is correct // ensure command is correct
if cc.cmd != "CLOSE" { if cc.cmd == "CLOSE" {
Err(Error::CommandUnknownError)
} else {
Ok(Close { id: cc.id }) Ok(Close { id: cc.id })
} else {
Err(Error::CommandUnknownError)
} }
} }
} }

View File

@ -1,6 +1,6 @@
//! Configuration file and settings management //! Configuration file and settings management
use config::{Config, ConfigError, File}; use config::{Config, ConfigError, File};
use log::*; use log::warn;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::time::Duration; use std::time::Duration;
@ -97,28 +97,36 @@ impl VerifiedUsers {
self.verify_update_frequency_duration = self.verify_update_duration(); self.verify_update_frequency_duration = self.verify_update_duration();
} }
#[must_use]
pub fn is_enabled(&self) -> bool { pub fn is_enabled(&self) -> bool {
self.mode == VerifiedUsersMode::Enabled self.mode == VerifiedUsersMode::Enabled
} }
#[must_use]
pub fn is_active(&self) -> bool { pub fn is_active(&self) -> bool {
self.mode == VerifiedUsersMode::Enabled || self.mode == VerifiedUsersMode::Passive self.mode == VerifiedUsersMode::Enabled || self.mode == VerifiedUsersMode::Passive
} }
#[must_use]
pub fn is_passive(&self) -> bool { pub fn is_passive(&self) -> bool {
self.mode == VerifiedUsersMode::Passive self.mode == VerifiedUsersMode::Passive
} }
#[must_use]
pub fn verify_expiration_duration(&self) -> Option<Duration> { pub fn verify_expiration_duration(&self) -> Option<Duration> {
self.verify_expiration self.verify_expiration
.as_ref() .as_ref()
.and_then(|x| parse_duration::parse(x).ok()) .and_then(|x| parse_duration::parse(x).ok())
} }
#[must_use]
pub fn verify_update_duration(&self) -> Option<Duration> { pub fn verify_update_duration(&self) -> Option<Duration> {
self.verify_update_frequency self.verify_update_frequency
.as_ref() .as_ref()
.and_then(|x| parse_duration::parse(x).ok()) .and_then(|x| parse_duration::parse(x).ok())
} }
#[must_use]
pub fn is_valid(&self) -> bool { pub fn is_valid(&self) -> bool {
self.verify_expiration_duration().is_some() && self.verify_update_duration().is_some() self.verify_expiration_duration().is_some() && self.verify_update_duration().is_some()
} }
@ -139,6 +147,7 @@ pub struct Settings {
} }
impl Settings { impl Settings {
#[must_use]
pub fn new() -> Self { pub fn new() -> Self {
let default_settings = Self::default(); let default_settings = Self::default();
// attempt to construct settings with file // attempt to construct settings with file
@ -162,16 +171,17 @@ impl Settings {
.build()?; .build()?;
let mut settings: Settings = config.try_deserialize()?; let mut settings: Settings = config.try_deserialize()?;
// ensure connection pool size is logical // ensure connection pool size is logical
if settings.database.min_conn > settings.database.max_conn { assert!(
panic!( settings.database.min_conn <= settings.database.max_conn,
"Database min_conn setting ({}) cannot exceed max_conn ({})", "Database min_conn setting ({}) cannot exceed max_conn ({})",
settings.database.min_conn, settings.database.max_conn settings.database.min_conn,
settings.database.max_conn
); );
}
// ensure durations parse // ensure durations parse
if !settings.verified_users.is_valid() { assert!(
panic!("VerifiedUsers time settings could not be parsed"); settings.verified_users.is_valid(),
} "VerifiedUsers time settings could not be parsed"
);
// initialize durations for verified users // initialize durations for verified users
settings.verified_users.init(); settings.verified_users.init();
Ok(settings) Ok(settings)

View File

@ -5,7 +5,7 @@ use crate::error::Result;
use crate::event::Event; use crate::event::Event;
use crate::subscription::Subscription; use crate::subscription::Subscription;
use log::*; use log::{debug, info};
use std::collections::HashMap; use std::collections::HashMap;
use uuid::Uuid; use uuid::Uuid;
@ -30,6 +30,7 @@ impl Default for ClientConn {
impl ClientConn { impl ClientConn {
/// Create a new, empty connection state. /// Create a new, empty connection state.
#[must_use]
pub fn new() -> Self { pub fn new() -> Self {
let client_id = Uuid::new_v4(); let client_id = Uuid::new_v4();
ClientConn { ClientConn {
@ -41,14 +42,16 @@ impl ClientConn {
/// Get a short prefix of the client's unique identifier, suitable /// Get a short prefix of the client's unique identifier, suitable
/// for logging. /// for logging.
#[must_use]
pub fn get_client_prefix(&self) -> String { pub fn get_client_prefix(&self) -> String {
self.client_id.to_string().chars().take(8).collect() self.client_id.to_string().chars().take(8).collect()
} }
/// Find all matching subscriptions. /// Find all matching subscriptions.
#[must_use]
pub fn get_matching_subscriptions(&self, e: &Event) -> Vec<&str> { pub fn get_matching_subscriptions(&self, e: &Event) -> Vec<&str> {
let mut v: Vec<&str> = vec![]; let mut v: Vec<&str> = vec![];
for (id, sub) in self.subscriptions.iter() { for (id, sub) in &self.subscriptions {
if sub.interested_in_event(e) { if sub.interested_in_event(e) {
v.push(id); v.push(id);
} }

View File

@ -130,8 +130,8 @@ impl Event {
// ensure a vector exists for this tag // ensure a vector exists for this tag
idx.entry(tagnamechar).or_insert_with(HashSet::new); idx.entry(tagnamechar).or_insert_with(HashSet::new);
// get the tag vec and insert entry // get the tag vec and insert entry
let tidx = idx.get_mut(&tagnamechar).expect("could not get tag vector"); let idx_tag_vec = idx.get_mut(&tagnamechar).expect("could not get tag vector");
tidx.insert(tagval.clone()); idx_tag_vec.insert(tagval.clone());
} }
// save the tag structure // save the tag structure
self.tagidx = Some(idx); self.tagidx = Some(idx);

View File

@ -60,11 +60,10 @@ pub fn hex_range(s: &str) -> Option<HexSearch> {
upper[byte_len] = b + 16; // bump up the first character in this byte upper[byte_len] = b + 16; // bump up the first character in this byte
// increment done, stop iterating through the vec // increment done, stop iterating through the vec
break; break;
} else { }
// if it is 'f', reset the byte to 0 and do a carry // if it is 'f', reset the byte to 0 and do a carry
// reset and carry // reset and carry
upper[byte_len] = 0; upper[byte_len] = 0;
}
// done with odd logic, so don't repeat this // done with odd logic, so don't repeat this
odd = false; odd = false;
} else { } else {

View File

@ -249,9 +249,9 @@ impl Verifier {
// HTTP request with timeout // HTTP request with timeout
match tokio::time::timeout(Duration::from_secs(5), response_fut).await { match tokio::time::timeout(Duration::from_secs(5), response_fut).await {
Ok(response_res) => { Ok(response_res) => {
let response = response_res?;
// limit size of verification document to 1MB. // limit size of verification document to 1MB.
const MAX_ALLOWED_RESPONSE_SIZE: u64 = 1024 * 1024; const MAX_ALLOWED_RESPONSE_SIZE: u64 = 1024 * 1024;
let response = response_res?;
// determine content length from response // determine content length from response
let response_content_length = match response.body().size_hint().upper() { let response_content_length = match response.body().size_hint().upper() {
Some(v) => v, Some(v) => v,
@ -267,13 +267,12 @@ impl Verifier {
let body_matches = body_contains_user(&nip.local, pubkey, body_bytes)?; let body_matches = body_contains_user(&nip.local, pubkey, body_bytes)?;
if body_matches { if body_matches {
return Ok(UserWebVerificationStatus::Verified); return Ok(UserWebVerificationStatus::Verified);
} else { }
// successful response, parsed as a nip-05 // successful response, parsed as a nip-05
// document, but this name/pubkey was not // document, but this name/pubkey was not
// present. // present.
return Ok(UserWebVerificationStatus::Unverified); return Ok(UserWebVerificationStatus::Unverified);
} }
}
} else { } else {
info!( info!(
"content length missing or exceeded limits for account: {:?}", "content length missing or exceeded limits for account: {:?}",

View File

@ -484,7 +484,7 @@ async fn nostr_server(
make_notice_message("binary messages are not accepted")).await.ok(); make_notice_message("binary messages are not accepted")).await.ok();
continue; continue;
}, },
Some(Ok(Message::Ping(_))) | Some(Ok(Message::Pong(_))) => { Some(Ok(Message::Ping(_) | Message::Pong(_))) => {
// get a ping/pong, ignore. tungstenite will // get a ping/pong, ignore. tungstenite will
// send responses automatically. // send responses automatically.
continue; continue;
@ -496,10 +496,9 @@ async fn nostr_server(
continue; continue;
}, },
None | None |
Some(Ok(Message::Close(_))) | Some(Ok(Message::Close(_)) |
Some(Err(WsError::AlreadyClosed)) | Err(WsError::AlreadyClosed | WsError::ConnectionClosed |
Some(Err(WsError::ConnectionClosed)) | WsError::Protocol(tungstenite::error::ProtocolError::ResetWithoutClosingHandshake)))
Some(Err(WsError::Protocol(tungstenite::error::ProtocolError::ResetWithoutClosingHandshake)))
=> { => {
debug!("websocket close from client: {:?}",cid); debug!("websocket close from client: {:?}",cid);
break; break;