fetchlet_http/service/
fetchlet_service.rs1use 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#[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 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 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 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 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 pub fn stream_request_bodies(mut self) -> Self {
126 self.stream_request_bodies = true;
127 self
128 }
129
130 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 fetchlet::Body::from_http_body(body)
146 } else {
147 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 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}