1use fs_change_notifier::*;
2use headers::{
3 AcceptRanges, ContentLength, ContentRange, ContentType, ETag, HeaderMapExt, IfMatch, IfModifiedSince, IfNoneMatch,
4 IfUnmodifiedSince, LastModified,
5};
6use impulse_server_kit::prelude::*;
7use impulse_server_kit::salvo::http::HttpRange;
8use salvo::fs::NamedFile;
9use salvo::http::header::{CONTENT_DISPOSITION, CONTENT_ENCODING, CONTENT_TYPE, IF_NONE_MATCH, RANGE};
10use salvo::http::{HeaderMap, HeaderValue};
11use std::cmp;
12use std::collections::HashMap;
13use std::path::{Path, PathBuf};
14use std::sync::Arc;
15use tokio::sync::Mutex;
16
17const CHUNK_SIZE: u64 = 1024 * 1024;
18
19#[derive(Clone)]
20pub struct CachedFile {
21 pub etag: Option<ETag>,
22 pub last_modified: Option<std::time::SystemTime>,
23 pub content_type: mime::Mime,
24 pub content_encoding: Option<HeaderValue>,
25 pub length: u64,
26 pub content_disposition: Option<String>,
27 pub bytes: Vec<u8>,
28}
29
30fn any_match(etag: Option<&ETag>, req_headers: &HeaderMap) -> bool {
32 match req_headers.typed_get::<IfMatch>() {
33 None => true,
34 Some(if_match) => {
35 if if_match == IfMatch::any() {
36 true
37 } else if let Some(etag) = etag {
38 if_match.precondition_passes(etag)
39 } else {
40 false
41 }
42 }
43 }
44}
45
46fn none_match(etag: Option<&ETag>, req_headers: &HeaderMap) -> bool {
48 match req_headers.typed_get::<IfNoneMatch>() {
49 None => true,
50 Some(if_none_match) => {
51 if if_none_match == IfNoneMatch::any() {
52 false
53 } else if let Some(etag) = etag {
54 if_none_match.precondition_passes(etag)
55 } else {
56 true
57 }
58 }
59 }
60}
61
62impl CachedFile {
63 pub async fn construct_from(filename: &str, path: &Path, known_length: u64) -> MResult<Self> {
64 let named_file = NamedFile::builder(path)
65 .attached_name(filename)
66 .use_etag(true)
67 .use_last_modified(true)
68 .build()
69 .await
70 .map_err(|e| ServerError::from_private(e).with_404())?;
71
72 let etag = named_file.etag();
73 let last_modified = named_file.last_modified();
74 let content_type = named_file.content_type().clone();
75 let content_encoding = named_file.content_encoding().cloned();
76
77 Ok(Self {
78 etag,
79 last_modified,
80 content_type,
81 content_encoding,
82 content_disposition: Some(format!(r#"attachment; filename="{filename}""#)),
83 length: known_length,
84 bytes: tokio::fs::read(path)
85 .await
86 .map_err(|e| ServerError::from_private(e).with_404())?,
87 })
88 }
89
90 pub async fn send(&self, req_headers: &HeaderMap, res: &mut Response) {
91 let precondition_failed = if !any_match(self.etag.as_ref(), req_headers) {
93 true
94 } else if let (Some(last_modified), Some(since)) =
95 (&self.last_modified, req_headers.typed_get::<IfUnmodifiedSince>())
96 {
97 !since.precondition_passes(*last_modified)
98 } else {
99 false
100 };
101
102 let not_modified = if !none_match(self.etag.as_ref(), req_headers) {
104 true
105 } else if req_headers.contains_key(IF_NONE_MATCH) {
106 false
107 } else if let (Some(last_modified), Some(since)) = (&self.last_modified, req_headers.typed_get::<IfModifiedSince>())
108 {
109 !since.is_modified(*last_modified)
110 } else {
111 false
112 };
113
114 if let Some(content_disposition) = self.content_disposition.as_deref()
115 && let Ok(content_disposition) = content_disposition.parse::<HeaderValue>()
116 {
117 res.headers_mut().insert(CONTENT_DISPOSITION, content_disposition);
118 } else {
119 res
120 .headers_mut()
121 .insert(CONTENT_DISPOSITION, HeaderValue::from_static("inline"));
122 }
123 if !res.headers().contains_key(CONTENT_TYPE) {
124 res
125 .headers_mut()
126 .typed_insert(ContentType::from(self.content_type.clone()));
127 }
128 if let Some(lm) = self.last_modified {
129 res.headers_mut().typed_insert(LastModified::from(lm));
130 }
131 if let Some(etag) = self.etag.clone() {
132 res.headers_mut().typed_insert(etag);
133 }
134 res.headers_mut().typed_insert(AcceptRanges::bytes());
135
136 let mut length = self.length;
137 if let Some(content_encoding) = &self.content_encoding {
138 res.headers_mut().insert(CONTENT_ENCODING, content_encoding.clone());
139 }
140 let mut offset = 0;
141
142 let range = req_headers.get(RANGE);
144 if let Some(range) = range {
145 if let Ok(range) = range.to_str() {
146 if let Ok(range) = HttpRange::parse(range, length) {
147 length = range[0].length;
148 offset = range[0].start;
149 } else {
150 res.headers_mut().typed_insert(ContentRange::unsatisfied_bytes(length));
151 res.status_code(StatusCode::RANGE_NOT_SATISFIABLE);
152 return;
153 };
154 } else {
155 res.status_code(StatusCode::BAD_REQUEST);
156 return;
157 };
158 }
159
160 if precondition_failed {
161 res.status_code(StatusCode::PRECONDITION_FAILED);
162 return;
163 } else if not_modified {
164 res.status_code(StatusCode::NOT_MODIFIED);
165 return;
166 }
167
168 if offset != 0 || length != self.length || range.is_some() {
169 res.status_code(StatusCode::PARTIAL_CONTENT);
170 match ContentRange::bytes(offset..offset + length, self.length) {
171 Ok(content_range) => {
172 res.headers_mut().typed_insert(content_range);
173 }
174 Err(e) => {
175 tracing::error!(error = ?e, "Set file's content range failed");
176 }
177 }
178 let total_size = cmp::min(length, self.length);
179 res.headers_mut().typed_insert(ContentLength(total_size));
180
181 let max_bytes = cmp::min(total_size, CHUNK_SIZE) as usize;
182 let mut buf = Vec::<u8>::with_capacity(max_bytes);
183 let end = (offset as usize + max_bytes).min(self.bytes.len());
184 buf.extend_from_slice(&self.bytes[offset as usize..end]);
185
186 if let Err(e) = res.write_body(buf) {
187 tracing::error!(error = ?e, "Failed to send file part!");
188 }
189 } else {
190 res.status_code(StatusCode::OK);
191 res.headers_mut().typed_insert(ContentLength(length));
192
193 if let Err(e) = res.write_body(self.bytes.clone()) {
194 tracing::error!(error = ?e, "Failed to send file part!");
195 }
196 }
197 }
198}
199
200pub async fn send_file(
202 cacher: &Option<Arc<Mutex<CacheMap>>>,
203 req: &mut Request,
204 depot: &mut Depot,
205 res: &mut Response,
206 filename: &str,
207 path: &Path,
208) -> MResult<()> {
209 use salvo::Writer;
210
211 if let Some(cacher) = cacher.as_ref() {
212 {
213 let guard = cacher.lock().await;
214 if let Ok(Some(cached)) = guard.fetch(path) {
215 cached.send(req.headers(), res).await;
216 return Ok(());
217 }
218 }
219 let length = tokio::fs::metadata(path)
220 .await
221 .map_err(|e| ServerError::from_private(e).with_404())?
222 .len();
223 if length > 16 * 1024 * 1024 {
224 file_upload!(path.to_path_buf(), filename.to_string())
225 .write(req, depot, res)
226 .await;
227 } else {
228 let cached = CachedFile::construct_from(filename, path, length).await?;
229 {
230 let mut guard = cacher.lock().await;
231 guard.upsert(path, cached.clone())?;
232 }
233 cached.send(req.headers(), res).await;
234 }
235 } else {
236 file_upload!(path.to_path_buf(), filename.to_string())
237 .write(req, depot, res)
238 .await;
239 }
240 Ok(())
241}
242
243pub async fn send_html(
245 cacher: &Option<Arc<Mutex<CacheMap>>>,
246 req: &mut Request,
247 depot: &mut Depot,
248 res: &mut Response,
249 filename: &str,
250 path: &Path,
251) -> MResult<()> {
252 use salvo::Writer;
253
254 if let Some(cacher) = cacher.as_ref() {
255 let cached = {
256 let guard = cacher.lock().await;
257 guard.fetch(path)
258 };
259 if let Ok(Some(cached)) = cached {
260 let site = String::from_utf8_lossy_owned(cached.bytes);
261 html!(site).unwrap().write(req, depot, res).await;
262 return Ok(());
263 }
264 let length = tokio::fs::metadata(path)
265 .await
266 .map_err(|e| ServerError::from_private(e).with_404())?
267 .len();
268 if length > 16 * 1024 * 1024 {
269 let site = tokio::fs::read_to_string(path)
270 .await
271 .map_err(|e| ServerError::from_private(e).with_404())?;
272 html!(site).unwrap().write(req, depot, res).await;
273 } else {
274 let cached = CachedFile::construct_from(filename, path, length).await?;
275 {
276 let mut guard = cacher.lock().await;
277 guard.upsert(path, cached.clone())?;
278 }
279 let site = String::from_utf8_lossy_owned(cached.bytes);
280 html!(site).unwrap().write(req, depot, res).await;
281 }
282 } else {
283 let site = tokio::fs::read_to_string(path)
284 .await
285 .map_err(|e| ServerError::from_private(e).with_404())?;
286 html!(site).unwrap().write(req, depot, res).await;
287 }
288 Ok(())
289}
290
291pub struct CacheMap(HashMap<PathBuf, CachedFile>);
293
294impl CacheMap {
295 pub fn new() -> Arc<Mutex<Self>> {
297 Arc::new(Mutex::new(Self(HashMap::new())))
298 }
299
300 pub fn clear(&mut self) {
302 self.0.clear();
303 }
304
305 pub fn upsert(&mut self, path: impl AsRef<Path>, content: CachedFile) -> MResult<()> {
307 let path = std::fs::canonicalize(path.as_ref()).map_err(ServerError::from_private)?;
308 self.0.insert(path, content);
309 Ok(())
310 }
311
312 pub fn fetch(&self, path: impl AsRef<Path>) -> MResult<Option<CachedFile>> {
314 let path = std::fs::canonicalize(path.as_ref()).map_err(ServerError::from_private)?;
315 Ok(self.0.get(&path).cloned())
316 }
317
318 pub fn invalidate(&mut self, path: impl AsRef<Path>) -> MResult<()> {
320 let path = std::fs::canonicalize(path.as_ref()).map_err(ServerError::from_private)?;
321 self.0.remove(&path);
322 Ok(())
323 }
324}
325
326pub async fn cache_runner(path: impl AsRef<Path>, cache_map: Arc<Mutex<CacheMap>>) -> MResult<()> {
328 let empty = std::collections::HashSet::new();
329 loop {
330 let (mut wr, rx) = create_watcher(|e| tracing::error!("{e:?}")).map_err(|e| {
331 ServerError::from_private_str(e.to_string())
332 .with_public("Can't create FS watcher to cache runner!")
333 .with_500()
334 })?;
335 wr.watch(path.as_ref(), RecursiveMode::Recursive)
336 .map_err(ServerError::from_private)?;
337
338 let files = fetch_changed(path.as_ref(), rx, &empty).await;
339 {
340 let mut guard = cache_map.lock().await;
341 for file in files {
342 guard.invalidate(file)?;
343 }
344 }
345 }
346}