use std::borrow::Cow;
use std::fmt;
use std::time::Duration;
use bytes::Bytes;
use fetchlet::{Body, FetchPolicy, FetchService, HostServices, transport_fn};
use http::uri::{Authority, PathAndQuery, Scheme};
use http::{HeaderValue, Method, Request, StatusCode, Uri};
use http_body_util::{BodyExt, Empty};
use hyper_util::client::legacy::Client;
use hyper_util::client::legacy::connect::HttpConnector;
use hyper_util::rt::{TokioExecutor, TokioTimer};
use tokio::runtime::Handle;
use super::ViteProxy;
use crate::{Artifact, ArtifactError};
pub const VITE_BINDING: &str = "FETCHLET_VITE";
const IDLE_CONNECTION: Duration = Duration::from_secs(2);
const BINDING_ORIGIN: &str = "http://vite.fetchlet.internal";
const ARTIFACT_PATH: &str = "/@fetchlet/artifact/";
#[derive(Debug, thiserror::Error)]
pub enum ViteDevError {
#[error("the Vite dev server URL {0} is not an http origin")]
Url(String),
#[error("the request to the Vite dev server for {path} failed: {message}")]
Request { path: String, message: String },
#[error(
"the Vite dev server answered {path} with {status}; is fetchlet/vite one of its plugins?"
)]
Status { path: String, status: StatusCode },
#[error(transparent)]
Artifact(#[from] ArtifactError),
}
#[derive(Clone)]
pub struct ViteDev {
scheme: Scheme,
authority: Authority,
client: Client<HttpConnector, Body>,
runtime: Option<Handle>,
}
impl fmt::Debug for ViteDev {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("ViteDev")
.field(
"origin",
&format_args!("{}://{}", self.scheme, self.authority),
)
.finish_non_exhaustive()
}
}
impl ViteDev {
pub fn new(url: &str) -> Result<Self, ViteDevError> {
let invalid = || ViteDevError::Url(url.into());
let uri: Uri = url.parse().map_err(|_| invalid())?;
let (Some(scheme), Some(authority)) = (uri.scheme(), uri.authority()) else {
return Err(invalid());
};
if *scheme != Scheme::HTTP {
return Err(invalid());
}
Ok(Self {
scheme: scheme.clone(),
authority: authority.clone(),
client: Client::builder(TokioExecutor::new())
.pool_timer(TokioTimer::new())
.pool_idle_timeout(IDLE_CONNECTION)
.build_http(),
runtime: Handle::try_current().ok(),
})
}
pub async fn artifact(&self) -> Result<Artifact, ViteDevError> {
let manifest = self.get(&format!("{ARTIFACT_PATH}fetchlet.json")).await?;
let path = format!("{ARTIFACT_PATH}server.js");
let server = String::from_utf8(self.get(&path).await?.to_vec()).map_err(|_| {
ViteDevError::Request {
path,
message: "the server module is not UTF-8".into(),
}
})?;
Ok(Artifact::embedded(&manifest, Cow::Owned(server), None)?)
}
pub fn host_services(&self, services: HostServices) -> fetchlet::Result<HostServices> {
let policy = FetchPolicy::deny_all().allow_origin(BINDING_ORIGIN)?;
let connection = self.clone();
services.service(
VITE_BINDING,
FetchService::new(
transport_fn(move |request: fetchlet::Request| {
let connection = connection.clone();
async move { connection.forward(request).await }
}),
policy,
),
)
}
pub fn proxy<S>(&self, app: S) -> ViteProxy<S> {
ViteProxy::new(self.clone(), app)
}
pub(super) fn uri(&self, path_and_query: Option<&PathAndQuery>) -> Uri {
let mut parts = http::uri::Parts::default();
parts.scheme = Some(self.scheme.clone());
parts.authority = Some(self.authority.clone());
parts.path_and_query = Some(
path_and_query
.cloned()
.unwrap_or_else(|| PathAndQuery::from_static("/")),
);
Uri::from_parts(parts).expect("a scheme, an authority and a path form a URI")
}
pub(super) fn host(&self) -> HeaderValue {
HeaderValue::from_str(self.authority.as_str()).expect("an authority is a header value")
}
pub(super) fn client(&self) -> &Client<HttpConnector, Body> {
&self.client
}
async fn get(&self, path: &str) -> Result<Bytes, ViteDevError> {
let failed = |message: String| ViteDevError::Request {
path: path.into(),
message,
};
let path_and_query = PathAndQuery::try_from(path).map_err(|e| failed(e.to_string()))?;
let request = Request::builder()
.method(Method::GET)
.uri(self.uri(Some(&path_and_query)))
.body(Body::from_http_body(Empty::<Bytes>::new()))
.map_err(|e| failed(e.to_string()))?;
let response = self
.client
.request(request)
.await
.map_err(|e| failed(e.to_string()))?;
if response.status() != StatusCode::OK {
return Err(ViteDevError::Status {
path: path.into(),
status: response.status(),
});
}
let body = response
.into_body()
.collect()
.await
.map_err(|e| failed(e.to_string()))?;
Ok(body.to_bytes())
}
async fn forward(&self, request: fetchlet::Request) -> fetchlet::Result<fetchlet::Response> {
let (mut parts, body) = request.into_parts();
parts.uri = self.uri(parts.uri.path_and_query());
parts.headers.insert(http::header::HOST, self.host());
let client = self.client.clone();
let request = Request::from_parts(parts, body);
let sent = async move { client.request(request).await };
let failed = |error: &dyn fmt::Display| {
fetchlet::Error::Transport(format!("Vite dev server: {error}"))
};
let response = match &self.runtime {
Some(runtime) => runtime.spawn(sent).await.map_err(|error| failed(&error))?,
None => sent.await,
}
.map_err(|error| failed(&error))?;
Ok(response.map(Body::from_http_body))
}
}