Skip to main content

fetchlet_http/hyper_server/
service.rs

1use std::convert::Infallible;
2use std::future::Future;
3use std::net::{IpAddr, SocketAddr};
4use std::pin::Pin;
5
6use http::request::Parts;
7use http::{Request, Response};
8use hyper::body::Incoming;
9use serde::Serialize;
10
11use fetchlet::AppHandle;
12
13use crate::{Error, FetchletService};
14
15type ResponseFuture =
16    Pin<Box<dyn Future<Output = Result<Response<fetchlet::Body>, Infallible>> + Send>>;
17
18/// The peer address of the connection a request arrived on.
19///
20/// [`HyperConnection`] inserts it into each request's extensions.
21#[derive(Clone, Copy, Debug)]
22pub struct PeerAddr(pub SocketAddr);
23
24/// The client address recorded by [`HyperService::connection`].
25pub fn peer_addr(parts: &Parts) -> Option<IpAddr> {
26    parts
27        .extensions
28        .get::<PeerAddr>()
29        .map(|PeerAddr(address)| address.ip())
30}
31
32/// [`FetchletService`] as a hyper 1 service.
33///
34/// Serve each accepted connection with [`HyperService::connection`] so the
35/// default context's client address is the peer address. The service itself
36/// also implements hyper's trait, for connections without a peer address.
37/// Everything else, including the public origin, body budgets, the trusted
38/// Context and error responses, is the Tower service's behavior.
39#[derive(Clone)]
40pub struct HyperService {
41    inner: FetchletService,
42}
43
44impl HyperService {
45    pub fn new(app: AppHandle, public_origin: &str) -> Result<Self, Error> {
46        let inner = FetchletService::new(app, public_origin)?.client_address(peer_addr);
47        Ok(Self { inner })
48    }
49
50    /// The service for one connection from `peer`.
51    pub fn connection(&self, peer: SocketAddr) -> HyperConnection {
52        HyperConnection {
53            inner: self.inner.clone(),
54            peer: Some(PeerAddr(peer)),
55        }
56    }
57
58    /// See [`FetchletService::context`].
59    pub fn context<C, F>(self, context: F) -> Self
60    where
61        C: Serialize,
62        F: Fn(&Parts) -> C + Send + Sync + 'static,
63    {
64        self.map(|inner| inner.context(context))
65    }
66
67    /// See [`FetchletService::trusted_context`].
68    pub fn trusted_context(
69        self,
70        context: impl Fn(&Parts) -> fetchlet::Context + Send + Sync + 'static,
71    ) -> Self {
72        self.map(|inner| inner.trusted_context(context))
73    }
74
75    /// See [`FetchletService::on_error`].
76    pub fn on_error(self, callback: impl Fn(&Error) + Send + Sync + 'static) -> Self {
77        self.map(|inner| inner.on_error(callback))
78    }
79
80    /// See [`FetchletService::stream_request_bodies`].
81    pub fn stream_request_bodies(self) -> Self {
82        self.map(FetchletService::stream_request_bodies)
83    }
84
85    /// The underlying Tower service.
86    pub fn into_inner(self) -> FetchletService {
87        self.inner
88    }
89
90    fn map(self, change: impl FnOnce(FetchletService) -> FetchletService) -> Self {
91        Self {
92            inner: change(self.inner),
93        }
94    }
95}
96
97impl hyper::service::Service<Request<Incoming>> for HyperService {
98    type Response = Response<fetchlet::Body>;
99
100    type Error = Infallible;
101
102    type Future = ResponseFuture;
103
104    fn call(&self, request: Request<Incoming>) -> Self::Future {
105        respond(self.inner.clone(), request)
106    }
107}
108
109/// [`HyperService`] for one connection, recording its peer address.
110#[derive(Clone)]
111pub struct HyperConnection {
112    inner: FetchletService,
113    peer: Option<PeerAddr>,
114}
115
116impl hyper::service::Service<Request<Incoming>> for HyperConnection {
117    type Response = Response<fetchlet::Body>;
118
119    type Error = Infallible;
120
121    type Future = ResponseFuture;
122
123    fn call(&self, mut request: Request<Incoming>) -> Self::Future {
124        if let Some(peer) = self.peer {
125            request.extensions_mut().insert(peer);
126        }
127        respond(self.inner.clone(), request)
128    }
129}
130
131/// Dropping the future, as hyper does when the client disconnects, cancels
132/// the invocation.
133fn respond(service: FetchletService, request: Request<Incoming>) -> ResponseFuture {
134    Box::pin(async move {
135        Ok(match service.fetch(request).await {
136            Ok(response) => response,
137            Err(error) => service.error_response(&error),
138        })
139    })
140}