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
15pub 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
52pub 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 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 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 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 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 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 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 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}