impulse_static_server/
static_routes.rs

1use impulse_server_kit::impulse_utils::prelude::*;
2use impulse_server_kit::prelude::*;
3use impulse_server_kit::salvo::FlowCtrl;
4use std::path::{Path, PathBuf};
5use std::sync::Arc;
6use tokio::sync::Mutex;
7
8use crate::caching::{CacheMap, cache_runner, send_file, send_html};
9
10const LOCAL_FRONTEND_DISTRIBUTABLE: &str = "dist";
11const CONTAINER_FRONTEND_DISTRIBUTABLE: &str = "/usr/local/frontend-dist";
12
13async fn common_handle(
14  cacher: &Option<Arc<Mutex<CacheMap>>>,
15  dist_path: &Path,
16  filename: String,
17  filepath: PathBuf,
18  req: &mut Request,
19  depot: &mut Depot,
20  res: &mut Response,
21) {
22  use salvo::Writer;
23
24  if filename.contains(".") {
25    match filename.split('.').collect::<Vec<_>>().last() {
26      Some(&"html") => {
27        if let Err(e) = send_html(cacher, req, depot, res, &filename, &filepath).await {
28          e.with_public("There is no such file!")
29            .with_404()
30            .write(req, depot, res)
31            .await;
32        }
33      }
34      _ => {
35        if let Err(e) = send_file(cacher, req, depot, res, &filename, &filepath).await {
36          e.with_public("There is no such file!")
37            .with_404()
38            .write(req, depot, res)
39            .await;
40        }
41      }
42    }
43  } else if filepath.exists() {
44    if let Err(e) = send_file(cacher, req, depot, res, &filename, &filepath).await {
45      e.with_public("There is no such file!")
46        .with_404()
47        .write(req, depot, res)
48        .await;
49    }
50  } else if let Err(e) = send_html(cacher, req, depot, res, "index.html", &dist_path.join("index.html")).await {
51    e.with_public("There is no such file!")
52      .with_404()
53      .write(req, depot, res)
54      .await;
55  }
56}
57
58/// Static router.
59pub struct StaticRouter {
60  path: PathBuf,
61  cacher: Option<Arc<Mutex<CacheMap>>>,
62}
63
64/// Static router with no redirections allowed.
65///
66/// It serves all files from given path, but if server requested non-existing file, it will not redirect it to `index.html`.
67pub struct NoRedirectStaticRouter {
68  path: PathBuf,
69  cacher: Option<Arc<Mutex<CacheMap>>>,
70}
71
72/// Static router with only provided routes.
73pub struct ProvidedRoutesStaticRouter {
74  path: PathBuf,
75  possible_routes: Vec<String>,
76  cacher: Option<Arc<Mutex<CacheMap>>>,
77}
78
79impl StaticRouter {
80  /// Create static router from given path.
81  pub fn new(path: impl AsRef<Path>) -> MResult<Self> {
82    if !path.as_ref().exists() {
83      ServerError::from_private_str(format!("There is no such folder as {:?}!", path.as_ref()))
84        .with_500()
85        .bail()?;
86    }
87
88    Ok(Self {
89      path: path.as_ref().to_owned(),
90      cacher: None,
91    })
92  }
93
94  /// Create static router from given path with in-memory cacher.
95  pub fn new_with_cacher(path: impl AsRef<Path>) -> MResult<Self> {
96    if !path.as_ref().exists() {
97      ServerError::from_private_str(format!("There is no such folder as {:?}!", path.as_ref()))
98        .with_500()
99        .bail()?;
100    }
101
102    let cacher = CacheMap::new();
103    tokio::task::spawn({
104      let path = path.as_ref().to_path_buf();
105      let cacher = cacher.clone();
106
107      async move {
108        if let Err(e) = cache_runner(&path, cacher).await {
109          tracing::error!("{e}");
110        }
111      }
112    });
113
114    Ok(Self {
115      path: path.as_ref().to_owned(),
116      cacher: Some(cacher),
117    })
118  }
119
120  /// Disable redirect to `index.html` when no requested file found.
121  pub fn with_no_redirect(self) -> NoRedirectStaticRouter {
122    NoRedirectStaticRouter {
123      path: self.path,
124      cacher: self.cacher,
125    }
126  }
127
128  /// Disable redirect and provide routes' list.
129  pub fn with_routes_list(self, routes: Vec<String>) -> ProvidedRoutesStaticRouter {
130    ProvidedRoutesStaticRouter {
131      path: self.path,
132      possible_routes: routes,
133      cacher: self.cacher,
134    }
135  }
136}
137
138#[salvo::async_trait]
139impl salvo::Handler for StaticRouter {
140  #[tracing::instrument(skip_all, fields(http.uri = req.uri().path(), http.method = req.method().as_str()))]
141  async fn handle(&self, req: &mut Request, depot: &mut Depot, res: &mut Response, _: &mut FlowCtrl) {
142    let mut filename = req.param::<String>("rest_path").unwrap_or(String::from("index.html"));
143    if filename.is_empty() {
144      filename = String::from("index.html");
145    }
146    let filepath = self.path.join(&filename);
147    common_handle(&self.cacher, &self.path, filename, filepath, req, depot, res).await;
148  }
149}
150
151#[salvo::async_trait]
152impl salvo::Handler for NoRedirectStaticRouter {
153  async fn handle(&self, req: &mut Request, depot: &mut Depot, res: &mut Response, flow: &mut salvo::FlowCtrl) {
154    let mut filename = req.param::<String>("rest_path").unwrap_or(String::from("index.html"));
155    if filename.is_empty() {
156      filename = String::from("index.html");
157    }
158    let filepath = self.path.join(&filename);
159
160    if !filepath.exists() {
161      while flow.has_next() {
162        flow.call_next(req, depot, res).await;
163      }
164      return;
165    }
166    common_handle(&self.cacher, &self.path, filename, filepath, req, depot, res).await;
167  }
168}
169
170#[salvo::async_trait]
171impl salvo::Handler for ProvidedRoutesStaticRouter {
172  async fn handle(&self, req: &mut Request, depot: &mut Depot, res: &mut Response, flow: &mut salvo::FlowCtrl) {
173    let mut filename = req.param::<String>("rest_path").unwrap_or(String::from("index.html"));
174    if filename.is_empty() {
175      filename = String::from("index.html");
176    }
177    let filepath = self.path.join(&filename);
178
179    if !filepath.exists() || !self.possible_routes.iter().any(|pr| pr.as_str().eq(filename.as_str())) {
180      while flow.has_next() {
181        flow.call_next(req, depot, res).await;
182      }
183      return;
184    }
185    common_handle(&self.cacher, &self.path, filename, filepath, req, depot, res).await;
186  }
187}
188
189/// Static router with given `dist` path.
190///
191/// Returns error if dist folder doesn't exist.
192///
193/// Note that your `dist` folder must contains `index.html` file.
194pub fn frontend_router_from_given_dist(dist: &Path) -> MResult<Router> {
195  Ok(Router::with_path("{**rest_path}").get(StaticRouter::new_with_cacher(dist)?))
196}
197
198/// Static router.
199///
200/// All that you need to include your app internals inside your application.
201///
202/// Note that `cc-static-server` serves only files from `dist` or `/usr/local/frontend-dist` folders.
203/// Make sure that `dist` folder is located in one folder with your application, not in current working
204/// directory provided by `$ pwd`.
205///
206/// Returns error if neither `dist` nor `/usr/local/frontend-dist` folder exists.
207pub fn frontend_router() -> MResult<Router> {
208  let dist = StaticRouter::new_with_cacher(LOCAL_FRONTEND_DISTRIBUTABLE)
209    .or(StaticRouter::new_with_cacher(CONTAINER_FRONTEND_DISTRIBUTABLE))?;
210
211  Ok(Router::with_path("{**rest_path}").get(dist))
212}