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