1use 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 pub base_url: String,
13 handle: ServerHandle,
14}
15
16impl Server {
17 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 {
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 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}