Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass a Trait as application data to Actix Web?

I want to create a actix-web server where I can provide my Search trait as application data in order to easily swap between multiple implementations or use mock implementation for testing. Whatever I try I can't get it to compile or when I get it to compile I get the following error when visiting the route in the web browser:

App data is not configured, to configure use App::data()

Here is what I have so far

// main.rs

use actix_web::dev::Server;
use actix_web::{get, web, App, HttpServer, Responder};

pub trait Search {
    fn search(&self, query: &str) -> String;
}

#[derive(Clone)]
pub struct SearchClient {
    base_url: String,
}

impl SearchClient {
    pub fn new() -> Self {
        Self {
            base_url: String::from("/search"),
        }
    }
}

impl Search for SearchClient {
    fn search(&self, query: &str) -> String {
        format!("Searching in SearchClient: {}", query)
    }
}

#[get("/{query}")]
async fn index(
    web::Path(query): web::Path<String>,
    search: web::Data<dyn Search>,
) -> impl Responder {
    search.into_inner().search(&query)
}

pub fn create_server(
    search: impl Search + Send + Sync + 'static + Clone,
) -> Result<Server, std::io::Error> {
    let server = HttpServer::new(move || App::new().data(search.clone()).service(index))
        .bind("127.0.0.1:8080")?
        .run();
    Ok(server)
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    let search_client = SearchClient::new();
    create_server(search_client).unwrap().await
}

#[cfg(test)]
mod tests {
    use super::*;

    #[derive(Clone)]
    pub struct TestClient;

    impl Search for TestClient {
        fn search(&self, query: &str) -> String {
            format!("Searching in TestClient: {}", query)
        }
    }

    #[actix_rt::test]
    async fn test_search() {
        let search_client = TestClient {};
        let server = create_server(search_client).unwrap();
        tokio::spawn(server);
    }
}

# Cargo.toml

[package]
name = "actix-trait"
version = "0.1.0"
edition = "2018"

[dependencies]
actix-rt = "1.1.1"
actix-web = "3.3.2"

[dev-dependencies]
tokio = "0.2.22"
like image 517
Oskar Persson Avatar asked Jan 09 '21 17:01

Oskar Persson


1 Answers

When adding the data to your App, you have to specify that you want it to be downcasted as a trait object. Data does not accept unsized types directly, so you have to first create an Arc (which does accept unsized types) and then convert it to a Data. We will use the app_data method to avoid wrapping the searcher in a double arc.

pub fn create_server(
    search: impl Search + Send + Sync + 'static,
) -> Result<Server, std::io::Error> {
    let search: Data<dyn Search> = Data::from(Arc::new(search));
    
    HttpServer::new(move || {
        App::new()
            .app_data(search.clone())
    })
}

async fn index(
    query: Path<String>,
    search: Data<dyn Search>,
) -> impl Responder {     
    search.into_inner().search(&*query)
}

An alternative approach is using generics. Your handler and create_server functions would be generic over a Search implementation:

async fn index<T: Search>(
    web::Path(query): web::Path<String>,
    search: web::Data<T>,
-> impl Responder {
    search.into_inner().search(&query)
}

pub fn create_server<T: Search + Send + Sync + 'static + Clone>(
    search: T,
) -> Result<Server, std::io::Error> {
    let server = HttpServer::new(move || {
        App::new()
            .data(search.clone())
            .route("/{query}", web::get().to(index::<T>))
    })
    .bind("127.0.0.1:8080")?
    .run();
    Ok(server)
}

Now, when you create the server in main, you can use SearchClient:

#[actix_web::main]
async fn main() -> std::io::Result<()> {
     let search_client = SearchClient::new();
     create_server(search_client).unwrap().await
}

And when you create the server for testing purposes, you could use a TestClient:

#[actix_rt::test]
async fn test_search() {
    let search_client = TestClient {};
    let server = create_server(search_client).unwrap();
}

The downside to the generics based approach is that you cannot use the #[get("")] macros for routing because you have to specify the handler's generic parameters:

App::new()
    .route("/{query}", web::get().to(index::<T>))
like image 156
Ibraheem Ahmed Avatar answered Sep 29 '22 03:09

Ibraheem Ahmed