gotham-rs / gotham

A flexible web framework that promotes stability, safety, security and speed.
https://gotham.rs
Other
2.23k stars 125 forks source link

Investigate adopting `impl Trait` instead of our current `Box<HandlerFuture>` #32

Open smangelsdorf opened 7 years ago

smangelsdorf commented 7 years ago

Originally discussed in the announcement thread, it would be nice if we could support concrete future types using the impl Trait feature which is currently only available on nightly Rust.

What we actually need, though, is for impl Trait to be supported in the associated type position, and for the inferred type to be able to vary with the generic type parameters, which is being discussed at:

We'll need a Middleware trait that looks something like:

trait Middleware<R>
where
    R: Future<Item = (State, Response), Error = (State, Error)> + Send,
{
    type Output: Future<Item = (State, Response), Error = (State, Error)> + Send;

    fn call<Chain>(self, state: State, request: Request, chain: Chain) -> Self::Output
    where
        Chain: FnOnce(State, Request) -> R,
        Self: Sized;
}

Here, R is the concrete type of the future returned by the next Middleware. Though it's only used for the call function, it's likely to be important that this exists at the trait level instead, as SomeUsefulMiddleware::<R>::Output will need to vary with the R type.

Implementing Middleware would then look something like:

struct MyMiddleware;
impl<R> Middleware<R> for MyMiddleware {
    type Output = impl Future<Item = (State, Response), Error = (State, Error)> + Send;

    fn call<Chain>(self, state: State, request: Request, chain: Chain) -> Self::Output
    where
        Chain: FnOnce(State, Request) -> R,
        Self: Sized,
    {
        unimplemented!()
    }
}

Constructing the middleware pipeline will be considerably more difficult with the R parameter here, so this will take some experimentation to prove that the idea works. If this is deemed a suitable way forward, we could investigate making a similar change to Handler.

msrd0 commented 3 years ago

The required RFC has landed but not been standardized, tracking issue is https://github.com/rust-lang/rust/issues/63063