MikeMoolenaar / RATH-stack

The RATH stack (Rust + Axum + Turso + HTMX) for building web apps
https://rust-api-plus-htmx.fly.dev
MIT License
5 stars 0 forks source link

Connection as shared state causes error after idle without requests #2

Open jregistr opened 6 months ago

jregistr commented 6 months ago

Hi. I found this repo searching for example using turso and axum. I've done some testing and found that using a Connection that is shared as State results in errors after a some successful requests if there's a pause.

called `Result::unwrap()` on an `Err` value: Hrana(Api("{\"message\":\"The stream has expired due to inactivity\",\"code\":\"STREAM_EXPIRED\"}"))

Here's what I tested. main.rs

let url = env::var("LIBSQL_URL").expect("LIBSQL_URL must be set");
let token = env::var("LIBSQL_AUTH_TOKEN").expect("LIBSQL auth token must be set");

let db = Builder::new_remote(url, token).build().await.unwrap();
let conn = db.connect().unwrap();

let app = Router::new()
        .merge(user::show())
        .with_state(Arc::new(AppState {conn}));
let address = format!("127.0.0.1:{}", 3000).parse().unwrap()
let listener = tokio::net::TcpListener::bind(address).await.unwrap();
let svc = app.into_make_service_with_connect_info::<SocketAddr>();
axum::serve(listener, svc).await.unwrap();

file with user route

pub async fn show_user(
    Path(user_id): Path<String>,
    State(app): State<Arc<AppState>>
) -> String {
    let conn = &app.conn;
    let mut stmt = conn
        .prepare("SELECT * FROM users WHERE id = ?1")
        .await
        .unwrap();
    let row = stmt.query_row([user_id.as_str()]).await.unwrap();
    let id = row.get_value(1).unwrap().as_text().unwrap().clone();
    id
}

Worth noting Turso has an example over here: https://docs.turso.tech/sdk/rust/guides/axum They construct both the DB and the connection in the handler.

jregistr commented 6 months ago

Anyways, I've switched to sharing the DB and then getting a new connection in the handler and I no longer get the issue.

MikeMoolenaar commented 6 months ago

Hi thanks for letting me know! I can't reproduce it though, how exactly did you get the error? I tried starting the app, opening a page which contains a database call, waiting 10 minutes and then refreshing the page.

jregistr commented 4 months ago

Interesting. I'll try it again. Perhaps there's something else in my environment. I'll submit a branch with example.