1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
use crate::handler::{Extractor, Factory, Handler};
use crate::request::{FromRequest, Request};
use crate::response::ToResponse;
use futures::future::{ready, BoxFuture, Future, FutureExt};
use http::{Method, StatusCode};
use hyper::service::Service;
use hyper::{Body, Response};
use std::task::{Context, Poll};

type BoxedMakeEndpoint<Req, Res> = Box<
  dyn Service<
      Req,
      Response = Res,
      Error = hyper::Error,
      Future = BoxFuture<'static, Result<Res, hyper::Error>>,
    > + Send,
>;

/// Resource endpoint definition
///
/// Endpoint uses builder-like pattern for configuration.
pub struct Endpoint {
  pub method: Option<Method>,
  pub handler: BoxedMakeEndpoint<Request, Response<Body>>,
}

impl Endpoint {
  #[allow(clippy::new_without_default)]
  /// Create new endpoint which matches any request
  /// ```rust
  /// use turbofish::{Endpoint, Response, Body};
  ///
  /// Endpoint::new().to(|| async {
  ///   Response::new(Body::default())
  /// });
  /// ```
  pub fn new() -> Self {
    Endpoint {
      method: None,
      handler: Box::new(MakeEndpoint::new(Extractor::new(Handler::new(|| {
        ready(
          Response::builder()
            .status(StatusCode::NOT_FOUND)
            .body(Body::default())
            .unwrap(),
        )
      })))),
    }
  }

  /// Create *endpoint* for http `GET` requests.
  /// ```rust
  /// use turbofish::{Endpoint, Response, Body};
  ///
  /// Endpoint::get().to(|| async {
  ///   Response::new(Body::default())
  /// });
  /// ```
  pub fn method(method: Method) -> Endpoint {
    Endpoint::new().set_method(method)
  }

  /// Create *endpoint* for http `GET` requests.
  /// ```rust
  /// use turbofish::{Endpoint, Response, Body};
  ///
  /// Endpoint::patch().to(|| async {
  ///   Response::new(Body::default())
  /// });
  /// ```
  pub fn get() -> Endpoint {
    Endpoint::new().set_method(Method::GET)
  }

  /// Create *endpoint* for http `POST` requests.
  /// ```rust
  /// use turbofish::{Endpoint, Response, Body};
  ///
  /// Endpoint::post().to(|| async {
  ///   Response::new(Body::default())
  /// });
  /// ```
  pub fn post() -> Endpoint {
    Endpoint::new().set_method(Method::POST)
  }

  /// Create *endpoint* for http `PUT` requests.
  /// ```rust
  /// use turbofish::{Endpoint, Response, Body};
  ///
  /// Endpoint::put().to(|| async {
  ///   Response::new(Body::default())
  /// });
  /// ```
  pub fn put() -> Endpoint {
    Endpoint::new().set_method(Method::PUT)
  }

  /// Create *endpoint* for http `PATCH` requests.
  /// ```rust
  /// use turbofish::{Endpoint, Response, Body};
  ///
  /// Endpoint::patch().to(|| async {
  ///   Response::new(Body::default())
  /// });
  /// ```
  pub fn patch() -> Endpoint {
    Endpoint::new().set_method(Method::PATCH)
  }

  /// Create *endpoint* for http `DELETE` requests.
  /// ```rust
  /// use turbofish::{Endpoint, Response, Body};
  ///
  /// Endpoint::delete().to(|| async {
  ///   Response::new(Body::default())
  /// });
  /// ```
  pub fn delete() -> Endpoint {
    Endpoint::new().set_method(Method::DELETE)
  }

  /// Create *endpoint* for http `HEAD` requests.
  /// ```rust
  /// use turbofish::{Endpoint, Response, Body};
  ///
  /// Endpoint::head().to(|| async {
  ///   Response::new(Body::default())
  /// });
  /// ```
  pub fn head() -> Endpoint {
    Endpoint::new().set_method(Method::HEAD)
  }

  /// Set handler function, use request extractors for parameters.
  /// ```rust
  /// use turbofish::{Endpoint, Response, Body};
  ///
  /// Endpoint::new().to(|| async {
  ///   Response::new(Body::default())
  /// });
  /// ```
  pub fn to<F, T, R, U>(mut self, handler: F) -> Self
  where
    F: Factory<T, R, U> + Send,
    T: FromRequest + 'static,
    R: Future<Output = U> + Send + 'static,
    U: ToResponse + 'static,
  {
    self.handler = Box::new(MakeEndpoint::new(Extractor::new(Handler::new(handler))));
    self
  }

  /// Assign the endpoint to an HTTP Method.
  pub fn set_method(mut self, method: Method) -> Self {
    self.method = Some(method);
    self
  }
}

struct MakeEndpoint<T: Service<Request>> {
  service: T,
}

impl<T> MakeEndpoint<T>
where
  T::Future: 'static,
  T: Service<Request, Response = Response<Body>, Error = (hyper::Error, Request)>,
{
  fn new(service: T) -> Self {
    MakeEndpoint { service }
  }
}

impl<T> Service<Request> for MakeEndpoint<T>
where
  T::Future: 'static + Send,
  T: Service<Request, Response = Response<Body>, Error = (hyper::Error, Request)>,
{
  type Response = Response<Body>;
  type Error = hyper::Error;
  type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>;

  fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
    self.service.poll_ready(cx).map_err(|(e, _)| e)
  }

  fn call(&mut self, req: Request) -> Self::Future {
    self
      .service
      .call(req)
      .map(|res| match res {
        Ok(res) => Ok(res),
        Err((_err, _req)) => Ok(
          // [TODO] error response
          Response::new(Body::default()),
        ),
      })
      .boxed()
  }
}