rsocket / rsocket-rust

RSocket Rust Implementation using Tokio
Apache License 2.0
209 stars 19 forks source link

Non Trivial Examples? #15

Closed eiswind closed 4 years ago

eiswind commented 4 years ago

As I'm quite new to async programming in rust, I really would appreciate some non trivial examples with a real backend. (I tried tokio_postgres, but fail to get it right).

I implemented RSocket trait, but when I try to Box::pin() my result from the db, it complains about the missing sync trait in the tokio_postgres code. I have absolutely no clue how to solve that.

jjeffcaii commented 4 years ago

@eiswind Thanks for report! That because async rust use sync trait to make sure thread-safe. Could you show some code snippets?

eiswind commented 4 years ago

I think it is with deadpool and/or tokio postgres

fn request_response(&self, req: Payload) -> Mono<Result<Payload, RSocketError>> {
        info!("{:?}", req);

        let x = async move {
            let tasks = self.taskDao.get_tasks().await;
            for t in tasks {
                info!("Task {}", t.title)
            }
            Result::Ok(req)
        };

        Box::pin(x)
    }

Inside of taskDao I have a reference to the connection pool:

pub struct TaskDAO {
    pub pool: Pool,
}

impl TaskDAO {

    pub async fn get_tasks(&self) -> Result<Vec<Task>, Error> {
        let client =
            tokio_postgres::connect("host=localhost user=postgres password=*** dbname=demo", NoTls).await?;
        let stmt = client.prepare("SELECT id, title FROM task").await?;
        let rows = client.as_ref().query(stmt.as_ref(), &[]).await?;
        let result: Vec<Task> = rows
            .into_iter()
            .map(|row| Task {
                id: row.get(0),
                title: row.get(1),
            })
            .collect();
        Ok(result)
    }
}
eiswind commented 4 years ago

I tried quite a bunch of things, but it is always that the db libraries don't provide sync. That the dao keeps a reference to the pool in the moment is a result of pure desparation...

jjeffcaii commented 4 years ago

@eiswind Yes, I found a similar issue: https://github.com/sfackler/rust-postgres/issues/229. Also I tried using r2d2-postgres, but it still had some problems. I've create an issue https://github.com/sfackler/r2d2-postgres/issues/22 and hope that they can help us. 🤣

PS: You can checkout my testing codes in branch develop, then execute RUST_LOG=info cargo run --example postgres in example folder.

jjeffcaii commented 4 years ago

@eiswind I've removed the Sync trait in Mono and Flux. Now you can use tokio-postgres. Since we didn't release new version, you can add a dependency of develop branch in Cargo.toml.

PS: Example source code is examples/postgres.rs.

eiswind commented 4 years ago

That should help. Thx.

jjeffcaii commented 4 years ago

I've released v0.5.3 which includes some examples.

eiswind commented 4 years ago

Thanks again for helping me out with this.