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