How to Handle Async Mutex in Actix Web Middleware for Conditional Redirects?

31 views Asked by At

I'm seeking assistance with implementing middleware in Actix Web. I'm facing a challenge where I need to access shared state through an asynchronous mutex within a non-async function. Specifically, I'm trying to maintain the logic for redirecting and continuing the execution of middleware based on the state of a database connection.

I use tokio::sync::Mutex; and would like to use them further for productivity

Here is the part of the code I'm struggling with:

struct StateDb{
    azs_db: Mutex<AzsDb>,
    sqlite: SqlitePool,
}

pub struct AzsDb{
    pub mysql: Option<MySqlPool>,
    pub mysql_info_success: MysqlInfo,
    pub mysql_info_last: MysqlInfo,
    is_connecting: bool,
    pub logs_error: String,
}

fn call(&self, req: ServiceRequest) -> Self::Future {
    println!("Hi from start. You requested: {}", req.path());
    let state = req.app_data::<web::Data<StateDb>>().unwrap();
    let azs_db = state.azs_db.lock().await;
    if azs_db.mysql.is_none() {
        let response = HttpResponse::Found()
            .insert_header((http::header::LOCATION, "/settings/dbproperties"))
            .finish().map_into_right_body();
        Box::pin(async move {
            Ok(ServiceResponse::new(req.into_parts().0, response))
        })
    } else {
        let fut = self.service.call(req);
        
        Box::pin(async move {
            fut.await.map(ServiceResponse::map_into_left_body)
        })
    }
}

The issue I encounter is related to managing asynchronous state access within the middleware's synchronous call function, and integrating this logic with redirect actions. How can I correctly implement the async lock and conditional redirect while conforming to Actix Web's middleware structure?

Any guidance or examples on how to handle this would be greatly appreciated. Thank you in advance for your help.

It can be done, but at the expense of the redirection logic, but that doesn't work for me.

0

There are 0 answers