Skip to main content

vertigo_cli/serve/
serve_run.rs

1use actix_web::{
2    App, HttpServer,
3    middleware::{Compress, Condition, from_fn},
4    rt::System,
5};
6use std::{num::NonZeroUsize, time::Duration};
7
8use crate::commons::{
9    ErrorCode,
10    spawn::{ServerOwner, term_signal},
11};
12use crate::serve::{html::local_origin, mount_path::MountConfig};
13
14use super::{
15    ServeOpts, ServeOptsInner, proxy::install_proxy, server_state::ServerState,
16    vary::vary_accept_encoding, vertigo_install::vertigo_install,
17};
18
19async fn wait_for_port(addr: &str, port: u16) {
20    for i in 0..20 {
21        match std::net::TcpListener::bind(addr) {
22            Ok(listener) => {
23                // Drop the listener to free the port for actix
24                drop(listener);
25                break;
26            }
27            Err(_) => {
28                log::warn!(
29                    "Port {} is still in use, waiting 1s... ({}/20)",
30                    port,
31                    i + 1
32                );
33                tokio::time::sleep(Duration::from_secs(1)).await;
34            }
35        }
36    }
37}
38
39pub async fn run(opts: ServeOpts, port_watch: Option<u16>) -> Result<(), ErrorCode> {
40    log::info!("serve params => {opts:#?}");
41
42    let ServeOptsInner {
43        host,
44        port,
45        proxy,
46        mount_point,
47        env,
48        wasm_preload,
49        disable_hydration,
50        ssr_fetch_base,
51        ssr_cookie,
52        ssr_fetch_cookie,
53        pretty_html,
54        disable_compression,
55        precompress,
56        threads,
57    } = opts.inner;
58
59    let mut mount_config = MountConfig::new(
60        mount_point,
61        opts.common.dest_dir,
62        env,
63        wasm_preload,
64        disable_hydration,
65    )?;
66    // By default through this server, so relative URLs hit `--proxy` like the browser's requests
67    mount_config.ssr_fetch_base = Some(ssr_fetch_base.unwrap_or_else(|| local_origin(&host, port)));
68    mount_config.ssr_cookies = ssr_cookie;
69    mount_config.ssr_fetch_cookies = ssr_fetch_cookie;
70    mount_config.pretty_html = pretty_html;
71    mount_config.precompress = precompress;
72
73    ServerState::init_with_watch(&mount_config, port_watch)?;
74
75    let app = move || {
76        // Already-encoded responses (what `install_proxy` forwards) carry a `Content-Encoding`
77        // and `Compress` leaves those alone.
78        let mut app = App::new()
79            .wrap(Condition::new(!disable_compression, Compress::default()))
80            // Wrapped around `Compress`, it sees what `Compress` did
81            .wrap(Condition::new(
82                !disable_compression,
83                from_fn(vary_accept_encoding),
84            ));
85
86        for (path, target) in &proxy {
87            app = install_proxy(app, path.clone(), target.clone());
88        }
89
90        app.configure(|cfg| {
91            vertigo_install(cfg, &mount_config);
92        })
93    };
94
95    let addr = format!("{host}:{port}");
96
97    wait_for_port(&addr, port).await;
98
99    let server =
100        HttpServer::new(app)
101            .workers(threads.unwrap_or_else(|| {
102                std::thread::available_parallelism().map_or(2, NonZeroUsize::get)
103            }))
104            .bind(addr.clone())
105            .map_err(|err| {
106                log::error!("Can't bind/serve on {addr}: {err}");
107                ErrorCode::ServeCantOpenPort
108            })?;
109
110    let server = server
111        .disable_signals()
112        .client_disconnect_timeout(Duration::from_secs(2))
113        .shutdown_timeout(5)
114        .run();
115
116    let handle = server.handle();
117    let handle2 = server.handle();
118
119    std::thread::spawn(move || System::new().block_on(server));
120
121    tokio::select! {
122        _ = ServerOwner { handle } => {},
123        msg = term_signal() => {
124            log::info!("{msg} received, shutting down");
125            handle2.stop(false).await;
126        }
127    }
128
129    Ok(())
130}