Skip to main content

vertigo_testing/
serve.rs

1//! A build served in this process, as `vertigo serve` does it (SSR included), for apps that
2//! need no backend of their own.
3
4use std::path::Path;
5
6use actix_web::{App, HttpServer, dev::ServerHandle, rt::System};
7use anyhow::{Context, Result, anyhow};
8use vertigo_cli::serve::{MountConfigBuilder, ServerState, vertigo_install};
9
10pub struct Server {
11    /// `http://127.0.0.1:<port>`, without a trailing slash.
12    pub base_url: String,
13    handle: ServerHandle,
14}
15
16impl Server {
17    /// Serves `build_dir` at `/` on a free port. The directory is given by its absolute path,
18    /// so the static files are served under it.
19    pub async fn start(build_dir: &Path) -> Result<Self> {
20        let mount_config = MountConfigBuilder::new("/", build_dir.to_string_lossy())
21            .build()
22            .map_err(|err| anyhow!("can't read the build in {}: {err:?}", build_dir.display()))?;
23
24        // Compiles the wasm module for SSR, which takes a while for a debug build
25        {
26            let mount_config = mount_config.clone();
27            tokio::task::spawn_blocking(move || ServerState::init(&mount_config))
28                .await?
29                .map_err(|err| anyhow!("can't load {} for SSR: {err:?}", build_dir.display()))?;
30        }
31
32        let server = HttpServer::new(move || {
33            App::new().configure(|cfg| vertigo_install(cfg, &mount_config))
34        })
35        .workers(2)
36        .disable_signals()
37        .bind(("127.0.0.1", 0))
38        .context("can't open a port for the server")?;
39        let port = server
40            .addrs()
41            .first()
42            .context("the server has no address")?
43            .port();
44
45        let server = server.run();
46        let handle = server.handle();
47        // Like in `vertigo serve`, actix gets a thread with its own system
48        std::thread::spawn(move || System::new().block_on(server));
49
50        Ok(Self {
51            base_url: format!("http://127.0.0.1:{port}"),
52            handle,
53        })
54    }
55
56    pub async fn stop(&self) {
57        self.handle.stop(false).await;
58    }
59}