2023-12-07 03:30:33 +00:00
|
|
|
use std::sync::Arc;
|
|
|
|
|
2023-12-07 00:32:20 +00:00
|
|
|
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};
|
2023-12-07 03:30:33 +00:00
|
|
|
use tokio::sync::Notify;
|
2023-12-07 00:32:20 +00:00
|
|
|
|
|
|
|
#[derive(Message)]
|
|
|
|
#[rtype(result = "Result<(), EmgauwaError>")]
|
|
|
|
pub struct Reload {}
|
|
|
|
|
|
|
|
#[derive(Message)]
|
|
|
|
#[rtype(result = "Controller")]
|
|
|
|
pub struct GetThis {}
|
|
|
|
|
2023-12-07 03:30:33 +00:00
|
|
|
#[derive(Message)]
|
|
|
|
#[rtype(result = "Arc<Notify>")]
|
|
|
|
pub struct GetNotifier {}
|
|
|
|
|
2023-12-07 00:32:20 +00:00
|
|
|
pub struct AppState {
|
|
|
|
pub pool: Pool<Sqlite>,
|
|
|
|
pub this: Controller,
|
2023-12-07 03:30:33 +00:00
|
|
|
pub notifier: Arc<Notify>,
|
2023-12-07 00:32:20 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl AppState {
|
|
|
|
pub fn new(pool: Pool<Sqlite>, this: Controller) -> AppState {
|
2023-12-07 03:30:33 +00:00
|
|
|
AppState {
|
|
|
|
pool,
|
|
|
|
this,
|
|
|
|
notifier: Arc::new(Notify::new()),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn notify_change(&self) {
|
|
|
|
self.notifier.notify_one();
|
2023-12-07 00:32:20 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Actor for AppState {
|
|
|
|
type Context = Context<Self>;
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Handler<Reload> for AppState {
|
|
|
|
type Result = Result<(), EmgauwaError>;
|
|
|
|
|
|
|
|
fn handle(&mut self, _msg: Reload, _ctx: &mut Self::Context) -> Self::Result {
|
|
|
|
let mut pool_conn = block_on(self.pool.acquire())?;
|
|
|
|
|
|
|
|
self.this.reload(&mut pool_conn)?;
|
|
|
|
|
2023-12-07 03:30:33 +00:00
|
|
|
self.notify_change();
|
|
|
|
|
2023-12-07 00:32:20 +00:00
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Handler<GetThis> for AppState {
|
|
|
|
type Result = Controller;
|
|
|
|
|
|
|
|
fn handle(&mut self, _msg: GetThis, _ctx: &mut Self::Context) -> Self::Result {
|
|
|
|
self.this.clone()
|
|
|
|
}
|
|
|
|
}
|
2023-12-07 03:30:33 +00:00
|
|
|
|
|
|
|
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)
|
|
|
|
}
|
|
|
|
}
|