use std::future::Future;
use std::net::SocketAddr;
use std::num::NonZeroUsize;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use axum::Router;
use tokio::net::TcpListener;
use fetchlet::{
App, AppHandle, Backend, CancelledCalls, HostServices, Instances, Limits, Module, WorkerOptions,
};
use super::{AxumService, artifact_router};
use crate::artifact::{
DEFAULT_BOA_RECURSION, DEFAULT_BOA_STACK_SLOTS, DEFAULT_HEAP_BYTES,
DEFAULT_QUICKJS_STACK_BYTES, MINIMUM_STACK_FOR_DEFAULT_LIMITS,
};
use crate::{Artifact, ArtifactError, WebviewResponder, WebviewScheme};
fn format_artifact_path(path: &Path) -> String {
if path.is_relative()
&& let Ok(cwd) = std::env::current_dir()
{
return format!(
"{} (resolved to {})",
path.display(),
cwd.join(path).display()
);
}
path.display().to_string()
}
pub const VITE_URL_VARIABLE: &str = "FETCHLET_VITE_URL";
type ServicesFn = dyn Fn() -> fetchlet::Result<HostServices> + Send + Sync;
type RenderingFn = dyn Fn(AxumService) -> AxumService + Send + Sync;
type RoutesFn = dyn Fn(&AppHandle) -> Router + Send + Sync;
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum ServerError {
#[error(
"could not open the build in {}: {source}; build the frontend before starting the server",
format_artifact_path(directory)
)]
Artifact {
directory: PathBuf,
source: ArtifactError,
},
#[error("could not start the application: {0}")]
App(#[from] fetchlet::Error),
#[error("invalid public origin: {0}")]
PublicOrigin(#[from] crate::Error),
#[error(transparent)]
Io(#[from] std::io::Error),
#[cfg(feature = "dev-reload")]
#[error(transparent)]
Reload(#[from] crate::ReloadError),
#[cfg(feature = "vite-dev")]
#[error("could not run from the Vite dev server at {url}: {source}")]
Vite {
url: String,
source: crate::ViteDevError,
},
}
enum ArtifactSource {
Directory(PathBuf),
Embedded {
artifact: Box<Artifact>,
dev_directory: Option<PathBuf>,
},
}
pub struct Server {
source: ArtifactSource,
backend: Option<Backend>,
services: Arc<ServicesFn>,
routes: Arc<RoutesFn>,
limits: Limits,
worker: Option<WorkerOptions>,
queue_capacity: Option<NonZeroUsize>,
instances: Option<Instances>,
public_origin: Option<String>,
rendering: Arc<RenderingFn>,
#[cfg(feature = "process")]
isolation: fetchlet::Isolation,
}
impl Server {
pub fn new(directory: impl Into<PathBuf>) -> Self {
Self::with_source(ArtifactSource::Directory(directory.into()))
}
pub fn from_artifact(artifact: Artifact) -> Self {
Self::with_source(ArtifactSource::Embedded {
artifact: Box::new(artifact),
dev_directory: None,
})
}
pub fn dev_directory(mut self, directory: impl Into<PathBuf>) -> Self {
if let ArtifactSource::Embedded { dev_directory, .. } = &mut self.source {
*dev_directory = Some(directory.into());
}
self
}
fn with_source(source: ArtifactSource) -> Self {
Self {
source,
backend: None,
services: Arc::new(|| Ok(HostServices::new())),
routes: Arc::new(|_| Router::new()),
limits: Self::default_limits(),
worker: None,
queue_capacity: None,
instances: None,
public_origin: None,
rendering: Arc::new(|service| service),
#[cfg(feature = "process")]
isolation: fetchlet::Isolation::default(),
}
}
pub fn backend(mut self, backend: Backend) -> Self {
self.backend = Some(backend);
self
}
pub fn host_services(
mut self,
services: impl Fn() -> fetchlet::Result<HostServices> + Send + Sync + 'static,
) -> Self {
self.services = Arc::new(services);
self
}
pub fn routes(mut self, routes: impl Fn(&AppHandle) -> Router + Send + Sync + 'static) -> Self {
self.routes = Arc::new(routes);
self
}
pub fn limits(mut self, limits: Limits) -> Self {
self.limits = limits;
self
}
pub fn default_limits() -> Limits {
Artifact::default_limits()
}
pub fn worker(mut self, worker: WorkerOptions) -> Self {
self.worker = Some(worker);
self
}
pub fn queue_capacity(mut self, capacity: NonZeroUsize) -> Self {
self.queue_capacity = Some(capacity);
self
}
pub fn instances(mut self, instances: Instances) -> Self {
self.instances = Some(instances);
self
}
#[cfg(feature = "process")]
pub fn isolation(mut self, isolation: fetchlet::Isolation) -> Self {
self.isolation = isolation;
self
}
pub fn public_origin(mut self, origin: impl Into<String>) -> Self {
self.public_origin = Some(origin.into());
self
}
pub fn rendering(
mut self,
configure: impl Fn(AxumService) -> AxumService + Send + Sync + 'static,
) -> Self {
self.rendering = Arc::new(configure);
self
}
pub async fn webview(
self,
scheme: WebviewScheme,
response_body_bytes: usize,
) -> Result<Webview, ServerError> {
let origin = self
.public_origin
.clone()
.unwrap_or_else(|| scheme.origin());
let (settings, services, source) = self.into_settings(origin);
let builds = match source {
ArtifactSource::Directory(directory) => {
#[cfg(feature = "dev-reload")]
{
WebviewBuilds::Reloading(
start_webview_reload(directory, settings, services).await?,
)
}
#[cfg(not(feature = "dev-reload"))]
{
let artifact = open(&directory)?;
let (router, app) = settings.application(&artifact, services()?).await?;
WebviewBuilds::Static(Built { router, app })
}
}
ArtifactSource::Embedded {
artifact,
dev_directory,
} => {
#[cfg(feature = "dev-reload")]
if let Some(directory) = dev_directory {
WebviewBuilds::Reloading(
start_webview_reload(directory, settings, services).await?,
)
} else {
let (router, app) = settings.application(&artifact, services()?).await?;
WebviewBuilds::Static(Built { router, app })
}
#[cfg(not(feature = "dev-reload"))]
{
let _ = dev_directory;
let (router, app) = settings.application(&artifact, services()?).await?;
WebviewBuilds::Static(Built { router, app })
}
}
};
Ok(Webview {
inner: Arc::new(WebviewInner {
builds,
response_body_bytes,
}),
})
}
fn into_settings(self, origin: String) -> (Arc<Settings>, Arc<ServicesFn>, ArtifactSource) {
let settings = Arc::new(Settings {
backend: self.backend,
routes: self.routes,
limits: self.limits,
worker: self.worker,
queue_capacity: self.queue_capacity,
instances: self.instances,
origin,
rendering: self.rendering,
#[cfg(feature = "process")]
isolation: self.isolation,
});
(settings, self.services, self.source)
}
pub async fn serve(self, listener: TcpListener) -> Result<(), ServerError> {
self.serve_with_shutdown(listener, async {
if let Err(error) = tokio::signal::ctrl_c().await {
eprintln!("fetchlet: could not listen for Ctrl-C: {error}");
std::future::pending::<()>().await;
}
})
.await
}
pub async fn serve_with_shutdown(
self,
listener: TcpListener,
signal: impl Future<Output = ()> + Send + 'static,
) -> Result<(), ServerError> {
let origin = match &self.public_origin {
Some(origin) => origin.clone(),
None => format!("http://{}", listener.local_addr()?),
};
let (settings, services, source) = self.into_settings(origin);
#[cfg(feature = "vite-dev")]
if let Ok(url) = std::env::var(VITE_URL_VARIABLE) {
return serve_vite(listener, signal, &settings, &services, &url).await;
}
match source {
ArtifactSource::Directory(directory) => {
#[cfg(feature = "dev-reload")]
return serve_reloading(listener, signal, settings, services, directory).await;
#[cfg(not(feature = "dev-reload"))]
{
let artifact = open(&directory)?;
serve_static(listener, signal, &settings, &services, &artifact).await
}
}
ArtifactSource::Embedded {
artifact,
dev_directory,
} => {
#[cfg(feature = "dev-reload")]
if let Some(directory) = dev_directory {
return serve_reloading(listener, signal, settings, services, directory).await;
}
let _ = dev_directory;
serve_static(listener, signal, &settings, &services, &artifact).await
}
}
}
}
#[derive(Clone)]
pub struct Webview {
inner: Arc<WebviewInner>,
}
enum WebviewBuilds {
#[cfg(feature = "dev-reload")]
Reloading(crate::DevReload<Built>),
Static(Built),
}
struct WebviewInner {
builds: WebviewBuilds,
response_body_bytes: usize,
}
#[derive(Clone)]
struct Built {
router: Router,
app: AppHandle,
}
impl Webview {
pub async fn respond(&self, request: http::Request<Vec<u8>>) -> http::Response<Vec<u8>> {
WebviewResponder::new(|| self.router(), self.inner.response_body_bytes)
.respond(request)
.await
}
pub fn router(&self) -> Router {
self.current().router
}
pub fn app(&self) -> AppHandle {
self.current().app
}
#[cfg(feature = "dev-reload")]
pub fn reloads(&self) -> crate::Reloads {
match &self.inner.builds {
WebviewBuilds::Reloading(reload) => reload.reloads(),
WebviewBuilds::Static(_) => crate::Reloads::closed(),
}
}
pub async fn shutdown(&self) -> Result<(), ServerError> {
match &self.inner.builds {
#[cfg(feature = "dev-reload")]
WebviewBuilds::Reloading(reload) => reload.shutdown().await?,
WebviewBuilds::Static(built) => built.app.shutdown().await?,
}
Ok(())
}
fn current(&self) -> Built {
match &self.inner.builds {
#[cfg(feature = "dev-reload")]
WebviewBuilds::Reloading(reload) => reload.current(),
WebviewBuilds::Static(built) => built.clone(),
}
}
}
struct Settings {
backend: Option<Backend>,
routes: Arc<RoutesFn>,
limits: Limits,
worker: Option<WorkerOptions>,
queue_capacity: Option<NonZeroUsize>,
instances: Option<Instances>,
origin: String,
rendering: Arc<RenderingFn>,
#[cfg(feature = "process")]
isolation: fetchlet::Isolation,
}
impl Settings {
async fn application(
&self,
artifact: &Artifact,
services: HostServices,
) -> Result<(Router, AppHandle), ServerError> {
self.start(artifact, services, None).await
}
async fn start(
&self,
artifact: &Artifact,
services: HostServices,
cancelled_calls: Option<CancelledCalls>,
) -> Result<(Router, AppHandle), ServerError> {
let mut worker = self
.worker
.clone()
.unwrap_or_else(Artifact::default_worker_options);
if let Some(capacity) = self.queue_capacity {
worker.queue_capacity = capacity;
}
if let Some(instances) = self.instances {
worker.instances = instances;
}
if let Some(cancelled_calls) = cancelled_calls {
worker.cancelled_calls = cancelled_calls;
}
let mut limits = self.limits.clone();
let backend = match self.backend {
Some(backend) => backend,
None => {
let backend = default_backend(artifact, &worker)?;
if backend.bounds_heap() {
limits.heap_bytes.get_or_insert(DEFAULT_HEAP_BYTES);
}
backend
}
};
let mut builder =
App::builder(backend)
.module(
Module::new(artifact.server_source().map_err(|source| {
ServerError::Artifact {
directory: artifact.directory().map(PathBuf::from).unwrap_or_default(),
source,
}
})?)
.requires(artifact.requirements()),
)
.fetch_handler(artifact.handler())
.host_services(services)
.limits(limits);
#[cfg(feature = "process")]
{
let mut isolation = self.isolation.clone();
if let fetchlet::Isolation::Process(options) = &mut isolation
&& options.stack_bytes.is_none()
{
options.stack_bytes = worker.stack_size_bytes.map(NonZeroUsize::get);
}
builder = builder.isolation(isolation);
}
if let Ok(runtime) = tokio::runtime::Handle::try_current()
&& runtime.runtime_flavor() == tokio::runtime::RuntimeFlavor::MultiThread
{
builder = builder.host_runtime(runtime);
}
let app = builder.spawn(worker).await?;
let rendering = AxumService::new(app.clone(), &self.origin)?
.on_error(|error| eprintln!("fetchlet: request failed: {error:#}"));
let rendering = (self.rendering)(rendering);
let router = (self.routes)(&app).merge(artifact_router(artifact, rendering));
Ok((router, app))
}
}
fn default_backend(artifact: &Artifact, worker: &WorkerOptions) -> Result<Backend, ServerError> {
let backend = Backend::for_target(artifact.backend().unwrap_or("portable"))?;
if worker.stack_size_bytes >= Some(MINIMUM_STACK_FOR_DEFAULT_LIMITS) {
return Ok(backend
.with_default_quickjs_stack(DEFAULT_QUICKJS_STACK_BYTES)
.with_default_boa_stack(DEFAULT_BOA_STACK_SLOTS, DEFAULT_BOA_RECURSION));
}
Ok(backend)
}
#[cfg(not(feature = "dev-reload"))]
fn open(directory: &std::path::Path) -> Result<Artifact, ServerError> {
Artifact::open(directory).map_err(|source| ServerError::Artifact {
directory: directory.to_path_buf(),
source,
})
}
async fn serve_static(
listener: TcpListener,
signal: impl Future<Output = ()> + Send + 'static,
settings: &Settings,
services: &Arc<ServicesFn>,
artifact: &Artifact,
) -> Result<(), ServerError> {
let (router, app) = settings.application(artifact, services()?).await?;
let result = run(listener, router, signal).await;
app.shutdown().await?;
result
}
#[cfg(feature = "dev-reload")]
async fn start_webview_reload(
directory: PathBuf,
settings: Arc<Settings>,
services: Arc<ServicesFn>,
) -> Result<crate::DevReload<Built>, ServerError> {
use crate::{DevReload, Generation, ReloadError};
DevReload::watch(directory.clone())
.start(move |artifact| {
let (settings, services) = (settings.clone(), services.clone());
async move {
let (router, app) = settings.application(&artifact, services()?).await?;
let built = Built {
router,
app: app.clone(),
};
Ok::<_, ServerError>(Generation::new(built).with_app(app))
}
})
.await
.map_err(|error| match error {
ReloadError::Artifact(source) => ServerError::Artifact { directory, source },
error => ServerError::Reload(error),
})
}
async fn run(
listener: TcpListener,
router: Router,
signal: impl Future<Output = ()> + Send + 'static,
) -> Result<(), ServerError> {
axum::serve(
listener,
router.into_make_service_with_connect_info::<SocketAddr>(),
)
.with_graceful_shutdown(signal)
.await?;
Ok(())
}
#[cfg(feature = "dev-reload")]
async fn serve_reloading(
listener: TcpListener,
signal: impl Future<Output = ()> + Send + 'static,
settings: Arc<Settings>,
services: Arc<ServicesFn>,
directory: PathBuf,
) -> Result<(), ServerError> {
use crate::{DevReload, Generation, ReloadError};
let reload = DevReload::watch(directory.clone())
.start(move |artifact| {
let (settings, services) = (settings.clone(), services.clone());
async move {
let (router, app) = settings.application(&artifact, services()?).await?;
Ok::<_, ServerError>(Generation::new(router).with_app(app))
}
})
.await
.map_err(|error| match error {
ReloadError::Artifact(source) => ServerError::Artifact { directory, source },
error => ServerError::Reload(error),
})?;
let result = run(
listener,
Router::new().fallback_service(reload.service()),
signal,
)
.await;
reload.shutdown().await?;
result
}
#[cfg(feature = "vite-dev")]
async fn serve_vite(
listener: TcpListener,
signal: impl Future<Output = ()> + Send + 'static,
settings: &Settings,
services: &Arc<ServicesFn>,
url: &str,
) -> Result<(), ServerError> {
use crate::ViteDev;
let failed = |source| ServerError::Vite {
url: url.into(),
source,
};
let vite = ViteDev::new(url).map_err(failed)?;
let artifact = vite.artifact().await.map_err(failed)?;
let services = vite
.host_services(services()?)?
.console(|level, message| eprintln!("[{level:?}] {message}"));
let (router, app) = settings
.start(&artifact, services, Some(CancelledCalls::Finish))
.await?;
let result = run(
listener,
Router::new().fallback_service(vite.proxy(router)),
signal,
)
.await;
app.shutdown().await?;
result
}