Skip to main content

fetchlet_http/vite_dev/
proxy.rs

1use std::fmt;
2use std::future::{Future, poll_fn};
3use std::pin::Pin;
4use std::task::{Context, Poll};
5
6use fetchlet::Body;
7use http::header::UPGRADE;
8use http::{HeaderMap, Method, Request, Response, StatusCode};
9use http_body_util::Either;
10use hyper::body::Incoming;
11use tower_service::Service;
12
13use super::ViteDev;
14
15/// The response body of a [`ViteProxy`]: Vite's or the app's.
16pub type ViteBody<B> = Either<Incoming, B>;
17
18/// The Tower service of [`ViteDev::proxy`].
19///
20/// `GET` and `HEAD` requests go to the Vite dev server first, which answers
21/// browser modules, its HMR client and public files; a 404 from Vite, a
22/// request it cannot be reached for, and every other method go to the app.
23/// So do WebSocket upgrades, which the app may accept: the browser opens
24/// Vite's HMR socket on Vite's own port, and Vite would hold an upgrade it
25/// does not serve without answering.
26/// Requests under `/@fetchlet/` other than the client entry stay with the
27/// app, so the runner's endpoints are not reachable through the proxy.
28#[derive(Clone)]
29pub struct ViteProxy<S> {
30    vite: ViteDev,
31    app: S,
32}
33
34impl<S> fmt::Debug for ViteProxy<S> {
35    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
36        formatter
37            .debug_struct("ViteProxy")
38            .field("vite", &self.vite)
39            .finish_non_exhaustive()
40    }
41}
42
43impl<S> ViteProxy<S> {
44    pub(super) fn new(vite: ViteDev, app: S) -> Self {
45        Self { vite, app }
46    }
47}
48
49/// Whether Vite may answer a request for `path`.
50fn vite_may_answer(method: &Method, path: &str, headers: &HeaderMap) -> bool {
51    (method == Method::GET || method == Method::HEAD)
52        && (!path.starts_with("/@fetchlet/") || path == "/@fetchlet/client")
53        && !headers.contains_key(UPGRADE)
54}
55
56impl<S, ReqBody, ResBody> Service<Request<ReqBody>> for ViteProxy<S>
57where
58    S: Service<Request<ReqBody>, Response = Response<ResBody>> + Clone + Send + 'static,
59    S::Future: Send + 'static,
60    S::Error: Send + 'static,
61    ReqBody: Send + 'static,
62{
63    type Response = Response<ViteBody<ResBody>>;
64
65    type Error = S::Error;
66
67    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, S::Error>> + Send>>;
68
69    fn poll_ready(&mut self, _context: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
70        // Each request clones the app and waits for its readiness.
71        Poll::Ready(Ok(()))
72    }
73
74    fn call(&mut self, request: Request<ReqBody>) -> Self::Future {
75        let vite = self.vite.clone();
76        let mut app = self.app.clone();
77        Box::pin(async move {
78            if vite_may_answer(request.method(), request.uri().path(), request.headers()) {
79                let mut forwarded = Request::new(Body::empty());
80                *forwarded.method_mut() = request.method().clone();
81                *forwarded.uri_mut() = vite.uri(request.uri().path_and_query());
82                *forwarded.headers_mut() = request.headers().clone();
83                forwarded
84                    .headers_mut()
85                    .insert(http::header::HOST, vite.host());
86                if let Ok(response) = vite.client().request(forwarded).await
87                    && response.status() != StatusCode::NOT_FOUND
88                {
89                    return Ok(response.map(Either::Left));
90                }
91            }
92            poll_fn(|context| app.poll_ready(context)).await?;
93            let response = app.call(request).await?;
94            Ok(response.map(Either::Right))
95        })
96    }
97}
98
99#[cfg(test)]
100mod tests {
101    use super::*;
102
103    #[test]
104    fn keeps_the_runner_endpoints_from_the_browser() {
105        let none = HeaderMap::new();
106        assert!(vite_may_answer(&Method::GET, "/src/client.ts", &none));
107        assert!(vite_may_answer(&Method::HEAD, "/@vite/client", &none));
108        assert!(vite_may_answer(&Method::GET, "/@fetchlet/client", &none));
109        assert!(!vite_may_answer(
110            &Method::GET,
111            "/@fetchlet/artifact/server.js",
112            &none
113        ));
114        assert!(!vite_may_answer(&Method::POST, "/@fetchlet/invoke", &none));
115        assert!(!vite_may_answer(&Method::POST, "/api/echo", &none));
116    }
117
118    #[test]
119    fn leaves_upgrades_to_the_app() {
120        let mut upgrade = HeaderMap::new();
121        upgrade.insert(UPGRADE, http::HeaderValue::from_static("websocket"));
122        assert!(!vite_may_answer(&Method::GET, "/api/socket", &upgrade));
123    }
124}