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