rustrust-actix

Panic at spawn_local when trying to run an actor from actix-web


rust-actix

Panic at spawn_local when trying to run an actor from actix-web

I'm trying to start an actor in an actix-web server and pass its address using data.

use actix::prelude::*;
use actix_web::{web, App, HttpRequest, HttpServer, Responder};

struct MyActor;

impl Actor for MyActor {
    type Context = Context<Self>;
}

struct AppState {
    actor_addr: Addr<MyActor>,
}

async fn greet(req: HttpRequest, data: web::Data<AppState>) -> impl Responder {
    format!("Hello!")
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    let addr = MyActor.start();
    
    HttpServer::new(move || {
        App::new()
            .data(AppState {
                actor_addr: addr.clone(),
            })
            .route("/", web::get().to(greet))
    })
    .bind(("127.0.0.1", 8080))?
    .run()
    .await
}

The idea is to send a message from the greet function to the actor. When trying to run this I get the following panic:

thread 'main' panicked at '`spawn_local` called from outside of a `task::LocalSet`', /Users/myuser/.cargo/registry/src/github.com-1ecc6299db9ec823/tokio-1.12.0/src/task/local.rs:305:18

I have tried to substitute the #[actix_web::main] for #[actix_rt::main] and it starts the actor. Lurking the code, I realized that #[actix_web::main] is a re-export of #[actix_rt::main], so it should work. The dependencies versions are:

actix-web = "3.3.2"
actix = "0.12.0"

Maybe there are a mismatch in the dependencies.

Is this way to achieve what I am trying?

Thanks in advance.


Solution

  • Change to actix = "0.10", actix 0.12 seems to have a lot of updated dependencies that conflict with actix-web 3.3.