Axum interoperability, or: Mutable shared resource #571
-
Hi, I started with this example and tried to modify it in a way that allows me to have a mutable shared resource. Background: I want to use an pub async fn function_handler(event: Request, app: &mut axum::Router ) -> Result<Response<Body>, Error> {
let axum_request = convert_request(event);
let response = app.call(axum_request).await?;
Ok(convert_response(response)
} Now, I tried to wrap To not have you to deal with my code, I extended the example from the repo to also expose this behaviour. use lambda_http::{service_fn, Body, Error, IntoResponse, Request, RequestExt, Response};
use std::sync::{Arc, Mutex};
struct SharedClient {
name: &'static str,
}
impl SharedClient {
fn response(&self, req_id: String, first_name: &str) -> String {
format!(
"{}: Client ({}) invoked by {}.",
req_id, self.name, first_name
)
}
}
#[tokio::main]
async fn main() -> Result<(), Error> {
// The runtime logging can be enabled here by initializing `tracing` with `tracing-subscriber`
// While `tracing` is used internally, `log` can be used as well if preferred.
tracing_subscriber::fmt()
.with_max_level(tracing::Level::INFO)
// disabling time is handy because CloudWatch will add the ingestion time.
.without_time()
.init();
// Create the "client" and a reference to it, so that we can pass this into the handler closure below.
let mut shared_client = SharedClient {
name: "random_client_name_1",
};
let shared_client_ref = Arc::new(Mutex::new(shared_client));
// Define a closure here that makes use of the shared client.
let handler_func_closure = move |event: Request| async move {
Result::<Response<Body>, Error>::Ok(
match event.query_string_parameters().first("first_name") {
Some(first_name) => {
shared_client_ref
.lock()
.unwrap()
.response(event.lambda_context().request_id, first_name)
.into_response()
.await
}
_ => Response::builder()
.status(400)
.body("Empty first name".into())
.expect("failed to render response"),
},
)
};
// Pass the closure to the runtime here.
lambda_http::run(service_fn(handler_func_closure)).await?;
Ok(())
} Compiler tells me:
I understand: Although I am locking, wrapping, ... eventually I am sending the unlocked, unwrapped value around and this does not work. Can someone give me a hint how I would accomplish this? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
https://crates.io/crates/lambda-web this crate has it already implemented. Maybe you can use this crate or see how they did it. |
Beta Was this translation helpful? Give feedback.
https://crates.io/crates/lambda-web this crate has it already implemented. Maybe you can use this crate or see how they did it.