Skip to main content

vertigo_cli/serve/
vertigo_install.rs

1use actix_files::Files;
2use actix_web::web;
3
4use crate::serve::MountConfig;
5
6use super::{
7    precompress::precompressed_files, server_state::ServerState, vertigo_handler::vertigo_handler,
8};
9
10/// Install vertigo handler and static files based on mount config.
11///
12/// The handler can work only if ServerState is initialized before.
13/// This can't be done automatically because initialization compiles the WASM which takes some time
14///
15/// Example:
16///
17/// ```no_run
18/// use actix_web::{web, App};
19/// use vertigo_cli::serve::{MountConfigBuilder, ServerState, vertigo_install};
20///
21/// let mount_config = MountConfigBuilder::new("/", "./build").build().unwrap();
22/// ServerState::init(&mount_config).unwrap();
23///
24/// let app = App::new();
25///
26/// app.configure(|srvc| vertigo_install(srvc, &mount_config));
27/// ```
28///
29/// To bootstrap a project using this method, use fullstack template; run:
30///
31/// ```sh
32/// vertigo-cli new -t fullstack my_project
33/// ```
34///
35pub fn vertigo_install(cfg: &mut web::ServiceConfig, mount_config: &MountConfig) {
36    let mount_point = mount_config.mount_point();
37
38    vertigo_files(cfg, mount_config);
39
40    if mount_point == "/" {
41        cfg.default_service(vertigo_handler(mount_config));
42    } else {
43        cfg.service(web::scope(mount_point).default_service(vertigo_handler(mount_config)));
44    };
45}
46
47/// Install only the build's static files, the precompressed ones too if
48/// [`MountConfigBuilder::precompress`](crate::serve::MountConfigBuilder::precompress) asked for
49/// them - for a back-end that renders the pages by itself, f. ex. with redirects before SSR,
50/// and calls [`vertigo_handler`] or [`ServerState`] on its own.
51///
52/// [`vertigo_install`] does this and then mounts the handler. Like it, it needs ServerState
53/// initialized before.
54///
55/// ```no_run
56/// use actix_web::{web, App, HttpResponse};
57/// use vertigo_cli::serve::{MountConfigBuilder, ServerState, vertigo_files};
58///
59/// let mount_config = MountConfigBuilder::new("/", "./build").precompress(true).build().unwrap();
60/// ServerState::init(&mount_config).unwrap();
61///
62/// let app = App::new()
63///     .configure(|cfg| vertigo_files(cfg, &mount_config))
64///     .default_service(web::to(|| async { HttpResponse::Ok().body("my own page") }));
65/// ```
66pub fn vertigo_files(cfg: &mut web::ServiceConfig, mount_config: &MountConfig) {
67    if mount_config.precompress {
68        let files = ServerState::global(mount_config.mount_point()).precompressed();
69        cfg.service(precompressed_files(&mount_config.dest_http_root(), files));
70    }
71
72    cfg.service(Files::new(
73        &mount_config.dest_http_root(),
74        mount_config.dest_dir(),
75    ));
76}
77
78#[cfg(test)]
79mod tests {
80    use actix_web::{
81        App, HttpResponse,
82        http::{StatusCode, header},
83        test::{TestRequest, call_service, init_service, read_body},
84        web,
85    };
86    use vertigo::dev::VERTIGO_PUBLIC_BUILD_PATH_PLACEHOLDER;
87
88    use super::vertigo_files;
89    use crate::serve::{MountConfigBuilder, ServerState};
90
91    #[actix_web::test]
92    async fn files_go_precompressed_and_pages_to_the_back_end() -> std::io::Result<()> {
93        let dest_dir = std::env::temp_dir().join(format!("vertigo-files-{}", std::process::id()));
94        std::fs::create_dir_all(&dest_dir)?;
95        std::fs::write(
96            dest_dir.join("index.json"),
97            format!(
98                r#"{{"run_js": "{VERTIGO_PUBLIC_BUILD_PATH_PLACEHOLDER}/wasm_run.js", "wasm": "{VERTIGO_PUBLIC_BUILD_PATH_PLACEHOLDER}/app.wasm"}}"#
99            ),
100        )?;
101        // An empty module is enough for `ServerState` to start
102        std::fs::write(dest_dir.join("app.wasm"), b"\0asm\x01\0\0\0")?;
103        let script = "console.log('vertigo');\n".repeat(100);
104        std::fs::write(dest_dir.join("wasm_run.js"), &script)?;
105
106        // Its own mount point, as the state is global for the tests running alongside
107        let Ok(mount_config) = MountConfigBuilder::new("/files", dest_dir.to_string_lossy())
108            .precompress(true)
109            .build()
110        else {
111            panic!("index.json in {dest_dir:?} should read");
112        };
113        let Ok(()) = ServerState::init(&mount_config) else {
114            panic!("the build in {dest_dir:?} should load");
115        };
116
117        let app = init_service(
118            App::new()
119                .configure(|cfg| vertigo_files(cfg, &mount_config))
120                .default_service(web::to(|| async { HttpResponse::Ok().body("page") })),
121        )
122        .await;
123
124        let get = |uri: &str, accept_encoding: &str| {
125            TestRequest::get()
126                .uri(uri)
127                .insert_header((header::ACCEPT_ENCODING, accept_encoding.to_string()))
128                .to_request()
129        };
130        let script_uri = format!("{}/wasm_run.js", mount_config.dest_http_root());
131
132        let response = call_service(&app, get(&script_uri, "gzip, br")).await;
133        assert_eq!(response.status(), StatusCode::OK);
134        assert_eq!(
135            response.headers().get(header::CONTENT_ENCODING),
136            Some(&header::HeaderValue::from_static("br"))
137        );
138
139        let response = call_service(&app, get(&script_uri, "gzip")).await;
140        assert_eq!(response.headers().get(header::CONTENT_ENCODING), None);
141        assert_eq!(read_body(response).await, script.as_bytes());
142
143        let response = call_service(&app, get("/files/some/page", "br")).await;
144        assert_eq!(read_body(response).await, "page".as_bytes());
145
146        std::fs::remove_dir_all(&dest_dir)
147    }
148}