1
0

layer.rs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. use std::pin::Pin;
  2. use http::{Request, Response};
  3. pub trait Layer: Send + Sync + 'static {
  4. fn layer(&self, inner: BoxedService) -> BoxedService;
  5. }
  6. impl<L> Layer for L
  7. where
  8. L: tower_layer::Layer<BoxedService> + Sync + Send + 'static,
  9. L::Service: Service + Send + 'static,
  10. {
  11. fn layer(&self, inner: BoxedService) -> BoxedService {
  12. BoxedService(Box::new(self.layer(inner)))
  13. }
  14. }
  15. pub trait Service {
  16. fn run(
  17. &mut self,
  18. req: http::Request<hyper::body::Body>,
  19. ) -> Pin<
  20. Box<
  21. dyn std::future::Future<
  22. Output = Result<Response<hyper::body::Body>, server_fn::ServerFnError>,
  23. > + Send,
  24. >,
  25. >;
  26. }
  27. impl<S> Service for S
  28. where
  29. S: tower::Service<http::Request<hyper::body::Body>, Response = Response<hyper::body::Body>>,
  30. S::Future: Send + 'static,
  31. S::Error: Into<server_fn::ServerFnError>,
  32. {
  33. fn run(
  34. &mut self,
  35. req: http::Request<hyper::body::Body>,
  36. ) -> Pin<
  37. Box<
  38. dyn std::future::Future<
  39. Output = Result<Response<hyper::body::Body>, server_fn::ServerFnError>,
  40. > + Send,
  41. >,
  42. > {
  43. let fut = self.call(req);
  44. Box::pin(async move { fut.await.map_err(|err| err.into()) })
  45. }
  46. }
  47. pub struct BoxedService(pub Box<dyn Service + Send>);
  48. impl tower::Service<http::Request<hyper::body::Body>> for BoxedService {
  49. type Response = http::Response<hyper::body::Body>;
  50. type Error = server_fn::ServerFnError;
  51. type Future = Pin<
  52. Box<
  53. dyn std::future::Future<
  54. Output = Result<http::Response<hyper::body::Body>, server_fn::ServerFnError>,
  55. > + Send,
  56. >,
  57. >;
  58. fn poll_ready(
  59. &mut self,
  60. _cx: &mut std::task::Context<'_>,
  61. ) -> std::task::Poll<Result<(), Self::Error>> {
  62. Ok(()).into()
  63. }
  64. fn call(&mut self, req: Request<hyper::body::Body>) -> Self::Future {
  65. self.0.run(req)
  66. }
  67. }