From 3428a637ce420baef9aa9f9803e71bd587867005 Mon Sep 17 00:00:00 2001 From: FxQnLr Date: Wed, 10 Apr 2024 00:16:55 +0200 Subject: Closes #24. Changed postgres to json directory storage --- src/routes/device.rs | 118 ++++++++++++--------------------------------------- src/routes/start.rs | 92 ++++++++------------------------------- src/routes/status.rs | 24 ++--------- 3 files changed, 50 insertions(+), 184 deletions(-) (limited to 'src/routes') diff --git a/src/routes/device.rs b/src/routes/device.rs index 40b5cd8..b6bd9d0 100644 --- a/src/routes/device.rs +++ b/src/routes/device.rs @@ -1,47 +1,15 @@ -use crate::db::Device; use crate::error::Error; -use axum::extract::{Path, State}; +use crate::storage::Device; +use axum::extract::Path; use axum::Json; +use ipnetwork::IpNetwork; use mac_address::MacAddress; use serde::Deserialize; use serde_json::{json, Value}; -use sqlx::types::ipnetwork::IpNetwork; -use std::{str::FromStr, sync::Arc}; +use std::str::FromStr; use tracing::{debug, info}; use utoipa::ToSchema; -#[utoipa::path( - get, - path = "/device", - request_body = GetDevicePayload, - responses( - (status = 200, description = "Get `Device` information", body = [Device]) - ), - security(("api_key" = [])) -)] -#[deprecated] -pub async fn get_payload( - State(state): State>, - Json(payload): Json, -) -> Result, Error> { - info!("get device {}", payload.id); - let device = sqlx::query_as!( - Device, - r#" - SELECT id, mac, broadcast_addr, ip, times - FROM devices - WHERE id = $1; - "#, - payload.id - ) - .fetch_one(&state.db) - .await?; - - debug!("got device {:?}", device); - - Ok(Json(json!(device))) -} - #[utoipa::path( get, path = "/device/{id}", @@ -53,22 +21,10 @@ pub async fn get_payload( ), security((), ("api_key" = [])) )] -pub async fn get( - State(state): State>, - Path(path): Path, -) -> Result, Error> { - info!("get device from path {}", path); - let device = sqlx::query_as!( - Device, - r#" - SELECT id, mac, broadcast_addr, ip, times - FROM devices - WHERE id = $1; - "#, - path - ) - .fetch_one(&state.db) - .await?; +pub async fn get(Path(id): Path) -> Result, Error> { + info!("get device from path {}", id); + + let device = Device::read(&id)?; debug!("got device {:?}", device); @@ -76,13 +32,7 @@ pub async fn get( } #[derive(Deserialize, ToSchema)] -#[deprecated] -pub struct GetDevicePayload { - id: String, -} - -#[derive(Deserialize, ToSchema)] -pub struct DevicePayload { +pub struct Payload { id: String, mac: String, broadcast_addr: String, @@ -92,15 +42,14 @@ pub struct DevicePayload { #[utoipa::path( put, path = "/device", - request_body = DevicePayload, + request_body = Payload, responses( (status = 200, description = "add device to storage", body = [DeviceSchema]) ), security((), ("api_key" = [])) )] pub async fn put( - State(state): State>, - Json(payload): Json, + Json(payload): Json, ) -> Result, Error> { info!( "add device {} ({}, {}, {})", @@ -109,20 +58,14 @@ pub async fn put( let ip = IpNetwork::from_str(&payload.ip)?; let mac = MacAddress::from_str(&payload.mac)?; - let device = sqlx::query_as!( - Device, - r#" - INSERT INTO devices (id, mac, broadcast_addr, ip) - VALUES ($1, $2, $3, $4) - RETURNING id, mac, broadcast_addr, ip, times; - "#, - payload.id, + let device = Device { + id: payload.id, mac, - payload.broadcast_addr, - ip - ) - .fetch_one(&state.db) - .await?; + broadcast_addr: payload.broadcast_addr, + ip, + times: None, + }; + device.write()?; Ok(Json(json!(device))) } @@ -130,15 +73,14 @@ pub async fn put( #[utoipa::path( post, path = "/device", - request_body = DevicePayload, + request_body = Payload, responses( (status = 200, description = "update device in storage", body = [DeviceSchema]) ), security((), ("api_key" = [])) )] pub async fn post( - State(state): State>, - Json(payload): Json, + Json(payload): Json, ) -> Result, Error> { info!( "edit device {} ({}, {}, {})", @@ -146,20 +88,16 @@ pub async fn post( ); let ip = IpNetwork::from_str(&payload.ip)?; let mac = MacAddress::from_str(&payload.mac)?; - let device = sqlx::query_as!( - Device, - r#" - UPDATE devices - SET mac = $1, broadcast_addr = $2, ip = $3 WHERE id = $4 - RETURNING id, mac, broadcast_addr, ip, times; - "#, + let times = Device::read(&payload.id)?.times; + + let device = Device { + id: payload.id, mac, - payload.broadcast_addr, + broadcast_addr: payload.broadcast_addr, ip, - payload.id - ) - .fetch_one(&state.db) - .await?; + times, + }; + device.write()?; Ok(Json(json!(device))) } diff --git a/src/routes/start.rs b/src/routes/start.rs index ff3d1be..6907193 100644 --- a/src/routes/start.rs +++ b/src/routes/start.rs @@ -1,7 +1,7 @@ -use crate::db::Device; +use crate::storage::Device; use crate::error::Error; use crate::services::ping::Value as PingValue; -use crate::wol::{create_buffer, send_packet}; +use crate::wol::send_packet; use axum::extract::{Path, State}; use axum::Json; use serde::{Deserialize, Serialize}; @@ -11,55 +11,6 @@ use tracing::{debug, info}; use utoipa::ToSchema; use uuid::Uuid; -#[utoipa::path( - post, - path = "/start", - request_body = PayloadOld, - responses( - (status = 200, description = "DEP", body = [Response]) - ), - security((), ("api_key" = [])) -)] -#[deprecated] -pub async fn start_payload( - State(state): State>, - Json(payload): Json, -) -> Result, Error> { - info!("POST request"); - let device = sqlx::query_as!( - Device, - r#" - SELECT id, mac, broadcast_addr, ip, times - FROM devices - WHERE id = $1; - "#, - payload.id - ) - .fetch_one(&state.db) - .await?; - - info!("starting {}", device.id); - - let bind_addr = "0.0.0.0:0"; - - let _ = send_packet( - bind_addr, - &device.broadcast_addr, - &create_buffer(&device.mac.to_string())?, - )?; - let dev_id = device.id.clone(); - let uuid = if payload.ping.is_some_and(|ping| ping) { - Some(setup_ping(state, device)) - } else { - None - }; - Ok(Json(json!(Response { - id: dev_id, - boot: true, - uuid - }))) -} - #[utoipa::path( post, path = "/start/{id}", @@ -77,7 +28,7 @@ pub async fn post( Path(id): Path, payload: Option>, ) -> Result, Error> { - send_wol(state, &id, payload).await + send_wol(state, &id, payload) } #[utoipa::path( @@ -95,26 +46,16 @@ pub async fn get( State(state): State>, Path(id): Path, ) -> Result, Error> { - send_wol(state, &id, None).await + send_wol(state, &id, None) } -async fn send_wol( +fn send_wol( state: Arc, id: &str, payload: Option>, ) -> Result, Error> { - info!("Start request for {id}"); - let device = sqlx::query_as!( - Device, - r#" - SELECT id, mac, broadcast_addr, ip, times - FROM devices - WHERE id = $1; - "#, - id - ) - .fetch_one(&state.db) - .await?; + info!("start request for {id}"); + let device = Device::read(id)?; info!("starting {}", device.id); @@ -122,8 +63,8 @@ async fn send_wol( let _ = send_packet( bind_addr, - &device.broadcast_addr, - &create_buffer(&device.mac.to_string())?, + &device.broadcast_addr.to_string(), + &device.mac.bytes() )?; let dev_id = device.id.clone(); let uuid = if let Some(pl) = payload { @@ -163,6 +104,7 @@ fn setup_ping(state: Arc, device: Device) -> String { uuid_gen.clone(), PingValue { ip: device.ip, + eta: get_eta(device.clone().times), online: false, }, ); @@ -174,7 +116,6 @@ fn setup_ping(state: Arc, device: Device) -> String { device, uuid_gen, &state.ping_map, - &state.db, ) .await; }); @@ -182,11 +123,14 @@ fn setup_ping(state: Arc, device: Device) -> String { uuid_ret } -#[derive(Deserialize, ToSchema)] -#[deprecated] -pub struct PayloadOld { - id: String, - ping: Option, +fn get_eta(times: Option>) -> i64 { + let times = if let Some(times) = times { + times + } else { + vec![0] + }; + + times.iter().sum::() / i64::try_from(times.len()).unwrap() } #[derive(Deserialize, ToSchema)] diff --git a/src/routes/status.rs b/src/routes/status.rs index 0e25f7d..b38202b 100644 --- a/src/routes/status.rs +++ b/src/routes/status.rs @@ -3,7 +3,6 @@ use crate::AppState; use axum::extract::ws::{Message, WebSocket}; use axum::extract::{State, WebSocketUpgrade}; use axum::response::Response; -use sqlx::PgPool; use std::sync::Arc; use tracing::{debug, trace}; @@ -18,13 +17,13 @@ pub async fn websocket(mut socket: WebSocket, state: Arc) { trace!("Search for uuid: {}", uuid); - let eta = get_eta(&state.db).await; - let _ = socket - .send(Message::Text(format!("eta_{eta}_{uuid}"))) - .await; let device_exists = state.ping_map.contains_key(&uuid); if device_exists { + let eta = state.ping_map.get(&uuid).unwrap().eta; + let _ = socket + .send(Message::Text(format!("eta_{eta}_{uuid}"))) + .await; let _ = socket .send(receive_ping_broadcast(state.clone(), uuid).await) .await; @@ -62,18 +61,3 @@ async fn receive_ping_broadcast(state: Arc, uuid: String) -> Message { } } } - -async fn get_eta(db: &PgPool) -> i64 { - let query = sqlx::query!(r#"SELECT times FROM devices;"#) - .fetch_one(db) - .await - .unwrap(); - - let times = if let Some(times) = query.times { - times - } else { - vec![0] - }; - - times.iter().sum::() / i64::try_from(times.len()).unwrap() -} -- cgit v1.2.3 From 07740f3d985b4cc921b69cd45ec9191a2daecd67 Mon Sep 17 00:00:00 2001 From: FxQnLr Date: Wed, 10 Apr 2024 13:29:01 +0200 Subject: Closes #31. Renamed Payloads --- src/main.rs | 4 ++-- src/routes/device.rs | 10 +++++----- src/routes/start.rs | 8 ++++---- 3 files changed, 11 insertions(+), 11 deletions(-) (limited to 'src/routes') diff --git a/src/main.rs b/src/main.rs index 779385f..8af8c63 100644 --- a/src/main.rs +++ b/src/main.rs @@ -41,9 +41,9 @@ mod wol; ), components( schemas( - start::Payload, + start::SPayload, start::Response, - device::Payload, + device::DPayload, storage::DeviceSchema, ) ), diff --git a/src/routes/device.rs b/src/routes/device.rs index b6bd9d0..49361f2 100644 --- a/src/routes/device.rs +++ b/src/routes/device.rs @@ -32,7 +32,7 @@ pub async fn get(Path(id): Path) -> Result, Error> { } #[derive(Deserialize, ToSchema)] -pub struct Payload { +pub struct DPayload { id: String, mac: String, broadcast_addr: String, @@ -42,14 +42,14 @@ pub struct Payload { #[utoipa::path( put, path = "/device", - request_body = Payload, + request_body = DPayload, responses( (status = 200, description = "add device to storage", body = [DeviceSchema]) ), security((), ("api_key" = [])) )] pub async fn put( - Json(payload): Json, + Json(payload): Json, ) -> Result, Error> { info!( "add device {} ({}, {}, {})", @@ -73,14 +73,14 @@ pub async fn put( #[utoipa::path( post, path = "/device", - request_body = Payload, + request_body = DPayload, responses( (status = 200, description = "update device in storage", body = [DeviceSchema]) ), security((), ("api_key" = [])) )] pub async fn post( - Json(payload): Json, + Json(payload): Json, ) -> Result, Error> { info!( "edit device {} ({}, {}, {})", diff --git a/src/routes/start.rs b/src/routes/start.rs index 6907193..ae2b384 100644 --- a/src/routes/start.rs +++ b/src/routes/start.rs @@ -14,7 +14,7 @@ use uuid::Uuid; #[utoipa::path( post, path = "/start/{id}", - request_body = Option, + request_body = Option, responses( (status = 200, description = "start the device with the given id", body = [Response]) ), @@ -26,7 +26,7 @@ use uuid::Uuid; pub async fn post( State(state): State>, Path(id): Path, - payload: Option>, + payload: Option>, ) -> Result, Error> { send_wol(state, &id, payload) } @@ -52,7 +52,7 @@ pub async fn get( fn send_wol( state: Arc, id: &str, - payload: Option>, + payload: Option>, ) -> Result, Error> { info!("start request for {id}"); let device = Device::read(id)?; @@ -134,7 +134,7 @@ fn get_eta(times: Option>) -> i64 { } #[derive(Deserialize, ToSchema)] -pub struct Payload { +pub struct SPayload { ping: Option, } -- cgit v1.2.3