Skip to main content

fetchlet_http/vite_dev/
connection.rs

1use std::borrow::Cow;
2use std::fmt;
3use std::time::Duration;
4
5use bytes::Bytes;
6use fetchlet::{Body, FetchPolicy, FetchService, HostServices, transport_fn};
7use http::uri::{Authority, PathAndQuery, Scheme};
8use http::{HeaderValue, Method, Request, StatusCode, Uri};
9use http_body_util::{BodyExt, Empty};
10use hyper_util::client::legacy::Client;
11use hyper_util::client::legacy::connect::HttpConnector;
12use hyper_util::rt::{TokioExecutor, TokioTimer};
13use tokio::runtime::Handle;
14
15use super::ViteProxy;
16use crate::{Artifact, ArtifactError};
17
18/// The binding name through which the development artifact reaches the Vite
19/// dev server; `fetchlet/vite/dev-runner` reads the same name.
20pub const VITE_BINDING: &str = "FETCHLET_VITE";
21
22/// How long an idle connection to the dev server is kept for reuse. Node's
23/// HTTP server, Vite's included, closes a keep-alive connection after 5
24/// seconds of idleness (`server.keepAliveTimeout`), and a request sent as it
25/// closes fails without a retry. The engine's runner can stay longer than
26/// that between requests while it evaluates a large module, so the client
27/// gives connections up first.
28const IDLE_CONNECTION: Duration = Duration::from_secs(2);
29
30/// The origin the development artifact addresses the binding with. It never
31/// resolves; the binding sends each request to the Vite dev server.
32const BINDING_ORIGIN: &str = "http://vite.fetchlet.internal";
33
34/// Where `fetchlet/vite` serves the development artifact.
35const ARTIFACT_PATH: &str = "/@fetchlet/artifact/";
36
37/// A failure to reach the Vite dev server or to read what it served.
38#[derive(Debug, thiserror::Error)]
39pub enum ViteDevError {
40    /// The URL is not an `http` origin.
41    #[error("the Vite dev server URL {0} is not an http origin")]
42    Url(String),
43    /// The request did not complete.
44    #[error("the request to the Vite dev server for {path} failed: {message}")]
45    Request { path: String, message: String },
46    /// The server answered with an unexpected status.
47    #[error(
48        "the Vite dev server answered {path} with {status}; is fetchlet/vite one of its plugins?"
49    )]
50    Status { path: String, status: StatusCode },
51    /// The development artifact is not valid.
52    #[error(transparent)]
53    Artifact(#[from] ArtifactError),
54}
55
56/// A connection to a Vite dev server running `fetchlet/vite`, for
57/// development without a build.
58///
59/// [`artifact`](Self::artifact) reads a development artifact whose server
60/// module runs Vite's module runner in the engine and loads the app's server
61/// module from Vite on each call, so a server edit takes effect on the next
62/// request. [`host_services`](Self::host_services) adds the binding the runner
63/// reaches Vite through, beside the application's own services and their
64/// [`FetchPolicy`]s, and [`proxy`](Self::proxy) serves Vite's browser modules
65/// in front of the app.
66#[derive(Clone)]
67pub struct ViteDev {
68    scheme: Scheme,
69    authority: Authority,
70    client: Client<HttpConnector, Body>,
71    /// The runtime the runner's requests go out on; see [`ViteDev::new`].
72    runtime: Option<Handle>,
73}
74
75impl fmt::Debug for ViteDev {
76    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
77        formatter
78            .debug_struct("ViteDev")
79            .field(
80                "origin",
81                &format_args!("{}://{}", self.scheme, self.authority),
82            )
83            .finish_non_exhaustive()
84    }
85}
86
87impl ViteDev {
88    /// A connection to the Vite dev server at `url`, such as
89    /// `http://localhost:5173`. Nothing is requested until it is used.
90    ///
91    /// The engine's requests to the dev server go out on the Tokio runtime
92    /// `new` is called on, such as the HTTP server's. A pooled connection
93    /// is a task on the runtime that opened it, and each application worker
94    /// runs its own runtime, which stalls while its engine evaluates; a
95    /// connection another worker reused would stall with it.
96    pub fn new(url: &str) -> Result<Self, ViteDevError> {
97        let invalid = || ViteDevError::Url(url.into());
98        let uri: Uri = url.parse().map_err(|_| invalid())?;
99        let (Some(scheme), Some(authority)) = (uri.scheme(), uri.authority()) else {
100            return Err(invalid());
101        };
102        if *scheme != Scheme::HTTP {
103            return Err(invalid());
104        }
105        Ok(Self {
106            scheme: scheme.clone(),
107            authority: authority.clone(),
108            client: Client::builder(TokioExecutor::new())
109                .pool_timer(TokioTimer::new())
110                .pool_idle_timeout(IDLE_CONNECTION)
111                .build_http(),
112            runtime: Handle::try_current().ok(),
113        })
114    }
115
116    /// The development artifact, which the dev server builds for its
117    /// configured backend when first requested. It has no client directory;
118    /// browser modules come from Vite through [`proxy`](Self::proxy).
119    pub async fn artifact(&self) -> Result<Artifact, ViteDevError> {
120        let manifest = self.get(&format!("{ARTIFACT_PATH}fetchlet.json")).await?;
121        let path = format!("{ARTIFACT_PATH}server.js");
122        let server = String::from_utf8(self.get(&path).await?.to_vec()).map_err(|_| {
123            ViteDevError::Request {
124                path,
125                message: "the server module is not UTF-8".into(),
126            }
127        })?;
128        Ok(Artifact::embedded(&manifest, Cow::Owned(server), None)?)
129    }
130
131    /// `services` with the binding the development artifact loads modules
132    /// through. The binding accepts only its own origin and forwards to the
133    /// dev server; the application's services and policies are unchanged,
134    /// and the binding is hidden from the server module's `env`.
135    pub fn host_services(&self, services: HostServices) -> fetchlet::Result<HostServices> {
136        let policy = FetchPolicy::deny_all().allow_origin(BINDING_ORIGIN)?;
137        let connection = self.clone();
138        services.service(
139            VITE_BINDING,
140            FetchService::new(
141                transport_fn(move |request: fetchlet::Request| {
142                    let connection = connection.clone();
143                    async move { connection.forward(request).await }
144                }),
145                policy,
146            ),
147        )
148    }
149
150    /// A Tower service that answers the `GET` and `HEAD` requests Vite
151    /// serves, such as browser modules and public files, and passes every
152    /// other request, and whatever Vite answers with 404, to `app`.
153    pub fn proxy<S>(&self, app: S) -> ViteProxy<S> {
154        ViteProxy::new(self.clone(), app)
155    }
156
157    pub(super) fn uri(&self, path_and_query: Option<&PathAndQuery>) -> Uri {
158        let mut parts = http::uri::Parts::default();
159        parts.scheme = Some(self.scheme.clone());
160        parts.authority = Some(self.authority.clone());
161        parts.path_and_query = Some(
162            path_and_query
163                .cloned()
164                .unwrap_or_else(|| PathAndQuery::from_static("/")),
165        );
166        Uri::from_parts(parts).expect("a scheme, an authority and a path form a URI")
167    }
168
169    pub(super) fn host(&self) -> HeaderValue {
170        HeaderValue::from_str(self.authority.as_str()).expect("an authority is a header value")
171    }
172
173    pub(super) fn client(&self) -> &Client<HttpConnector, Body> {
174        &self.client
175    }
176
177    async fn get(&self, path: &str) -> Result<Bytes, ViteDevError> {
178        let failed = |message: String| ViteDevError::Request {
179            path: path.into(),
180            message,
181        };
182        let path_and_query = PathAndQuery::try_from(path).map_err(|e| failed(e.to_string()))?;
183        let request = Request::builder()
184            .method(Method::GET)
185            .uri(self.uri(Some(&path_and_query)))
186            .body(Body::from_http_body(Empty::<Bytes>::new()))
187            .map_err(|e| failed(e.to_string()))?;
188        let response = self
189            .client
190            .request(request)
191            .await
192            .map_err(|e| failed(e.to_string()))?;
193        if response.status() != StatusCode::OK {
194            return Err(ViteDevError::Status {
195                path: path.into(),
196                status: response.status(),
197            });
198        }
199        let body = response
200            .into_body()
201            .collect()
202            .await
203            .map_err(|e| failed(e.to_string()))?;
204        Ok(body.to_bytes())
205    }
206
207    /// Sends a request of the runner to the dev server, keeping its path.
208    async fn forward(&self, request: fetchlet::Request) -> fetchlet::Result<fetchlet::Response> {
209        let (mut parts, body) = request.into_parts();
210        parts.uri = self.uri(parts.uri.path_and_query());
211        parts.headers.insert(http::header::HOST, self.host());
212        let client = self.client.clone();
213        let request = Request::from_parts(parts, body);
214        let sent = async move { client.request(request).await };
215        let failed = |error: &dyn fmt::Display| {
216            fetchlet::Error::Transport(format!("Vite dev server: {error}"))
217        };
218        let response = match &self.runtime {
219            Some(runtime) => runtime.spawn(sent).await.map_err(|error| failed(&error))?,
220            None => sent.await,
221        }
222        .map_err(|error| failed(&error))?;
223        Ok(response.map(Body::from_http_body))
224    }
225}