Skip to main content

fetchlet_http/axum_server/
service.rs

1use std::convert::Infallible;
2use std::future::Future;
3use std::net::{IpAddr, SocketAddr};
4use std::pin::Pin;
5use std::task::{Context, Poll};
6
7use axum::body::Body;
8use axum::extract::{ConnectInfo, Request};
9use axum::http::request::Parts;
10use axum::response::Response;
11use serde::Serialize;
12use tower_service::Service;
13
14use fetchlet::AppHandle;
15
16use crate::{Error, FetchletService};
17
18/// The client address recorded by `into_make_service_with_connect_info`.
19pub fn connect_info(parts: &Parts) -> Option<IpAddr> {
20    parts
21        .extensions
22        .get::<ConnectInfo<SocketAddr>>()
23        .map(|ConnectInfo(address)| address.ip())
24}
25
26/// [`FetchletService`] with axum's request and response types.
27///
28/// The default context's client address comes from `ConnectInfo<SocketAddr>`.
29/// Everything else, including the public origin, body budgets, the trusted
30/// Context and error responses, is the Tower service's behavior.
31#[derive(Clone)]
32pub struct AxumService {
33    inner: FetchletService,
34}
35
36impl AxumService {
37    pub fn new(app: AppHandle, public_origin: &str) -> Result<Self, Error> {
38        let inner = FetchletService::new(app, public_origin)?.client_address(connect_info);
39        Ok(Self { inner })
40    }
41
42    /// See [`FetchletService::context`].
43    pub fn context<C, F>(self, context: F) -> Self
44    where
45        C: Serialize,
46        F: Fn(&Parts) -> C + Send + Sync + 'static,
47    {
48        self.map(|inner| inner.context(context))
49    }
50
51    /// See [`FetchletService::trusted_context`].
52    pub fn trusted_context(
53        self,
54        context: impl Fn(&Parts) -> fetchlet::Context + Send + Sync + 'static,
55    ) -> Self {
56        self.map(|inner| inner.trusted_context(context))
57    }
58
59    /// See [`FetchletService::on_error`].
60    pub fn on_error(self, callback: impl Fn(&Error) + Send + Sync + 'static) -> Self {
61        self.map(|inner| inner.on_error(callback))
62    }
63
64    /// See [`FetchletService::stream_request_bodies`].
65    pub fn stream_request_bodies(self) -> Self {
66        self.map(FetchletService::stream_request_bodies)
67    }
68
69    /// Run the handler, returning detailed errors.
70    pub async fn fetch(&self, request: Request) -> Result<Response, Error> {
71        Ok(self.inner.fetch(request).await?.map(Body::new))
72    }
73
74    /// The underlying Tower service.
75    pub fn into_inner(self) -> FetchletService {
76        self.inner
77    }
78
79    fn map(self, change: impl FnOnce(FetchletService) -> FetchletService) -> Self {
80        Self {
81            inner: change(self.inner),
82        }
83    }
84}
85
86impl Service<Request> for AxumService {
87    type Response = Response;
88
89    type Error = Infallible;
90
91    type Future = Pin<Box<dyn Future<Output = Result<Response, Infallible>> + Send>>;
92
93    fn poll_ready(&mut self, _context: &mut Context<'_>) -> Poll<Result<(), Infallible>> {
94        Poll::Ready(Ok(()))
95    }
96
97    fn call(&mut self, request: Request) -> Self::Future {
98        let service = self.inner.clone();
99        Box::pin(async move {
100            #[cfg(feature = "axum-websocket")]
101            if super::websocket::asks_for_upgrade(&request) {
102                return Ok(super::websocket::serve(&service, request).await);
103            }
104            let response = match service.fetch(request).await {
105                Ok(response) => response,
106                Err(error) => service.error_response(&error),
107            };
108            Ok(response.map(Body::new))
109        })
110    }
111}