Skip to main content

fetchlet_http/webview/
responder.rs

1use std::fmt::Display;
2use std::future::poll_fn;
3
4use bytes::Bytes;
5use http::header::{CONTENT_TYPE, HeaderValue};
6use http::{Request, Response, StatusCode};
7use http_body::Body;
8use http_body_util::{BodyExt, Full, Limited};
9use tower_service::Service;
10
11/// Answers a webview's custom-protocol requests in-process with an HTTP
12/// service, such as an axum `Router` or a [`FetchletService`](crate::FetchletService).
13///
14/// A custom URI scheme passes each request with its whole body and takes a
15/// whole response, as Tauri's `UriSchemeResponder` does, so the responder
16/// collects each response body. `response_body_bytes` bounds what it
17/// collects: it is the caller's memory budget for one response, since the
18/// body is held in full before the webview receives it. A larger response
19/// becomes a `502 Bad Gateway`.
20///
21/// `services` makes the service for each request, so a host that replaces
22/// its application, such as one using [`DevReload`](crate::DevReload)'s
23/// `current`, answers each request with the build current when it arrives.
24#[derive(Clone)]
25pub struct WebviewResponder<F> {
26    services: F,
27    response_body_bytes: usize,
28}
29
30impl<F> WebviewResponder<F> {
31    /// A responder that answers with the service `services` returns for each
32    /// request, collecting at most `response_body_bytes` of each response.
33    pub fn new(services: F, response_body_bytes: usize) -> Self {
34        Self {
35            services,
36            response_body_bytes,
37        }
38    }
39
40    /// The response to `request`, whose body the service receives as a
41    /// `Full<Bytes>`. Errors of the service and of the response
42    /// body are written to standard error and answered with a status.
43    pub async fn respond<S, R>(&self, request: Request<Vec<u8>>) -> Response<Vec<u8>>
44    where
45        F: Fn() -> S,
46        S: Service<Request<Full<Bytes>>, Response = Response<R>>,
47        S::Error: Display,
48        R: Body,
49        R::Error: Into<crate::BoxError>,
50    {
51        let mut service = (self.services)();
52        let request = request.map(|body| Full::new(Bytes::from(body)));
53        let response = match poll_fn(|context| service.poll_ready(context)).await {
54            Ok(()) => service.call(request).await,
55            Err(error) => Err(error),
56        };
57        let response = match response {
58            Ok(response) => response,
59            Err(error) => {
60                eprintln!("fetchlet: webview request failed: {error}");
61                return text_response(StatusCode::INTERNAL_SERVER_ERROR, "Internal Server Error");
62            }
63        };
64        let (parts, body) = response.into_parts();
65        match Limited::new(body, self.response_body_bytes).collect().await {
66            Ok(collected) => Response::from_parts(parts, collected.to_bytes().to_vec()),
67            Err(error) => {
68                eprintln!("fetchlet: webview response failed: {error}");
69                text_response(StatusCode::BAD_GATEWAY, "Bad Gateway")
70            }
71        }
72    }
73}
74
75fn text_response(status: StatusCode, body: &'static str) -> Response<Vec<u8>> {
76    let mut response = Response::new(body.as_bytes().to_vec());
77    *response.status_mut() = status;
78    response.headers_mut().insert(
79        CONTENT_TYPE,
80        HeaderValue::from_static("text/plain; charset=utf-8"),
81    );
82    response
83}