Skip to main content

fetchlet_http/axum_server/
server.rs

1use std::future::Future;
2use std::net::SocketAddr;
3use std::num::NonZeroUsize;
4use std::path::{Path, PathBuf};
5use std::sync::Arc;
6
7use axum::Router;
8use tokio::net::TcpListener;
9
10use fetchlet::{
11    App, AppHandle, Backend, CancelledCalls, HostServices, Instances, Limits, Module, WorkerOptions,
12};
13
14use super::{AxumService, artifact_router};
15use crate::artifact::{
16    DEFAULT_BOA_RECURSION, DEFAULT_BOA_STACK_SLOTS, DEFAULT_HEAP_BYTES,
17    DEFAULT_QUICKJS_STACK_BYTES, MINIMUM_STACK_FOR_DEFAULT_LIMITS,
18};
19use crate::{Artifact, ArtifactError, WebviewResponder, WebviewScheme};
20
21/// Format an artifact directory path for diagnostics, including the resolved
22/// path against the current working directory when `path` is relative.
23fn format_artifact_path(path: &Path) -> String {
24    if path.is_relative()
25        && let Ok(cwd) = std::env::current_dir()
26    {
27        return format!(
28            "{} (resolved to {})",
29            path.display(),
30            cwd.join(path).display()
31        );
32    }
33    path.display().to_string()
34}
35
36/// The environment variable that names a Vite dev server to run from, read
37/// when the `vite-dev` feature is enabled.
38pub const VITE_URL_VARIABLE: &str = "FETCHLET_VITE_URL";
39
40type ServicesFn = dyn Fn() -> fetchlet::Result<HostServices> + Send + Sync;
41type RenderingFn = dyn Fn(AxumService) -> AxumService + Send + Sync;
42type RoutesFn = dyn Fn(&AppHandle) -> Router + Send + Sync;
43
44/// A failure to start serving.
45#[derive(Debug, thiserror::Error)]
46#[non_exhaustive]
47pub enum ServerError {
48    #[error(
49        "could not open the build in {}: {source}; build the frontend before starting the server",
50        format_artifact_path(directory)
51    )]
52    Artifact {
53        directory: PathBuf,
54        source: ArtifactError,
55    },
56    #[error("could not start the application: {0}")]
57    App(#[from] fetchlet::Error),
58    #[error("invalid public origin: {0}")]
59    PublicOrigin(#[from] crate::Error),
60    #[error(transparent)]
61    Io(#[from] std::io::Error),
62    #[cfg(feature = "dev-reload")]
63    #[error(transparent)]
64    Reload(#[from] crate::ReloadError),
65    #[cfg(feature = "vite-dev")]
66    #[error("could not run from the Vite dev server at {url}: {source}")]
67    Vite {
68        url: String,
69        source: crate::ViteDevError,
70    },
71}
72
73enum ArtifactSource {
74    Directory(PathBuf),
75    Embedded {
76        artifact: Box<Artifact>,
77        dev_directory: Option<PathBuf>,
78    },
79}
80
81/// An axum server for one `fetchlet/build` artifact: Rust routes first, then
82/// the artifact's client assets, then the application.
83///
84/// ```rust,ignore
85/// let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await?;
86/// Server::new("build")
87///     .host_services(|| HostServices::new().env("MESSAGE", "Hello"))
88///     .routes(|_app| Router::new().route("/api/rust", get(rust_endpoint)))
89///     .serve(listener)
90///     .await?;
91/// ```
92///
93/// The engine is the one the artifact was built for. How the build is
94/// served follows the crate's features:
95///
96/// - With `vite-dev` and [`VITE_URL_VARIABLE`] set, the server module runs
97///   from that Vite dev server through [`ViteDev`](crate::ViteDev), which
98///   also serves the browser modules, and console output goes to standard
99///   error. A request the client cancels runs to its end
100///   ([`CancelledCalls::Finish`]), since a new instance would load every
101///   module from Vite again.
102/// - Otherwise, with `dev`, [`DevReload`](crate::DevReload) serves each build
103///   written to the directory and reloads open pages.
104/// - Otherwise the build is opened once.
105///
106/// Keep `dev` and `vite-dev` out of release builds.
107pub struct Server {
108    source: ArtifactSource,
109    backend: Option<Backend>,
110    services: Arc<ServicesFn>,
111    routes: Arc<RoutesFn>,
112    limits: Limits,
113    worker: Option<WorkerOptions>,
114    queue_capacity: Option<NonZeroUsize>,
115    instances: Option<Instances>,
116    public_origin: Option<String>,
117    rendering: Arc<RenderingFn>,
118    #[cfg(feature = "process")]
119    isolation: fetchlet::Isolation,
120}
121
122impl Server {
123    /// A server for the artifact in `directory`, the output directory of
124    /// `fetchlet/build`. A relative path is resolved against the working
125    /// directory.
126    pub fn new(directory: impl Into<PathBuf>) -> Self {
127        Self::with_source(ArtifactSource::Directory(directory.into()))
128    }
129
130    /// A server for an already-opened or embedded [`Artifact`], such as one
131    /// created with [`include_artifact!`](crate::include_artifact).
132    ///
133    /// Combine with [`dev_directory`](Self::dev_directory) to reload from a
134    /// build directory when `dev-reload` is enabled while serving the embedded
135    /// artifact in release builds without `#[cfg]` branches.
136    pub fn from_artifact(artifact: Artifact) -> Self {
137        Self::with_source(ArtifactSource::Embedded {
138            artifact: Box::new(artifact),
139            dev_directory: None,
140        })
141    }
142
143    /// When built with `dev-reload` and started from an embedded artifact via
144    /// [`from_artifact`](Self::from_artifact), watch and reload builds from
145    /// `directory` instead of serving the embedded copy. Ignored when
146    /// `dev-reload` is disabled.
147    pub fn dev_directory(mut self, directory: impl Into<PathBuf>) -> Self {
148        if let ArtifactSource::Embedded { dev_directory, .. } = &mut self.source {
149            *dev_directory = Some(directory.into());
150        }
151        self
152    }
153
154    fn with_source(source: ArtifactSource) -> Self {
155        Self {
156            source,
157            backend: None,
158            services: Arc::new(|| Ok(HostServices::new())),
159            routes: Arc::new(|_| Router::new()),
160            limits: Self::default_limits(),
161            worker: None,
162            queue_capacity: None,
163            instances: None,
164            public_origin: None,
165            rendering: Arc::new(|service| service),
166            #[cfg(feature = "process")]
167            isolation: fetchlet::Isolation::default(),
168        }
169    }
170
171    /// The engine and its options. By default, the engine the artifact was
172    /// built for, through [`Backend::for_target`]; on QuickJS or V8 the
173    /// limits then get a 64 MiB `Limits::heap_bytes` unless they set one.
174    /// While the worker keeps its default stack, QuickJS also gets a 4 MiB
175    /// stack limit and Boa a value stack of 131,072 slots and a recursion
176    /// limit of 10,000 calls. A backend given here is used as it is, with
177    /// the limits as they are. `V8Options::reliable_termination` stays off
178    /// unless a backend given here sets it.
179    pub fn backend(mut self, backend: Backend) -> Self {
180        self.backend = Some(backend);
181        self
182    }
183
184    /// The host services, made once for each application the server starts:
185    /// one, or one per build under `dev`.
186    pub fn host_services(
187        mut self,
188        services: impl Fn() -> fetchlet::Result<HostServices> + Send + Sync + 'static,
189    ) -> Self {
190        self.services = Arc::new(services);
191        self
192    }
193
194    /// Rust routes, which answer before the artifact's assets and the
195    /// application. They are made for each application the server starts,
196    /// whose handle they receive, so a route can call the module's named
197    /// exports with [`AppHandle::call_json`].
198    pub fn routes(mut self, routes: impl Fn(&AppHandle) -> Router + Send + Sync + 'static) -> Self {
199        self.routes = Arc::new(routes);
200        self
201    }
202
203    /// The application's caller budgets, used as they are.
204    /// [`Server::default_limits`] by default; start from it to keep its
205    /// timeouts, or from [`Limits::default`] to run without them.
206    pub fn limits(mut self, limits: Limits) -> Self {
207        self.limits = limits;
208        self
209    }
210
211    /// The limits a server has unless [`limits`](Self::limits) replaces
212    /// them: a 10 s `busy_timeout` and a 60 s `startup_timeout`, which retire
213    /// an instance whose JavaScript stops returning to the event loop or
214    /// whose module never finishes evaluating; no others.
215    pub fn default_limits() -> Limits {
216        Artifact::default_limits()
217    }
218
219    /// The application's worker options. By default, a queue of 8 commands,
220    /// one instance and a 64 MiB native stack for each worker thread.
221    pub fn worker(mut self, worker: WorkerOptions) -> Self {
222        self.worker = Some(worker);
223        self
224    }
225
226    /// Commands queued behind the running call, keeping the rest of the
227    /// worker options. 8 by default.
228    pub fn queue_capacity(mut self, capacity: NonZeroUsize) -> Self {
229        self.queue_capacity = Some(capacity);
230        self
231    }
232
233    /// The instances that serve requests, keeping the rest of the worker
234    /// options. One by default. Each runs one request at a time and has its
235    /// own engine heap and module state; see [`Instances`].
236    pub fn instances(mut self, instances: Instances) -> Self {
237        self.instances = Some(instances);
238        self
239    }
240
241    /// Where each instance's engine runs. In this process by default. Under
242    /// [`Isolation::Process`](fetchlet::Isolation::Process), each instance
243    /// runs in a child process, which the server's executable serves when
244    /// `main` calls [`fetchlet::serve_if_child`] first. Unless the options
245    /// set `ProcessOptions::stack_bytes`, the child's engine thread gets the
246    /// worker's native stack, which the default engine stack limits need.
247    #[cfg(feature = "process")]
248    pub fn isolation(mut self, isolation: fetchlet::Isolation) -> Self {
249        self.isolation = isolation;
250        self
251    }
252
253    /// The origin the application sees in request URLs, such as the one a
254    /// proxy serves it under. By default, `http://` and the listener's
255    /// address.
256    pub fn public_origin(mut self, origin: impl Into<String>) -> Self {
257        self.public_origin = Some(origin.into());
258        self
259    }
260
261    /// Adjust the service that passes requests to the application, such as
262    /// with [`AxumService::stream_request_bodies`] or
263    /// [`AxumService::trusted_context`]. Errors are written to standard
264    /// error before this runs.
265    pub fn rendering(
266        mut self,
267        configure: impl Fn(AxumService) -> AxumService + Send + Sync + 'static,
268    ) -> Self {
269        self.rendering = Arc::new(configure);
270        self
271    }
272
273    /// Start the application for a webview's custom URI scheme, such as
274    /// Tauri's, instead of a listener. The application sees the scheme's
275    /// origin unless [`public_origin`](Self::public_origin) names another.
276    /// `response_body_bytes` bounds each response the webview receives
277    /// whole ([`WebviewResponder`]).
278    ///
279    /// With `dev`, each build written to the directory serves the next
280    /// request, and [`Webview::reloads`] tells the host when to reload its
281    /// window; pages get no reload script. `vite-dev` does not apply.
282    pub async fn webview(
283        self,
284        scheme: WebviewScheme,
285        response_body_bytes: usize,
286    ) -> Result<Webview, ServerError> {
287        let origin = self
288            .public_origin
289            .clone()
290            .unwrap_or_else(|| scheme.origin());
291        let (settings, services, source) = self.into_settings(origin);
292
293        let builds = match source {
294            ArtifactSource::Directory(directory) => {
295                #[cfg(feature = "dev-reload")]
296                {
297                    WebviewBuilds::Reloading(
298                        start_webview_reload(directory, settings, services).await?,
299                    )
300                }
301                #[cfg(not(feature = "dev-reload"))]
302                {
303                    let artifact = open(&directory)?;
304                    let (router, app) = settings.application(&artifact, services()?).await?;
305                    WebviewBuilds::Static(Built { router, app })
306                }
307            }
308            ArtifactSource::Embedded {
309                artifact,
310                dev_directory,
311            } => {
312                #[cfg(feature = "dev-reload")]
313                if let Some(directory) = dev_directory {
314                    WebviewBuilds::Reloading(
315                        start_webview_reload(directory, settings, services).await?,
316                    )
317                } else {
318                    let (router, app) = settings.application(&artifact, services()?).await?;
319                    WebviewBuilds::Static(Built { router, app })
320                }
321                #[cfg(not(feature = "dev-reload"))]
322                {
323                    let _ = dev_directory;
324                    let (router, app) = settings.application(&artifact, services()?).await?;
325                    WebviewBuilds::Static(Built { router, app })
326                }
327            }
328        };
329        Ok(Webview {
330            inner: Arc::new(WebviewInner {
331                builds,
332                response_body_bytes,
333            }),
334        })
335    }
336
337    fn into_settings(self, origin: String) -> (Arc<Settings>, Arc<ServicesFn>, ArtifactSource) {
338        let settings = Arc::new(Settings {
339            backend: self.backend,
340            routes: self.routes,
341            limits: self.limits,
342            worker: self.worker,
343            queue_capacity: self.queue_capacity,
344            instances: self.instances,
345            origin,
346            rendering: self.rendering,
347            #[cfg(feature = "process")]
348            isolation: self.isolation,
349        });
350        (settings, self.services, self.source)
351    }
352
353    /// Serve on `listener` until Ctrl-C, then shut the application down.
354    pub async fn serve(self, listener: TcpListener) -> Result<(), ServerError> {
355        self.serve_with_shutdown(listener, async {
356            if let Err(error) = tokio::signal::ctrl_c().await {
357                eprintln!("fetchlet: could not listen for Ctrl-C: {error}");
358                std::future::pending::<()>().await;
359            }
360        })
361        .await
362    }
363
364    /// Serve on `listener` until `signal` completes, finish the requests in
365    /// progress, then shut the application down.
366    pub async fn serve_with_shutdown(
367        self,
368        listener: TcpListener,
369        signal: impl Future<Output = ()> + Send + 'static,
370    ) -> Result<(), ServerError> {
371        let origin = match &self.public_origin {
372            Some(origin) => origin.clone(),
373            None => format!("http://{}", listener.local_addr()?),
374        };
375        let (settings, services, source) = self.into_settings(origin);
376
377        #[cfg(feature = "vite-dev")]
378        if let Ok(url) = std::env::var(VITE_URL_VARIABLE) {
379            return serve_vite(listener, signal, &settings, &services, &url).await;
380        }
381
382        match source {
383            ArtifactSource::Directory(directory) => {
384                #[cfg(feature = "dev-reload")]
385                return serve_reloading(listener, signal, settings, services, directory).await;
386
387                #[cfg(not(feature = "dev-reload"))]
388                {
389                    let artifact = open(&directory)?;
390                    serve_static(listener, signal, &settings, &services, &artifact).await
391                }
392            }
393            ArtifactSource::Embedded {
394                artifact,
395                dev_directory,
396            } => {
397                #[cfg(feature = "dev-reload")]
398                if let Some(directory) = dev_directory {
399                    return serve_reloading(listener, signal, settings, services, directory).await;
400                }
401                let _ = dev_directory;
402                serve_static(listener, signal, &settings, &services, &artifact).await
403            }
404        }
405    }
406}
407
408/// A [`Server`] started for a webview's custom URI scheme: answers its
409/// requests and holds the application. Clones share it.
410///
411/// ```rust,ignore
412/// const SCHEME: WebviewScheme = WebviewScheme::new("app");
413/// let webview = Server::new("build").webview(SCHEME, 16 << 20).await?;
414/// tauri::Builder::default()
415///     .register_asynchronous_uri_scheme_protocol(SCHEME.name(), move |_, request, responder| {
416///         let webview = webview.clone();
417///         tauri::async_runtime::spawn(async move {
418///             responder.respond(webview.respond(request).await);
419///         });
420///     })
421/// ```
422#[derive(Clone)]
423pub struct Webview {
424    inner: Arc<WebviewInner>,
425}
426
427enum WebviewBuilds {
428    #[cfg(feature = "dev-reload")]
429    Reloading(crate::DevReload<Built>),
430    Static(Built),
431}
432
433struct WebviewInner {
434    builds: WebviewBuilds,
435    response_body_bytes: usize,
436}
437
438/// One build's routes and application.
439#[derive(Clone)]
440struct Built {
441    router: Router,
442    app: AppHandle,
443}
444
445impl Webview {
446    /// The response to a webview request, from the build current when it
447    /// arrives: Rust routes, then client assets, then the application.
448    pub async fn respond(&self, request: http::Request<Vec<u8>>) -> http::Response<Vec<u8>> {
449        WebviewResponder::new(|| self.router(), self.inner.response_body_bytes)
450            .respond(request)
451            .await
452    }
453
454    /// The routes of the current build, for a host that answers its
455    /// requests itself.
456    pub fn router(&self) -> Router {
457        self.current().router
458    }
459
460    /// The application of the current build, whose named exports Rust can
461    /// call with [`AppHandle::call`].
462    pub fn app(&self) -> AppHandle {
463        self.current().app
464    }
465
466    /// Each new build from now on, for the host to reload its window.
467    /// Ends immediately when started from an embedded artifact without
468    /// [`Server::dev_directory`].
469    #[cfg(feature = "dev-reload")]
470    pub fn reloads(&self) -> crate::Reloads {
471        match &self.inner.builds {
472            WebviewBuilds::Reloading(reload) => reload.reloads(),
473            WebviewBuilds::Static(_) => crate::Reloads::closed(),
474        }
475    }
476
477    /// Shut the application down; requests after this fail.
478    pub async fn shutdown(&self) -> Result<(), ServerError> {
479        match &self.inner.builds {
480            #[cfg(feature = "dev-reload")]
481            WebviewBuilds::Reloading(reload) => reload.shutdown().await?,
482            WebviewBuilds::Static(built) => built.app.shutdown().await?,
483        }
484        Ok(())
485    }
486
487    fn current(&self) -> Built {
488        match &self.inner.builds {
489            #[cfg(feature = "dev-reload")]
490            WebviewBuilds::Reloading(reload) => reload.current(),
491            WebviewBuilds::Static(built) => built.clone(),
492        }
493    }
494}
495
496/// What every application of one server shares.
497struct Settings {
498    backend: Option<Backend>,
499    routes: Arc<RoutesFn>,
500    limits: Limits,
501    worker: Option<WorkerOptions>,
502    queue_capacity: Option<NonZeroUsize>,
503    instances: Option<Instances>,
504    origin: String,
505    rendering: Arc<RenderingFn>,
506    #[cfg(feature = "process")]
507    isolation: fetchlet::Isolation,
508}
509
510impl Settings {
511    /// Start the application for `artifact` and route to it.
512    async fn application(
513        &self,
514        artifact: &Artifact,
515        services: HostServices,
516    ) -> Result<(Router, AppHandle), ServerError> {
517        self.start(artifact, services, None).await
518    }
519
520    /// [`application`](Self::application), with the worker's
521    /// `cancelled_calls` replaced when given.
522    async fn start(
523        &self,
524        artifact: &Artifact,
525        services: HostServices,
526        cancelled_calls: Option<CancelledCalls>,
527    ) -> Result<(Router, AppHandle), ServerError> {
528        let mut worker = self
529            .worker
530            .clone()
531            .unwrap_or_else(Artifact::default_worker_options);
532        if let Some(capacity) = self.queue_capacity {
533            worker.queue_capacity = capacity;
534        }
535        if let Some(instances) = self.instances {
536            worker.instances = instances;
537        }
538        if let Some(cancelled_calls) = cancelled_calls {
539            worker.cancelled_calls = cancelled_calls;
540        }
541        let mut limits = self.limits.clone();
542        let backend = match self.backend {
543            Some(backend) => backend,
544            None => {
545                let backend = default_backend(artifact, &worker)?;
546                if backend.bounds_heap() {
547                    limits.heap_bytes.get_or_insert(DEFAULT_HEAP_BYTES);
548                }
549                backend
550            }
551        };
552        let mut builder =
553            App::builder(backend)
554                .module(
555                    Module::new(artifact.server_source().map_err(|source| {
556                        ServerError::Artifact {
557                            directory: artifact.directory().map(PathBuf::from).unwrap_or_default(),
558                            source,
559                        }
560                    })?)
561                    .requires(artifact.requirements()),
562                )
563                .fetch_handler(artifact.handler())
564                .host_services(services)
565                .limits(limits);
566        #[cfg(feature = "process")]
567        {
568            let mut isolation = self.isolation.clone();
569            if let fetchlet::Isolation::Process(options) = &mut isolation
570                && options.stack_bytes.is_none()
571            {
572                options.stack_bytes = worker.stack_size_bytes.map(NonZeroUsize::get);
573            }
574            builder = builder.isolation(isolation);
575        }
576        // Host transport tasks, such as pooled connections, run on the
577        // server's runtime, so no instance's JavaScript holds them up. A
578        // current-thread runtime progresses only while its own thread waits,
579        // so it is left to the workers.
580        if let Ok(runtime) = tokio::runtime::Handle::try_current()
581            && runtime.runtime_flavor() == tokio::runtime::RuntimeFlavor::MultiThread
582        {
583            builder = builder.host_runtime(runtime);
584        }
585        let app = builder.spawn(worker).await?;
586        let rendering = AxumService::new(app.clone(), &self.origin)?
587            .on_error(|error| eprintln!("fetchlet: request failed: {error:#}"));
588        let rendering = (self.rendering)(rendering);
589        let router = (self.routes)(&app).merge(artifact_router(artifact, rendering));
590        Ok((router, app))
591    }
592}
593
594/// The artifact's own engine, with QuickJS and Boa stack limits that fit
595/// the default worker stack.
596fn default_backend(artifact: &Artifact, worker: &WorkerOptions) -> Result<Backend, ServerError> {
597    let backend = Backend::for_target(artifact.backend().unwrap_or("portable"))?;
598    if worker.stack_size_bytes >= Some(MINIMUM_STACK_FOR_DEFAULT_LIMITS) {
599        return Ok(backend
600            .with_default_quickjs_stack(DEFAULT_QUICKJS_STACK_BYTES)
601            .with_default_boa_stack(DEFAULT_BOA_STACK_SLOTS, DEFAULT_BOA_RECURSION));
602    }
603    Ok(backend)
604}
605
606#[cfg(not(feature = "dev-reload"))]
607fn open(directory: &std::path::Path) -> Result<Artifact, ServerError> {
608    Artifact::open(directory).map_err(|source| ServerError::Artifact {
609        directory: directory.to_path_buf(),
610        source,
611    })
612}
613
614async fn serve_static(
615    listener: TcpListener,
616    signal: impl Future<Output = ()> + Send + 'static,
617    settings: &Settings,
618    services: &Arc<ServicesFn>,
619    artifact: &Artifact,
620) -> Result<(), ServerError> {
621    let (router, app) = settings.application(artifact, services()?).await?;
622    let result = run(listener, router, signal).await;
623    app.shutdown().await?;
624    result
625}
626
627#[cfg(feature = "dev-reload")]
628async fn start_webview_reload(
629    directory: PathBuf,
630    settings: Arc<Settings>,
631    services: Arc<ServicesFn>,
632) -> Result<crate::DevReload<Built>, ServerError> {
633    use crate::{DevReload, Generation, ReloadError};
634
635    DevReload::watch(directory.clone())
636        .start(move |artifact| {
637            let (settings, services) = (settings.clone(), services.clone());
638            async move {
639                let (router, app) = settings.application(&artifact, services()?).await?;
640                let built = Built {
641                    router,
642                    app: app.clone(),
643                };
644                Ok::<_, ServerError>(Generation::new(built).with_app(app))
645            }
646        })
647        .await
648        .map_err(|error| match error {
649            ReloadError::Artifact(source) => ServerError::Artifact { directory, source },
650            error => ServerError::Reload(error),
651        })
652}
653
654async fn run(
655    listener: TcpListener,
656    router: Router,
657    signal: impl Future<Output = ()> + Send + 'static,
658) -> Result<(), ServerError> {
659    axum::serve(
660        listener,
661        router.into_make_service_with_connect_info::<SocketAddr>(),
662    )
663    .with_graceful_shutdown(signal)
664    .await?;
665    Ok(())
666}
667
668/// Serve each build written to `directory`.
669#[cfg(feature = "dev-reload")]
670async fn serve_reloading(
671    listener: TcpListener,
672    signal: impl Future<Output = ()> + Send + 'static,
673    settings: Arc<Settings>,
674    services: Arc<ServicesFn>,
675    directory: PathBuf,
676) -> Result<(), ServerError> {
677    use crate::{DevReload, Generation, ReloadError};
678
679    let reload = DevReload::watch(directory.clone())
680        .start(move |artifact| {
681            let (settings, services) = (settings.clone(), services.clone());
682            async move {
683                let (router, app) = settings.application(&artifact, services()?).await?;
684                Ok::<_, ServerError>(Generation::new(router).with_app(app))
685            }
686        })
687        .await
688        .map_err(|error| match error {
689            ReloadError::Artifact(source) => ServerError::Artifact { directory, source },
690            error => ServerError::Reload(error),
691        })?;
692    let result = run(
693        listener,
694        Router::new().fallback_service(reload.service()),
695        signal,
696    )
697    .await;
698    reload.shutdown().await?;
699    result
700}
701
702/// Run the server module from the Vite dev server at `url`.
703#[cfg(feature = "vite-dev")]
704async fn serve_vite(
705    listener: TcpListener,
706    signal: impl Future<Output = ()> + Send + 'static,
707    settings: &Settings,
708    services: &Arc<ServicesFn>,
709    url: &str,
710) -> Result<(), ServerError> {
711    use crate::ViteDev;
712
713    let failed = |source| ServerError::Vite {
714        url: url.into(),
715        source,
716    };
717    let vite = ViteDev::new(url).map_err(failed)?;
718    let artifact = vite.artifact().await.map_err(failed)?;
719    // Development shows what the server module logs.
720    let services = vite
721        .host_services(services()?)?
722        .console(|level, message| eprintln!("[{level:?}] {message}"));
723    // A new instance fetches and evaluates every module from Vite again, so
724    // a cancelled request finishes in the instance instead of retiring it.
725    let (router, app) = settings
726        .start(&artifact, services, Some(CancelledCalls::Finish))
727        .await?;
728    let result = run(
729        listener,
730        Router::new().fallback_service(vite.proxy(router)),
731        signal,
732    )
733    .await;
734    app.shutdown().await?;
735    result
736}