actix web with mongodb project fails to build after an async call to mongodb is added

512 views Asked by At

I'm implementing a REST API using actix-web and mongodb for the data back-end. I am using version 1.1.1 of the official rust-mongodb driver from crates.io and Rust 1.46.

If I add code to make a call to the mongodb collection to get records for example, even though cargo check shows no errors or warnings, cargo build takes a long time and then terminates with an error that it could not compile my project and a (signal 9, SIGKILL: kill). After searching for the problem, I get that this is probably an out of memory error caused during the build/linking process. I am working on a Debian 10 machine with 16GB of RAM, so this is not very reasonable.

This only happens when I make the call in code inside a "handler" using async and await.

For example, if I try to get the names of the sample collection like so:

pub async fn samples() -> Result<HttpResponse, Error> {
    let dbnames = get_samples().await;

    Ok(HttpResponse::Ok().json(dbnames.unwrap()))
}

async fn get_samples() -> Result<Vec<String>, ServiceError> {
    let mut dbnames: Vec<String> = Vec::new();
    let client_uri = String::from("mongodb+srv://<...MONGODB_CONNECTION_INFO...>/sample_mflix?retryWrites=true&w=majority");
    let client = mongodb::Client::with_uri_str(client_uri.as_ref()).await?;

    for name in client.list_database_names(None, None).await? {
        dbnames.push(format!("- {}", name));
    }

    Ok(dbnames)
}

The cargo build will never complete and will stop with the aforementioned error.

Just to make sure, I used code to get the sample collection names, directly inside main.rs in the main function and it worked with no issues and the compile and build time were reasonable.

let client = mongodb::Client::with_uri_str(client_uri.as_ref()).await;
println!("Databases:");
for name in client.unwrap().list_database_names(None, None).await {
    for item in name {
        println!("- {}", item);
    }
}

Same result even if use cargo build --release to avoid having too much debug info

This only happens when using the async API of the rust-mongodb driver. With the sync API everything build and works properly.

What could be the cause of this?

1

There are 1 answers

2
gembin On BEST ANSWER

I got the exactly the same issue after upgrade to 1.1.1 with async API. cargo build will never complete, it will consume 100% CPU and will keep consuming memory until exhausted.

Found related issues:

Two ways to workaround:

  • Downgrade to rust 1.45.2
  • Switch to async-std-runtime to workaround this issue. mongodb = { version = "1.1.1", default-features = false, features = ["async-std-runtime"] }