Add fmt options and move handlers

This commit is contained in:
Tobias Reisinger 2023-11-29 14:27:46 +01:00
parent 50bcac2a1b
commit fdca5b7277
Signed by: serguzim
GPG key ID: 13AD60C237A28DFE
28 changed files with 84 additions and 70 deletions

View file

@ -1,2 +1,9 @@
unstable_features = true
newline_style = "Unix" newline_style = "Unix"
hard_tabs = true hard_tabs = true
# unstable
group_imports = "StdExternalCrate"
reorder_impl_items = true
imports_granularity = "Module"
blank_lines_upper_bound = 2

BIN
Cargo.lock generated

Binary file not shown.

View file

@ -16,3 +16,6 @@ clean-db:
rm ./emgauwa-core.sqlite || true rm ./emgauwa-core.sqlite || true
rm ./emgauwa-controller.sqlite || true rm ./emgauwa-controller.sqlite || true
$(MAKE) sqlx $(MAKE) sqlx
fmt:
cargo +nightly fmt

View file

@ -1,21 +1,20 @@
use std::time::Duration;
use crate::relay_loop::run_relay_loop;
use crate::settings::Settings;
use emgauwa_lib::constants::WEBSOCKET_RETRY_TIMEOUT; use emgauwa_lib::constants::WEBSOCKET_RETRY_TIMEOUT;
use emgauwa_lib::db::{DbController, DbRelay}; use emgauwa_lib::db::{DbController, DbRelay};
use emgauwa_lib::handlers::v1::ws::controllers::ControllerWsAction;
use emgauwa_lib::models::{Controller, FromDbModel}; use emgauwa_lib::models::{Controller, FromDbModel};
use emgauwa_lib::types::ControllerUid; use emgauwa_lib::types::{ControllerUid, ControllerWsAction};
use emgauwa_lib::{db, utils}; use emgauwa_lib::{db, utils};
use futures::{SinkExt, StreamExt}; use futures::{SinkExt, StreamExt};
use sqlx::pool::PoolConnection; use sqlx::pool::PoolConnection;
use sqlx::Sqlite; use sqlx::Sqlite;
use tokio::time; use tokio::time;
use tokio_tungstenite::connect_async;
use tokio_tungstenite::tungstenite::protocol::Message;
use tokio_tungstenite::tungstenite::Error; use tokio_tungstenite::tungstenite::Error;
use tokio_tungstenite::{connect_async, tungstenite::protocol::Message};
use utils::init_logging; use utils::init_logging;
use crate::relay_loop::run_relay_loop;
use crate::settings::Settings;
mod driver; mod driver;
mod relay_loop; mod relay_loop;
mod settings; mod settings;
@ -123,7 +122,7 @@ async fn main() {
} }
} }
pub async fn handle_message(message_result: Result<Message, Error>) { async fn handle_message(message_result: Result<Message, Error>) {
match message_result { match message_result {
Ok(message) => { Ok(message) => {
if let Message::Text(msg_text) = message { if let Message::Text(msg_text) = message {

View file

@ -1,8 +1,10 @@
use crate::settings::Settings;
use chrono::Local;
use std::time::Duration; use std::time::Duration;
use chrono::Local;
use tokio::time; use tokio::time;
use crate::settings::Settings;
#[allow(unused_variables)] #[allow(unused_variables)]
pub async fn run_relay_loop(settings: Settings) { pub async fn run_relay_loop(settings: Settings) {
let default_duration = Duration::from_millis(1000); let default_duration = Duration::from_millis(1000);

View file

@ -21,5 +21,7 @@ serde = "1.0"
serde_json = "1.0" serde_json = "1.0"
serde_derive = "1.0" serde_derive = "1.0"
sqlx = { version = "0.7", features = ["sqlite", "runtime-tokio", "macros", "chrono"] }
futures = "0.3.29" futures = "0.3.29"
libc = "0.2" libc = "0.2"

View file

@ -1,9 +1,10 @@
use crate::db::errors::DatabaseError; use std::fmt::{Display, Formatter};
use actix_web::http::StatusCode; use actix_web::http::StatusCode;
use actix_web::HttpResponse; use actix_web::HttpResponse;
use emgauwa_lib::db::errors::DatabaseError;
use serde::ser::SerializeStruct; use serde::ser::SerializeStruct;
use serde::{Serialize, Serializer}; use serde::{Serialize, Serializer};
use std::fmt::{Display, Formatter};
#[derive(Debug)] #[derive(Debug)]
pub enum ApiError { pub enum ApiError {

View file

@ -1,12 +1,9 @@
use actix_web::{get, web, HttpResponse}; use actix_web::{get, web, HttpResponse};
use emgauwa_lib::db::DbController;
use emgauwa_lib::models::{convert_db_list, Controller};
use sqlx::{Pool, Sqlite}; use sqlx::{Pool, Sqlite};
use crate::db::DbController;
use crate::handlers::errors::ApiError; use crate::handlers::errors::ApiError;
use crate::models::{convert_db_list, Controller};
use crate::types::ConnectedControllersType;
#[get("/api/v1/controllers")] #[get("/api/v1/controllers")]
pub async fn index(pool: web::Data<Pool<Sqlite>>) -> Result<HttpResponse, ApiError> { pub async fn index(pool: web::Data<Pool<Sqlite>>) -> Result<HttpResponse, ApiError> {

View file

@ -1,12 +1,10 @@
use actix_web::{get, web, HttpResponse}; use actix_web::{get, web, HttpResponse};
use emgauwa_lib::db::DbRelay;
use emgauwa_lib::models::{convert_db_list, Relay};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use sqlx::{Pool, Sqlite}; use sqlx::{Pool, Sqlite};
use crate::db::DbRelay;
use crate::handlers::errors::ApiError; use crate::handlers::errors::ApiError;
use crate::models::{convert_db_list, Relay};
#[derive(Debug, Serialize, Deserialize)] #[derive(Debug, Serialize, Deserialize)]
pub struct RequestRelay { pub struct RequestRelay {

View file

@ -1,14 +1,13 @@
use actix_web::{delete, get, post, put, web, HttpResponse}; use actix_web::{delete, get, post, put, web, HttpResponse};
use emgauwa_lib::db::errors::DatabaseError;
use emgauwa_lib::db::{DbPeriods, DbSchedule, DbTag};
use emgauwa_lib::models::{convert_db_list, FromDbModel, Schedule};
use emgauwa_lib::types::ScheduleUid;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use sqlx::pool::PoolConnection; use sqlx::pool::PoolConnection;
use sqlx::{Pool, Sqlite}; use sqlx::{Pool, Sqlite};
use crate::db::errors::DatabaseError;
use crate::db::DbTag;
use crate::db::{DbPeriods, DbSchedule};
use crate::handlers::errors::ApiError; use crate::handlers::errors::ApiError;
use crate::models::{convert_db_list, FromDbModel, Schedule};
use crate::types::ScheduleUid;
#[derive(Debug, Serialize, Deserialize)] #[derive(Debug, Serialize, Deserialize)]
pub struct RequestSchedule { pub struct RequestSchedule {

View file

@ -1,22 +1,17 @@
use crate::constants::{HEARTBEAT_INTERVAL, HEARTBEAT_TIMEOUT}; use std::time::Instant;
use crate::db::errors::DatabaseError;
use crate::db::{DbController, DbRelay};
use crate::models::{Controller, FromDbModel};
use crate::types::{ConnectedControllersType, ControllerUid};
use actix::{Actor, ActorContext, AsyncContext, StreamHandler}; use actix::{Actor, ActorContext, AsyncContext, StreamHandler};
use actix_web_actors::ws; use actix_web_actors::ws;
use actix_web_actors::ws::ProtocolError; use actix_web_actors::ws::ProtocolError;
use serde_derive::{Deserialize, Serialize}; use emgauwa_lib::constants::{HEARTBEAT_INTERVAL, HEARTBEAT_TIMEOUT};
use emgauwa_lib::db::errors::DatabaseError;
use emgauwa_lib::db::{DbController, DbRelay};
use emgauwa_lib::models::{Controller, FromDbModel};
use emgauwa_lib::types::{ConnectedControllersType, ControllerUid, ControllerWsAction};
use sqlx::pool::PoolConnection; use sqlx::pool::PoolConnection;
use sqlx::{Pool, Sqlite}; use sqlx::{Pool, Sqlite};
use std::time::Instant;
use ws::Message; use ws::Message;
#[derive(Debug, Serialize, Deserialize)]
pub enum ControllerWsAction {
Register(Controller),
}
pub struct ControllerWs { pub struct ControllerWs {
pub pool: Pool<Sqlite>, pub pool: Pool<Sqlite>,
pub controller_uid: Option<ControllerUid>, pub controller_uid: Option<ControllerUid>,

View file

@ -1,10 +1,12 @@
use crate::handlers::errors::ApiError; use std::time::Instant;
use crate::handlers::v1::ws::controllers::ControllerWs;
use crate::types::ConnectedControllersType;
use actix_web::{get, web, HttpRequest, HttpResponse}; use actix_web::{get, web, HttpRequest, HttpResponse};
use actix_web_actors::ws; use actix_web_actors::ws;
use emgauwa_lib::types::ConnectedControllersType;
use sqlx::{Pool, Sqlite}; use sqlx::{Pool, Sqlite};
use std::time::Instant;
use crate::handlers::errors::ApiError;
use crate::handlers::v1::ws::controllers::ControllerWs;
pub mod controllers; pub mod controllers;

View file

@ -1,17 +1,17 @@
use actix_cors::Cors;
use std::collections::HashMap; use std::collections::HashMap;
use std::net::TcpListener; use std::net::TcpListener;
use std::str::FromStr;
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
use crate::utils::drop_privileges; use actix_cors::Cors;
use actix_web::middleware::TrailingSlash; use actix_web::middleware::TrailingSlash;
use actix_web::{middleware, web, App, HttpServer}; use actix_web::{middleware, web, App, HttpServer};
use emgauwa_lib::db::DbController; use emgauwa_lib::db::DbController;
use emgauwa_lib::handlers;
use emgauwa_lib::types::ConnectedControllersType; use emgauwa_lib::types::ConnectedControllersType;
use emgauwa_lib::utils::init_logging; use emgauwa_lib::utils::init_logging;
use crate::utils::drop_privileges;
mod handlers;
mod settings; mod settings;
mod utils; mod utils;

View file

@ -1,8 +1,8 @@
use crate::settings::Settings;
use log::log;
use std::ffi::CString; use std::ffi::CString;
use std::io::{Error, ErrorKind}; use std::io::{Error, ErrorKind};
use crate::settings::Settings;
// https://blog.lxsang.me/post/id/28.0 // https://blog.lxsang.me/post/id/28.0
pub fn drop_privileges(settings: &Settings) -> Result<(), Error> { pub fn drop_privileges(settings: &Settings) -> Result<(), Error> {
log::info!( log::info!(

View file

@ -1,6 +1,6 @@
use serde_derive::{Deserialize, Serialize};
use std::ops::DerefMut; use std::ops::DerefMut;
use serde_derive::{Deserialize, Serialize};
use sqlx::pool::PoolConnection; use sqlx::pool::PoolConnection;
use sqlx::Sqlite; use sqlx::Sqlite;

View file

@ -1,8 +1,9 @@
use std::str::FromStr;
use log::{info, trace}; use log::{info, trace};
use sqlx::migrate::Migrator; use sqlx::migrate::Migrator;
use sqlx::sqlite::{SqliteConnectOptions, SqlitePoolOptions}; use sqlx::sqlite::{SqliteConnectOptions, SqlitePoolOptions};
use sqlx::{Pool, Sqlite}; use sqlx::{Pool, Sqlite};
use std::str::FromStr;
use crate::db::errors::DatabaseError; use crate::db::errors::DatabaseError;
use crate::db::model_utils::Period; use crate::db::model_utils::Period;

View file

@ -1,4 +1,3 @@
use crate::db::DbPeriods;
use chrono::{NaiveTime, Timelike}; use chrono::{NaiveTime, Timelike};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use sqlx::database::HasArguments; use sqlx::database::HasArguments;
@ -7,6 +6,8 @@ use sqlx::error::BoxDynError;
use sqlx::sqlite::{SqliteTypeInfo, SqliteValueRef}; use sqlx::sqlite::{SqliteTypeInfo, SqliteValueRef};
use sqlx::{Decode, Encode, Sqlite, Type}; use sqlx::{Decode, Encode, Sqlite, Type};
use crate::db::DbPeriods;
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)] #[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
pub struct Period { pub struct Period {
#[serde(with = "period_format")] #[serde(with = "period_format")]

View file

@ -1,12 +1,11 @@
use serde_derive::{Deserialize, Serialize};
use std::ops::DerefMut; use std::ops::DerefMut;
use crate::db::DbController; use serde_derive::{Deserialize, Serialize};
use sqlx::pool::PoolConnection; use sqlx::pool::PoolConnection;
use sqlx::Sqlite; use sqlx::Sqlite;
use crate::db::errors::DatabaseError; use crate::db::errors::DatabaseError;
use crate::db::DbTag; use crate::db::{DbController, DbTag};
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DbRelay { pub struct DbRelay {

View file

@ -1,7 +1,7 @@
use serde_derive::{Deserialize, Serialize};
use std::borrow::Borrow; use std::borrow::Borrow;
use std::ops::DerefMut; use std::ops::DerefMut;
use serde_derive::{Deserialize, Serialize};
use sqlx::pool::PoolConnection; use sqlx::pool::PoolConnection;
use sqlx::Sqlite; use sqlx::Sqlite;

View file

@ -1,6 +1,6 @@
use serde_derive::Serialize;
use std::ops::DerefMut; use std::ops::DerefMut;
use serde_derive::Serialize;
use sqlx::pool::PoolConnection; use sqlx::pool::PoolConnection;
use sqlx::Sqlite; use sqlx::Sqlite;

View file

@ -1,6 +1,5 @@
pub mod constants; pub mod constants;
pub mod db; pub mod db;
pub mod handlers;
pub mod models; pub mod models;
pub mod types; pub mod types;
pub mod utils; pub mod utils;

View file

@ -1,11 +1,12 @@
use crate::db::errors::DatabaseError;
use crate::db::{DbController, DbRelay, DbSchedule};
use crate::types::ControllerUid;
use futures::executor; use futures::executor;
use serde_derive::{Deserialize, Serialize}; use serde_derive::{Deserialize, Serialize};
use sqlx::pool::PoolConnection; use sqlx::pool::PoolConnection;
use sqlx::Sqlite; use sqlx::Sqlite;
use crate::db::errors::DatabaseError;
use crate::db::{DbController, DbRelay, DbSchedule};
use crate::types::ControllerUid;
pub trait FromDbModel { pub trait FromDbModel {
type DbModel: Clone; type DbModel: Clone;

View file

@ -1,10 +1,11 @@
use std::str::FromStr;
use serde::{Deserialize, Deserializer, Serialize, Serializer}; use serde::{Deserialize, Deserializer, Serialize, Serializer};
use sqlx::database::HasArguments; use sqlx::database::HasArguments;
use sqlx::encode::IsNull; use sqlx::encode::IsNull;
use sqlx::error::BoxDynError; use sqlx::error::BoxDynError;
use sqlx::sqlite::{SqliteTypeInfo, SqliteValueRef}; use sqlx::sqlite::{SqliteTypeInfo, SqliteValueRef};
use sqlx::{Decode, Encode, Sqlite, Type}; use sqlx::{Decode, Encode, Sqlite, Type};
use std::str::FromStr;
use uuid::Uuid; use uuid::Uuid;
#[derive(Clone, Debug, Eq, PartialEq, Hash)] #[derive(Clone, Debug, Eq, PartialEq, Hash)]

View file

@ -1,12 +1,18 @@
mod controller_uid; mod controller_uid;
mod schedule_uid; mod schedule_uid;
use crate::models::Controller;
pub use controller_uid::ControllerUid;
pub use schedule_uid::ScheduleUid;
use std::collections::HashMap; use std::collections::HashMap;
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
pub use controller_uid::ControllerUid;
pub use schedule_uid::ScheduleUid;
use serde_derive::{Deserialize, Serialize};
use crate::models::Controller;
pub type ConnectedControllersType = Arc<Mutex<HashMap<ControllerUid, Controller>>>; pub type ConnectedControllersType = Arc<Mutex<HashMap<ControllerUid, Controller>>>;
#[derive(Debug, Serialize, Deserialize)]
pub enum ControllerWsAction {
Register(Controller),
}

View file

@ -19,11 +19,11 @@ pub enum ScheduleUid {
impl ScheduleUid { impl ScheduleUid {
const OFF_STR: &'static str = "off"; const OFF_STR: &'static str = "off";
const ON_STR: &'static str = "on";
const OFF_U8: u8 = 0;
const ON_U8: u8 = 1;
const OFF_U128: u128 = 0; const OFF_U128: u128 = 0;
const OFF_U8: u8 = 0;
const ON_STR: &'static str = "on";
const ON_U128: u128 = 1; const ON_U128: u128 = 1;
const ON_U8: u8 = 1;
} }
impl Default for ScheduleUid { impl Default for ScheduleUid {

View file

@ -1,6 +1,7 @@
use std::str::FromStr;
use log::LevelFilter; use log::LevelFilter;
use simple_logger::SimpleLogger; use simple_logger::SimpleLogger;
use std::str::FromStr;
pub fn load_settings<T>(config_name: &str, env_prefix: &str) -> T pub fn load_settings<T>(config_name: &str, env_prefix: &str) -> T
where where