Hi I'm building an API gateway that is responsible for accepting requests from the web and publishing them to a pubsub topic in GCP. In order to optimize the app, I'm trying to pass the pubsub connection to the app data
so that it can be reused by workers rather than establishing a connection with pubsub with every request. As an added layer, I need to add a CORS to the App wrap method so the API can accept request across orgins.
Below is the code in my main function:
#[actix_web::main]
async fn main() -> anyhow::Result<(), anyhow::Error> {
const PORT: &str = "8000";
const HOST: &str = "0.0.0.0";
const TOPIC_ID: &str = "XXXXX";
println!("{}", format!("Starting service...").bold().red(), );
println!("Serving on address: http://{}:{}", HOST, PORT);
// Create PubSub client
let pubsub_client = Client::default().await?;
let publisher = pubsub_client
.topic(TOPIC_ID)
.new_publisher(Some(PublisherConfig {
flush_interval: Duration::from_millis(50),
..Default::default()
}));
let publisher_for_web = web::Data::new(publisher.clone());
let cors = Cors::default()
.allow_any_origin()
.send_wildcard()
.allowed_methods(["GET", "POST", "OPTIONS"])
.allow_any_header();
let web_task = tokio::spawn(async move {
let server = HttpServer::new(move || {
App::new()
.app_data(publisher_for_web.clone())
.configure(init)
.wrap(cors)
})
.bind(format!("{}:{}", HOST, PORT))?
.run();
server.await.context("server error")
});
let _ = web_task.await;
let mut publisher = publisher;
let _ = publisher.shutdown();
Ok(())
}
However, I am getting the below compile time error:
error[E0277]: `Rc<actix_cors::inner::Inner>` cannot be sent between threads safely
--> src/main.rs:170:22
|
170 | let server = HttpServer::new(move || {
| ______________________^^^^^^^^^^^^^^^_-
| | |
| | `Rc<actix_cors::inner::Inner>` cannot be sent between threads safely
171 | | App::new()
172 | | .app_data(publisher_for_web.clone())
173 | | .configure(init)
174 | | .wrap(cors)
175 | | })
| |_________- within this `[closure@src/main.rs:170:38: 175:10]`