1use anyhow::Result;
12use include_dir::{Dir, include_dir};
13use notify::{Config, Event, RecommendedWatcher, RecursiveMode, Watcher};
14use std::path::{Path, PathBuf};
15use std::sync::Arc;
16use std::time::Duration;
17use tokio::sync::RwLock;
18use tokio::time::sleep;
19use warp::{Filter, Reply};
20
21use crate::file_scanner::list_files_recursive_with_changes;
22use crate::git_helper::get_repository_url;
23use crate::models::Feature;
24
25static STATIC_DIR: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/public");
27
28#[derive(Debug, Clone)]
30pub struct ServerConfig {
31 pub port: u16,
33 pub host: [u8; 4],
35}
36
37impl Default for ServerConfig {
38 fn default() -> Self {
39 Self {
40 port: 3000,
41 host: [127, 0, 0, 1],
42 }
43 }
44}
45
46impl ServerConfig {
47 pub fn new(port: u16) -> Self {
49 Self {
50 port,
51 ..Default::default()
52 }
53 }
54
55 #[allow(dead_code)]
57 pub fn with_host(mut self, host: [u8; 4]) -> Self {
58 self.host = host;
59 self
60 }
61}
62
63pub async fn serve_features_with_watching(
79 features: &[Feature],
80 port: u16,
81 watch_path: PathBuf,
82 on_ready: Option<Box<dyn FnOnce() + Send>>,
83 skip_changes: bool,
84 ignore_paths: Vec<PathBuf>,
85 include_skipped_dirs: bool,
86) -> Result<()> {
87 let config = ServerConfig::new(port);
88 serve_features_with_config_and_watching(
89 features,
90 config,
91 Some(watch_path.clone()),
92 on_ready,
93 skip_changes,
94 ignore_paths,
95 include_skipped_dirs,
96 )
97 .await
98}
99
100pub async fn serve_features_with_config_and_watching(
116 features: &[Feature],
117 config: ServerConfig,
118 watch_path: Option<PathBuf>,
119 on_ready: Option<Box<dyn FnOnce() + Send>>,
120 skip_changes: bool,
121 ignore_paths: Vec<PathBuf>,
122 include_skipped_dirs: bool,
123) -> Result<()> {
124 let features_data = Arc::new(RwLock::new(features.to_vec()));
126
127 let repository_url = watch_path
129 .as_ref()
130 .and_then(|path| get_repository_url(path));
131
132 if let Some(ref path) = watch_path {
134 let features_data_clone = Arc::clone(&features_data);
135 let watch_path_clone = path.clone();
136
137 tokio::spawn(async move {
138 if let Err(e) = setup_file_watcher(
139 features_data_clone,
140 watch_path_clone,
141 ignore_paths,
142 include_skipped_dirs,
143 )
144 .await
145 {
146 eprintln!("File watcher error: {}", e);
147 }
148 });
149 }
150
151 let features_data_clone = Arc::clone(&features_data);
153 let features_route = warp::path("features.json")
154 .and(warp::get())
155 .and_then(move || {
156 let features_data = Arc::clone(&features_data_clone);
157 async move {
158 let features = features_data.read().await;
159 let features_json = match serde_json::to_string_pretty(&*features) {
160 Ok(json) => json,
161 Err(e) => {
162 eprintln!("Failed to serialize features: {}", e);
163 return Err(warp::reject::custom(SerializationError));
164 }
165 };
166
167 Ok::<_, warp::Rejection>(warp::reply::with_header(
168 features_json,
169 "content-type",
170 "application/json",
171 ))
172 }
173 });
174
175 let metadata_route = warp::path("metadata.json")
177 .and(warp::get())
178 .and_then(move || {
179 let repo_url = repository_url.clone();
180 async move {
181 let mut metadata = serde_json::json!({
182 "version": env!("CARGO_PKG_VERSION"),
183 "skipChanges": skip_changes
184 });
185
186 if let Some(url) = repo_url {
188 metadata["repository"] = serde_json::json!(url);
189 }
190
191 let metadata_json = match serde_json::to_string_pretty(&metadata) {
192 Ok(json) => json,
193 Err(e) => {
194 eprintln!("Failed to serialize metadata: {}", e);
195 return Err(warp::reject::custom(SerializationError));
196 }
197 };
198
199 Ok::<_, warp::Rejection>(warp::reply::with_header(
200 metadata_json,
201 "content-type",
202 "application/json",
203 ))
204 }
205 });
206
207 let index_route = warp::path::end().and(warp::get()).and_then(serve_index);
209
210 let static_route = warp::path::tail()
212 .and(warp::get())
213 .and_then(serve_static_file);
214
215 let routes = features_route
216 .or(metadata_route)
217 .or(index_route)
218 .or(static_route)
219 .with(warp::cors().allow_any_origin())
220 .recover(handle_rejection);
221
222 if let Some(callback) = on_ready {
224 callback();
225 }
226
227 println!(
228 "Server running at http://{}:{}",
229 config
230 .host
231 .iter()
232 .map(|&b| b.to_string())
233 .collect::<Vec<_>>()
234 .join("."),
235 config.port,
236 );
237 warp::serve(routes).run((config.host, config.port)).await;
238
239 Ok(())
240}
241
242async fn setup_file_watcher(
244 features_data: Arc<RwLock<Vec<Feature>>>,
245 watch_path: PathBuf,
246 ignore_paths: Vec<PathBuf>,
247 include_skipped_dirs: bool,
248) -> Result<()> {
249 let (tx, mut rx) = tokio::sync::mpsc::channel(100);
250
251 let watch_path_clone = watch_path.clone();
253 let _watcher = tokio::task::spawn_blocking(move || -> Result<RecommendedWatcher> {
254 let mut watcher = RecommendedWatcher::new(
255 move |res: notify::Result<Event>| {
256 match res {
257 Ok(event) => {
258 if let Err(e) = tx.blocking_send(event) {
260 eprintln!("Failed to send file system event: {}", e);
261 }
262 }
263 Err(e) => eprintln!("File watcher error: {:?}", e),
264 }
265 },
266 Config::default(),
267 )?;
268
269 watcher.watch(&watch_path_clone, RecursiveMode::Recursive)?;
270 Ok(watcher)
271 })
272 .await??;
273
274 while let Some(event) = rx.recv().await {
276 let should_recompute = event.paths.iter().any(|path| {
278 path.file_name()
279 .map(|name| name == "README.md")
280 .unwrap_or(false)
281 || event.kind.is_create()
282 || event.kind.is_remove()
283 });
284
285 if should_recompute {
286 sleep(Duration::from_millis(500)).await;
288
289 match list_files_recursive_with_changes(
290 &watch_path,
291 &ignore_paths,
292 include_skipped_dirs,
293 ) {
294 Ok(new_features) => {
295 let mut features = features_data.write().await;
296 *features = new_features;
297 println!("â
Features updated successfully");
298 }
299 Err(e) => {
300 eprintln!("â Failed to recompute features: {}", e);
301 }
302 }
303 }
304 }
305
306 Ok(())
307}
308
309#[derive(Debug)]
311struct SerializationError;
312impl warp::reject::Reject for SerializationError {}
313
314async fn serve_index() -> Result<impl warp::Reply, warp::Rejection> {
323 if let Some(file) = STATIC_DIR.get_file("index.html") {
324 let content = file.contents_utf8().unwrap_or("");
325 Ok(
326 warp::reply::with_header(content, "content-type", "text/html; charset=utf-8")
327 .into_response(),
328 )
329 } else {
330 let html = create_default_index_html();
331 Ok(
332 warp::reply::with_header(html, "content-type", "text/html; charset=utf-8")
333 .into_response(),
334 )
335 }
336}
337
338async fn serve_static_file(path: warp::path::Tail) -> Result<impl warp::Reply, warp::Rejection> {
348 let path_str = path.as_str();
349
350 if let Some(file) = STATIC_DIR.get_file(path_str) {
352 let content_type = get_content_type(path_str);
353
354 if let Some(contents) = file.contents_utf8() {
355 Ok(warp::reply::with_header(contents, "content-type", content_type).into_response())
357 } else {
358 Ok(
360 warp::reply::with_header(file.contents(), "content-type", content_type)
361 .into_response(),
362 )
363 }
364 } else {
365 Err(warp::reject::not_found())
366 }
367}
368
369fn get_content_type(path: &str) -> &'static str {
379 let extension = Path::new(path)
380 .extension()
381 .and_then(|ext| ext.to_str())
382 .unwrap_or("");
383
384 match extension.to_lowercase().as_str() {
385 "html" => "text/html; charset=utf-8",
386 "css" => "text/css; charset=utf-8",
387 "js" => "application/javascript; charset=utf-8",
388 "json" => "application/json; charset=utf-8",
389 "svg" => "image/svg+xml",
390 "png" => "image/png",
391 "jpg" | "jpeg" => "image/jpeg",
392 "gif" => "image/gif",
393 "ico" => "image/x-icon",
394 "txt" => "text/plain; charset=utf-8",
395 "pdf" => "application/pdf",
396 "xml" => "application/xml; charset=utf-8",
397 "woff" => "font/woff",
398 "woff2" => "font/woff2",
399 "ttf" => "font/ttf",
400 "eot" => "application/vnd.ms-fontobject",
401 _ => "application/octet-stream",
402 }
403}
404
405fn create_default_index_html() -> String {
407 r#"<!DOCTYPE html>
408<html lang="en">
409<head>
410 <meta charset="UTF-8">
411 <meta name="viewport" content="width=device-width, initial-scale=1.0">
412 <title>Features Dashboard</title>
413 <style>
414 body {
415 font-family: Arial, sans-serif;
416 margin: 40px;
417 line-height: 1.6;
418 background: #f5f5f5;
419 }
420 .container {
421 max-width: 800px;
422 margin: 0 auto;
423 background: white;
424 padding: 30px;
425 border-radius: 8px;
426 box-shadow: 0 2px 10px rgba(0,0,0,0.1);
427 }
428 h1 { color: #333; }
429 .links { list-style: none; padding: 0; }
430 .links li { margin: 10px 0; }
431 .links a {
432 color: #007acc;
433 text-decoration: none;
434 padding: 8px 15px;
435 border: 1px solid #007acc;
436 border-radius: 4px;
437 display: inline-block;
438 }
439 .links a:hover { background: #007acc; color: white; }
440 </style>
441</head>
442<body>
443 <div class="container">
444 <h1>đī¸ Features Dashboard</h1>
445 <p>Welcome to the feature-based architecture server!</p>
446 <ul class="links">
447 <li><a href="/features.json">đ View Features JSON</a></li>
448 <li><a href="/metadata.json">âšī¸ View Metadata JSON</a></li>
449 </ul>
450 <p><small>This server provides features data and serves embedded static files from the binary.</small></p>
451 </div>
452</body>
453</html>"#.to_string()
454}
455
456async fn handle_rejection(
458 err: warp::Rejection,
459) -> Result<impl warp::Reply, std::convert::Infallible> {
460 let (code, message) = if err.is_not_found() {
461 (warp::http::StatusCode::NOT_FOUND, "NOT_FOUND")
462 } else if err
463 .find::<warp::filters::body::BodyDeserializeError>()
464 .is_some()
465 {
466 (warp::http::StatusCode::BAD_REQUEST, "BAD_REQUEST")
467 } else if err.find::<warp::reject::MethodNotAllowed>().is_some() {
468 (
469 warp::http::StatusCode::METHOD_NOT_ALLOWED,
470 "METHOD_NOT_ALLOWED",
471 )
472 } else {
473 eprintln!("Unhandled rejection: {:?}", err);
474 (
475 warp::http::StatusCode::INTERNAL_SERVER_ERROR,
476 "INTERNAL_SERVER_ERROR",
477 )
478 };
479
480 Ok(warp::reply::with_status(message, code))
481}