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). The files `vertigo build`
109    /// saved compressed next to them (`name.ext.br`, unless built with `--precompress false`)
110    /// take no time: the server only checks that they unpack to the files, so one copied with
111    /// the build but stale doesn't get served.
112    pub fn precompress(mut self, precompress: bool) -> Self {
113        self.precompress = precompress;
114        self
115    }
116
117    /// [`precompress`](Self::precompress) in a release build of the server, none in a debug one:
118    /// brotli built without optimizations, on a debug build of the app's wasm (tens of megabytes),
119    /// takes minutes before the server starts.
120    ///
121    /// A build counts as release when it has no debug assertions, as `cargo build --release` by
122    /// default.
123    pub fn precompress_in_release(self) -> Self {
124        self.precompress(!cfg!(debug_assertions))
125    }
126
127    pub fn build(self) -> Result<MountConfig, ErrorCode> {
128        let mut config = MountConfig::new(
129            self.mount_point,
130            self.dest_dir,
131            self.env,
132            self.wasm_preload,
133            self.disable_hydration,
134        )?;
135        config.ssr_fetch_base = self.ssr_fetch_base;
136        config.ssr_cookies = self.ssr_cookies;
137        config.ssr_fetch_cookies = self.ssr_fetch_cookies;
138        config.pretty_html = self.pretty_html;
139        config.precompress = self.precompress;
140        Ok(config)
141    }
142}
143
144#[derive(Clone, Debug)]
145pub struct MountConfig {
146    /// Mount point in URL
147    mount_point: String,
148    /// Build destination directory (where wasm file and wasm_run.js are stored)
149    dest_dir: String,
150    /// waasm_run.js taken from index.json
151    run_js: String,
152    /// path to wasm-file taken from index.json
153    wasm_path: String,
154    /// Environment variables passed to WASM runtime - together with the mount point and the
155    /// public path of the build (`vertigo-mount-point`, `vertigo-public-path`)
156    pub env: Arc<HashMap<String, String>>,
157    /// Whether the runtime starts downloading the wasm while the page loads, instead of after
158    pub wasm_preload: bool,
159    /// Whether to disable hydration
160    pub disable_hydration: bool,
161    /// See [`MountConfigBuilder::ssr_fetch_base`]
162    pub ssr_fetch_base: Option<String>,
163    /// See [`MountConfigBuilder::ssr_cookie`]
164    pub ssr_cookies: Vec<String>,
165    /// See [`MountConfigBuilder::ssr_fetch_cookie`]
166    pub ssr_fetch_cookies: Vec<String>,
167    /// See [`MountConfigBuilder::pretty_html`]
168    pub pretty_html: bool,
169    /// See [`MountConfigBuilder::precompress`]
170    pub precompress: bool,
171}
172
173impl MountConfig {
174    pub fn new(
175        public_mount_point: impl Into<String>,
176        dest_dir: impl Into<String>,
177        env: Vec<(String, String)>,
178        wasm_preload: bool,
179        disable_hydration: bool,
180    ) -> Result<MountConfig, ErrorCode> {
181        let dest_dir = dest_dir.into();
182        let index_model = read_index(&dest_dir)?;
183
184        let mut config = MountConfig {
185            dest_dir,
186            mount_point: public_mount_point.into(),
187            run_js: index_model.run_js,
188            wasm_path: index_model.wasm,
189            env: Arc::default(),
190            wasm_preload,
191            disable_hydration,
192            ssr_fetch_base: None,
193            ssr_cookies: vec![],
194            ssr_fetch_cookies: vec![],
195            pretty_html: false,
196            precompress: false,
197        };
198
199        // The app gets them wherever it runs - in the browser as `data-env-*`, during SSR from
200        // the host - so both sides build the same paths (`Driver::route_to_public`,
201        // `Driver::public_build_path`)
202        let mut env: HashMap<String, String> = env.into_iter().collect();
203        env.insert(VERTIGO_MOUNT_POINT_ENV.into(), config.mount_point.clone());
204        env.insert(VERTIGO_PUBLIC_PATH_ENV.into(), config.dest_http_root());
205        config.env = Arc::new(env);
206
207        Ok(config)
208    }
209
210    pub fn mount_point(&self) -> &str {
211        self.mount_point.as_str()
212    }
213
214    pub fn dest_dir(&self) -> &str {
215        self.dest_dir.trim_start_matches("./")
216    }
217
218    pub fn dest_http_root(&self) -> String {
219        Path::new(&self.mount_point)
220            .join(self.dest_dir())
221            .components()
222            .as_path()
223            .to_string_lossy()
224            .into_owned()
225    }
226
227    pub fn get_wasm_http_path(&self) -> String {
228        self.translate_to_http(&self.wasm_path)
229    }
230
231    pub fn get_run_js_http_path(&self) -> String {
232        self.translate_to_http(&self.run_js)
233    }
234
235    pub fn get_wasm_fs_path(&self) -> String {
236        self.translate_to_fs(&self.wasm_path)
237    }
238
239    fn translate_to_http(&self, fs_path: impl Into<String>) -> String {
240        let fs_path = fs_path.into();
241        fs_path.replace(
242            VERTIGO_PUBLIC_BUILD_PATH_PLACEHOLDER,
243            &self.dest_http_root(),
244        )
245    }
246
247    fn translate_to_fs(&self, http_path: impl Into<String>) -> String {
248        let http_path = http_path.into();
249        replace_prefix(&self.dest_dir, &http_path)
250    }
251}
252
253fn read_index(dest_dir: &str) -> Result<IndexModel, ErrorCode> {
254    let index_path = Path::new(dest_dir).join("index.json");
255    let index_html = match std::fs::read_to_string(&index_path) {
256        Ok(data) => data,
257        Err(err) => {
258            log::error!("File read error: file={index_path:?}, error={err}, dest_dir={dest_dir}");
259            return Err(ErrorCode::ServeCantReadIndexFile);
260        }
261    };
262
263    serde_json::from_str::<IndexModel>(&index_html).map_err(|err| {
264        log::error!("File read error 2: file={index_path:?}, error={err}, dest_dir={dest_dir}");
265        ErrorCode::ServeCantReadIndexFile
266    })
267}
268
269fn replace_prefix(dest_dir: &str, path: &str) -> String {
270    if path.starts_with(VERTIGO_PUBLIC_BUILD_PATH_PLACEHOLDER) {
271        // Dynamic path resolution
272        path.replace(VERTIGO_PUBLIC_BUILD_PATH_PLACEHOLDER, dest_dir)
273    } else {
274        // Static path resolution
275        path.to_string()
276    }
277}
278
279#[cfg(test)]
280mod tests {
281    use vertigo::dev::VERTIGO_PUBLIC_BUILD_PATH_PLACEHOLDER;
282
283    use super::{MountConfig, MountConfigBuilder, replace_prefix};
284
285    #[test]
286    fn html_is_indented_only_when_asked() -> std::io::Result<()> {
287        let dest_dir = std::env::temp_dir().join(format!("vertigo-pretty-{}", std::process::id()));
288        std::fs::create_dir_all(&dest_dir)?;
289        std::fs::write(
290            dest_dir.join("index.json"),
291            r#"{"run_js": "wasm_run.js", "wasm": "app.wasm"}"#,
292        )?;
293
294        let builder = || MountConfigBuilder::new("/", dest_dir.to_string_lossy());
295        let (Ok(default), Ok(pretty)) = (builder().build(), builder().pretty_html(true).build())
296        else {
297            panic!("index.json in {dest_dir:?} should read");
298        };
299
300        assert!(!default.pretty_html);
301        assert!(pretty.pretty_html);
302
303        std::fs::remove_dir_all(&dest_dir)
304    }
305
306    #[test]
307    fn precompress_in_release_follows_the_build() {
308        let builder = MountConfigBuilder::new("/", "build").precompress_in_release();
309
310        // `cargo test` builds with debug assertions, `cargo test --release` without
311        assert_eq!(builder.precompress, !cfg!(debug_assertions));
312    }
313
314    #[test]
315    fn env_carries_mount_point_and_public_path() -> std::io::Result<()> {
316        let dest_dir = std::env::temp_dir().join(format!("vertigo-mount-{}", std::process::id()));
317        std::fs::create_dir_all(&dest_dir)?;
318        std::fs::write(
319            dest_dir.join("index.json"),
320            r#"{"run_js": "wasm_run.js", "wasm": "app.wasm"}"#,
321        )?;
322
323        let Ok(config) = MountConfig::new(
324            "/panel",
325            dest_dir.to_string_lossy(),
326            vec![
327                ("api_url".into(), "/api".into()),
328                // the server knows better where it mounted the app
329                ("vertigo-mount-point".into(), "/elsewhere".into()),
330            ],
331            false,
332            false,
333        ) else {
334            panic!("index.json in {dest_dir:?} should read");
335        };
336
337        assert_eq!(config.env["api_url"], "/api");
338        assert_eq!(config.env["vertigo-mount-point"], "/panel");
339        assert_eq!(config.env["vertigo-public-path"], config.dest_http_root());
340
341        std::fs::remove_dir_all(&dest_dir)
342    }
343
344    #[test]
345    fn test_replace_prefix() {
346        assert_eq!(
347            replace_prefix("demo_build", "build/vertigo_demo.33.wasm"),
348            "build/vertigo_demo.33.wasm".to_string()
349        );
350
351        assert_eq!(
352            replace_prefix("demo_build", "build/vertigo_demo.33.wasm"),
353            "build/vertigo_demo.33.wasm".to_string()
354        );
355
356        assert_eq!(
357            replace_prefix(
358                "demo_build",
359                &format!("{VERTIGO_PUBLIC_BUILD_PATH_PLACEHOLDER}/vertigo_demo.33.wasm")
360            ),
361            "demo_build/vertigo_demo.33.wasm".to_string()
362        );
363    }
364}