fetchlet_http/vite_dev/
connection.rs1use 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
18pub const VITE_BINDING: &str = "FETCHLET_VITE";
21
22const IDLE_CONNECTION: Duration = Duration::from_secs(2);
29
30const BINDING_ORIGIN: &str = "http://vite.fetchlet.internal";
33
34const ARTIFACT_PATH: &str = "/@fetchlet/artifact/";
36
37#[derive(Debug, thiserror::Error)]
39pub enum ViteDevError {
40 #[error("the Vite dev server URL {0} is not an http origin")]
42 Url(String),
43 #[error("the request to the Vite dev server for {path} failed: {message}")]
45 Request { path: String, message: String },
46 #[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 #[error(transparent)]
53 Artifact(#[from] ArtifactError),
54}
55
56#[derive(Clone)]
67pub struct ViteDev {
68 scheme: Scheme,
69 authority: Authority,
70 client: Client<HttpConnector, Body>,
71 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 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 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 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 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 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}