Skip to main content

vertigo_cli/serve/
mount_path.rs

1#![allow(clippy::question_mark)]
2use std::{collections::HashMap, path::Path, sync::Arc};
3use vertigo::dev::{
4    VERTIGO_MOUNT_POINT_ENV, VERTIGO_PUBLIC_BUILD_PATH_PLACEHOLDER, VERTIGO_PUBLIC_PATH_ENV,
5};
6
7use crate::commons::{ErrorCode, models::IndexModel};
8
9pub struct MountConfigBuilder {
10    pub mount_point: String,
11    pub dest_dir: String,
12    pub env: Vec<(String, String)>,
13    pub wasm_preload: bool,
14    pub disable_hydration: bool,
15    pub ssr_fetch_base: Option<String>,
16    pub ssr_cookies: Vec<String>,
17    pub pretty_html: bool,
18    pub precompress: bool,
19}
20
21impl MountConfigBuilder {
22    pub fn new(mount_point: impl Into<String>, dest_dir: impl Into<String>) -> MountConfigBuilder {
23        MountConfigBuilder {
24            mount_point: mount_point.into(),
25            dest_dir: dest_dir.into(),
26            env: vec![],
27            wasm_preload: false,
28            disable_hydration: false,
29            ssr_fetch_base: None,
30            ssr_cookies: vec![],
31            pretty_html: false,
32            precompress: false,
33        }
34    }
35
36    pub fn envs(mut self, envs: Vec<(String, String)>) -> Self {
37        self.env = envs;
38        self
39    }
40
41    pub fn env(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
42        self.env.push((key.into(), value.into()));
43        self
44    }
45
46    pub fn wasm_preload(mut self, wasm_preload: bool) -> Self {
47        self.wasm_preload = wasm_preload;
48        self
49    }
50
51    pub fn disable_hydration(mut self, disable_hydration: bool) -> Self {
52        self.disable_hydration = disable_hydration;
53        self
54    }
55
56    /// Origin against which SSR resolves relative fetch URLs (`/api/posts`), e.g. `http://127.0.0.1:8080`.
57    ///
58    /// Without it, fetching a relative URL during SSR fails.
59    pub fn ssr_fetch_base(mut self, origin: impl Into<String>) -> Self {
60        self.ssr_fetch_base = Some(origin.into());
61        self
62    }
63
64    /// A cookie the app may read with `get_driver().cookie_get()` while the server renders the
65    /// page, f. ex. the language the user picked, so the page comes rendered as the browser will
66    /// show it. Others read as empty there, as they always did.
67    ///
68    /// Only for a cookie the browser shows the app too: not `HttpOnly`. The `Cookie` header doesn't
69    /// tell which are, and the server would render what the browser can't.
70    pub fn ssr_cookie(mut self, name: impl Into<String>) -> Self {
71        self.ssr_cookies.push(name.into());
72        self
73    }
74
75    /// Indent the server-rendered HTML, to read it in the page source.
76    ///
77    /// Off by default: the indentation is whitespace between elements, which the app's own tree
78    /// doesn't have - until the app starts it shows as gaps between inline elements, and
79    /// hydration then takes it out, one node at a time.
80    pub fn pretty_html(mut self, pretty_html: bool) -> Self {
81        self.pretty_html = pretty_html;
82        self
83    }
84
85    /// Compress the build's wasm, `wasm_run.js` and other text files with brotli at its highest
86    /// level once, in [`ServerState::init`](crate::serve::ServerState::init), and serve those to
87    /// the browsers that accept brotli - [`vertigo_install`](crate::serve::vertigo_install) and
88    /// [`vertigo_files`](crate::serve::vertigo_files) do.
89    ///
90    /// They come out about a quarter smaller than compressed per response, for about a second
91    /// of startup per megabyte - in a release build of the server, in a debug one far more,
92    /// see [`precompress_in_release`](Self::precompress_in_release).
93    pub fn precompress(mut self, precompress: bool) -> Self {
94        self.precompress = precompress;
95        self
96    }
97
98    /// [`precompress`](Self::precompress) in a release build of the server, none in a debug one:
99    /// brotli built without optimizations, on a debug build of the app's wasm (tens of megabytes),
100    /// takes minutes before the server starts.
101    ///
102    /// A build counts as release when it has no debug assertions, as `cargo build --release` by
103    /// default.
104    pub fn precompress_in_release(self) -> Self {
105        self.precompress(!cfg!(debug_assertions))
106    }
107
108    pub fn build(self) -> Result<MountConfig, ErrorCode> {
109        let mut config = MountConfig::new(
110            self.mount_point,
111            self.dest_dir,
112            self.env,
113            self.wasm_preload,
114            self.disable_hydration,
115        )?;
116        config.ssr_fetch_base = self.ssr_fetch_base;
117        config.ssr_cookies = self.ssr_cookies;
118        config.pretty_html = self.pretty_html;
119        config.precompress = self.precompress;
120        Ok(config)
121    }
122}
123
124#[derive(Clone, Debug)]
125pub struct MountConfig {
126    /// Mount point in URL
127    mount_point: String,
128    /// Build destination directory (where wasm file and wasm_run.js are stored)
129    dest_dir: String,
130    /// waasm_run.js taken from index.json
131    run_js: String,
132    /// path to wasm-file taken from index.json
133    wasm_path: String,
134    /// Environment variables passed to WASM runtime - together with the mount point and the
135    /// public path of the build (`vertigo-mount-point`, `vertigo-public-path`)
136    pub env: Arc<HashMap<String, String>>,
137    /// Whether the runtime starts downloading the wasm while the page loads, instead of after
138    pub wasm_preload: bool,
139    /// Whether to disable hydration
140    pub disable_hydration: bool,
141    /// See [`MountConfigBuilder::ssr_fetch_base`]
142    pub ssr_fetch_base: Option<String>,
143    /// See [`MountConfigBuilder::ssr_cookie`]
144    pub ssr_cookies: Vec<String>,
145    /// See [`MountConfigBuilder::pretty_html`]
146    pub pretty_html: bool,
147    /// See [`MountConfigBuilder::precompress`]
148    pub precompress: bool,
149}
150
151impl MountConfig {
152    pub fn new(
153        public_mount_point: impl Into<String>,
154        dest_dir: impl Into<String>,
155        env: Vec<(String, String)>,
156        wasm_preload: bool,
157        disable_hydration: bool,
158    ) -> Result<MountConfig, ErrorCode> {
159        let dest_dir = dest_dir.into();
160        let index_model = read_index(&dest_dir)?;
161
162        let mut config = MountConfig {
163            dest_dir,
164            mount_point: public_mount_point.into(),
165            run_js: index_model.run_js,
166            wasm_path: index_model.wasm,
167            env: Arc::default(),
168            wasm_preload,
169            disable_hydration,
170            ssr_fetch_base: None,
171            ssr_cookies: vec![],
172            pretty_html: false,
173            precompress: false,
174        };
175
176        // The app gets them wherever it runs - in the browser as `data-env-*`, during SSR from
177        // the host - so both sides build the same paths (`Driver::route_to_public`,
178        // `Driver::public_build_path`)
179        let mut env: HashMap<String, String> = env.into_iter().collect();
180        env.insert(VERTIGO_MOUNT_POINT_ENV.into(), config.mount_point.clone());
181        env.insert(VERTIGO_PUBLIC_PATH_ENV.into(), config.dest_http_root());
182        config.env = Arc::new(env);
183
184        Ok(config)
185    }
186
187    pub fn mount_point(&self) -> &str {
188        self.mount_point.as_str()
189    }
190
191    pub fn dest_dir(&self) -> &str {
192        self.dest_dir.trim_start_matches("./")
193    }
194
195    pub fn dest_http_root(&self) -> String {
196        Path::new(&self.mount_point)
197            .join(self.dest_dir())
198            .components()
199            .as_path()
200            .to_string_lossy()
201            .into_owned()
202    }
203
204    pub fn get_wasm_http_path(&self) -> String {
205        self.translate_to_http(&self.wasm_path)
206    }
207
208    pub fn get_run_js_http_path(&self) -> String {
209        self.translate_to_http(&self.run_js)
210    }
211
212    pub fn get_wasm_fs_path(&self) -> String {
213        self.translate_to_fs(&self.wasm_path)
214    }
215
216    fn translate_to_http(&self, fs_path: impl Into<String>) -> String {
217        let fs_path = fs_path.into();
218        fs_path.replace(
219            VERTIGO_PUBLIC_BUILD_PATH_PLACEHOLDER,
220            &self.dest_http_root(),
221        )
222    }
223
224    fn translate_to_fs(&self, http_path: impl Into<String>) -> String {
225        let http_path = http_path.into();
226        replace_prefix(&self.dest_dir, &http_path)
227    }
228}
229
230fn read_index(dest_dir: &str) -> Result<IndexModel, ErrorCode> {
231    let index_path = Path::new(dest_dir).join("index.json");
232    let index_html = match std::fs::read_to_string(&index_path) {
233        Ok(data) => data,
234        Err(err) => {
235            log::error!("File read error: file={index_path:?}, error={err}, dest_dir={dest_dir}");
236            return Err(ErrorCode::ServeCantReadIndexFile);
237        }
238    };
239
240    serde_json::from_str::<IndexModel>(&index_html).map_err(|err| {
241        log::error!("File read error 2: file={index_path:?}, error={err}, dest_dir={dest_dir}");
242        ErrorCode::ServeCantReadIndexFile
243    })
244}
245
246fn replace_prefix(dest_dir: &str, path: &str) -> String {
247    if path.starts_with(VERTIGO_PUBLIC_BUILD_PATH_PLACEHOLDER) {
248        // Dynamic path resolution
249        path.replace(VERTIGO_PUBLIC_BUILD_PATH_PLACEHOLDER, dest_dir)
250    } else {
251        // Static path resolution
252        path.to_string()
253    }
254}
255
256#[cfg(test)]
257mod tests {
258    use vertigo::dev::VERTIGO_PUBLIC_BUILD_PATH_PLACEHOLDER;
259
260    use super::{MountConfig, MountConfigBuilder, replace_prefix};
261
262    #[test]
263    fn html_is_indented_only_when_asked() -> std::io::Result<()> {
264        let dest_dir = std::env::temp_dir().join(format!("vertigo-pretty-{}", std::process::id()));
265        std::fs::create_dir_all(&dest_dir)?;
266        std::fs::write(
267            dest_dir.join("index.json"),
268            r#"{"run_js": "wasm_run.js", "wasm": "app.wasm"}"#,
269        )?;
270
271        let builder = || MountConfigBuilder::new("/", dest_dir.to_string_lossy());
272        let (Ok(default), Ok(pretty)) = (builder().build(), builder().pretty_html(true).build())
273        else {
274            panic!("index.json in {dest_dir:?} should read");
275        };
276
277        assert!(!default.pretty_html);
278        assert!(pretty.pretty_html);
279
280        std::fs::remove_dir_all(&dest_dir)
281    }
282
283    #[test]
284    fn precompress_in_release_follows_the_build() {
285        let builder = MountConfigBuilder::new("/", "build").precompress_in_release();
286
287        // `cargo test` builds with debug assertions, `cargo test --release` without
288        assert_eq!(builder.precompress, !cfg!(debug_assertions));
289    }
290
291    #[test]
292    fn env_carries_mount_point_and_public_path() -> std::io::Result<()> {
293        let dest_dir = std::env::temp_dir().join(format!("vertigo-mount-{}", std::process::id()));
294        std::fs::create_dir_all(&dest_dir)?;
295        std::fs::write(
296            dest_dir.join("index.json"),
297            r#"{"run_js": "wasm_run.js", "wasm": "app.wasm"}"#,
298        )?;
299
300        let Ok(config) = MountConfig::new(
301            "/panel",
302            dest_dir.to_string_lossy(),
303            vec![
304                ("api_url".into(), "/api".into()),
305                // the server knows better where it mounted the app
306                ("vertigo-mount-point".into(), "/elsewhere".into()),
307            ],
308            false,
309            false,
310        ) else {
311            panic!("index.json in {dest_dir:?} should read");
312        };
313
314        assert_eq!(config.env["api_url"], "/api");
315        assert_eq!(config.env["vertigo-mount-point"], "/panel");
316        assert_eq!(config.env["vertigo-public-path"], config.dest_http_root());
317
318        std::fs::remove_dir_all(&dest_dir)
319    }
320
321    #[test]
322    fn test_replace_prefix() {
323        assert_eq!(
324            replace_prefix("demo_build", "build/vertigo_demo.33.wasm"),
325            "build/vertigo_demo.33.wasm".to_string()
326        );
327
328        assert_eq!(
329            replace_prefix("demo_build", "build/vertigo_demo.33.wasm"),
330            "build/vertigo_demo.33.wasm".to_string()
331        );
332
333        assert_eq!(
334            replace_prefix(
335                "demo_build",
336                &format!("{VERTIGO_PUBLIC_BUILD_PATH_PLACEHOLDER}/vertigo_demo.33.wasm")
337            ),
338            "demo_build/vertigo_demo.33.wasm".to_string()
339        );
340    }
341}