1use crate::http::response::request_templates::return_status;
2
3use super::super::http::response::*;
4use super::super::http::http_value::*;
5use super::super::context::Rc;
6use std::future::Future;
7use std::pin::Pin;
8use std::slice::Iter;
9use std::sync::Arc;
10use std::sync::OnceLock;
11use std::sync::RwLock;
12use regex::Regex;
13pub static ROOT_URL: OnceLock<Url> = OnceLock::new();
14use super::super::app::middleware::*;
15
16pub trait AsyncUrlHandler: Send + Sync + 'static {
17 fn handle(
18 &self,
19 rc: Rc
20 ) -> Pin<Box<dyn Future<Output = Rc> + Send + 'static>>;
21}
22
23impl<F, Fut> AsyncUrlHandler for F
24where
25 F: Fn(Rc) -> Fut + Send + Sync + 'static,
26 Fut: Future<Output = Rc> + Send + 'static,
27{
28 fn handle(
29 &self,
30 rc: Rc
31 ) -> Pin<Box<dyn Future<Output = Rc> + Send + 'static>> {
32 Box::pin(self(rc))
33 }
34}
35
36pub struct Url {
37 pub path: PathPattern,
38 pub children: RwLock<Children>,
39 pub ancestor: Ancestor,
40 pub method: RwLock<Option<Arc<dyn AsyncUrlHandler>>>,
41 pub middlewares: RwLock<MiddleWares>,
42 pub params: RwLock<Params>,
43}
44
45#[derive(Clone, Debug)]
46pub enum PathPattern {
47 Literal(String), Regex(String), Pattern(String, String), Any, Argument(String), AnyPath, }
54
55impl PathPattern{
56 pub fn literal_path<T: Into<String>>(path: T) -> Self {
57 Self::Literal(path.into())
58 }
59
60 pub fn regex_path<T: Into<String>>(path: T) -> Self {
61 Self::Regex(path.into())
62 }
63
64 pub fn regex_pattern<T: Into<String>, A: Into<String>>(path: T, name: A) -> Self {
65 Self::Pattern(path.into(), name.into())
66 }
67
68 pub fn any() -> Self {
69 Self::Any
70 }
71
72 pub fn argument<A: Into<String>>(name: A) -> Self {
73 Self::Argument(name.into())
74 }
75
76 pub fn any_path() -> Self {
77 Self::AnyPath
78 }
79}
80
81pub mod path_pattern_creator {
82 use super::PathPattern;
83
84 pub fn literal_path<T: Into<String>>(path: T) -> PathPattern {
88 PathPattern::Literal(path.into())
89 }
90
91 pub fn trailing_slash() -> PathPattern {
92 PathPattern::Literal("".to_string())
93 }
94
95 pub fn regex_path<T: Into<String>>(path: T) -> PathPattern {
99 PathPattern::Regex(path.into())
100 }
101
102 pub fn regex_pattern<T: Into<String>, A: Into<String>>(path: T, name: A) -> PathPattern {
107 PathPattern::regex_pattern(path.into(), name.into())
108 }
109
110 pub fn any() -> PathPattern {
114 PathPattern::Any
115 }
116
117 pub fn argument<A: Into<String>>(name: A) -> PathPattern {
121 PathPattern::Argument(name.into())
122 }
123
124 pub fn any_path() -> PathPattern {
128 PathPattern::AnyPath
129 }
130}
131
132impl PartialEq for PathPattern {
133 fn eq(&self, other: &Self) -> bool {
134 match (self, other) {
135 (PathPattern::Literal(l), PathPattern::Literal(r)) => l == r,
136 (PathPattern::Regex(l), PathPattern::Regex(r)) => l == r,
137 (PathPattern::Any, PathPattern::Any) => true,
138 (PathPattern::AnyPath, PathPattern::AnyPath) => true,
139 _ => false,
140 }
141 }
142}
143
144impl std::fmt::Display for PathPattern {
145 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
146 match self {
147 PathPattern::Literal(path) => write!(f, "Literal: {}", path),
148 PathPattern::Regex(path) => write!(f, "Regex: {}", path),
149 PathPattern::Pattern(path, arg) => write!(f, "Regex {}: {}", arg, path),
150 PathPattern::Any => write!(f, "*"),
151 PathPattern::Argument(arg) => write!(f, "* {}", arg),
152 PathPattern::AnyPath => write!(f, "**"),
153 }
154 }
155}
156
157pub enum Children {
158 Nil,
159 Some(Vec<Arc<Url>>),
160}
161
162pub enum Ancestor {
163 Nil,
164 Some(Arc<Url>),
165}
166
167impl std::fmt::Display for Url {
168 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
169 let mut children_str = String::new();
171 let mut func_str = String::new();
172 if let Some(_) = self.method.read().unwrap().as_ref() {
174 func_str.push_str(&format!("Function Exists, "));
175 } else {
176 func_str.push_str("None, ");
177 }
178 if let Children::Some(children) = &*self.children.read().unwrap() {
179 for child in children.iter() {
180 children_str.push_str(&format!("{}\n", child));
181 }
182 } else {
183 children_str.push_str("");
184 }
185 write!(f, "Url: {}, Function: {}, {{{}}}", self.path, func_str, children_str)
186 }
187}
188
189#[derive(Clone, Debug)]
190pub struct Params {
191 pub max_body_size: Option<usize>,
192 pub allowed_methods: Option<Vec<HttpMethod>>,
193 pub allowed_content_type: Option<Vec<HttpContentType>>,
194}
195
196impl Params {
197 pub fn new() -> Self {
198 Self {
199 max_body_size: None,
200 allowed_methods: None,
201 allowed_content_type: None,
202 }
203 }
204
205 pub fn set_max_body_size(&mut self, size: usize) {
206 self.max_body_size = Some(size);
207 }
208
209 pub fn reset_max_body_size(&mut self) {
210 self.max_body_size = None;
211 }
212
213 pub fn set_allowed_methods(&mut self, methods: Vec<HttpMethod>) {
214 self.allowed_methods = Some(methods);
215 }
216
217 pub fn add_allowed_methods(&mut self, method: HttpMethod) {
218 if let Some(ref mut methods) = self.allowed_methods {
219 methods.push(method);
220 } else {
221 self.allowed_methods = Some(vec![method]);
222 }
223 }
224
225 pub fn remove_allowed_method(&mut self, method: HttpMethod) {
226 if let Some(ref mut methods) = self.allowed_methods {
227 methods.retain(|m| *m != method);
228 }
229 }
230
231 pub fn reset_allowed_methods(&mut self) {
232 self.allowed_methods = None;
233 }
234
235 pub fn set_allowed_content_type(&mut self, content_types: Vec<HttpContentType>) {
236 self.allowed_content_type = Some(content_types);
237 }
238
239 pub fn add_allowed_content_type(&mut self, content_type: HttpContentType) {
240 if let Some(ref mut content_types) = self.allowed_content_type {
241 content_types.push(content_type);
242 } else {
243 self.allowed_content_type = Some(vec![content_type]);
244 }
245 }
246
247 pub fn remove_allowed_content_type(&mut self, content_type: HttpContentType) {
248 if let Some(ref mut content_types) = self.allowed_content_type {
249 content_types.retain(|ct| *ct != content_type);
250 }
251 }
252
253 pub fn reset_allowed_content_type(&mut self) {
254 self.allowed_content_type = None;
255 }
256
257 pub fn combine(&self, mut c: Params) -> Self {
258 if None == c.max_body_size {
259 c.max_body_size = self.max_body_size.clone();
260 }
261 if None == c.allowed_methods {
262 c.allowed_methods = self.allowed_methods.clone();
263 }
264 if None == c.allowed_content_type {
265 c.allowed_content_type = self.allowed_content_type.clone();
266 }
267 c
268 }
269}
270
271impl Default for Params {
272 fn default() -> Self {
273 Self::new()
274 }
275}
276
277#[derive(Clone)]
278pub enum MiddleWares {
279 Nil,
280 MiddleWare(Arc<Vec<Arc<dyn AsyncMiddleware>>>),
281}
282
283impl MiddleWares{
284 pub fn new() -> Self {
285 Self::Nil
286 }
287
288 pub fn add_middleware(&mut self, middleware: Arc<dyn AsyncMiddleware>) {
289 match self {
290 MiddleWares::Nil => {
291 *self = MiddleWares::MiddleWare(Arc::new(vec![middleware]));
292 }
293 MiddleWares::MiddleWare(middlewares) => {
294 let middlewares = Arc::make_mut(middlewares);
295 middlewares.push(middleware);
296 }
297 }
298 }
299
300 pub fn remove_middleware(&mut self, target: &Arc<dyn AsyncMiddleware>) -> bool {
303 match self {
304 MiddleWares::Nil => false,
305 MiddleWares::MiddleWare(middlewares) => {
306 let middlewares = Arc::make_mut(middlewares);
308 if let Some(pos) = middlewares.iter().position(|m| Arc::ptr_eq(m, target)) {
309 middlewares.remove(pos);
310 if middlewares.is_empty() {
312 *self = MiddleWares::Nil;
313 }
314 return true;
315 }
316 false
317 }
318 }
319 }
320
321 pub fn get_middlewares(&self) -> Option<Arc<Vec<Arc<dyn AsyncMiddleware>>>> {
322 match self {
323 MiddleWares::Nil => None,
324 MiddleWares::MiddleWare(middlewares) => Some(middlewares.clone()),
325 }
326 }
327
328 pub fn parse(
329 middlewares: &Option<Arc<Vec<Arc<dyn AsyncMiddleware>>>>
330 ) -> MiddleWares {
331 match middlewares {
332 Some(middlewares) => MiddleWares::MiddleWare(middlewares.clone()),
333 None => MiddleWares::Nil,
334 }
335 }
336}
337
338impl IntoIterator for MiddleWares {
339 type Item = Arc<dyn AsyncMiddleware>;
340 type IntoIter = std::vec::IntoIter<Self::Item>;
341
342 fn into_iter(self) -> Self::IntoIter {
343 match self {
344 MiddleWares::Nil => Vec::new().into_iter(),
345 MiddleWares::MiddleWare(vec_arc) => {
346 match Arc::try_unwrap(vec_arc) {
349 Ok(vec) => vec.into_iter(),
350 Err(arc) => (*arc).clone().into_iter(),
351 }
352 }
353 }
354 }
355}
356
357impl Url {
358 pub async fn run(&self, mut rc: Rc) -> Rc {
359 let handler_opt = {
360 let guard = self.method.read().unwrap();
361 guard.clone()
362 };
363 let middlewares = {
365 let guard = self.middlewares.read().unwrap();
366 guard.clone()
367 };
368 if let Some(method) = handler_opt {
370 if let MiddleWares::MiddleWare(_) = middlewares {
372 let base = Arc::new(move |rc: Rc| {
373 method.handle(rc)
374 }) as Arc<dyn Fn(Rc) -> Pin<Box<dyn Future<Output = Rc> + Send>> + Send + Sync>;
375
376 println!("Start middleware chain building");
377 let chain = middlewares.clone().into_iter().rev().fold(base, |next, mw| {
379 let next_clone = next.clone();
380 Arc::new(move |rc: Rc| {
381 let next_fn = next_clone.clone();
383 mw.handle(rc, Box::new(move |r| next_fn(r)))
384 }) as Arc<dyn Fn(Rc) -> Pin<Box<dyn Future<Output = Rc> + Send>> + Send + Sync>
385 });
386 return chain(rc).await
388 } else {
389 return method.handle(rc).await;
390 }
391 }
393 rc.response = request_templates::return_status(StatusCode::NOT_FOUND);
394 rc
396 }
397
398 pub fn walk<'a>(
401 self: Arc<Self>,
402 mut path: Iter<'a, &str>,
403 ) -> Pin<Box<dyn Future<Output = Option<Arc<Self>>> + Send + 'a>> {
404
405 let this_segment = match path.next() {
410 Some(s) => *s,
411 None => "",
412 };
413
414 let guard = self.children.read().unwrap();
416 let children = if let Children::Some(children) = &*guard {
418 children.clone()
419 } else {
420 return Box::pin(async { None });
421 };
422 drop(guard); Box::pin(async move {
426 for child_url in children.iter() {
427 match &child_url.path {
429
430 PathPattern::Literal(p) => {
432 if p == this_segment {
433 if path.len() >= 1 {
435 return child_url.clone().walk(path).await;
436 } else {
437 return Some(child_url.clone());
438 }
439 }
440 }
441
442 PathPattern::Regex(regex_str) | PathPattern::Pattern(regex_str, _ )=> {
444 let re = Regex::new(regex_str).unwrap();
445 if re.is_match(this_segment) {
447 if path.len() > 1 {
448 return child_url.clone().walk(path).await;
449 } else {
450 return Some(child_url.clone());
451 }
452 }
453 }
454
455 PathPattern::Any | PathPattern::Argument(_) => {
457 if path.len() >= 1 {
458 return child_url.clone().walk(path).await;
460 } else {
461 return Some(child_url.clone());
462 }
463 }
464
465 PathPattern::AnyPath => {
467 return Some(child_url.clone());
468 }
469 }
470 }
471 None
472 })
473 }
474
475 pub async fn walk_str(self: Arc<Self>, path: &str) -> Arc<Url> {
476 let mut path = path.split('/').collect::<Vec<&str>>();
477 path.remove(0);
478 self.walk(path.iter()).await.unwrap_or_else(|| {
481 dangling_url()
483 })
484 }
485
486 pub fn get_segment_index<S: AsRef<str>>(self: &Arc<Self>, name: S) -> Option<usize> {
490 let mut index = None;
491 self._step_get_segment_index(name.as_ref(), &mut index);
492 index
493 }
494
495 fn _step_get_segment_index(self: &Arc<Self>, match_path: &str, index: &mut Option<usize>) {
498 if let None = index {
499 match &self.path {
500 PathPattern::Argument(arg) | PathPattern::Pattern(_, arg) => {
501 if arg == &match_path {
502 *index = Some(0);
503 }
504 }
505 _ => {}
506 }
507 }
508
509 match &self.ancestor {
510 Ancestor::Nil => {
511 if let Some(i) = index {
512 if *i > 0 {
513 *i -= 1;
514 }
515 }
516 }
517 Ancestor::Some(ancestor) => {
518 if let Some(i) = index {
519 *i += 1;
520 }
521 ancestor._step_get_segment_index(match_path, index);
522 }
523 }
524 }
525
526 pub async fn request_check(self: Arc<Self>, rc: &mut Rc) -> bool {
530 if let Some(methods) = self.get_allowed_methods () {
531 if !methods.contains(&rc.method()) {
532 rc.response = return_status(StatusCode::METHOD_NOT_ALLOWED);
533 return false;
534 }
535 }
536 if let Some(content_types) = self.get_allowed_content_type() {
537 if let Some(uploaded_content_type) = rc.meta.get_content_type() {
538 if !content_types.contains(&uploaded_content_type) {
539 rc.response = return_status(StatusCode::UNSUPPORTED_MEDIA_TYPE);
540 return false;
541 }
542 }
543 }
544 true
545 }
546
547 pub fn run_child(
550 self: Arc<Self>,
551 mut rc: Rc,
552 ) -> Pin<Box<dyn Future<Output = Rc> + Send>> {
553 Box::pin(async move {
554 let handler_opt = {
555 let guard = self.method.read().unwrap();
556 guard.clone()
557 };
558 if let Some(handler) = handler_opt {
559 return handler.handle(rc).await;
560 } else {
561 rc.response = request_templates::return_status(StatusCode::NOT_FOUND);
562 return rc;
563 }
564 })
565 }
566
567 pub fn kill_child(self: &Arc<Self>, child: PathPattern) -> Result<(), String> {
575 let mut guard = self.children.write().unwrap();
577 match &mut *guard {
578 Children::Nil => Err(format!("No children found")),
579 Children::Some(children) => {
580 if let Some(pos) = children.iter().position(|c| c.path == child) {
582 children.remove(pos);
583 Ok(())
584 } else {
585 Err(format!("Child not found: {}", child))
586 }
587 }
588 }
589 }
590
591 pub fn childbirth(
605 self: &Arc<Self>,
606 child: PathPattern,
607 function: Option<Arc<dyn AsyncUrlHandler>>,
608 middleware: Option<Arc<Vec<Arc<dyn AsyncMiddleware>>>>,
609 params: Params,
610 ) -> Result<Arc<Url>, String> {
611 println!("Creating child URL: {:?}", child);
612
613 if self.clone().child_exists(&child) {
615 self.kill_child(child.clone())?;
616 }
617
618 let new_child = Arc::new(Url {
620 path: child,
621 children: RwLock::new(Children::Nil),
622 ancestor: Ancestor::Some(Arc::clone(&self)),
623 method: RwLock::new(function),
624 middlewares: RwLock::new(MiddleWares::parse(&middleware)),
625 params: RwLock::new(self.combine_params_for(params)),
626 });
627
628 let mut guard = self.children.write().unwrap();
630 match &mut *guard {
631 Children::Nil => {
632 *guard = Children::Some(vec![new_child.clone()]);
633 }
634 Children::Some(vec_children) => {
635 vec_children.push(new_child.clone());
636 }
637 }
638
639 Ok(new_child)
640 }
641
642 pub fn get_children(self: Arc<Self>, child: PathPattern) -> Result<Arc<Url>, String> {
643 let guard = self.children.read().unwrap();
645 match &*guard {
646 Children::Nil => Err(format!("No children found")),
647 Children::Some(children) => {
648 for child_url in children.iter() {
649 if child_url.path == child {
650 return Ok(child_url.clone());
651 }
652 }
653 Err(format!("Child not found: {}", child))
654 }
655 }
656 }
657
658 pub fn default_url(self: &Arc<Self>, path: PathPattern) -> Arc<Self> {
659 let new_url = Arc::new(Url {
661 path,
662 children: RwLock::new(Children::Nil),
663 ancestor: Ancestor::Nil,
664 method: RwLock::new(None),
665 middlewares: RwLock::new(MiddleWares::Nil),
666 params: RwLock::new(Params::new()),
667 });
668 new_url
669 }
670
671 pub fn get_child_or_create(self: Arc<Self>, child: PathPattern) -> Result<Arc<Self>, String> {
680 {
681 let guard = self.children.read().unwrap();
682 match &*guard {
683 Children::Nil => {
684 }
686 Children::Some(children) => {
687 for child_url in children.iter() {
689 if child_url.path == child {
690 return Ok(child_url.clone());
693 }
694 }
695 }
696 }
697 }
698 self.childbirth(child, None, None, Params::default())
700 }
701
702 pub fn child_exists(self: Arc<Self>, child: &PathPattern) -> bool {
703 let guard = self.children.read().unwrap();
705 match &*guard {
706 Children::Nil => false,
707 Children::Some(children) => {
708 children.iter().any(|c| c.path == *child)
709 }
710 }
711 }
712
713 pub fn literal_url(
715 self: Arc<Self>,
716 path: &str,
717 function: Option<Arc<dyn AsyncUrlHandler>>,
718 middleware: Option<Arc<Vec<Arc<dyn AsyncMiddleware>>>>,
719 params: Params,
720 ) -> Result<Arc<Url>, String> {
721 println!("Changing url into path pattern: {}", path);
722 let path = if path.starts_with('/') {
724 &path[1..]
725 } else {
726 path
727 };
728 let path_vec: Vec<PathPattern> = path.split('/').map(|s| PathPattern::literal_path(s)).collect();
730 println!("Path vector: {:?}", path_vec);
731 let result = self.register(path_vec, function, middleware, params);
733 match result {
735 Ok(url) => Ok(url),
736 Err(e) => Err(format!("Error registering URL: {}", e)),
737 }
738 }
739
740 pub fn register(
742 self: Arc<Self>,
743 path: Vec<PathPattern>,
744 function: Option<Arc<dyn AsyncUrlHandler>>,
745 middleware: Option<Arc<Vec<Arc<dyn AsyncMiddleware>>>>,
746 params: Params,
747 ) -> Result<Arc<Self>, String> {
748 println!("Registering URL: {:?}", path);
749 if path.len() == 1 {
750 return self.childbirth(path[0].clone(), function, middleware, params);
751 } else {
752 println!("Recursion: Registering child URL: {:?}", path[0]);
753 return self.get_child_or_create(path[0].clone())?.register(path[1..].to_vec(), function, middleware, params);
754 }
755 }
756
757 pub fn look_for_child(self: Arc<Self>, path: PathPattern) -> Option<Arc<Self>> {
758 let guard = self.children.read().unwrap();
760 match &*guard {
761 Children::Nil => None,
762 Children::Some(children) => {
763 for child in children.iter() {
764 if child.path == path {
765 return Some(child.clone());
766 }
767 }
768 None
769 }
770 }
771 }
772
773 pub fn set_method(&self, handler: Arc<dyn AsyncUrlHandler>) {
774 let mut guard = self.method.write().unwrap();
775 *guard = Some(handler);
776 }
777
778 pub fn set_middlewares(&self, middlewares: Option<Arc<Vec<Arc<dyn AsyncMiddleware>>>>) {
779 let mut guard = self.middlewares.write().unwrap();
780 match middlewares {
781 Some(middlewares) => {
782 *guard = MiddleWares::MiddleWare(middlewares);
783 }
784 None => {
785 *guard = MiddleWares::Nil;
786 }
787 }
788 }
789
790 pub fn combine_params_for(&self, params: Params) -> Params {
791 let guard = self.params.read().unwrap();
792 return guard.combine(params);
793 }
794
795 pub fn get_max_body_size(&self) -> Option<usize> {
796 let guard = self.params.read().unwrap();
797 return guard.max_body_size;
798 }
799
800 pub fn set_max_body_size(&self, size: usize) {
801 let mut guard = self.params.write().unwrap();
802 guard.max_body_size = Some(size);
803 }
804
805 pub fn reset_max_body_size(&self) {
806 let mut guard = self.params.write().unwrap();
807 guard.max_body_size = None;
808 }
809
810 pub fn get_allowed_methods(&self) -> Option<Vec<HttpMethod>> {
811 let guard = self.params.read().unwrap();
812 return guard.allowed_methods.clone();
813 }
814
815 pub fn set_allowed_methods(&self, methods: Vec<HttpMethod>) {
816 let mut guard = self.params.write().unwrap();
817 guard.set_allowed_methods(methods);
818 }
819
820 pub fn remove_allowed_method(&self, method: HttpMethod) {
821 let mut guard = self.params.write().unwrap();
822 guard.remove_allowed_method(method);
823 }
824
825 pub fn add_allowed_method(&self, method: HttpMethod) {
826 let mut guard = self.params.write().unwrap();
827 guard.add_allowed_methods(method);
828 }
829
830 pub fn reset_allowed_methods(&self) {
831 let mut guard = self.params.write().unwrap();
832 guard.allowed_methods = None;
833 }
834
835 pub fn get_allowed_content_type(&self) -> Option<Vec<HttpContentType>> {
836 let guard = self.params.read().unwrap();
837 return guard.allowed_content_type.clone();
838 }
839
840 pub fn set_allowed_content_type(&self, content_types: Vec<HttpContentType>) {
841 let mut guard = self.params.write().unwrap();
842 guard.set_allowed_content_type(content_types);
843 }
844
845 pub fn remove_allowed_content_type(&self, content_type: HttpContentType) {
846 let mut guard = self.params.write().unwrap();
847 guard.remove_allowed_content_type(content_type);
848 }
849
850 pub fn add_allowed_content_type(&self, content_type: HttpContentType) {
851 let mut guard = self.params.write().unwrap();
852 guard.add_allowed_content_type(content_type);
853 }
854
855 pub fn reset_allowed_content_type(&self) {
856 let mut guard = self.params.write().unwrap();
857 guard.allowed_content_type = None;
858 }
859}
860
861pub fn dangling_url() -> Arc<Url> {
862 Arc::new(Url {
863 path: PathPattern::Any,
864 children: RwLock::new(Children::Nil),
865 ancestor: Ancestor::Nil,
866 method: RwLock::new(None),
867 middlewares: RwLock::new(MiddleWares::Nil),
868 params: RwLock::new(Params::default()),
869 })
870}