tokio-rs / tokio-service

The core `Service` trait in Tokio and support
Apache License 2.0
82 stars 19 forks source link

Connection state #25

Closed anton-dutov closed 6 years ago

anton-dutov commented 7 years ago

By example, some rpc service with persistent connections, typical work is

  1. Connect
  2. Auth
  3. Quering...

At step two we created auth token and bound to socket (all socket's have bounded HashMap, where state saves), how to impl that via Service?

carllerche commented 7 years ago

The rule of thumb is that anything that is socket specific should not be at the Service layer (there are, of course, exceptions). It can be done at the transport layer, which is per socket: https://tokio.rs/docs/going-deeper-tokio/transports/.

That said, it can also be possible to do at the Service layer once NewService returns a future:

impl NewService for MyService {
    fn new_service(&self) -> Self::Future {
        let token = self.token.clone();
        self.proto.new_service()
            .and_then(|s| s.call(Auth(token))
            .and_then(|resp| {
                validate_resp(resp)?
                // return authenticated service
            })
    }
}
anton-dutov commented 7 years ago

So, where are save state between requests?

carllerche commented 7 years ago

If you want to save state between requests, you should use an Rc or Arc somewhere. The "somewhere" depends on the details of what you want the state to be shared across.