2

I am trying to implement a server that serves both gRPC and REST calls and that is started by a single binary.

In this main function, I am trying to start a tonic gRPC server and an actix-web REST API.

I found this answer but it didn't work for me: Using Actix from a Tokio App: mixing actix_web::main and tokio::main?

Tonic uses #[tokio::main] while actix uses #[actix_web::main].

I ran cargo expand over the two main functions and got the following:

  • #[tokio::main]
fn main() -> Result<(), Box<dyn std::error::Error>> {
    tokio::runtime::Builder::new_multi_thread()
        .enable_all()
        .build()
        .expect("Failed building the Runtime")
        .block_on(async {
            # my code goes here
        })
}
  • #[actix_web::main]
fn main() -> Result<(), Box<dyn std::error::Error>> {
    actix_web::rt::System::new("main").block_on(async move {
        {
            # my code goes here
        }
    })
}

I tried following the code in this discussion: https://github.com/actix/actix-web/issues/1283 where they use this code:

#[tokio::main]
async fn main() -> std::io::Result<()>{
    let local = tokio::task::LocalSet::new();
    let sys = actix_web::rt::System::run_in_tokio("server", &local);
    let server_res = HttpServer::new(|| App::new().route("/", web::get().to(hello_world)))
        .bind("0.0.0.0:8000")?
        .run()
        .await?;
    sys.await?;
    Ok(server_res)
}

but I get a compilation error saying that `expected struct tokio::task::local::LocalSet, found struct LocalSet and I don't know how to proceed.

I am quite new to Rust so any suggestion is appreciated.

Svetlin Zarev
  • 14,713
  • 4
  • 53
  • 82
  • 1
    Spawn an async task for each one? – Netwave Jul 30 '21 at 09:05
  • Compiler error might be explained in the [post](https://stackoverflow.com/questions/66416174/using-actix-from-a-tokio-app-mixing-actix-webmain-and-tokiomain) you've shared, _However be aware that you need to match up the versions of Tokio correctly_ – Ömer Erden Jul 30 '21 at 09:45
  • @ÖmerErden thanks for the suggestion. I went through the dependency tree of `tonic` and `actix`. Using `tokio="1.6.1"` solved the issue I was having. In summary, I used `tonic="0.5"`, `actix-web="3"` and `tokio="1.6.1"`. – Carlos Natalino Aug 03 '21 at 11:03

0 Answers0