Skip to main content

fetchlet_http/service/
transport.rs

1use std::fmt;
2use std::future::poll_fn;
3
4use bytes::Bytes;
5use http::Response;
6use tower_service::Service;
7
8use fetchlet::{FetchTransport, TransportFuture};
9
10/// Serve host fetches with a Tower service, such as an axum `Router`.
11///
12/// The same service can serve public HTTP and in-process fetches from
13/// JavaScript. Requests keep their method, absolute URI, headers, body and
14/// extensions, so handlers read the trusted [`fetchlet::Context`] from the
15/// extensions when the route receives it (see
16/// [`fetchlet::OriginRouter::internal`]). In-process requests carry no
17/// connection data; handlers that need it should get it from the Context.
18/// Response bodies stream back to JavaScript. Dropping the fetch drops the
19/// service future. A service error rejects the fetch with a general transport
20/// error; its detail stays in Rust.
21pub fn service_transport<S, B>(service: S) -> impl FetchTransport
22where
23    S: Service<http::Request<fetchlet::Body>, Response = Response<B>>
24        + Clone
25        + Send
26        + Sync
27        + 'static,
28    S::Error: fmt::Display,
29    S::Future: Send + 'static,
30    B: http_body::Body<Data = Bytes> + Send + 'static,
31    B::Error: fmt::Display,
32{
33    ServiceTransport { service }
34}
35
36struct ServiceTransport<S> {
37    service: S,
38}
39
40impl<S, B> FetchTransport for ServiceTransport<S>
41where
42    S: Service<http::Request<fetchlet::Body>, Response = Response<B>>
43        + Clone
44        + Send
45        + Sync
46        + 'static,
47    S::Error: fmt::Display,
48    S::Future: Send + 'static,
49    B: http_body::Body<Data = Bytes> + Send + 'static,
50    B::Error: fmt::Display,
51{
52    fn send(&self, request: fetchlet::Request) -> TransportFuture {
53        let mut service = self.service.clone();
54        Box::pin(async move {
55            let failed = |error: S::Error| fetchlet::Error::Transport(error.to_string());
56            poll_fn(|context| service.poll_ready(context))
57                .await
58                .map_err(failed)?;
59            let response = service.call(request).await.map_err(failed)?;
60            Ok(response.map(fetchlet::Body::from_http_body))
61        })
62    }
63}