Skip to main content

vertigo_cli/serve/
vertigo_install.rs

1use std::path::PathBuf;
2
3use actix_files::Files;
4use actix_web::{dev::Service, web};
5
6use crate::serve::MountConfig;
7
8use super::{
9    immutable::{is_build_file_named_by_content, mark_immutable},
10    precompress::precompressed_files,
11    server_state::ServerState,
12    vertigo_handler::vertigo_handler,
13};
14
15/// Install vertigo handler and static files based on mount config.
16///
17/// The handler can work only if ServerState is initialized before.
18/// This can't be done automatically because initialization compiles the WASM which takes some time
19///
20/// Example:
21///
22/// ```no_run
23/// use actix_web::{web, App};
24/// use vertigo_cli::serve::{MountConfigBuilder, ServerState, vertigo_install};
25///
26/// let mount_config = MountConfigBuilder::new("/", "./build").build().unwrap();
27/// ServerState::init(&mount_config).unwrap();
28///
29/// let app = App::new();
30///
31/// app.configure(|srvc| vertigo_install(srvc, &mount_config));
32/// ```
33///
34/// To bootstrap a project using this method, use fullstack template; run:
35///
36/// ```sh
37/// vertigo-cli new -t fullstack my_project
38/// ```
39///
40pub fn vertigo_install(cfg: &mut web::ServiceConfig, mount_config: &MountConfig) {
41    let mount_point = mount_config.mount_point();
42
43    vertigo_files(cfg, mount_config);
44
45    if mount_point == "/" {
46        cfg.default_service(vertigo_handler(mount_config));
47    } else {
48        cfg.service(web::scope(mount_point).default_service(vertigo_handler(mount_config)));
49    };
50}
51
52/// Install only the build's static files, the precompressed ones too if
53/// [`MountConfigBuilder::precompress`](crate::serve::MountConfigBuilder::precompress) asked for
54/// them - for a back-end that renders the pages by itself, f. ex. with redirects before SSR,
55/// and calls [`vertigo_handler`] or [`ServerState`] on its own. A page handler using
56/// [`ServerState`] should refuse the app's SSR fetches, see [`is_ssr_fetch`](crate::serve::is_ssr_fetch).
57///
58/// [`vertigo_install`] does this and then mounts the handler. Like it, it needs ServerState
59/// initialized before.
60///
61/// A file named by its content (`name.HASH.ext`, as `vertigo build` and `include_static!` save
62/// them) goes with `Cache-Control: public, max-age=31536000, immutable`: a new content gets
63/// a new name, so a browser and a CDN keep the file without asking again. The rest of the build
64/// (`index.json`) the browser checks with its ETag.
65///
66/// ```no_run
67/// use actix_web::{web, App, HttpResponse};
68/// use vertigo_cli::serve::{MountConfigBuilder, ServerState, vertigo_files};
69///
70/// let mount_config = MountConfigBuilder::new("/", "./build").precompress(true).build().unwrap();
71/// ServerState::init(&mount_config).unwrap();
72///
73/// let app = App::new()
74///     .configure(|cfg| vertigo_files(cfg, &mount_config))
75///     .default_service(web::to(|| async { HttpResponse::Ok().body("my own page") }));
76/// ```
77pub fn vertigo_files(cfg: &mut web::ServiceConfig, mount_config: &MountConfig) {
78    let files = web::scope(&mount_config.dest_http_root());
79    let files = match mount_config.precompress {
80        true => {
81            let precompressed = ServerState::global(mount_config.mount_point()).precompressed();
82            // in the scope, so its paths start after the build's root
83            files.service(precompressed_files("", precompressed))
84        }
85        false => files,
86    };
87
88    let dest_dir = PathBuf::from(mount_config.dest_dir());
89    cfg.service(
90        files
91            .service(Files::new("", mount_config.dest_dir()))
92            .wrap_fn(move |req, service| {
93                let named = is_build_file_named_by_content(&dest_dir, &req);
94                let res = service.call(req);
95                async move { Ok(mark_immutable(res.await?, named)) }
96            }),
97    );
98}
99
100#[cfg(test)]
101mod tests {
102    use actix_web::{
103        App, HttpResponse,
104        http::{StatusCode, header},
105        test::{TestRequest, call_service, init_service, read_body},
106        web,
107    };
108    use vertigo::dev::VERTIGO_PUBLIC_BUILD_PATH_PLACEHOLDER;
109
110    use super::vertigo_files;
111    use crate::serve::{MountConfigBuilder, ServerState};
112
113    #[actix_web::test]
114    async fn files_go_precompressed_and_pages_to_the_back_end() -> std::io::Result<()> {
115        let dest_dir = std::env::temp_dir().join(format!("vertigo-files-{}", std::process::id()));
116        std::fs::create_dir_all(&dest_dir)?;
117        std::fs::write(
118            dest_dir.join("index.json"),
119            format!(
120                r#"{{"run_js": "{VERTIGO_PUBLIC_BUILD_PATH_PLACEHOLDER}/wasm_run.js", "wasm": "{VERTIGO_PUBLIC_BUILD_PATH_PLACEHOLDER}/app.wasm"}}"#
121            ),
122        )?;
123        // An empty module is enough for `ServerState` to start
124        std::fs::write(dest_dir.join("app.wasm"), b"\0asm\x01\0\0\0")?;
125        let script = "console.log('vertigo');\n".repeat(100);
126        std::fs::write(dest_dir.join("wasm_run.js"), &script)?;
127        // named by their content - compressed at start and not
128        std::fs::write(dest_dir.join("style.Mh5rjJWAfXI.css"), &script)?;
129        std::fs::write(dest_dir.join("font.jx-LW7_aanc.woff2"), vec![0; 1000])?;
130
131        // Its own mount point, as the state is global for the tests running alongside
132        let Ok(mount_config) = MountConfigBuilder::new("/files", dest_dir.to_string_lossy())
133            .precompress(true)
134            .build()
135        else {
136            panic!("index.json in {dest_dir:?} should read");
137        };
138        let Ok(()) = ServerState::init(&mount_config) else {
139            panic!("the build in {dest_dir:?} should load");
140        };
141
142        let app = init_service(
143            App::new()
144                .configure(|cfg| vertigo_files(cfg, &mount_config))
145                .default_service(web::to(|| async { HttpResponse::Ok().body("page") })),
146        )
147        .await;
148
149        let get = |uri: &str, accept_encoding: &str| {
150            TestRequest::get()
151                .uri(uri)
152                .insert_header((header::ACCEPT_ENCODING, accept_encoding.to_string()))
153                .to_request()
154        };
155        let script_uri = format!("{}/wasm_run.js", mount_config.dest_http_root());
156
157        let response = call_service(&app, get(&script_uri, "gzip, br")).await;
158        assert_eq!(response.status(), StatusCode::OK);
159        assert_eq!(
160            response.headers().get(header::CONTENT_ENCODING),
161            Some(&header::HeaderValue::from_static("br"))
162        );
163
164        let response = call_service(&app, get(&script_uri, "gzip")).await;
165        assert_eq!(response.headers().get(header::CONTENT_ENCODING), None);
166        assert_eq!(read_body(response).await, script.as_bytes());
167
168        let response = call_service(&app, get("/files/some/page", "br")).await;
169        assert_eq!(read_body(response).await, "page".as_bytes());
170
171        let cache_control = |response: &actix_web::dev::ServiceResponse| {
172            response
173                .headers()
174                .get(header::CACHE_CONTROL)
175                .and_then(|value| value.to_str().ok())
176                .map(str::to_string)
177        };
178        let immutable = Some("public, max-age=31536000, immutable".to_string());
179        let root = mount_config.dest_http_root();
180        for (file, accept_encoding) in [
181            ("style.Mh5rjJWAfXI.css", "br"),
182            ("style.Mh5rjJWAfXI.css", "gzip"),
183            ("font.jx-LW7_aanc.woff2", "br"),
184        ] {
185            let response =
186                call_service(&app, get(&format!("{root}/{file}"), accept_encoding)).await;
187            assert_eq!(response.status(), StatusCode::OK, "{file}");
188            assert_eq!(
189                cache_control(&response),
190                immutable,
191                "{file}, {accept_encoding}"
192            );
193        }
194        // the same on revalidation of a copy from before
195        let response =
196            call_service(&app, get(&format!("{root}/style.Mh5rjJWAfXI.css"), "br")).await;
197        let etag = response.headers().get(header::ETAG).cloned();
198        let Some(etag) = etag else {
199            panic!("a build file should have an ETag");
200        };
201        let revalidate = TestRequest::get()
202            .uri(&format!("{root}/style.Mh5rjJWAfXI.css"))
203            .insert_header((header::ACCEPT_ENCODING, "br"))
204            .insert_header((header::IF_NONE_MATCH, etag))
205            .to_request();
206        let response = call_service(&app, revalidate).await;
207        assert_eq!(response.status(), StatusCode::NOT_MODIFIED);
208        assert_eq!(cache_control(&response), immutable);
209
210        // a file without the hash, and a missing one, may change
211        let response = call_service(&app, get(&script_uri, "br")).await;
212        assert_eq!(cache_control(&response), None);
213        let response = call_service(&app, get(&format!("{root}/index.json"), "br")).await;
214        assert_eq!(response.status(), StatusCode::OK);
215        assert_eq!(cache_control(&response), None);
216        // a missing one goes to the page, as before
217        let response = call_service(&app, get(&format!("{root}/gone.Mh5rjJWAfXI.css"), "br")).await;
218        assert_eq!(cache_control(&response), None);
219        assert_eq!(read_body(response).await, "page".as_bytes());
220
221        std::fs::remove_dir_all(&dest_dir)
222    }
223}