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
58pub struct StaticRouter {
60 path: PathBuf,
61 cacher: Option<Arc<Mutex<CacheMap>>>,
62}
63
64pub struct NoRedirectStaticRouter {
68 path: PathBuf,
69 cacher: Option<Arc<Mutex<CacheMap>>>,
70}
71
72pub struct ProvidedRoutesStaticRouter {
74 path: PathBuf,
75 possible_routes: Vec<String>,
76 cacher: Option<Arc<Mutex<CacheMap>>>,
77}
78
79impl StaticRouter {
80 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 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 pub fn with_no_redirect(self) -> NoRedirectStaticRouter {
122 NoRedirectStaticRouter {
123 path: self.path,
124 cacher: self.cacher,
125 }
126 }
127
128 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
189pub 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
198pub 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}