eaze / tide-sqlx

Tide middleware for SQLx pooled connections & transactions
https://crates.io/crates/tide-sqlx
Other
40 stars 9 forks source link

using tide-websockets causes panic #16

Open chinatsu opened 2 years ago

chinatsu commented 2 years ago

hi!

i originally posted this issue over at https://github.com/http-rs/tide-websockets/issues/23 where i was informed that

The invariant described here is not correct. In the case of websockets, the response is upgraded and request extensions are moved from the request to the websocket connection. tide-sqlx should not panic in this circumstance.

i'll post the issue again here!


i've just started a new project where i'd like to have a service that handles websockets and does some fiddling with a database, perhaps even at the same time. so i figured it would be a good idea to use tide-websockets and tide-sqlx, since both projects are listed as middlewares in the tide readme!

consider these dependencies

[dependencies]
tide = "0.16.0"
async-std = { version = "1.10.0", features = ["attributes"] }
serde = { version = "1.0", features = ["derive"] }
tide-sqlx = "0.6.1"
sqlx = { version = "0.5", features = [ "runtime-async-std-native-tls", "postgres" ] }
tide-websockets = "0.4.0"
dotenv = "0.15.0"

and this (simplified) program,

use tide::Request;
use async_std::prelude::*;
use sqlx::postgres::Postgres;
use tide_sqlx::SQLxMiddleware;
use dotenv::dotenv;
use std::env;
use tide_websockets::{Message, WebSocket, WebSocketConnection};

#[async_std::main]
async fn main() -> tide::Result<()> {
    dotenv().ok();

    let mut app = tide::new();
    app.with(SQLxMiddleware::<Postgres>::new(&env::var("DATABASE_URL")?).await?);
    app.at("/quiz/").get(WebSocket::new(get_quiz));
    app.listen("127.0.0.1:3000").await?;
    Ok(())
}

async fn get_quiz(_req: Request<()>, mut stream: WebSocketConnection) -> tide::Result<()> {
    while let Some(Ok(Message::Text(input))) = stream.next().await {
        let output: String = input.chars().rev().collect();
        stream
            .send_string(format!("{} | {}", &input, &output))
            .await?;
    }

    Ok(())
}

running websocat to test the endpoint

websocat ws://localhost:3000/quiz/

returns a WebSocket protocol error and the server returns thread 'async-std/runtime' panicked at 'We have err'd egregiously! Could not unwrap refcounted SQLx connection for COMMIT; handler may be storing connection or request inappropiately?', /home/cn/.cargo/registry/src/github.com-1ecc6299db9ec823/tide-sqlx-0.6.1/src/lib.rs:312:17

i'm not really sure how to responsibly handle this case, so i'm kind of posting for awareness at this point.

Fishrock123 commented 2 years ago

See https://github.com/http-rs/tide-websockets/issues/23#issuecomment-996110797 for the root of this issue.

Sadly, I don't work on this anymore. Maybe I should have asked about moving it to my personal before I left Eaze. Unsure.