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.
92    pub fn precompress(mut self, precompress: bool) -> Self {
93        self.precompress = precompress;
94        self
95    }
96
97    pub fn build(self) -> Result<MountConfig, ErrorCode> {
98        let mut config = MountConfig::new(
99            self.mount_point,
100            self.dest_dir,
101            self.env,
102            self.wasm_preload,
103            self.disable_hydration,
104        )?;
105        config.ssr_fetch_base = self.ssr_fetch_base;
106        config.ssr_cookies = self.ssr_cookies;
107        config.pretty_html = self.pretty_html;
108        config.precompress = self.precompress;
109        Ok(config)
110    }
111}
112
113#[derive(Clone, Debug)]
114pub struct MountConfig {
115    /// Mount point in URL
116    mount_point: String,
117    /// Build destination directory (where wasm file and wasm_run.js are stored)
118    dest_dir: String,
119    /// waasm_run.js taken from index.json
120    run_js: String,
121    /// path to wasm-file taken from index.json
122    wasm_path: String,
123    /// Environment variables passed to WASM runtime - together with the mount point and the
124    /// public path of the build (`vertigo-mount-point`, `vertigo-public-path`)
125    pub env: Arc<HashMap<String, String>>,
126    /// Whether the runtime starts downloading the wasm while the page loads, instead of after
127    pub wasm_preload: bool,
128    /// Whether to disable hydration
129    pub disable_hydration: bool,
130    /// See [`MountConfigBuilder::ssr_fetch_base`]
131    pub ssr_fetch_base: Option<String>,
132    /// See [`MountConfigBuilder::ssr_cookie`]
133    pub ssr_cookies: Vec<String>,
134    /// See [`MountConfigBuilder::pretty_html`]
135    pub pretty_html: bool,
136    /// See [`MountConfigBuilder::precompress`]
137    pub precompress: bool,
138}
139
140impl MountConfig {
141    pub fn new(
142        public_mount_point: impl Into<String>,
143        dest_dir: impl Into<String>,
144        env: Vec<(String, String)>,
145        wasm_preload: bool,
146        disable_hydration: bool,
147    ) -> Result<MountConfig, ErrorCode> {
148        let dest_dir = dest_dir.into();
149        let index_model = read_index(&dest_dir)?;
150
151        let mut config = MountConfig {
152            dest_dir,
153            mount_point: public_mount_point.into(),
154            run_js: index_model.run_js,
155            wasm_path: index_model.wasm,
156            env: Arc::default(),
157            wasm_preload,
158            disable_hydration,
159            ssr_fetch_base: None,
160            ssr_cookies: vec![],
161            pretty_html: false,
162            precompress: false,
163        };
164
165        // The app gets them wherever it runs - in the browser as `data-env-*`, during SSR from
166        // the host - so both sides build the same paths (`Driver::route_to_public`,
167        // `Driver::public_build_path`)
168        let mut env: HashMap<String, String> = env.into_iter().collect();
169        env.insert(VERTIGO_MOUNT_POINT_ENV.into(), config.mount_point.clone());
170        env.insert(VERTIGO_PUBLIC_PATH_ENV.into(), config.dest_http_root());
171        config.env = Arc::new(env);
172
173        Ok(config)
174    }
175
176    pub fn mount_point(&self) -> &str {
177        self.mount_point.as_str()
178    }
179
180    pub fn dest_dir(&self) -> &str {
181        self.dest_dir.trim_start_matches("./")
182    }
183
184    pub fn dest_http_root(&self) -> String {
185        Path::new(&self.mount_point)
186            .join(self.dest_dir())
187            .components()
188            .as_path()
189            .to_string_lossy()
190            .into_owned()
191    }
192
193    pub fn get_wasm_http_path(&self) -> String {
194        self.translate_to_http(&self.wasm_path)
195    }
196
197    pub fn get_run_js_http_path(&self) -> String {
198        self.translate_to_http(&self.run_js)
199    }
200
201    pub fn get_wasm_fs_path(&self) -> String {
202        self.translate_to_fs(&self.wasm_path)
203    }
204
205    fn translate_to_http(&self, fs_path: impl Into<String>) -> String {
206        let fs_path = fs_path.into();
207        fs_path.replace(
208            VERTIGO_PUBLIC_BUILD_PATH_PLACEHOLDER,
209            &self.dest_http_root(),
210        )
211    }
212
213    fn translate_to_fs(&self, http_path: impl Into<String>) -> String {
214        let http_path = http_path.into();
215        replace_prefix(&self.dest_dir, &http_path)
216    }
217}
218
219fn read_index(dest_dir: &str) -> Result<IndexModel, ErrorCode> {
220    let index_path = Path::new(dest_dir).join("index.json");
221    let index_html = match std::fs::read_to_string(&index_path) {
222        Ok(data) => data,
223        Err(err) => {
224            log::error!("File read error: file={index_path:?}, error={err}, dest_dir={dest_dir}");
225            return Err(ErrorCode::ServeCantReadIndexFile);
226        }
227    };
228
229    serde_json::from_str::<IndexModel>(&index_html).map_err(|err| {
230        log::error!("File read error 2: file={index_path:?}, error={err}, dest_dir={dest_dir}");
231        ErrorCode::ServeCantReadIndexFile
232    })
233}
234
235fn replace_prefix(dest_dir: &str, path: &str) -> String {
236    if path.starts_with(VERTIGO_PUBLIC_BUILD_PATH_PLACEHOLDER) {
237        // Dynamic path resolution
238        path.replace(VERTIGO_PUBLIC_BUILD_PATH_PLACEHOLDER, dest_dir)
239    } else {
240        // Static path resolution
241        path.to_string()
242    }
243}
244
245#[cfg(test)]
246mod tests {
247    use vertigo::dev::VERTIGO_PUBLIC_BUILD_PATH_PLACEHOLDER;
248
249    use super::{MountConfig, MountConfigBuilder, replace_prefix};
250
251    #[test]
252    fn html_is_indented_only_when_asked() -> std::io::Result<()> {
253        let dest_dir = std::env::temp_dir().join(format!("vertigo-pretty-{}", std::process::id()));
254        std::fs::create_dir_all(&dest_dir)?;
255        std::fs::write(
256            dest_dir.join("index.json"),
257            r#"{"run_js": "wasm_run.js", "wasm": "app.wasm"}"#,
258        )?;
259
260        let builder = || MountConfigBuilder::new("/", dest_dir.to_string_lossy());
261        let (Ok(default), Ok(pretty)) = (builder().build(), builder().pretty_html(true).build())
262        else {
263            panic!("index.json in {dest_dir:?} should read");
264        };
265
266        assert!(!default.pretty_html);
267        assert!(pretty.pretty_html);
268
269        std::fs::remove_dir_all(&dest_dir)
270    }
271
272    #[test]
273    fn env_carries_mount_point_and_public_path() -> std::io::Result<()> {
274        let dest_dir = std::env::temp_dir().join(format!("vertigo-mount-{}", std::process::id()));
275        std::fs::create_dir_all(&dest_dir)?;
276        std::fs::write(
277            dest_dir.join("index.json"),
278            r#"{"run_js": "wasm_run.js", "wasm": "app.wasm"}"#,
279        )?;
280
281        let Ok(config) = MountConfig::new(
282            "/panel",
283            dest_dir.to_string_lossy(),
284            vec![
285                ("api_url".into(), "/api".into()),
286                // the server knows better where it mounted the app
287                ("vertigo-mount-point".into(), "/elsewhere".into()),
288            ],
289            false,
290            false,
291        ) else {
292            panic!("index.json in {dest_dir:?} should read");
293        };
294
295        assert_eq!(config.env["api_url"], "/api");
296        assert_eq!(config.env["vertigo-mount-point"], "/panel");
297        assert_eq!(config.env["vertigo-public-path"], config.dest_http_root());
298
299        std::fs::remove_dir_all(&dest_dir)
300    }
301
302    #[test]
303    fn test_replace_prefix() {
304        assert_eq!(
305            replace_prefix("demo_build", "build/vertigo_demo.33.wasm"),
306            "build/vertigo_demo.33.wasm".to_string()
307        );
308
309        assert_eq!(
310            replace_prefix("demo_build", "build/vertigo_demo.33.wasm"),
311            "build/vertigo_demo.33.wasm".to_string()
312        );
313
314        assert_eq!(
315            replace_prefix(
316                "demo_build",
317                &format!("{VERTIGO_PUBLIC_BUILD_PATH_PLACEHOLDER}/vertigo_demo.33.wasm")
318            ),
319            "demo_build/vertigo_demo.33.wasm".to_string()
320        );
321    }
322}