Using std::sync::RwLock
as state for from_fn_with_state
ends up in a "trait not satisfied error"
#2458
Answered
by
davidpdrsn
FelipeLema
asked this question in
Q&A
-
SummaryNot sure if a question or a bug, but using here is a MWE to trigger the error. There's also a Either not calling use axum::extract;
use axum::http::StatusCode;
use axum::middleware::{from_fn_with_state, Next};
use axum::response;
use axum::routing::method_routing::get;
use axum::Router;
use std::sync::Arc;
use std::sync::RwLock;
//use tokio::sync::RwLock; // change to «use tokio::sync::RwLock;» to fix
pub struct Storage {}
type StorageHandle = Arc<RwLock<Storage>>; // NOTE felo do we need RwLock for actual DB?
async fn get_something(
extract::State(_s): extract::State<StorageHandle>,
) -> impl response::IntoResponse {
StatusCode::OK
}
async fn my_layer(
extract::State(s): extract::State<StorageHandle>,
req: extract::Request,
next: Next,
) -> Result<response::Response, StatusCode> {
// ↓ removing this one line cleans up the error
let _s_readonly = s.read().map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
Ok(next.run(req).await)
}
#[tokio::main]
async fn main() {
let state = StorageHandle::new(RwLock::new(Storage {}));
let app = Router::new()
.route("/get_something", get(get_something))
.layer(from_fn_with_state(state, my_layer));
} axum versionv0.7.2 |
Beta Was this translation helpful? Give feedback.
Answered by
davidpdrsn
Dec 29, 2023
Replies: 1 comment
-
It's a bug in rust. It thinks the lock guard is held longer than it actually is. Adding an extra scope fixes it async fn my_layer(
extract::State(s): extract::State<StorageHandle>,
req: extract::Request,
next: Next,
) -> Result<response::Response, StatusCode> {
// ↓ removing this one line cleans up the error
{
let _s_readonly = s.read().map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
}
Ok(next.run(req).await)
} |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
FelipeLema
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It's a bug in rust. It thinks the lock guard is held longer than it actually is. Adding an extra scope fixes it