style: format with clippy
This commit is contained in:
parent
04a21c79f6
commit
b234914d8b
10 changed files with 38 additions and 52 deletions
|
@ -1,20 +1,19 @@
|
|||
|
||||
use nom::error::VerboseError;
|
||||
use std::fmt::{Debug};
|
||||
use std::fmt::Debug;
|
||||
use std::num::ParseFloatError;
|
||||
use thiserror::Error as ThisError;
|
||||
|
||||
#[allow(dead_code)]
|
||||
#[derive(Debug, ThisError)]
|
||||
pub enum Error<I: Debug> {
|
||||
#[error("Nom error: {0}")]
|
||||
NomError(#[from] nom::Err<VerboseError<I>>),
|
||||
Nom(#[from] nom::Err<VerboseError<I>>),
|
||||
|
||||
#[error("Failed to parse a timestamp")]
|
||||
TimestampParseError(ParseFloatError),
|
||||
|
||||
#[error("Unknown unit")]
|
||||
UnknownUnit(I),
|
||||
|
||||
#[error("Failed to parse a number")]
|
||||
DecimalParseError(#[from] rust_decimal::Error),
|
||||
DecimalParsing(#[from] rust_decimal::Error),
|
||||
}
|
||||
|
|
|
@ -19,7 +19,7 @@ use serde::{Deserialize, Serialize};
|
|||
use serde_with::serde_as;
|
||||
use ufmt::uwrite;
|
||||
|
||||
use std::collections::{BTreeMap, HashMap, HashSet};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::hash::{Hash, Hasher};
|
||||
|
||||
/// Данные с одного датчика.
|
||||
|
@ -118,8 +118,8 @@ impl NMDeviceDataPacket {
|
|||
|
||||
let device_exists: Option<bool> = redis.hget(key.as_str(), "exists").await?;
|
||||
|
||||
if !device_exists.is_some_and(|v| v == true) {
|
||||
return Err(AppError::DeviceNotFound(hex::encode(&self.mac)));
|
||||
if !device_exists.is_some_and(|v| v) {
|
||||
return Err(AppError::DeviceNotFound(hex::encode(self.mac)));
|
||||
}
|
||||
|
||||
// devices_{device_id}_{tai_timestamp}_{sensor_id}
|
||||
|
@ -150,7 +150,7 @@ impl NMDeviceDataPacket {
|
|||
}
|
||||
}
|
||||
|
||||
return Ok(());
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -165,6 +165,6 @@ impl NMJsonPacket {
|
|||
device.save_to_db(redis).await?;
|
||||
}
|
||||
|
||||
return Ok(());
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
|
|
@ -6,7 +6,6 @@ use nom::character::complete::hex_digit1;
|
|||
use std::str::FromStr;
|
||||
|
||||
use crate::ingest_protocol::error::Error;
|
||||
use crate::ingest_protocol::error::Error::TimestampParseError;
|
||||
use crate::ingest_protocol::{NMDeviceDataPacket, SensorValue};
|
||||
use nom::combinator::{map_parser, opt};
|
||||
use nom::error::context;
|
||||
|
@ -85,7 +84,7 @@ pub fn parse_packet_body<'a>(
|
|||
|
||||
let sensor_time = match sensor_time {
|
||||
Some(v) => Some(Epoch::from_unix_seconds(
|
||||
v.parse().map_err(TimestampParseError)?,
|
||||
v.parse().map_err(Error::TimestampParseError)?,
|
||||
)),
|
||||
None => None,
|
||||
};
|
||||
|
|
|
@ -43,14 +43,14 @@ impl<'de> Deserialize<'de> for EpochUTC {
|
|||
where
|
||||
E: de::Error,
|
||||
{
|
||||
return Ok(Epoch::from_unix_seconds(v as f64).into());
|
||||
Ok(Epoch::from_unix_seconds(v as f64).into())
|
||||
}
|
||||
|
||||
fn visit_f64<E>(self, v: f64) -> Result<Self::Value, E>
|
||||
where
|
||||
E: de::Error,
|
||||
{
|
||||
return Ok(Epoch::from_unix_seconds(v).into());
|
||||
Ok(Epoch::from_unix_seconds(v).into())
|
||||
}
|
||||
|
||||
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
|
||||
|
@ -65,9 +65,9 @@ impl<'de> Deserialize<'de> for EpochUTC {
|
|||
) as f64)
|
||||
.into());
|
||||
}
|
||||
return Ok(
|
||||
Ok(
|
||||
Epoch::from_unix_seconds(value.parse().map_err(de::Error::custom)?).into(),
|
||||
);
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -1,7 +1,6 @@
|
|||
//! Глобальный модуль для вспомогательных типов и утилит.
|
||||
//!
|
||||
|
||||
|
||||
mod hifitime_serde;
|
||||
|
||||
use phf::phf_map;
|
||||
|
@ -10,11 +9,11 @@ use std::borrow::Cow;
|
|||
|
||||
pub use hifitime_serde::EpochUTC;
|
||||
|
||||
|
||||
/// Поддерживаемые типы.
|
||||
///
|
||||
/// TODO: Решить необходимо ли к данным прикреплять единицы измерения.
|
||||
/// TODO: Сейчас вообще сомнительно оставлять ли это или нет.
|
||||
#[allow(dead_code)]
|
||||
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
|
||||
#[repr(u64)]
|
||||
pub enum SupportedUnit {
|
||||
|
@ -35,8 +34,8 @@ pub enum SupportedUnit {
|
|||
|
||||
impl Serialize for SupportedUnit {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
serializer.serialize_str(match self {
|
||||
SupportedUnit::Celsius => "C",
|
||||
|
@ -58,8 +57,8 @@ impl Serialize for SupportedUnit {
|
|||
|
||||
impl<'de> Deserialize<'de> for SupportedUnit {
|
||||
fn deserialize<'a, D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
let color_str = Cow::<'a, str>::deserialize(deserializer)?;
|
||||
match STR_TO_UNITS.get(color_str.as_ref()) {
|
||||
|
|
|
@ -13,7 +13,6 @@ use crate::web_server::old_device_sensor_api::qs_parser::QSParserError;
|
|||
use rust_decimal::Decimal;
|
||||
use serde_json::json;
|
||||
|
||||
|
||||
/// Главный объект ошибки [std::error::Error] для всего Web API.
|
||||
///
|
||||
/// В целом, все Result у Web сервера должны использовать этот Error.
|
||||
|
@ -50,7 +49,7 @@ pub enum AppError {
|
|||
},
|
||||
|
||||
#[display(fmt = "IDK")]
|
||||
DeviceNotFound(String)
|
||||
DeviceNotFound(String),
|
||||
}
|
||||
|
||||
impl web::error::WebResponseError for AppError {
|
||||
|
@ -64,7 +63,7 @@ impl web::error::WebResponseError for AppError {
|
|||
AppError::ApiKeyInvalid { .. } => StatusCode::BAD_REQUEST,
|
||||
AppError::UnknownBody { .. } => StatusCode::BAD_REQUEST,
|
||||
AppError::QSError(..) => StatusCode::BAD_REQUEST,
|
||||
AppError::DeviceNotFound(..) => StatusCode::BAD_REQUEST
|
||||
AppError::DeviceNotFound(..) => StatusCode::BAD_REQUEST,
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -118,16 +117,15 @@ impl web::error::WebResponseError for AppError {
|
|||
AppError::ApiKeyInvalid { reason } => {
|
||||
insert_header!(headers, "X-Error-Description", *reason);
|
||||
}
|
||||
AppError::QSError(err) => match err {
|
||||
QSParserError::ParsingError(desc) => {
|
||||
AppError::QSError(err) => {
|
||||
if let QSParserError::Parsing(desc) = err {
|
||||
insert_header!(
|
||||
headers,
|
||||
"X-Error-Description",
|
||||
desc.escape_default().to_string()
|
||||
);
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
}
|
||||
_ => {}
|
||||
};
|
||||
|
||||
|
|
|
@ -5,11 +5,9 @@
|
|||
//!
|
||||
//! TODO: Начать работу над TCP/UDP и MQTT сервером
|
||||
|
||||
use old_app_api::old_api_handler;
|
||||
use fred::bytes_utils::Str;
|
||||
use fred::prelude::*;
|
||||
|
||||
|
||||
use old_app_api::old_api_handler;
|
||||
|
||||
pub mod app_error;
|
||||
pub mod old_app_api;
|
||||
|
@ -32,7 +30,7 @@ pub async fn server_main() {
|
|||
let client = RedisClient::new(config, Some(perf), Some(policy));
|
||||
|
||||
// connect to the server, returning a handle to the task that drives the connection
|
||||
let _ = client.connect();
|
||||
client.connect().await.unwrap().unwrap();
|
||||
client.wait_for_connect().await.unwrap();
|
||||
|
||||
let asd: Str = client.ping().await.unwrap();
|
||||
|
|
|
@ -33,10 +33,7 @@ pub async fn old_api_handler(
|
|||
let mandatory_params: MandatoryParams<'_> = serde_json::from_slice(body_bytes)?; // TODO: Simd-JSON
|
||||
|
||||
// Ignore clippy singlematch
|
||||
match mandatory_params.cmd.as_ref() {
|
||||
"version" => return version((), &app_state).await,
|
||||
_ => {}
|
||||
}
|
||||
if mandatory_params.cmd.as_ref() == "version" { return version((), &app_state).await }
|
||||
|
||||
is_api_key_valid(&app_state.redis_client, mandatory_params.api_key.as_ref()).await?;
|
||||
|
||||
|
|
|
@ -4,19 +4,14 @@ pub mod qs_parser;
|
|||
|
||||
use crate::ingest_protocol::{NMDeviceDataPacket, NMJsonPacket};
|
||||
use crate::web_server::app_error::AppError;
|
||||
use fred::bytes_utils::Str;
|
||||
|
||||
use fred::prelude::*;
|
||||
use hifitime::Epoch;
|
||||
use ntex::http::{HttpMessage, StatusCode};
|
||||
use ntex::util::Bytes;
|
||||
use ntex::web::types::State;
|
||||
use ntex::{http, web};
|
||||
use qs_parser::QSParserError;
|
||||
use thiserror::Error;
|
||||
use ufmt::uwrite;
|
||||
|
||||
use futures_util::stream::StreamExt;
|
||||
|
||||
use super::NMAppState;
|
||||
|
||||
|
|
|
@ -11,18 +11,19 @@ use std::sync::Arc;
|
|||
use thiserror::Error;
|
||||
|
||||
/// В иделае было бы хорошо сделать всё как у [serde_json::Error], но это слишком большая морока
|
||||
#[allow(dead_code)]
|
||||
#[derive(Error, Clone, Debug)]
|
||||
pub enum QSParserError {
|
||||
#[error("asd")]
|
||||
SerdeQSError(#[from] Arc<serde_qs::Error>),
|
||||
SerdeQS(#[from] Arc<serde_qs::Error>),
|
||||
#[error("asd")]
|
||||
ParsingError(String),
|
||||
Parsing(String),
|
||||
|
||||
#[error("asd")]
|
||||
FloatParseError(#[from] ParseFloatError),
|
||||
FloatParse(#[from] ParseFloatError),
|
||||
|
||||
#[error("failed to parse into decimal")]
|
||||
DecimalParseError(#[from] rust_decimal::Error),
|
||||
DecimalParse(#[from] rust_decimal::Error),
|
||||
|
||||
#[error("asd")]
|
||||
NoMAC,
|
||||
|
@ -30,13 +31,13 @@ pub enum QSParserError {
|
|||
|
||||
impl From<Error<&str>> for QSParserError {
|
||||
fn from(value: Error<&str>) -> Self {
|
||||
QSParserError::ParsingError(format!("{:?}", value))
|
||||
QSParserError::Parsing(format!("{:?}", value))
|
||||
}
|
||||
}
|
||||
|
||||
impl From<serde_qs::Error> for QSParserError {
|
||||
fn from(value: serde_qs::Error) -> Self {
|
||||
QSParserError::SerdeQSError(Arc::new(value))
|
||||
QSParserError::SerdeQS(Arc::new(value))
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -68,22 +69,22 @@ pub fn parse_decimal_if_exists(
|
|||
parsed: &mut HashMap<String, String>,
|
||||
key: &str,
|
||||
) -> Result<Option<Decimal>, QSParserError> {
|
||||
return if let Some(unwrapped_value) = parsed.remove(key) {
|
||||
if let Some(unwrapped_value) = parsed.remove(key) {
|
||||
Ok(Some(Decimal::from_str(unwrapped_value.as_str())?))
|
||||
} else {
|
||||
Ok(None)
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse_epoch_if_exists(
|
||||
parsed: &mut HashMap<String, String>,
|
||||
key: &str,
|
||||
) -> Result<Option<Epoch>, QSParserError> {
|
||||
return if let Some(unwrapped_value) = parsed.remove(key) {
|
||||
if let Some(unwrapped_value) = parsed.remove(key) {
|
||||
Ok(Some(Epoch::from_unix_seconds(unwrapped_value.parse()?)))
|
||||
} else {
|
||||
Ok(None)
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn parse_nm_qs_format(input: &str) -> Result<NMDeviceDataPacket, QSParserError> {
|
||||
|
|
Loading…
Reference in a new issue