1use crate::{
2 static_files::StaticFiles, template::TemplateEngine, Handler, Request, Response, Router,
3};
4use async_trait::async_trait;
5use futures::FutureExt;
6use std::panic::AssertUnwindSafe;
7use std::sync::Arc;
8
9pub type ErrorHandlerFn =
10 Arc<dyn Fn(Box<dyn std::error::Error + Send + Sync>) -> Response + Send + Sync>;
11pub type NotFoundHandlerFn = Arc<dyn Fn(Request) -> Response + Send + Sync>;
12
13pub struct App {
14 router: Router,
15 static_handler: Option<Arc<StaticFiles>>,
16 pub template_engine: Option<Arc<tokio::sync::RwLock<TemplateEngine>>>,
17 error_handler: Option<ErrorHandlerFn>,
18 not_found_handler: Option<NotFoundHandlerFn>,
19}
20
21impl Default for App {
22 fn default() -> Self {
23 Self::new()
24 }
25}
26
27impl App {
28 pub fn new() -> Self {
29 App {
30 router: Router::new(),
31 static_handler: None,
32 template_engine: None,
33 error_handler: None,
34 not_found_handler: None,
35 }
36 }
37
38 pub fn router(mut self, router: Router) -> Self {
39 self.router = router;
40 self
41 }
42
43 pub fn static_files(mut self, dir: &str, prefix: &str) -> Self {
44 self.static_handler = Some(Arc::new(StaticFiles::new(dir, prefix)));
45 self
46 }
47
48 pub fn templates(mut self, engine: TemplateEngine) -> Self {
49 self.template_engine = Some(Arc::new(tokio::sync::RwLock::new(engine)));
50 self
51 }
52
53 pub fn error_handler<F>(mut self, handler: F) -> Self
54 where
55 F: Fn(Box<dyn std::error::Error + Send + Sync>) -> Response + Send + Sync + 'static,
56 {
57 self.error_handler = Some(Arc::new(handler));
58 self
59 }
60
61 pub fn not_found_handler<F>(mut self, handler: F) -> Self
62 where
63 F: Fn(Request) -> Response + Send + Sync + 'static,
64 {
65 self.not_found_handler = Some(Arc::new(handler));
66 self
67 }
68}
69
70#[async_trait]
71impl Handler for App {
72 async fn handle(
73 &self,
74 req: Request,
75 ) -> Result<Response, Box<dyn std::error::Error + Send + Sync>> {
76 if let Some(static_handler) = &self.static_handler {
77 if static_handler.matches(req.uri.path()) {
78 return static_handler.handle(req).await;
79 }
80 }
81
82 let not_found_handler = self.not_found_handler.clone();
83
84 let not_found_req_uri = req.uri.clone();
86 let not_found_req_method = req.method.clone();
87 let not_found_req_headers = req.headers.clone();
88 let request_id = req.request_id.clone();
89
90 let result = AssertUnwindSafe(async { self.router.handle_request(req).await })
92 .catch_unwind()
93 .await;
94
95 match result {
96 Ok(Ok(res)) => {
97 if res.status == hyper::StatusCode::NOT_FOUND {
99 if not_found_req_uri.path() == "/robots.txt" {
100 let site_url = std::env::var("SITE_URL").unwrap_or_else(|_| {
101 if let Some(host) = not_found_req_headers
102 .get("host")
103 .and_then(|h| h.to_str().ok())
104 {
105 format!("https://{}", host)
106 } else {
107 "http://localhost:3000".to_string()
108 }
109 });
110 let content = format!(
111 "User-agent: *\nAllow: /\nSitemap: {}/sitemap.xml\n",
112 site_url.trim_end_matches('/')
113 );
114 return Ok(Response::new()
115 .header("Content-Type", "text/plain; charset=utf-8")
116 .text(&content));
117 }
118
119 if not_found_req_uri.path() == "/sitemap.xml" {
120 let site_url = std::env::var("SITE_URL").unwrap_or_else(|_| {
121 if let Some(host) = not_found_req_headers
122 .get("host")
123 .and_then(|h| h.to_str().ok())
124 {
125 format!("https://{}", host)
126 } else {
127 "http://localhost:3000".to_string()
128 }
129 });
130 let base = site_url.trim_end_matches('/');
131 let content = format!(
132 r#"<?xml version="1.0" encoding="UTF-8"?>
133<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
134 <url>
135 <loc>{}/</loc>
136 <changefreq>daily</changefreq>
137 <priority>1.0</priority>
138 </url>
139</urlset>
140"#,
141 base
142 );
143 return Ok(Response::new()
144 .header("Content-Type", "application/xml; charset=utf-8")
145 .body(hyper::Body::from(content)));
146 }
147
148 if let Some(handler) = not_found_handler {
149 let mut builder = hyper::Request::builder()
151 .method(not_found_req_method)
152 .uri(not_found_req_uri);
153 for (key, value) in ¬_found_req_headers {
154 builder = builder.header(key, value);
155 }
156 let hyper_req = builder.body(hyper::Body::empty()).unwrap();
157 let actual_req = Request::from_hyper_with_addr(hyper_req, None)
158 .await
159 .unwrap();
160 return Ok(handler(actual_req));
161 }
162 }
163 Ok(res)
164 }
165 Ok(Err(e)) => {
166 if let Some(app_error) = e.downcast_ref::<crate::error::AppError>() {
167 return Ok(app_error.response_with_request_id(Some(&request_id)));
168 }
169
170 if let Some(handler) = &self.error_handler {
172 Ok(handler(e))
173 } else {
174 Ok(crate::error::AppError::Internal(e.to_string())
175 .response_with_request_id(Some(&request_id)))
176 }
177 }
178 Err(_panic_err) => {
179 tracing::error!(request_id = %request_id, "A handler thread panicked during execution!");
180 if let Some(handler) = &self.error_handler {
181 Ok(handler("Internal thread panic".into()))
182 } else {
183 Ok(
184 crate::error::AppError::Internal("handler panic".to_string())
185 .response_with_request_id(Some(&request_id)),
186 )
187 }
188 }
189 }
190 }
191}
192
193#[cfg(test)]
194mod tests {
195 use super::*;
196 use hyper::Body;
197 use tempfile::tempdir;
198
199 #[tokio::test]
200 async fn app_static_files_honors_custom_prefix() {
201 let dir = tempdir().unwrap();
202 std::fs::write(dir.path().join("hello.txt"), "hi").unwrap();
203
204 let app = App::new().static_files(dir.path().to_str().unwrap(), "/assets");
205 let req = Request::from_hyper(
206 hyper::Request::builder()
207 .method("GET")
208 .uri("/assets/hello.txt")
209 .body(Body::empty())
210 .unwrap(),
211 )
212 .await
213 .unwrap();
214
215 let response = app.handle(req).await.unwrap();
216 assert_eq!(response.status, hyper::StatusCode::OK);
217 }
218
219 #[tokio::test]
220 async fn app_maps_typed_errors_to_structured_responses() {
221 let router = Router::new().get("/fail", |_req: Request| async {
222 Err::<Response, Box<dyn std::error::Error + Send + Sync>>(Box::new(
223 crate::error::AppError::Validation("invalid title".to_string()),
224 ))
225 });
226 let app = App::new().router(router);
227 let req = Request::from_hyper(
228 hyper::Request::builder()
229 .method("GET")
230 .uri("/fail")
231 .body(Body::empty())
232 .unwrap(),
233 )
234 .await
235 .unwrap();
236 let request_id = req.request_id.clone();
237
238 let response = app.handle(req).await.unwrap();
239 let body = hyper::body::to_bytes(response.body).await.unwrap();
240 let document: serde_json::Value = serde_json::from_slice(&body).unwrap();
241
242 assert_eq!(response.status, hyper::StatusCode::BAD_REQUEST);
243 assert_eq!(response.headers.get("X-Request-ID"), Some(&request_id));
244 assert_eq!(document["error"]["code"], "VALIDATION_ERROR");
245 assert_eq!(document["error"]["message"], "invalid title");
246 }
247
248 #[tokio::test]
249 async fn app_auto_seo_serves_robots_and_sitemap() {
250 let app = App::new();
251
252 let req_robots = Request::from_hyper(
253 hyper::Request::builder()
254 .method("GET")
255 .uri("/robots.txt")
256 .body(Body::empty())
257 .unwrap(),
258 )
259 .await
260 .unwrap();
261
262 let res_robots = app.handle(req_robots).await.unwrap();
263 assert_eq!(res_robots.status, hyper::StatusCode::OK);
264
265 let req_sitemap = Request::from_hyper(
266 hyper::Request::builder()
267 .method("GET")
268 .uri("/sitemap.xml")
269 .body(Body::empty())
270 .unwrap(),
271 )
272 .await
273 .unwrap();
274
275 let res_sitemap = app.handle(req_sitemap).await.unwrap();
276 assert_eq!(res_sitemap.status, hyper::StatusCode::OK);
277 }
278}