Skip to main content

fetchlet_http/service/
fetchlet_service.rs

1use std::convert::Infallible;
2use std::fmt;
3use std::future::Future;
4use std::net::IpAddr;
5use std::pin::Pin;
6use std::sync::Arc;
7use std::task::{Context, Poll};
8
9use bytes::Bytes;
10use http::request::Parts;
11use http::{Request, Response};
12use http_body_util::{BodyExt, Limited};
13use serde::Serialize;
14use serde_json::Value;
15use tower_service::Service;
16
17use fetchlet::AppHandle;
18
19use super::{BoxError, Error, PublicOrigin, RequestContext};
20
21type ContextFactory = Arc<dyn Fn(&Parts) -> Result<Value, Error> + Send + Sync>;
22
23type AddressFactory = Arc<dyn Fn(&Parts) -> Option<IpAddr> + Send + Sync>;
24
25type TrustedContextFactory = Arc<dyn Fn(&Parts) -> fetchlet::Context + Send + Sync>;
26
27type ErrorCallback = Arc<dyn Fn(&Error) + Send + Sync>;
28
29/// A cloneable Tower service for a shared fetchlet application.
30///
31/// It accepts `http::Request<B>` for any body with `Bytes` data and returns
32/// `http::Response<fetchlet::Body>`, so it serves hyper connections and axum
33/// routers alike. The configured public origin supplies the scheme and
34/// authority; the incoming path, query, method, headers and body are kept. By
35/// default the incoming body is collected within the application's request
36/// body budget before the handler runs; [`FetchletService::stream_request_bodies`]
37/// passes it as a stream.
38#[derive(Clone)]
39pub struct FetchletService {
40    app: AppHandle,
41    origin: PublicOrigin,
42    context: Option<ContextFactory>,
43    client_address: Option<AddressFactory>,
44    trusted_context: Option<TrustedContextFactory>,
45    on_error: Option<ErrorCallback>,
46    stream_request_bodies: bool,
47}
48
49impl FetchletService {
50    pub fn new(app: AppHandle, public_origin: &str) -> Result<Self, Error> {
51        Ok(Self {
52            app,
53            origin: PublicOrigin::parse(public_origin)?,
54            context: None,
55            client_address: None,
56            trusted_context: None,
57            on_error: None,
58            stream_request_bodies: false,
59        })
60    }
61
62    #[cfg(feature = "axum-websocket")]
63    pub(crate) fn app(&self) -> &AppHandle {
64        &self.app
65    }
66
67    /// Supply the client address of the default [`RequestContext`].
68    ///
69    /// Servers keep connection data in their own request extensions, such as
70    /// axum's `ConnectInfo`; this callback reads it.
71    pub fn client_address(
72        mut self,
73        address: impl Fn(&Parts) -> Option<IpAddr> + Send + Sync + 'static,
74    ) -> Self {
75        self.client_address = Some(Arc::new(address));
76        self
77    }
78
79    /// Supply application metadata using the incoming HTTP request parts.
80    ///
81    /// It replaces the default [`RequestContext`] as the Fetch entry's second
82    /// argument, which JavaScript reads.
83    pub fn context<C, F>(mut self, context: F) -> Self
84    where
85        C: Serialize,
86        F: Fn(&Parts) -> C + Send + Sync + 'static,
87    {
88        self.context = Some(Arc::new(move |parts| {
89            serde_json::to_value(context(parts)).map_err(Error::Context)
90        }));
91        self
92    }
93
94    /// Derive the trusted [`fetchlet::Context`] of each request in Rust.
95    ///
96    /// The Context stays out of JavaScript. Host fetches of the request carry
97    /// it to in-process routes registered with
98    /// [`fetchlet::OriginRouter::internal`], for example a router served
99    /// through [`service_transport`](crate::service_transport). Use it for the
100    /// authenticated principal, tenant or trace data instead of request
101    /// headers that JavaScript can set. It replaces a Context that earlier
102    /// middleware put in the request extensions.
103    pub fn trusted_context(
104        mut self,
105        context: impl Fn(&Parts) -> fetchlet::Context + Send + Sync + 'static,
106    ) -> Self {
107        self.trusted_context = Some(Arc::new(context));
108        self
109    }
110
111    /// Observe detailed errors in Rust while HTTP responses use general messages.
112    pub fn on_error(mut self, callback: impl Fn(&Error) + Send + Sync + 'static) -> Self {
113        self.on_error = Some(Arc::new(callback));
114        self
115    }
116
117    /// Pass incoming bodies to the handler as a stream instead of collecting them.
118    ///
119    /// The handler starts before the body has arrived and reads it as a
120    /// `ReadableStream`. A declared `Content-Length` over the request body
121    /// budget is still rejected with 413 before execution. Bytes over the
122    /// budget without a declared length, and failures of the incoming body,
123    /// reach the handler as errors of its body stream, so the handler decides
124    /// the response status.
125    pub fn stream_request_bodies(mut self) -> Self {
126        self.stream_request_bodies = true;
127        self
128    }
129
130    /// Run the handler, returning detailed errors.
131    pub async fn fetch<B>(&self, request: Request<B>) -> Result<Response<fetchlet::Body>, Error>
132    where
133        B: http_body::Body<Data = Bytes> + Send + 'static,
134        B::Error: Into<BoxError> + fmt::Display,
135    {
136        let (mut parts, body) = request.into_parts();
137        parts.uri = self.origin.apply(parts.uri)?;
138        let context = self.context_value(&parts)?;
139        if let Some(trusted) = &self.trusted_context {
140            let trusted = trusted(&parts);
141            parts.extensions.insert(trusted);
142        }
143        let body = if self.stream_request_bodies {
144            // The invocation applies the budget to the bytes it reads.
145            fetchlet::Body::from_http_body(body)
146        } else {
147            // None delegates the budget to the host.
148            let limit = self.app.limits().request_body_bytes.unwrap_or(usize::MAX);
149            let collected = Limited::new(body, limit)
150                .collect()
151                .await
152                .map_err(Error::Body)?;
153            fetchlet::Body::from(collected.to_bytes())
154        };
155        let request = Request::from_parts(parts, body);
156        Ok(self.app.fetch_with_context(request, &context).await?)
157    }
158
159    fn context_value(&self, parts: &Parts) -> Result<Value, Error> {
160        if let Some(context) = &self.context {
161            return context(parts);
162        }
163        let address = self
164            .client_address
165            .as_ref()
166            .and_then(|address| address(parts));
167        serde_json::to_value(RequestContext::new(address)).map_err(Error::Context)
168    }
169
170    /// Report an error to the callback and answer with a general response.
171    pub fn error_response(&self, error: &Error) -> Response<fetchlet::Body> {
172        if let Some(callback) = &self.on_error {
173            callback(error);
174        }
175        error.response()
176    }
177}
178
179impl<B> Service<Request<B>> for FetchletService
180where
181    B: http_body::Body<Data = Bytes> + Send + 'static,
182    B::Error: Into<BoxError> + fmt::Display,
183{
184    type Response = Response<fetchlet::Body>;
185
186    type Error = Infallible;
187
188    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Infallible>> + Send>>;
189
190    fn poll_ready(&mut self, _context: &mut Context<'_>) -> Poll<Result<(), Infallible>> {
191        Poll::Ready(Ok(()))
192    }
193
194    fn call(&mut self, request: Request<B>) -> Self::Future {
195        let service = self.clone();
196        Box::pin(async move {
197            Ok(match service.fetch(request).await {
198                Ok(response) => response,
199                Err(error) => service.error_response(&error),
200            })
201        })
202    }
203}