From e4832b4cf36ba0eaed298ee458498eddd7176590 Mon Sep 17 00:00:00 2001 From: FxQnLr Date: Sun, 11 Feb 2024 21:17:58 +0100 Subject: fix clippy --- src/auth.rs | 12 ++++----- src/error.rs | 8 +++--- src/main.rs | 14 +++++----- src/routes/device.rs | 26 +++++++++---------- src/routes/start.rs | 72 +++++++++++++++++++++++++++++++++++----------------- src/routes/status.rs | 2 +- src/services/ping.rs | 14 +++++----- src/wol.rs | 14 +++++----- 8 files changed, 94 insertions(+), 68 deletions(-) (limited to 'src') diff --git a/src/auth.rs b/src/auth.rs index 90d920f..0321ade 100644 --- a/src/auth.rs +++ b/src/auth.rs @@ -1,17 +1,17 @@ use axum::http::{StatusCode, HeaderValue}; use axum::http::header::ToStrError; use tracing::{debug, error, trace}; -use crate::auth::AuthError::{MissingSecret, WrongSecret}; +use crate::auth::Error::{MissingSecret, WrongSecret}; use crate::config::SETTINGS; -pub fn auth(secret: Option<&HeaderValue>) -> Result { +pub fn auth(secret: Option<&HeaderValue>) -> Result { debug!("auth request with secret {:?}", secret); if let Some(value) = secret { trace!("value exists"); let key = SETTINGS .get_string("apikey") - .map_err(AuthError::Config)?; - if value.to_str().map_err(AuthError::HeaderToStr)? == key.as_str() { + .map_err(Error::Config)?; + if value.to_str().map_err(Error::HeaderToStr)? == key.as_str() { debug!("successful auth"); Ok(true) } else { @@ -25,14 +25,14 @@ pub fn auth(secret: Option<&HeaderValue>) -> Result { } #[derive(Debug)] -pub enum AuthError { +pub enum Error { WrongSecret, MissingSecret, Config(config::ConfigError), HeaderToStr(ToStrError) } -impl AuthError { +impl Error { pub fn get(self) -> (StatusCode, &'static str) { match self { Self::WrongSecret => (StatusCode::UNAUTHORIZED, "Wrong credentials"), diff --git a/src/error.rs b/src/error.rs index 5b82534..56d6c52 100644 --- a/src/error.rs +++ b/src/error.rs @@ -4,10 +4,10 @@ use axum::Json; use axum::response::{IntoResponse, Response}; use serde_json::json; use tracing::error; -use crate::auth::AuthError; +use crate::auth::Error as AuthError; #[derive(Debug)] -pub enum WebolError { +pub enum Error { Generic, Auth(AuthError), DB(sqlx::Error), @@ -16,7 +16,7 @@ pub enum WebolError { Broadcast(io::Error), } -impl IntoResponse for WebolError { +impl IntoResponse for Error { fn into_response(self) -> Response { let (status, error_message) = match self { Self::Auth(err) => { @@ -45,4 +45,4 @@ impl IntoResponse for WebolError { })); (status, body).into_response() } -} \ No newline at end of file +} diff --git a/src/main.rs b/src/main.rs index aab9df3..9d30548 100644 --- a/src/main.rs +++ b/src/main.rs @@ -11,10 +11,10 @@ use tracing::{info, level_filters::LevelFilter}; use tracing_subscriber::{EnvFilter, fmt::{self, time::LocalTime}, prelude::*}; use crate::config::SETTINGS; use crate::db::init_db_pool; -use crate::routes::device::{get_device, post_device, put_device}; +use crate::routes::device; use crate::routes::start::start; use crate::routes::status::status; -use crate::services::ping::{BroadcastCommands, PingMap}; +use crate::services::ping::{BroadcastCommands, StatusMap}; mod auth; mod config; @@ -54,15 +54,15 @@ async fn main() -> color_eyre::eyre::Result<()> { let (tx, _) = channel(32); - let ping_map: PingMap = DashMap::new(); + let ping_map: StatusMap = DashMap::new(); let shared_state = Arc::new(AppState { db, ping_send: tx, ping_map }); let app = Router::new() .route("/start", post(start)) - .route("/device", get(get_device)) - .route("/device", put(put_device)) - .route("/device", post(post_device)) + .route("/device", get(device::get)) + .route("/device", put(device::put)) + .route("/device", post(device::post)) .route("/status", get(status)) .with_state(shared_state); @@ -78,5 +78,5 @@ async fn main() -> color_eyre::eyre::Result<()> { pub struct AppState { db: PgPool, ping_send: Sender, - ping_map: PingMap, + ping_map: StatusMap, } diff --git a/src/routes/device.rs b/src/routes/device.rs index a3308d4..b80cb85 100644 --- a/src/routes/device.rs +++ b/src/routes/device.rs @@ -7,12 +7,12 @@ use serde_json::{json, Value}; use tracing::{debug, info}; use crate::auth::auth; use crate::db::Device; -use crate::error::WebolError; +use crate::error::Error; -pub async fn get_device(State(state): State>, headers: HeaderMap, Json(payload): Json) -> Result, WebolError> { +pub async fn get(State(state): State>, headers: HeaderMap, Json(payload): Json) -> Result, Error> { info!("add device {}", payload.id); let secret = headers.get("authorization"); - if auth(secret).map_err(WebolError::Auth)? { + if auth(secret).map_err(Error::Auth)? { let device = sqlx::query_as!( Device, r#" @@ -21,13 +21,13 @@ pub async fn get_device(State(state): State>, headers: Head WHERE id = $1; "#, payload.id - ).fetch_one(&state.db).await.map_err(WebolError::DB)?; + ).fetch_one(&state.db).await.map_err(Error::DB)?; debug!("got device {:?}", device); Ok(Json(json!(device))) } else { - Err(WebolError::Generic) + Err(Error::Generic) } } @@ -36,10 +36,10 @@ pub struct GetDevicePayload { id: String, } -pub async fn put_device(State(state): State>, headers: HeaderMap, Json(payload): Json) -> Result, WebolError> { +pub async fn put(State(state): State>, headers: HeaderMap, Json(payload): Json) -> Result, Error> { info!("add device {} ({}, {}, {})", payload.id, payload.mac, payload.broadcast_addr, payload.ip); let secret = headers.get("authorization"); - if auth(secret).map_err(WebolError::Auth)? { + if auth(secret).map_err(Error::Auth)? { sqlx::query!( r#" INSERT INTO devices (id, mac, broadcast_addr, ip) @@ -49,11 +49,11 @@ pub async fn put_device(State(state): State>, headers: Head payload.mac, payload.broadcast_addr, payload.ip - ).execute(&state.db).await.map_err(WebolError::DB)?; + ).execute(&state.db).await.map_err(Error::DB)?; Ok(Json(json!(PutDeviceResponse { success: true }))) } else { - Err(WebolError::Generic) + Err(Error::Generic) } } @@ -70,10 +70,10 @@ pub struct PutDeviceResponse { success: bool } -pub async fn post_device(State(state): State>, headers: HeaderMap, Json(payload): Json) -> Result, WebolError> { +pub async fn post(State(state): State>, headers: HeaderMap, Json(payload): Json) -> Result, Error> { info!("edit device {} ({}, {}, {})", payload.id, payload.mac, payload.broadcast_addr, payload.ip); let secret = headers.get("authorization"); - if auth(secret).map_err(WebolError::Auth)? { + if auth(secret).map_err(Error::Auth)? { let device = sqlx::query_as!( Device, r#" @@ -85,11 +85,11 @@ pub async fn post_device(State(state): State>, headers: Hea payload.broadcast_addr, payload.ip, payload.id - ).fetch_one(&state.db).await.map_err(WebolError::DB)?; + ).fetch_one(&state.db).await.map_err(Error::DB)?; Ok(Json(json!(device))) } else { - Err(WebolError::Generic) + Err(Error::Generic) } } diff --git a/src/routes/start.rs b/src/routes/start.rs index a206cbd..4264588 100644 --- a/src/routes/start.rs +++ b/src/routes/start.rs @@ -1,23 +1,27 @@ -use axum::Json; +use crate::auth::auth; +use crate::config::SETTINGS; +use crate::db::Device; +use crate::error::Error; +use crate::services::ping::Value as PingValue; +use crate::wol::{create_buffer, send_packet}; +use axum::extract::State; use axum::http::HeaderMap; +use axum::Json; use serde::{Deserialize, Serialize}; -use std::sync::Arc; -use axum::extract::State; use serde_json::{json, Value}; +use std::sync::Arc; use tracing::{debug, info}; use uuid::Uuid; -use crate::auth::auth; -use crate::config::SETTINGS; -use crate::wol::{create_buffer, send_packet}; -use crate::db::Device; -use crate::error::WebolError; -use crate::services::ping::PingValue; #[axum_macros::debug_handler] -pub async fn start(State(state): State>, headers: HeaderMap, Json(payload): Json) -> Result, WebolError> { +pub async fn start( + State(state): State>, + headers: HeaderMap, + Json(payload): Json, +) -> Result, Error> { info!("POST request"); let secret = headers.get("authorization"); - let authorized = auth(secret).map_err(WebolError::Auth)?; + let authorized = auth(secret).map_err(Error::Auth)?; if authorized { let device = sqlx::query_as!( Device, @@ -27,7 +31,10 @@ pub async fn start(State(state): State>, headers: HeaderMap WHERE id = $1; "#, payload.id - ).fetch_one(&state.db).await.map_err(WebolError::DB)?; + ) + .fetch_one(&state.db) + .await + .map_err(Error::DB)?; info!("starting {}", device.id); @@ -36,9 +43,9 @@ pub async fn start(State(state): State>, headers: HeaderMap .unwrap_or("0.0.0.0:1111".to_string()); let _ = send_packet( - &bind_addr.parse().map_err(WebolError::IpParse)?, - &device.broadcast_addr.parse().map_err(WebolError::IpParse)?, - create_buffer(&device.mac)? + &bind_addr.parse().map_err(Error::IpParse)?, + &device.broadcast_addr.parse().map_err(Error::IpParse)?, + &create_buffer(&device.mac)?, )?; let dev_id = device.id.clone(); let uuid = if payload.ping.is_some_and(|ping| ping) { @@ -49,7 +56,7 @@ pub async fn start(State(state): State>, headers: HeaderMap uuid = Some(key); break; } - }; + } let uuid_gen = match uuid { Some(u) => u, None => Uuid::new_v4().to_string(), @@ -58,26 +65,45 @@ pub async fn start(State(state): State>, headers: HeaderMap tokio::spawn(async move { debug!("init ping service"); - state.ping_map.insert(uuid_gen.clone(), PingValue { ip: device.ip.clone(), online: false }); + state.ping_map.insert( + uuid_gen.clone(), + PingValue { + ip: device.ip.clone(), + online: false, + }, + ); - crate::services::ping::spawn(state.ping_send.clone(), device, uuid_gen.clone(), &state.ping_map, &state.db).await; + crate::services::ping::spawn( + state.ping_send.clone(), + device, + uuid_gen.clone(), + &state.ping_map, + &state.db, + ) + .await; }); Some(uuid_genc) - } else { None }; - Ok(Json(json!(StartResponse { id: dev_id, boot: true, uuid }))) + } else { + None + }; + Ok(Json(json!(Response { + id: dev_id, + boot: true, + uuid + }))) } else { - Err(WebolError::Generic) + Err(Error::Generic) } } #[derive(Deserialize)] -pub struct StartPayload { +pub struct Payload { id: String, ping: Option, } #[derive(Serialize)] -struct StartResponse { +struct Response { id: String, boot: bool, uuid: Option, diff --git a/src/routes/status.rs b/src/routes/status.rs index 45f3e51..31ef996 100644 --- a/src/routes/status.rs +++ b/src/routes/status.rs @@ -7,4 +7,4 @@ use crate::services::ping::status_websocket; #[axum_macros::debug_handler] pub async fn status(State(state): State>, ws: WebSocketUpgrade) -> Response { ws.on_upgrade(move |socket| status_websocket(socket, state)) -} \ No newline at end of file +} diff --git a/src/services/ping.rs b/src/services/ping.rs index 0f773f4..7d71218 100644 --- a/src/services/ping.rs +++ b/src/services/ping.rs @@ -2,26 +2,26 @@ use std::str::FromStr; use std::net::IpAddr; use std::sync::Arc; -use axum::extract::{ws::WebSocket}; +use axum::extract::ws::WebSocket; use axum::extract::ws::Message; use dashmap::DashMap; use sqlx::PgPool; use time::{Duration, Instant}; -use tokio::sync::broadcast::{Sender}; +use tokio::sync::broadcast::Sender; use tracing::{debug, error, trace}; use crate::AppState; use crate::config::SETTINGS; use crate::db::Device; -pub type PingMap = DashMap; +pub type StatusMap = DashMap; #[derive(Debug, Clone)] -pub struct PingValue { +pub struct Value { pub ip: String, pub online: bool } -pub async fn spawn(tx: Sender, device: Device, uuid: String, ping_map: &PingMap, db: &PgPool) { +pub async fn spawn(tx: Sender, device: Device, uuid: String, ping_map: &StatusMap, db: &PgPool) { let timer = Instant::now(); let payload = [0; 8]; @@ -63,7 +63,7 @@ pub async fn spawn(tx: Sender, device: Device, uuid: String, timer.elapsed().whole_seconds(), device.id ).execute(db).await.unwrap(); - ping_map.insert(uuid.clone(), PingValue { ip: device.ip.clone(), online: true }); + ping_map.insert(uuid.clone(), Value { ip: device.ip.clone(), online: true }); tokio::time::sleep(tokio::time::Duration::from_secs(60)).await; } trace!("remove {} from ping_map", uuid); @@ -107,7 +107,7 @@ async fn get_eta(db: &PgPool) -> i64 { None => { vec![0] }, Some(t) => t, }; - times.iter().sum::() / times.len() as i64 + times.iter().sum::() / i64::try_from(times.len()).unwrap() } diff --git a/src/wol.rs b/src/wol.rs index 8755b21..83c0ee6 100644 --- a/src/wol.rs +++ b/src/wol.rs @@ -1,17 +1,17 @@ use std::net::{SocketAddr, UdpSocket}; -use crate::error::WebolError; +use crate::error::Error; /// Creates the magic packet from a mac address /// /// # Panics /// /// Panics if `mac_addr` is an invalid mac -pub fn create_buffer(mac_addr: &str) -> Result, WebolError> { +pub fn create_buffer(mac_addr: &str) -> Result, Error> { let mut mac = Vec::new(); let sp = mac_addr.split(':'); for f in sp { - mac.push(u8::from_str_radix(f, 16).map_err(WebolError::BufferParse)?); + mac.push(u8::from_str_radix(f, 16).map_err(Error::BufferParse)?); }; let mut buf = vec![255; 6]; for _ in 0..16 { @@ -23,8 +23,8 @@ pub fn create_buffer(mac_addr: &str) -> Result, WebolError> { } /// Sends a buffer on UDP broadcast -pub fn send_packet(bind_addr: &SocketAddr, broadcast_addr: &SocketAddr, buffer: Vec) -> Result { - let socket = UdpSocket::bind(bind_addr).map_err(WebolError::Broadcast)?; - socket.set_broadcast(true).map_err(WebolError::Broadcast)?; - socket.send_to(&buffer, broadcast_addr).map_err(WebolError::Broadcast) +pub fn send_packet(bind_addr: &SocketAddr, broadcast_addr: &SocketAddr, buffer: &[u8]) -> Result { + let socket = UdpSocket::bind(bind_addr).map_err(Error::Broadcast)?; + socket.set_broadcast(true).map_err(Error::Broadcast)?; + socket.send_to(buffer, broadcast_addr).map_err(Error::Broadcast) } -- cgit v1.2.3