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}
17
18impl MountConfigBuilder {
19    pub fn new(mount_point: impl Into<String>, dest_dir: impl Into<String>) -> MountConfigBuilder {
20        MountConfigBuilder {
21            mount_point: mount_point.into(),
22            dest_dir: dest_dir.into(),
23            env: vec![],
24            wasm_preload: false,
25            disable_hydration: false,
26            ssr_fetch_base: None,
27        }
28    }
29
30    pub fn envs(mut self, envs: Vec<(String, String)>) -> Self {
31        self.env = envs;
32        self
33    }
34
35    pub fn env(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
36        self.env.push((key.into(), value.into()));
37        self
38    }
39
40    pub fn wasm_preload(mut self, wasm_preload: bool) -> Self {
41        self.wasm_preload = wasm_preload;
42        self
43    }
44
45    pub fn disable_hydration(mut self, disable_hydration: bool) -> Self {
46        self.disable_hydration = disable_hydration;
47        self
48    }
49
50    /// Origin against which SSR resolves relative fetch URLs (`/api/posts`), e.g. `http://127.0.0.1:8080`.
51    ///
52    /// Without it, fetching a relative URL during SSR fails.
53    pub fn ssr_fetch_base(mut self, origin: impl Into<String>) -> Self {
54        self.ssr_fetch_base = Some(origin.into());
55        self
56    }
57
58    pub fn build(self) -> Result<MountConfig, ErrorCode> {
59        let mut config = MountConfig::new(
60            self.mount_point,
61            self.dest_dir,
62            self.env,
63            self.wasm_preload,
64            self.disable_hydration,
65        )?;
66        config.ssr_fetch_base = self.ssr_fetch_base;
67        Ok(config)
68    }
69}
70
71#[derive(Clone, Debug)]
72pub struct MountConfig {
73    /// Mount point in URL
74    mount_point: String,
75    /// Build destination directory (where wasm file and wasm_run.js are stored)
76    dest_dir: String,
77    /// waasm_run.js taken from index.json
78    run_js: String,
79    /// path to wasm-file taken from index.json
80    wasm_path: String,
81    /// Environment variables passed to WASM runtime - together with the mount point and the
82    /// public path of the build (`vertigo-mount-point`, `vertigo-public-path`)
83    pub env: Arc<HashMap<String, String>>,
84    /// Whether to preload wasm script using <link rel="preload">
85    pub wasm_preload: bool,
86    /// Whether to disable hydration
87    pub disable_hydration: bool,
88    /// See [`MountConfigBuilder::ssr_fetch_base`]
89    pub ssr_fetch_base: Option<String>,
90}
91
92impl MountConfig {
93    pub fn new(
94        public_mount_point: impl Into<String>,
95        dest_dir: impl Into<String>,
96        env: Vec<(String, String)>,
97        wasm_preload: bool,
98        disable_hydration: bool,
99    ) -> Result<MountConfig, ErrorCode> {
100        let dest_dir = dest_dir.into();
101        let index_model = read_index(&dest_dir)?;
102
103        let mut config = MountConfig {
104            dest_dir,
105            mount_point: public_mount_point.into(),
106            run_js: index_model.run_js,
107            wasm_path: index_model.wasm,
108            env: Arc::default(),
109            wasm_preload,
110            disable_hydration,
111            ssr_fetch_base: None,
112        };
113
114        // The app gets them wherever it runs - in the browser as `data-env-*`, during SSR from
115        // the host - so both sides build the same paths (`Driver::route_to_public`,
116        // `Driver::public_build_path`)
117        let mut env: HashMap<String, String> = env.into_iter().collect();
118        env.insert(VERTIGO_MOUNT_POINT_ENV.into(), config.mount_point.clone());
119        env.insert(VERTIGO_PUBLIC_PATH_ENV.into(), config.dest_http_root());
120        config.env = Arc::new(env);
121
122        Ok(config)
123    }
124
125    pub fn mount_point(&self) -> &str {
126        self.mount_point.as_str()
127    }
128
129    pub fn dest_dir(&self) -> &str {
130        self.dest_dir.trim_start_matches("./")
131    }
132
133    pub fn dest_http_root(&self) -> String {
134        Path::new(&self.mount_point)
135            .join(self.dest_dir())
136            .components()
137            .as_path()
138            .to_string_lossy()
139            .into_owned()
140    }
141
142    pub fn get_wasm_http_path(&self) -> String {
143        self.translate_to_http(&self.wasm_path)
144    }
145
146    pub fn get_run_js_http_path(&self) -> String {
147        self.translate_to_http(&self.run_js)
148    }
149
150    pub fn get_wasm_fs_path(&self) -> String {
151        self.translate_to_fs(&self.wasm_path)
152    }
153
154    fn translate_to_http(&self, fs_path: impl Into<String>) -> String {
155        let fs_path = fs_path.into();
156        fs_path.replace(
157            VERTIGO_PUBLIC_BUILD_PATH_PLACEHOLDER,
158            &self.dest_http_root(),
159        )
160    }
161
162    fn translate_to_fs(&self, http_path: impl Into<String>) -> String {
163        let http_path = http_path.into();
164        replace_prefix(&self.dest_dir, &http_path)
165    }
166}
167
168fn read_index(dest_dir: &str) -> Result<IndexModel, ErrorCode> {
169    let index_path = Path::new(dest_dir).join("index.json");
170    let index_html = match std::fs::read_to_string(&index_path) {
171        Ok(data) => data,
172        Err(err) => {
173            log::error!("File read error: file={index_path:?}, error={err}, dest_dir={dest_dir}");
174            return Err(ErrorCode::ServeCantReadIndexFile);
175        }
176    };
177
178    serde_json::from_str::<IndexModel>(&index_html).map_err(|err| {
179        log::error!("File read error 2: file={index_path:?}, error={err}, dest_dir={dest_dir}");
180        ErrorCode::ServeCantReadIndexFile
181    })
182}
183
184fn replace_prefix(dest_dir: &str, path: &str) -> String {
185    if path.starts_with(VERTIGO_PUBLIC_BUILD_PATH_PLACEHOLDER) {
186        // Dynamic path resolution
187        path.replace(VERTIGO_PUBLIC_BUILD_PATH_PLACEHOLDER, dest_dir)
188    } else {
189        // Static path resolution
190        path.to_string()
191    }
192}
193
194#[cfg(test)]
195mod tests {
196    use vertigo::dev::VERTIGO_PUBLIC_BUILD_PATH_PLACEHOLDER;
197
198    use super::{MountConfig, replace_prefix};
199
200    #[test]
201    fn env_carries_mount_point_and_public_path() -> std::io::Result<()> {
202        let dest_dir = std::env::temp_dir().join(format!("vertigo-mount-{}", std::process::id()));
203        std::fs::create_dir_all(&dest_dir)?;
204        std::fs::write(
205            dest_dir.join("index.json"),
206            r#"{"run_js": "wasm_run.js", "wasm": "app.wasm"}"#,
207        )?;
208
209        let Ok(config) = MountConfig::new(
210            "/panel",
211            dest_dir.to_string_lossy(),
212            vec![
213                ("api_url".into(), "/api".into()),
214                // the server knows better where it mounted the app
215                ("vertigo-mount-point".into(), "/elsewhere".into()),
216            ],
217            false,
218            false,
219        ) else {
220            panic!("index.json in {dest_dir:?} should read");
221        };
222
223        assert_eq!(config.env["api_url"], "/api");
224        assert_eq!(config.env["vertigo-mount-point"], "/panel");
225        assert_eq!(config.env["vertigo-public-path"], config.dest_http_root());
226
227        std::fs::remove_dir_all(&dest_dir)
228    }
229
230    #[test]
231    fn test_replace_prefix() {
232        assert_eq!(
233            replace_prefix("demo_build", "build/vertigo_demo.33.wasm"),
234            "build/vertigo_demo.33.wasm".to_string()
235        );
236
237        assert_eq!(
238            replace_prefix("demo_build", "build/vertigo_demo.33.wasm"),
239            "build/vertigo_demo.33.wasm".to_string()
240        );
241
242        assert_eq!(
243            replace_prefix(
244                "demo_build",
245                &format!("{VERTIGO_PUBLIC_BUILD_PATH_PLACEHOLDER}/vertigo_demo.33.wasm")
246            ),
247            "demo_build/vertigo_demo.33.wasm".to_string()
248        );
249    }
250}