Add notifier to break relay loop

This commit is contained in:
Tobias Reisinger 2023-12-07 04:30:33 +01:00
parent 83c1f033d5
commit 8785186dfa
Signed by: serguzim
GPG key ID: 13AD60C237A28DFE
12 changed files with 124 additions and 45 deletions

View file

@ -1,8 +1,11 @@
use std::sync::Arc;
use actix::{Actor, Context, Handler, Message};
use emgauwa_lib::errors::EmgauwaError;
use emgauwa_lib::models::Controller;
use futures::executor::block_on;
use sqlx::{Pool, Sqlite};
use tokio::sync::Notify;
#[derive(Message)]
#[rtype(result = "Result<(), EmgauwaError>")]
@ -12,14 +15,27 @@ pub struct Reload {}
#[rtype(result = "Controller")]
pub struct GetThis {}
#[derive(Message)]
#[rtype(result = "Arc<Notify>")]
pub struct GetNotifier {}
pub struct AppState {
pub pool: Pool<Sqlite>,
pub this: Controller,
pub notifier: Arc<Notify>,
}
impl AppState {
pub fn new(pool: Pool<Sqlite>, this: Controller) -> AppState {
AppState { pool, this }
AppState {
pool,
this,
notifier: Arc::new(Notify::new()),
}
}
pub fn notify_change(&self) {
self.notifier.notify_one();
}
}
@ -35,6 +51,8 @@ impl Handler<Reload> for AppState {
self.this.reload(&mut pool_conn)?;
self.notify_change();
Ok(())
}
}
@ -46,3 +64,11 @@ impl Handler<GetThis> for AppState {
self.this.clone()
}
}
impl Handler<GetNotifier> for AppState {
type Result = Arc<Notify>;
fn handle(&mut self, _msg: GetNotifier, _ctx: &mut Self::Context) -> Self::Result {
Arc::clone(&self.notifier)
}
}

View file

@ -1,5 +1,4 @@
use actix::Actor;
use emgauwa_lib::constants::WEBSOCKET_RETRY_TIMEOUT;
use emgauwa_lib::db;
use emgauwa_lib::db::{DbController, DbJunctionRelaySchedule, DbRelay, DbSchedule};
use emgauwa_lib::errors::EmgauwaError;
@ -8,11 +7,10 @@ use emgauwa_lib::types::ControllerUid;
use emgauwa_lib::utils::init_logging;
use sqlx::pool::PoolConnection;
use sqlx::Sqlite;
use tokio::time;
use crate::relay_loop::run_relay_loop;
use crate::relay_loop::run_relays_loop;
use crate::settings::Settings;
use crate::ws::run_websocket;
use crate::ws::run_ws_loop;
mod app_state;
mod driver;
@ -110,18 +108,11 @@ async fn main() -> Result<(), std::io::Error> {
settings.core.host, settings.core.port
);
tokio::spawn(run_relay_loop(settings));
loop {
let run_result = run_websocket(pool.clone(), &app_state, &url).await;
if let Err(err) = run_result {
log::error!("Error running websocket: {}", err);
}
log::info!(
"Retrying to connect in {} seconds...",
WEBSOCKET_RETRY_TIMEOUT.as_secs()
);
time::sleep(WEBSOCKET_RETRY_TIMEOUT).await;
tokio::select! {
_ = run_relays_loop(app_state.clone()) => {},
_ = run_ws_loop(pool.clone(), app_state.clone(), url) => {},
}
Ok(())
}

View file

@ -1,17 +1,42 @@
use std::time::Duration;
use actix::Addr;
use chrono::Local;
use emgauwa_lib::constants::RELAYS_RETRY_TIMEOUT;
use emgauwa_lib::errors::EmgauwaError;
use futures::pin_mut;
use tokio::time;
use tokio::time::Instant;
use tokio::time::timeout;
use utils::app_state_get_notifier;
use crate::settings::Settings;
use crate::app_state::AppState;
use crate::utils;
#[allow(unused_variables)]
pub async fn run_relay_loop(settings: Settings) {
let default_duration = Duration::from_millis(10000);
pub async fn run_relays_loop(app_state: Addr<AppState>) {
log::debug!("Spawned relays loop");
loop {
let next_timestamp = Instant::now() + default_duration;
time::sleep_until(next_timestamp).await;
log::debug!("Relay loop: {}", Local::now().naive_local().time())
let run_result = run_relays(&app_state).await;
if let Err(err) = run_result {
log::error!("Error running relays: {}", err);
}
time::sleep(RELAYS_RETRY_TIMEOUT).await;
}
}
async fn run_relays(app_state: &Addr<AppState>) -> Result<(), EmgauwaError> {
let default_duration = Duration::new(10, 0);
let notifier = &*app_state_get_notifier(app_state).await?;
loop {
let notifier_future = notifier.notified();
pin_mut!(notifier_future);
let timeout_result = timeout(default_duration, &mut notifier_future).await;
let changed = timeout_result.is_ok();
log::debug!(
"Relay loop at {} (changed: {})",
Local::now().naive_local().time(),
changed
);
}
}

View file

@ -1,9 +1,25 @@
use std::sync::Arc;
use actix::Addr;
use emgauwa_lib::errors::EmgauwaError;
use emgauwa_lib::models::Controller;
use tokio::sync::Notify;
use crate::app_state::{AppState, GetThis};
use crate::app_state;
use crate::app_state::AppState;
pub async fn get_this(app_state: &Addr<AppState>) -> Result<Controller, EmgauwaError> {
app_state.send(GetThis {}).await.map_err(EmgauwaError::from)
pub async fn app_state_get_this(app_state: &Addr<AppState>) -> Result<Controller, EmgauwaError> {
app_state
.send(app_state::GetThis {})
.await
.map_err(EmgauwaError::from)
}
pub async fn app_state_get_notifier(
app_state: &Addr<AppState>,
) -> Result<Arc<Notify>, EmgauwaError> {
app_state
.send(app_state::GetNotifier {})
.await
.map_err(EmgauwaError::from)
}

View file

@ -1,4 +1,5 @@
use actix::Addr;
use emgauwa_lib::constants::WEBSOCKET_RETRY_TIMEOUT;
use emgauwa_lib::db::DbController;
use emgauwa_lib::errors::{DatabaseError, EmgauwaError};
use emgauwa_lib::models::Controller;
@ -6,25 +7,44 @@ use emgauwa_lib::types::ControllerWsAction;
use futures::{SinkExt, StreamExt};
use sqlx::pool::PoolConnection;
use sqlx::{Pool, Sqlite};
use tokio::time;
use tokio_tungstenite::tungstenite::Message;
use tokio_tungstenite::{connect_async, tungstenite};
use crate::app_state;
use crate::app_state::AppState;
use crate::utils::get_this;
use crate::utils::app_state_get_this;
pub async fn run_websocket(
pub async fn run_ws_loop(pool: Pool<Sqlite>, app_state: Addr<AppState>, url: String) {
log::debug!("Spawned ws loop");
loop {
let run_result = run_websocket(pool.clone(), &app_state, &url).await;
if let Err(err) = run_result {
log::error!("Error running websocket: {}", err);
}
log::info!(
"Retrying to connect in {} seconds...",
WEBSOCKET_RETRY_TIMEOUT.as_secs()
);
time::sleep(WEBSOCKET_RETRY_TIMEOUT).await;
}
}
async fn run_websocket(
pool: Pool<Sqlite>,
app_state: &Addr<AppState>,
url: &str,
) -> Result<(), EmgauwaError> {
log::debug!("Trying to connect to {}", url);
match connect_async(url).await {
Ok(connection) => {
log::debug!("Websocket connected");
let (ws_stream, _) = connection;
let (mut write, read) = ws_stream.split();
let ws_action = ControllerWsAction::Register(get_this(app_state).await?);
let ws_action = ControllerWsAction::Register(app_state_get_this(app_state).await?);
let ws_action_json = serde_json::to_string(&ws_action)?;
if let Err(err) = write.send(Message::text(ws_action_json)).await {
@ -98,7 +118,7 @@ pub async fn handle_controller(
app_state: &Addr<AppState>,
controller: Controller,
) -> Result<(), EmgauwaError> {
let this = get_this(app_state).await?;
let this = app_state_get_this(app_state).await?;
if controller.c.uid != this.c.uid {
return Err(EmgauwaError::Other(String::from(
"Controller UID mismatch during update",