Update backend code to Rust Edition 2024
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
Pierre HUBERT 2025-03-28 19:25:15 +01:00
parent 658b10f5f8
commit 665a04c8a0
24 changed files with 915 additions and 479 deletions

File diff suppressed because it is too large Load Diff

View File

@ -1,31 +1,31 @@
[package] [package]
name = "central_backend" name = "central_backend"
version = "1.0.2" version = "1.0.2"
edition = "2021" edition = "2024"
[dependencies] [dependencies]
log = "0.4.22" log = "0.4.22"
env_logger = "0.11.5" env_logger = "0.11.7"
lazy_static = "1.5.0" lazy_static = "1.5.0"
dotenvy = "0.15.7" dotenvy = "0.15.7"
clap = { version = "4.5.20", features = ["derive", "env"] } clap = { version = "4.5.34", features = ["derive", "env"] }
anyhow = "1.0.89" anyhow = "1.0.89"
thiserror = "2.0.3" thiserror = "2.0.3"
openssl = { version = "0.10.66" } openssl = { version = "0.10.66" }
openssl-sys = "0.9.102" openssl-sys = "0.9.102"
libc = "0.2.159" libc = "0.2.159"
foreign-types-shared = "0.1.1" foreign-types-shared = "0.1.1"
asn1 = "0.20" asn1 = "0.21"
actix-web = { version = "4", features = ["openssl"] } actix-web = { version = "4", features = ["openssl"] }
futures = "0.3.31" futures = "0.3.31"
serde = { version = "1.0.215", features = ["derive"] } serde = { version = "1.0.215", features = ["derive"] }
reqwest = { version = "0.12.7", features = ["json"] } reqwest = { version = "0.12.7", features = ["json"] }
serde_json = "1.0.131" serde_json = "1.0.131"
rand = "0.8.5" rand = "0.9.0"
actix = "0.13.5" actix = "0.13.5"
actix-identity = "0.8.0" actix-identity = "0.8.0"
actix-session = { version = "0.10.1", features = ["cookie-session"] } actix-session = { version = "0.10.1", features = ["cookie-session"] }
actix-cors = "0.7.0" actix-cors = "0.7.1"
actix-multipart = { version = "0.7.2", features = ["derive"] } actix-multipart = { version = "0.7.2", features = ["derive"] }
actix-remote-ip = "0.1.0" actix-remote-ip = "0.1.0"
futures-util = "0.3.31" futures-util = "0.3.31"
@ -38,9 +38,9 @@ mime_guess = "2.0.5"
rust-embed = "8.5.0" rust-embed = "8.5.0"
jsonwebtoken = { version = "9.3.0", features = ["use_pem"] } jsonwebtoken = { version = "9.3.0", features = ["use_pem"] }
prettytable-rs = "0.10.0" prettytable-rs = "0.10.0"
chrono = "0.4.38" chrono = "0.4.40"
serde_yml = "0.0.12" serde_yml = "0.0.12"
bincode = "=2.0.0-rc.3" bincode = "2.0.1"
fs4 = { version = "0.12.0", features = ["sync"] } fs4 = { version = "0.13.1", features = ["sync"] }
zip = { version = "2.2.0", features = ["bzip2"] } zip = { version = "2.2.0", features = ["bzip2"] }
walkdir = "2.5.0" walkdir = "2.5.0"

View File

@ -13,10 +13,10 @@ use openssl::pkey::{PKey, Private};
use openssl::x509::extension::{ use openssl::x509::extension::{
BasicConstraints, ExtendedKeyUsage, KeyUsage, SubjectAlternativeName, SubjectKeyIdentifier, BasicConstraints, ExtendedKeyUsage, KeyUsage, SubjectAlternativeName, SubjectKeyIdentifier,
}; };
use openssl::x509::{CrlStatus, X509Crl, X509Name, X509NameBuilder, X509Req, X509}; use openssl::x509::{CrlStatus, X509, X509Crl, X509Name, X509NameBuilder, X509Req};
use openssl_sys::{ use openssl_sys::{
X509_CRL_add0_revoked, X509_CRL_new, X509_CRL_set1_lastUpdate, X509_CRL_set1_nextUpdate, X509_CRL_add0_revoked, X509_CRL_new, X509_CRL_set_issuer_name, X509_CRL_set_version,
X509_CRL_set_issuer_name, X509_CRL_set_version, X509_CRL_sign, X509_REVOKED_dup, X509_CRL_set1_lastUpdate, X509_CRL_set1_nextUpdate, X509_CRL_sign, X509_REVOKED_dup,
X509_REVOKED_new, X509_REVOKED_set_revocationDate, X509_REVOKED_set_serialNumber, X509_REVOKED_new, X509_REVOKED_set_revocationDate, X509_REVOKED_set_serialNumber,
}; };

View File

@ -325,9 +325,11 @@ mod tests {
..Default::default() ..Default::default()
}; };
dep_cycle_1.depends_on = vec![dep_cycle_3.id]; dep_cycle_1.depends_on = vec![dep_cycle_3.id];
assert!(dep_cycle_1 assert!(
.error(&[dep_cycle_2.clone(), dep_cycle_3.clone()]) dep_cycle_1
.is_some()); .error(&[dep_cycle_2.clone(), dep_cycle_3.clone()])
.is_some()
);
dep_cycle_1.depends_on = vec![]; dep_cycle_1.depends_on = vec![];
assert!(dep_cycle_1.error(&[dep_cycle_2, dep_cycle_3]).is_none()); assert!(dep_cycle_1.error(&[dep_cycle_2, dep_cycle_3]).is_none());
@ -351,21 +353,29 @@ mod tests {
..Default::default() ..Default::default()
}; };
assert!(target_relay assert!(
.error(&[other_dep.clone(), second_dep.clone()]) target_relay
.is_some()); .error(&[other_dep.clone(), second_dep.clone()])
assert!(target_relay .is_some()
.error(&[other_dep.clone(), second_dep.clone(), target_relay.clone()]) );
.is_some()); assert!(
target_relay
.error(&[other_dep.clone(), second_dep.clone(), target_relay.clone()])
.is_some()
);
second_dep.conflicts_with = vec![]; second_dep.conflicts_with = vec![];
assert!(target_relay assert!(
.error(&[other_dep.clone(), second_dep.clone()]) target_relay
.is_none()); .error(&[other_dep.clone(), second_dep.clone()])
assert!(target_relay .is_none()
.error(&[other_dep.clone(), second_dep.clone(), target_relay.clone()]) );
.is_none()); assert!(
target_relay
.error(&[other_dep.clone(), second_dep.clone(), target_relay.clone()])
.is_none()
);
// self loop // self loop
let mut self_loop = DeviceRelay { let mut self_loop = DeviceRelay {

View File

@ -4,7 +4,7 @@ use crate::devices::device::{
Device, DeviceGeneralInfo, DeviceId, DeviceInfo, DeviceRelay, DeviceRelayID, Device, DeviceGeneralInfo, DeviceId, DeviceInfo, DeviceRelay, DeviceRelayID,
}; };
use crate::utils::time_utils::time_secs; use crate::utils::time_utils::time_secs;
use openssl::x509::{X509Req, X509}; use openssl::x509::{X509, X509Req};
use std::collections::HashMap; use std::collections::HashMap;
#[derive(thiserror::Error, Debug)] #[derive(thiserror::Error, Debug)]

View File

@ -1,5 +1,5 @@
use crate::app_config::{AppConfig, ConsumptionBackend}; use crate::app_config::{AppConfig, ConsumptionBackend};
use rand::{thread_rng, Rng}; use rand::{Rng, rng};
use std::num::ParseIntError; use std::num::ParseIntError;
use std::path::Path; use std::path::Path;
@ -49,7 +49,7 @@ pub async fn get_curr_consumption() -> anyhow::Result<EnergyConsumption> {
match backend { match backend {
ConsumptionBackend::Constant { value } => Ok(*value), ConsumptionBackend::Constant { value } => Ok(*value),
ConsumptionBackend::Random { min, max } => Ok(thread_rng().gen_range(*min..*max)), ConsumptionBackend::Random { min, max } => Ok(rng().random_range(*min..*max)),
ConsumptionBackend::File { path } => { ConsumptionBackend::File { path } => {
let path = Path::new(path); let path = Path::new(path);

View File

@ -1,7 +1,7 @@
use std::collections::HashMap; use std::collections::HashMap;
use crate::app_config::AppConfig; use crate::app_config::AppConfig;
use prettytable::{row, Table}; use prettytable::{Table, row};
use crate::constants; use crate::constants;
use crate::devices::device::{Device, DeviceId, DeviceRelay, DeviceRelayID}; use crate::devices::device::{Device, DeviceId, DeviceRelay, DeviceRelayID};
@ -289,7 +289,11 @@ impl EnergyEngine {
continue; continue;
} }
log::info!("Forcefully turn on relay {} to catch up running constraints (only {}s this day)", r.name, total_runtime); log::info!(
"Forcefully turn on relay {} to catch up running constraints (only {}s this day)",
r.name,
total_runtime
);
new_relays_state.get_mut(&r.id).unwrap().on = true; new_relays_state.get_mut(&r.id).unwrap().on = true;
} }
} }

View File

@ -147,7 +147,7 @@ pub fn relay_total_runtime_adjusted(relay: &DeviceRelay) -> usize {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use crate::devices::device::DeviceRelayID; use crate::devices::device::DeviceRelayID;
use crate::energy::relay_state_history::{relay_total_runtime, RelayStateHistory}; use crate::energy::relay_state_history::{RelayStateHistory, relay_total_runtime};
#[test] #[test]
fn test_relay_state_history() { fn test_relay_state_history() {

View File

@ -5,7 +5,7 @@ use central_backend::energy::energy_actor::EnergyActor;
use central_backend::server::servers; use central_backend::server::servers;
use central_backend::utils::files_utils::create_directory_if_missing; use central_backend::utils::files_utils::create_directory_if_missing;
use futures::future; use futures::future;
use tokio_schedule::{every, Job}; use tokio_schedule::{Job, every};
#[actix_web::main] #[actix_web::main]
async fn main() -> std::io::Result<()> { async fn main() -> std::io::Result<()> {

View File

@ -1,5 +1,5 @@
use actix_identity::Identity; use actix_identity::Identity;
use std::future::{ready, Ready}; use std::future::{Ready, ready};
use std::rc::Rc; use std::rc::Rc;
use crate::app_config::AppConfig; use crate::app_config::AppConfig;
@ -7,8 +7,8 @@ use crate::constants;
use actix_web::body::EitherBody; use actix_web::body::EitherBody;
use actix_web::dev::Payload; use actix_web::dev::Payload;
use actix_web::{ use actix_web::{
dev::{forward_ready, Service, ServiceRequest, ServiceResponse, Transform},
Error, FromRequest, HttpResponse, Error, FromRequest, HttpResponse,
dev::{Service, ServiceRequest, ServiceResponse, Transform, forward_ready},
}; };
use futures_util::future::LocalBoxFuture; use futures_util::future::LocalBoxFuture;

View File

@ -1,6 +1,6 @@
use actix_web::HttpResponse;
use actix_web::body::BoxBody; use actix_web::body::BoxBody;
use actix_web::http::StatusCode; use actix_web::http::StatusCode;
use actix_web::HttpResponse;
use std::error::Error; use std::error::Error;
use std::fmt::{Display, Formatter}; use std::fmt::{Display, Formatter};
use std::io::ErrorKind; use std::io::ErrorKind;

View File

@ -1,9 +1,9 @@
use crate::logs::logs_manager; use crate::logs::logs_manager;
use crate::logs::severity::LogSeverity; use crate::logs::severity::LogSeverity;
use crate::server::WebEnergyActor;
use crate::server::custom_error::HttpResult; use crate::server::custom_error::HttpResult;
use crate::server::devices_api::jwt_parser::JWTRequest; use crate::server::devices_api::jwt_parser::JWTRequest;
use crate::server::WebEnergyActor; use actix_web::{HttpResponse, web};
use actix_web::{web, HttpResponse};
#[derive(Debug, serde::Deserialize)] #[derive(Debug, serde::Deserialize)]
pub struct LogRequest { pub struct LogRequest {

View File

@ -1,7 +1,7 @@
use crate::ota::ota_manager; use crate::ota::ota_manager;
use crate::ota::ota_update::OTAPlatform; use crate::ota::ota_update::OTAPlatform;
use crate::server::custom_error::HttpResult; use crate::server::custom_error::HttpResult;
use actix_web::{web, HttpResponse}; use actix_web::{HttpResponse, web};
#[derive(serde::Deserialize)] #[derive(serde::Deserialize)]
pub struct FirmwarePath { pub struct FirmwarePath {

View File

@ -4,10 +4,10 @@ use crate::energy::energy_actor;
use crate::energy::energy_actor::RelaySyncStatus; use crate::energy::energy_actor::RelaySyncStatus;
use crate::ota::ota_manager; use crate::ota::ota_manager;
use crate::ota::ota_update::OTAPlatform; use crate::ota::ota_update::OTAPlatform;
use crate::server::WebEnergyActor;
use crate::server::custom_error::HttpResult; use crate::server::custom_error::HttpResult;
use crate::server::devices_api::jwt_parser::JWTRequest; use crate::server::devices_api::jwt_parser::JWTRequest;
use crate::server::WebEnergyActor; use actix_web::{HttpResponse, web};
use actix_web::{web, HttpResponse};
use openssl::nid::Nid; use openssl::nid::Nid;
use openssl::x509::X509Req; use openssl::x509::X509Req;
use std::str::FromStr; use std::str::FromStr;

View File

@ -10,14 +10,14 @@ use crate::server::unsecure_server::*;
use crate::server::web_api::*; use crate::server::web_api::*;
use crate::server::web_app_controller; use crate::server::web_app_controller;
use actix_cors::Cors; use actix_cors::Cors;
use actix_identity::config::LogoutBehaviour;
use actix_identity::IdentityMiddleware; use actix_identity::IdentityMiddleware;
use actix_identity::config::LogoutBehaviour;
use actix_remote_ip::RemoteIPConfig; use actix_remote_ip::RemoteIPConfig;
use actix_session::storage::CookieSessionStore;
use actix_session::SessionMiddleware; use actix_session::SessionMiddleware;
use actix_session::storage::CookieSessionStore;
use actix_web::cookie::{Key, SameSite}; use actix_web::cookie::{Key, SameSite};
use actix_web::middleware::Logger; use actix_web::middleware::Logger;
use actix_web::{web, App, HttpServer}; use actix_web::{App, HttpServer, web};
use openssl::ssl::{SslAcceptor, SslMethod}; use openssl::ssl::{SslAcceptor, SslMethod};
use std::time::Duration; use std::time::Duration;

View File

@ -1,6 +1,6 @@
use crate::app_config::AppConfig; use crate::app_config::AppConfig;
use crate::server::custom_error::HttpResult; use crate::server::custom_error::HttpResult;
use actix_web::{web, HttpResponse}; use actix_web::{HttpResponse, web};
#[derive(serde::Deserialize)] #[derive(serde::Deserialize)]
pub struct ServeCRLPath { pub struct ServeCRLPath {

View File

@ -1,8 +1,8 @@
use crate::devices::device::DeviceRelayID; use crate::devices::device::DeviceRelayID;
use crate::energy::{energy_actor, relay_state_history}; use crate::energy::{energy_actor, relay_state_history};
use crate::server::custom_error::HttpResult;
use crate::server::WebEnergyActor; use crate::server::WebEnergyActor;
use actix_web::{web, HttpResponse}; use crate::server::custom_error::HttpResult;
use actix_web::{HttpResponse, web};
#[derive(serde::Deserialize)] #[derive(serde::Deserialize)]
pub struct LegacyStateRelay { pub struct LegacyStateRelay {

View File

@ -2,7 +2,7 @@ use crate::app_config::AppConfig;
use crate::server::custom_error::HttpResult; use crate::server::custom_error::HttpResult;
use actix_identity::Identity; use actix_identity::Identity;
use actix_remote_ip::RemoteIP; use actix_remote_ip::RemoteIP;
use actix_web::{web, HttpMessage, HttpRequest, HttpResponse}; use actix_web::{HttpMessage, HttpRequest, HttpResponse, web};
#[derive(serde::Deserialize)] #[derive(serde::Deserialize)]
pub struct AuthRequest { pub struct AuthRequest {
@ -17,11 +17,11 @@ pub async fn password_auth(
remote_ip: RemoteIP, remote_ip: RemoteIP,
) -> HttpResult { ) -> HttpResult {
if r.user != AppConfig::get().admin_username || r.password != AppConfig::get().admin_password { if r.user != AppConfig::get().admin_username || r.password != AppConfig::get().admin_password {
log::error!("Failed login attempt from {}!", remote_ip.0.to_string()); log::error!("Failed login attempt from {}!", remote_ip.0);
return Ok(HttpResponse::Unauthorized().json("Invalid credentials!")); return Ok(HttpResponse::Unauthorized().json("Invalid credentials!"));
} }
log::info!("Successful login attempt from {}!", remote_ip.0.to_string()); log::info!("Successful login attempt from {}!", remote_ip.0);
Identity::login(&request.extensions(), r.user.to_string())?; Identity::login(&request.extensions(), r.user.to_string())?;
Ok(HttpResponse::Ok().finish()) Ok(HttpResponse::Ok().finish())
} }

View File

@ -1,8 +1,8 @@
use crate::devices::device::{DeviceGeneralInfo, DeviceId}; use crate::devices::device::{DeviceGeneralInfo, DeviceId};
use crate::energy::energy_actor; use crate::energy::energy_actor;
use crate::server::custom_error::HttpResult;
use crate::server::WebEnergyActor; use crate::server::WebEnergyActor;
use actix_web::{web, HttpResponse}; use crate::server::custom_error::HttpResult;
use actix_web::{HttpResponse, web};
/// Get the list of pending (not accepted yet) devices /// Get the list of pending (not accepted yet) devices
pub async fn list_pending(actor: WebEnergyActor) -> HttpResult { pub async fn list_pending(actor: WebEnergyActor) -> HttpResult {

View File

@ -2,8 +2,8 @@ use crate::app_config::ConsumptionHistoryType;
use crate::energy::consumption::EnergyConsumption; use crate::energy::consumption::EnergyConsumption;
use crate::energy::consumption_history_file::ConsumptionHistoryFile; use crate::energy::consumption_history_file::ConsumptionHistoryFile;
use crate::energy::{consumption, energy_actor}; use crate::energy::{consumption, energy_actor};
use crate::server::custom_error::HttpResult;
use crate::server::WebEnergyActor; use crate::server::WebEnergyActor;
use crate::server::custom_error::HttpResult;
use crate::utils::time_utils::time_secs; use crate::utils::time_utils::time_secs;
use actix_web::HttpResponse; use actix_web::HttpResponse;

View File

@ -3,7 +3,7 @@ use crate::logs::logs_manager;
use crate::logs::severity::LogSeverity; use crate::logs::severity::LogSeverity;
use crate::server::custom_error::HttpResult; use crate::server::custom_error::HttpResult;
use crate::utils::time_utils::curr_day_number; use crate::utils::time_utils::curr_day_number;
use actix_web::{web, HttpResponse}; use actix_web::{HttpResponse, web};
#[derive(serde::Deserialize)] #[derive(serde::Deserialize)]
pub struct LogRequest { pub struct LogRequest {

View File

@ -3,11 +3,11 @@ use crate::devices::device::DeviceId;
use crate::energy::energy_actor; use crate::energy::energy_actor;
use crate::ota::ota_manager; use crate::ota::ota_manager;
use crate::ota::ota_update::OTAPlatform; use crate::ota::ota_update::OTAPlatform;
use crate::server::custom_error::HttpResult;
use crate::server::WebEnergyActor; use crate::server::WebEnergyActor;
use actix_multipart::form::tempfile::TempFile; use crate::server::custom_error::HttpResult;
use actix_multipart::form::MultipartForm; use actix_multipart::form::MultipartForm;
use actix_web::{web, HttpResponse}; use actix_multipart::form::tempfile::TempFile;
use actix_web::{HttpResponse, web};
pub async fn supported_platforms() -> HttpResult { pub async fn supported_platforms() -> HttpResult {
Ok(HttpResponse::Ok().json(OTAPlatform::supported_platforms())) Ok(HttpResponse::Ok().json(OTAPlatform::supported_platforms()))

View File

@ -1,8 +1,8 @@
use crate::devices::device::{DeviceId, DeviceRelay, DeviceRelayID}; use crate::devices::device::{DeviceId, DeviceRelay, DeviceRelayID};
use crate::energy::energy_actor; use crate::energy::energy_actor;
use crate::server::custom_error::HttpResult;
use crate::server::WebEnergyActor; use crate::server::WebEnergyActor;
use actix_web::{web, HttpResponse}; use crate::server::custom_error::HttpResult;
use actix_web::{HttpResponse, web};
/// Get the full list of relays /// Get the full list of relays
pub async fn get_list(actor: WebEnergyActor) -> HttpResult { pub async fn get_list(actor: WebEnergyActor) -> HttpResult {

View File

@ -19,7 +19,7 @@ mod serve_static_debug {
#[cfg(not(debug_assertions))] #[cfg(not(debug_assertions))]
mod serve_static_release { mod serve_static_release {
use actix_web::{web, HttpResponse, Responder}; use actix_web::{HttpResponse, Responder, web};
use rust_embed::RustEmbed; use rust_embed::RustEmbed;
#[derive(RustEmbed)] #[derive(RustEmbed)]